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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mattrajca/swift-corelibs-foundation
|
Foundation/URLSession/URLSessionTask.swift
|
4
|
26727
|
// Foundation/URLSession/URLSessionTask.swift - URLSession API
//
// 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
//
// -----------------------------------------------------------------------------
///
/// URLSession API code.
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// A cancelable object that refers to the lifetime
/// of processing a given request.
open class URLSessionTask : NSObject, NSCopying {
public var countOfBytesClientExpectsToReceive: Int64 { NSUnimplemented() }
public var countOfBytesClientExpectsToSend: Int64 { NSUnimplemented() }
public var earliestBeginDate: Date? { NSUnimplemented() }
/// How many times the task has been suspended, 0 indicating a running task.
internal var suspendCount = 1
internal var session: URLSessionProtocol! //change to nil when task completes
internal let body: _Body
fileprivate var _protocol: URLProtocol? = nil
private let syncQ = DispatchQueue(label: "org.swift.URLSessionTask.SyncQ")
/// All operations must run on this queue.
internal let workQueue: DispatchQueue
public override init() {
// Darwin Foundation oddly allows calling this initializer, even though
// such a task is quite broken -- it doesn't have a session. And calling
// e.g. `taskIdentifier` will crash.
//
// We set up the bare minimum for init to work, but don't care too much
// about things crashing later.
session = _MissingURLSession()
taskIdentifier = 0
originalRequest = nil
body = .none
workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
super.init()
}
/// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter
internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) {
if let bodyData = request.httpBody {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData)))
} else {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: .none)
}
}
internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) {
self.session = session
/* make sure we're actually having a serial queue as it's used for synchronization */
self.workQueue = DispatchQueue.init(label: "org.swift.URLSessionTask.WorkQueue", target: session.workQueue)
self.taskIdentifier = taskIdentifier
self.originalRequest = request
self.body = body
super.init()
if session.configuration.protocolClasses != nil {
guard let protocolClasses = session.configuration.protocolClasses else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
} else {
guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
}
}
} else {
guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
}
}
}
deinit {
//TODO: Do we remove the EasyHandle from the session here? This might run on the wrong thread / queue.
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone?) -> Any {
return self
}
/// An identifier for this task, assigned by and unique to the owning session
open let taskIdentifier: Int
/// May be nil if this is a stream task
/*@NSCopying*/ open let originalRequest: URLRequest?
/// May differ from originalRequest due to http server redirection
/*@NSCopying*/ open internal(set) var currentRequest: URLRequest? {
get {
return self.syncQ.sync { return self._currentRequest }
}
set {
self.syncQ.sync { self._currentRequest = newValue }
}
}
fileprivate var _currentRequest: URLRequest? = nil
/*@NSCopying*/ open internal(set) var response: URLResponse? {
get {
return self.syncQ.sync { return self._response }
}
set {
self.syncQ.sync { self._response = newValue }
}
}
fileprivate var _response: URLResponse? = nil
/* Byte count properties may be zero if no body is expected,
* or URLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/// Number of body bytes already received
open internal(set) var countOfBytesReceived: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesReceived }
}
set {
self.syncQ.sync { self._countOfBytesReceived = newValue }
}
}
fileprivate var _countOfBytesReceived: Int64 = 0
/// Number of body bytes already sent */
open internal(set) var countOfBytesSent: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesSent }
}
set {
self.syncQ.sync { self._countOfBytesSent = newValue }
}
}
fileprivate var _countOfBytesSent: Int64 = 0
/// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
open internal(set) var countOfBytesExpectedToSend: Int64 = 0
/// Number of bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
open internal(set) var countOfBytesExpectedToReceive: Int64 = 0
/// The taskDescription property is available for the developer to
/// provide a descriptive label for the task.
open var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
open func cancel() {
workQueue.sync {
guard self.state == .running || self.state == .suspended else { return }
self.state = .canceling
self.workQueue.async {
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
self.error = urlError
self._protocol?.stopLoading()
self._protocol?.client?.urlProtocol(self._protocol!, didFailWithError: urlError)
}
}
}
/*
* The current state of the task within the session.
*/
open var state: URLSessionTask.State {
get {
return self.syncQ.sync { self._state }
}
set {
self.syncQ.sync { self._state = newValue }
}
}
fileprivate var _state: URLSessionTask.State = .suspended
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ open internal(set) var error: Error?
/// Suspend the task.
///
/// Suspending a task will prevent the URLSession from continuing to
/// load data. There may still be delegate calls made on behalf of
/// this task (for instance, to report data received while suspending)
/// but no further transmissions will be made on behalf of the task
/// until -resume is sent. The timeout timer associated with the task
/// will be disabled while a task is suspended. -suspend and -resume are
/// nestable.
open func suspend() {
// suspend / resume is implemented simply by adding / removing the task's
// easy handle fromt he session's multi-handle.
//
// This might result in slightly different behaviour than the Darwin Foundation
// implementation, but it'll be difficult to get complete parity anyhow.
// Too many things depend on timeout on the wire etc.
//
// TODO: It may be worth looking into starting over a task that gets
// resumed. The Darwin Foundation documentation states that that's what
// it does for anything but download tasks.
// We perform the increment and call to `updateTaskState()`
// synchronous, to make sure the `state` is updated when this method
// returns, but the actual suspend will be done asynchronous to avoid
// dead-locks.
workQueue.sync {
self.suspendCount += 1
guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") }
self.updateTaskState()
if self.suspendCount == 1 {
self.workQueue.async {
self._protocol?.stopLoading()
}
}
}
}
/// Resume the task.
///
/// - SeeAlso: `suspend()`
open func resume() {
workQueue.sync {
self.suspendCount -= 1
guard 0 <= self.suspendCount else { fatalError("Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") }
self.updateTaskState()
if self.suspendCount == 0 {
self.workQueue.async {
if let _protocol = self._protocol {
_protocol.startLoading()
}
else if self.error == nil {
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "unsupported URL"]
if let url = self.originalRequest?.url {
userInfo[NSURLErrorFailingURLErrorKey] = url
userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain,
code: NSURLErrorUnsupportedURL,
userInfo: userInfo))
self.error = urlError
_ProtocolClient().urlProtocol(task: self, didFailWithError: urlError)
}
}
}
}
}
/// The priority of the task.
///
/// Sets a scaling factor for the priority of the task. The scaling factor is a
/// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
/// priority and 1.0 is considered the highest.
///
/// The priority is a hint and not a hard requirement of task performance. The
/// priority of a task may be changed using this API at any time, but not all
/// protocols support this; in these cases, the last priority that took effect
/// will be used.
///
/// If no priority is specified, the task will operate with the default priority
/// as defined by the constant URLSessionTask.defaultPriority. Two additional
/// priority levels are provided: URLSessionTask.lowPriority and
/// URLSessionTask.highPriority, but use is not restricted to these.
open var priority: Float {
get {
return self.workQueue.sync { return self._priority }
}
set {
self.workQueue.sync { self._priority = newValue }
}
}
fileprivate var _priority: Float = URLSessionTask.defaultPriority
}
extension URLSessionTask {
public enum State : Int {
/// The task is currently being serviced by the session
case running
case suspended
/// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message.
case canceling
/// The task has completed and the session will receive no more delegate notifications
case completed
}
}
extension URLSessionTask : ProgressReporting {
public var progress: Progress {
NSUnimplemented()
}
}
internal extension URLSessionTask {
/// Updates the (public) state based on private / internal state.
///
/// - Note: This must be called on the `workQueue`.
internal func updateTaskState() {
func calculateState() -> URLSessionTask.State {
if suspendCount == 0 {
return .running
} else {
return .suspended
}
}
state = calculateState()
}
}
internal extension URLSessionTask {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
internal extension URLSessionTask._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
fileprivate func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
public extension URLSessionTask {
/// The default URL session task priority, used implicitly for any task you
/// have not prioritized. The floating point value of this constant is 0.5.
public static let defaultPriority: Float = 0.5
/// A low URL session task priority, with a floating point value above the
/// minimum of 0 and below the default value.
public static let lowPriority: Float = 0.25
/// A high URL session task priority, with a floating point value above the
/// default value and below the maximum of 1.0.
public static let highPriority: Float = 0.75
}
/*
* An URLSessionDataTask does not provide any additional
* functionality over an URLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
open class URLSessionDataTask : URLSessionTask {
}
/*
* An URLSessionUploadTask does not currently provide any additional
* functionality over an URLSessionDataTask. All delegate messages
* that may be sent referencing an URLSessionDataTask equally apply
* to URLSessionUploadTasks.
*/
open class URLSessionUploadTask : URLSessionDataTask {
}
/*
* URLSessionDownloadTask is a task that represents a download to
* local storage.
*/
open class URLSessionDownloadTask : URLSessionTask {
internal var fileLength = -1.0
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
open func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) { NSUnimplemented() }
}
/*
* An URLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via URLSession. This task
* may be explicitly created from an URLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* URLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create InputStream and OutputStream
* instances from an URLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
open class URLSessionStreamTask : URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (Data?, Bool, Error?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
open func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (Error?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
open func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
open func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
open func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
open func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
open func stopSecureConnection() { NSUnimplemented() }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let URLSessionDownloadTaskResumeData: String = "NSURLSessionDownloadTaskResumeData"
extension _ProtocolClient : URLProtocolClient {
func urlProtocol(_ protocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy) {
guard let task = `protocol`.task else { fatalError("Received response, but there's no task.") }
task.response = response
let session = task.session as! URLSession
guard let dataTask = task as? URLSessionDataTask else { return }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate as URLSessionDataDelegate):
session.delegateQueue.addOperation {
delegate.urlSession(session, dataTask: dataTask, didReceive: response, completionHandler: { _ in
URLSession.printDebug("warning: Ignoring disposition from completion handler.")
})
}
case .noDelegate, .taskDelegate, .dataCompletionHandler, .downloadCompletionHandler:
break
}
}
func urlProtocolDidFinishLoading(_ protocol: URLProtocol) {
guard let task = `protocol`.task else { fatalError() }
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
if let downloadDelegate = delegate as? URLSessionDownloadDelegate, let downloadTask = task as? URLSessionDownloadTask {
session.delegateQueue.addOperation {
downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL)
}
}
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didCompleteWithError: nil)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .noDelegate:
task.state = .completed
session.taskRegistry.remove(task)
case .dataCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(`protocol`.properties[URLProtocol._PropertyKey.responseData] as? Data ?? Data(), task.response, nil)
task.state = .completed
session.taskRegistry.remove(task)
}
case .downloadCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(`protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as? URL, task.response, nil)
task.state = .completed
session.taskRegistry.remove(task)
}
}
task._protocol = nil
}
func urlProtocol(_ protocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, didLoad data: Data) {
`protocol`.properties[.responseData] = data
guard let task = `protocol`.task else { fatalError() }
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
let dataDelegate = delegate as? URLSessionDataDelegate
let dataTask = task as? URLSessionDataTask
session.delegateQueue.addOperation {
dataDelegate?.urlSession(session, dataTask: dataTask!, didReceive: data)
}
default: return
}
}
func urlProtocol(_ protocol: URLProtocol, didFailWithError error: Error) {
guard let task = `protocol`.task else { fatalError() }
urlProtocol(task: task, didFailWithError: error)
}
func urlProtocol(task: URLSessionTask, didFailWithError error: Error) {
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didCompleteWithError: error as Error)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .noDelegate:
task.state = .completed
session.taskRegistry.remove(task)
case .dataCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(nil, nil, error)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .downloadCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(nil, nil, error)
task.state = .completed
session.taskRegistry.remove(task)
}
}
task._protocol = nil
}
func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse) {
NSUnimplemented()
}
}
extension URLProtocol {
enum _PropertyKey: String {
case responseData
case temporaryFileURL
}
}
|
apache-2.0
|
15cb59ed63a788836c3b732cffedd8d0
| 40.695788 | 182 | 0.639466 | 5.264329 | false | false | false | false |
valitovaza/IntervalReminder
|
IntervalReminder/ImageGenerator.swift
|
1
|
7765
|
import Cocoa
protocol ImageGeneratable {
func generate() -> NSImage
func setInterval(_ timeInterval: Double)
func setPastInterval(_ timeInterval: Double)
func incrementInterval()
var delegate: ImageChangeListener? {get set}
}
protocol ImageChangeListener: class {
func imageChanged(image: NSImage)
}
class ImageGenerator: ImageGeneratable {
let imageSize = 16.0
weak var delegate: ImageChangeListener?
private(set) var currentPercent: Double = 0.0 {
didSet {
updateImage()
}
}
private(set) var interval: Double = 0.0 {
didSet {
countPercent()
}
}
private(set) var pastInterval: Double = 0.0 {
didSet {
countPercent()
}
}
func generate() -> NSImage {
let image = DrawImageInNSGraphicsContext(size: rectForImage().size) { () -> () in
drawImage(rectForImage(), currentPercent)
}
return imageForStatus(image)
}
func setInterval(_ timeInterval: Double) {
interval = timeInterval
}
func setPastInterval(_ timeInterval: Double) {
pastInterval = timeInterval
}
func incrementInterval() {
pastInterval += 1.0
updateImage()
}
private func updateImage() {
delegate?.imageChanged(image: generate())
}
private func countPercent() {
currentPercent = interval == 0 ? 0.0 : pastInterval / interval
}
private func rectForImage() -> NSRect {
let doubledSize = CGFloat(2.0 * imageSize)
return NSRect(origin: NSZeroPoint, size: NSMakeSize(doubledSize, doubledSize))
}
private func imageForStatus(_ image: NSImage) -> NSImage {
let resizedImage = image.resizeImage(width: imageSize, imageSize)
resizedImage.isTemplate = true
return resizedImage
}
private func drawImage(_ rect: NSRect, _ percent: Double) {
NSColor.black.set()
drawCircle(innerRectFrom(rect))
drawArc(rect, percent: percent)
}
private func innerRectFrom(_ rect: NSRect, margin: CGFloat = 1.0) -> NSRect {
let doubledMargin = 2 * margin
return NSRect(origin: NSMakePoint(margin, margin),
size: NSMakeSize(rect.size.width - doubledMargin, rect.size.height - doubledMargin))
}
private func drawCircle(_ rect: NSRect) {
let circlePath = NSBezierPath()
circlePath.appendOval(in: rect)
circlePath.lineWidth = 1.0
circlePath.stroke()
}
private func drawArc(_ rect: NSRect, percent: Double) {
let path = NSBezierPath()
moveToCenter(path, rect)
arcWith(rect: rect, percent: percent, in: path)
moveToCenter(path, rect)
path.fill()
}
private func moveToCenter(_ path: NSBezierPath, _ rect: NSRect) {
let center = rectCenter(rect)
path.move(to: center)
}
private func rectCenter(_ rect: NSRect) -> NSPoint {
return NSMakePoint(rect.size.width/2.0, rect.size.height/2.0)
}
private func arcWith(rect: NSRect, percent: Double, in path: NSBezierPath) {
let radius = innerRectFrom(rect).size.width/2.0
let angles = arcAngles(percent)
path.appendArc(withCenter: rectCenter(rect),
radius: radius,
startAngle: angles.startAngle,
endAngle: angles.endAngle,
clockwise: true)
}
private let topPosition: CGFloat = 90.0
private let fullCircleAngle: CGFloat = 360.0
private func arcAngles(_ percent: Double) -> (startAngle: CGFloat, endAngle: CGFloat) {
let diffAngle: CGFloat = fullCircleAngle * validPercent(percent)
let endAngle: CGFloat = topPosition - diffAngle
return (startAngle: topPosition, endAngle: endAngle)
}
private func validPercent(_ percent: Double) -> CGFloat {
var floatPercent = CGFloat(min(1.0, percent))
floatPercent = max(0.0, floatPercent)
return floatPercent
}
// MARK: - Graphics stuff
private func DrawImageInCGContext(size: CGSize, drawFunc: (_ context: CGContext) -> ()) -> NSImage? {
guard let context = getCGContext(size) else { return nil }
drawFunc(context)
return imageFrom(context: context, size: size)
}
private func getCGContext(_ size: CGSize) -> CGContext? {
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
return CGContext.init(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: Int(8),
bytesPerRow: Int(0),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: UInt32(bitmapInfo.rawValue))
}
private func imageFrom(context: CGContext, size: CGSize) -> NSImage? {
if let image = context.makeImage() {
return NSImage(cgImage: image, size: size)
}
return nil
}
private func DrawImageInNSGraphicsContext(size: CGSize, drawFunc: ()->()) -> NSImage {
let rep = bitmapImageRep(size)
let context = NSGraphicsContext(bitmapImageRep: rep)!
drawInGraphics(context: context, drawFunc: drawFunc)
return imageFromRepresentation(rep, size)
}
private func bitmapImageRep(_ size: CGSize) -> NSBitmapImageRep {
return NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0)!
}
private func drawInGraphics(context: NSGraphicsContext, drawFunc: ()->()) {
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrent(context)
drawFunc()
NSGraphicsContext.restoreGraphicsState()
}
private func imageFromRepresentation(_ rep: NSBitmapImageRep, _ size: CGSize) -> NSImage {
let image = NSImage(size: size)
image.addRepresentation(rep)
return image
}
}
extension NSImage {
func resizeImage(width: Double, _ height: Double) -> NSImage {
let img = NSImage(size: CGSize(width: width, height: height))
img.lockFocus()
let ctx = NSGraphicsContext.current()
ctx?.imageInterpolation = .high
self.draw(in: NSMakeRect(0, 0, CGFloat(width), CGFloat(height)),
from: NSMakeRect(0, 0, size.width, size.height),
operation: .copy,
fraction: 1.0)
img.unlockFocus()
return img
}
}
extension NSBezierPath {
var CGPath: CGPath {
let path = CGMutablePath()
var points = [CGPoint](repeating: .zero, count: 3)
for i in 0 ..< self.elementCount {
let type = self.element(at: i, associatedPoints: &points)
switch type {
case .moveToBezierPathElement:
path.move(to: CGPoint(x: points[0].x, y: points[0].y))
case .lineToBezierPathElement:
path.addLine(to: CGPoint(x: points[0].x, y: points[0].y))
case .curveToBezierPathElement:
path.addCurve(to: CGPoint(x: points[2].x, y: points[2].y),
control1: CGPoint(x: points[0].x, y: points[0].y),
control2: CGPoint(x: points[1].x, y: points[1].y))
case .closePathBezierPathElement: path.closeSubpath()
}
}
return path
}
}
|
mit
|
b63536176317813f2a8b2842d7cb62b1
| 37.440594 | 106 | 0.599099 | 4.691843 | false | false | false | false |
roambotics/swift
|
validation-test/compiler_crashers_2_fixed/0059-issue-45909.swift
|
2
|
946
|
// RUN: %target-swift-frontend %s -emit-ir
// RUN: %target-swift-frontend %s -emit-ir -O
// https://github.com/apple/swift/issues/45909
protocol ControllerB {
associatedtype T: Controller
}
protocol Controller {
associatedtype T
func shouldSelect<S: ControllerB>(_ a: T, b: S) where S.T == Self
}
struct ControllerAImpl {}
struct ControllerImpl : Controller {
typealias T = ControllerAImpl
func shouldSelect<S : ControllerB>(_ a: ControllerAImpl, b: S) where S.T == ControllerImpl {}
}
struct ControllerBImpl1 : ControllerB {
typealias T = ControllerImpl
}
struct ControllerBImpl2<C : Controller> : ControllerB {
typealias T = C
}
extension Controller {
func didSelect<S: ControllerB>(_ a: T, b: S) where S.T == Self {
shouldSelect(a, b: b)
}
}
ControllerImpl().didSelect(ControllerAImpl(), b: ControllerBImpl1())
ControllerImpl().didSelect(ControllerAImpl(), b: ControllerBImpl2<ControllerImpl>())
|
apache-2.0
|
f7a254716064df7b7a8734c23bb43ac2
| 23.25641 | 95 | 0.705074 | 3.556391 | false | false | false | false |
trupin/Beaver
|
Beaver/Type/Store.swift
|
2
|
6556
|
/// Responsible of dispatching actions and states.
/// It also holds a state, permitting to notify state changes to its subscribers.
///
/// - Parameters:
/// - ActionType: a type defining the action type
///
/// ## Important Notes: ##
/// 1. Subscribers are store in a set, which means they are called with an indefinite order!
/// 2. Subscribers are blocks, which means that the subscriber itself is responsible
/// of telling if its `self` should be retained or not by the store.
/// In main cases, stages need to declare a `weak self` in order to prevent retain cycles, when the scene
/// needs to declare a `strong self`.
/// 3. Subscribers registration is based on their name. Meaning that two subscribers with
/// the same name would override each others
public final class Store<StateType: State> {
/// Responsible of applying side effects for a given action or a state update
public struct Middleware {
public typealias Run = (_ action: ActionEnvelop?,
_ stateUpdate: (oldState: StateType?, newState: StateType)?) -> Void
public let name: String
public let run: Run
public init(name: String, run: @escaping Run) {
self.name = name
self.run = run
}
}
/// Current state
fileprivate(set) public var state: StateType
fileprivate func setState(_ newState: StateType, for envelop: ActionEnvelop, completion: @escaping () -> Void) {
if state == newState {
completion()
return
}
let oldState = self.state
self.state = newState
middleware.run(envelop, (oldState: oldState, newState: newState))
var pendingStateUpdateCompletions = subscribers.count
let stateDidUpdateCompletion = {
pendingStateUpdateCompletions -= 1
if pendingStateUpdateCompletions <= 0 {
completion()
}
}
guard subscribers.count > 0 else {
stateDidUpdateCompletion()
return
}
for subscriber in subscribers {
switch envelop.recipients {
case .emitter:
if subscriber.name != envelop.emitter {
stateDidUpdateCompletion()
continue
}
case .allExcludingEmitter:
if subscriber.name == envelop.emitter {
stateDidUpdateCompletion()
continue
}
case .authorized(to: let names):
if !names.contains(subscriber.name) {
stateDidUpdateCompletion()
continue
}
default:
break
}
subscriber.stateDidUpdate(oldState, newState, stateDidUpdateCompletion)
}
}
fileprivate let reducer: Reducer
fileprivate(set) public var subscribers = [Subscriber]()
fileprivate var middleware: Middleware {
return Middleware.composite(middlewares)
}
fileprivate var cancellable = Cancellable()
/// Registered actors
public let middlewares: [Middleware]
/// Store initialization
///
/// - Parameters:
/// - initialState: the first current state
/// - middlewares: a list of middleWares, responsible of side effects like logging, tracking, ...
/// - reducer: the reducer, responsible for new states generation
public init(initialState: StateType,
middlewares: [Middleware] = [],
reducer: @escaping Reducer) {
self.reducer = reducer
state = initialState
self.middlewares = middlewares
// stateDidSet is not called so we need to dispatch to actors here
middleware.run(nil, (oldState: nil, newState: initialState))
}
}
// MARK: - Dispatching
extension Store {
/// Dispatching interface
///
/// It is retaining a reference on the store
func dispatch(_ envelop: ActionEnvelop, completion: (() -> Void)? = nil) {
// Lifecycle actions are not cancellable
let cancellable = self.newCancellable()
self.middleware.run(envelop, nil)
var pendingStateUpdateCompletions = 2
let stateUpdateCompletion = {
pendingStateUpdateCompletions -= 1
if pendingStateUpdateCompletions == 0 {
completion?()
}
}
let newState = self.reducer(envelop, self.state) { newState in
if !cancellable.isCancelled {
self.setState(newState, for: envelop, completion: stateUpdateCompletion)
} else {
stateUpdateCompletion()
}
}
self.setState(newState, for: envelop, completion: stateUpdateCompletion)
}
}
// MARK: - Subscribing
extension Store {
/// Adds a new subscriber
public func subscribe(_ subscriber: Subscriber) {
subscribers.append(subscriber)
// Dispatching the state update permits to avoid infinite recursions when
// the `stateDidUpdate` method implementation refers the store
subscriber.stateDidUpdate(nil, self.state) {
// do nothing
}
}
/// Build and add a new subscriber
///
/// - Parameters:
/// - name: the subscriber's name
/// - stateDidUpdate: the subscriber state update handler
public func subscribe(name: String, stateDidUpdate: @escaping Subscriber.StateDidUpdate) {
subscribe(Subscriber(name: name, stateDidUpdate: stateDidUpdate))
}
/// Removes a subscriber
public func unsubscribe(_ name: String) {
guard let index = subscribers.index(where: { $0.name == name }) else {
return
}
subscribers.remove(at: index)
}
}
// MARK: - Description
extension Store: CustomDebugStringConvertible {
public var debugDescription: String {
return "\(self) - subscribers: [\(subscribers.map { $0.debugDescription })]"
}
}
// MARK: - Cancellation
fileprivate extension Store {
final class Cancellable {
private(set) var isCancelled: Bool = false
func cancel() {
isCancelled = true
}
}
func newCancellable() -> Cancellable {
cancellable.cancel()
let actionCancellable = Cancellable()
cancellable = actionCancellable
return actionCancellable
}
}
public protocol Storing {
associatedtype StateType: State
var store: Store<StateType> { get }
}
|
mit
|
b530fe38523c1d107ebde6a1ea5d7164
| 30.219048 | 116 | 0.606925 | 5.178515 | false | false | false | false |
imjerrybao/FutureKit
|
FutureKit/Synchronization.swift
|
1
|
40813
|
//
// NSData-Ext.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// 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
// Don't know what sort of synchronization is perfect?
// try them all!
// testing different strategys may result in different performances (depending on your implementations)
public protocol SynchronizationProtocol {
init()
// modify your shared object and return some value in the process
// the "then" block could execute inside ANY thread/queue so care should be taken.
// will try NOT to block the current thread (for Barrier/Queue strategies)
// Lock strategies may still end up blocking the calling thread.
func lockAndModify<T>(waitUntilDone wait: Bool, modifyBlock:() -> T,
then : ((T) -> Void)?)
// modify your shared object and return some value in the process
// the "then" block could execute inside ANY thread/queue so care should be taken.
// the "then" block is NOT protected by synchronization, but can process a value that was returned from
// the read block (ex: returned a lookup value from a shared Dictionary).
// will try NOT to block the current thread (for Barrier/Queue strategies)
// Lock strategies may still end up blocking the calling thread.
func lockAndRead<T>(waitUntilDone wait: Bool, readBlock:() -> T,
then : ((T) -> Void)?)
// -- The rest of these are convience methods.
// modify your object. The block() code may run asynchronously, but doesn't return any result
func lockAndModify(modifyBlock:() -> Void)
// modify your shared object and return some value in the process
// the "done" block could execute inside ANY thread/queue so care should be taken.
// will try NOT to block the current thread (for Barrier/Queue strategies)
// Lock strategies may still end up blocking the calling thread.
func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void)
// modify your container and retrieve a result/element to the same calling thread
// current thread will block until the modifyBlock is done running.
func lockAndModifySync<T>(modifyBlock:() -> T) -> T
// read your object. The block() code may run asynchronously, but doesn't return any result
// if you need to read the block and return a result, use readAsync/readSync
func lockAndRead(readBlock:() -> Void)
// perform a readonly query of your shared object and return some value/element T
// current thread may block until the read block is done running.
// do NOT modify your object inside this block
func lockAndReadSync<T>(readBlock:() -> T) -> T
// perform a readonly query of your object and return some value/element of type T.
// the results are delivered async inside the done() block.
// the done block is NOT protected by the synchronization - do not modify your shared data inside the "done:" block
// the done block could execute inside ANY thread/queue so care should be taken
// do NOT modify your object inside this block
func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void)
func readFuture<T>(executor _ : Executor, block:() -> T) -> Future<T>
func modifyFuture<T>(executor _ : Executor, block:() -> T) -> Future<T>
}
public enum SynchronizationType : CustomStringConvertible, CustomDebugStringConvertible {
case BarrierConcurrent
case BarrierSerial
case SerialQueue
case NSObjectLock
case NSLock
case NSRecursiveLock
case OSSpinLock
case PThreadMutex
// case NSLockWithSafetyChecks
// case NSRecursiveLockWithSafetyChecks
case Unsafe
public var maxLockWaitTimeAllowed : NSTimeInterval {
return 30.0
}
public static let allValues = [BarrierConcurrent, BarrierSerial, SerialQueue,NSObjectLock,NSLock,NSRecursiveLock,OSSpinLock,PThreadMutex]
public func lockObject() -> SynchronizationProtocol {
switch self {
case BarrierConcurrent:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_CONCURRENT)
case BarrierSerial:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_SERIAL)
case SerialQueue:
return QueueSerialSynchronization()
case NSObjectLock:
return NSObjectLockSynchronization()
case NSLock:
return NSLockSynchronization()
case NSRecursiveLock:
return NSRecursiveLockSynchronization()
case OSSpinLock:
return OSSpinLockSynchronization()
case PThreadMutex:
return PThreadMutexSynchronization()
/* case NSLockWithSafetyChecks:
return NSLockSynchronizationWithSafetyChecks()
case NSRecursiveLockWithSafetyChecks:
return NSRecursiveLockSynchronizationWithSafetyChecks() */
case Unsafe:
return UnsafeSynchronization()
}
}
public var description : String {
switch self {
case BarrierConcurrent:
return "BarrierConcurrent"
case BarrierSerial:
return "BarrierSerial"
case SerialQueue:
return "SerialQueue"
case NSObjectLock:
return "NSObjectLock"
case NSLock:
return "NSLock"
case NSRecursiveLock:
return "NSRecursiveLock"
case OSSpinLock:
return "OSSpinLock"
case PThreadMutex:
return "PThreadMutex"
case Unsafe:
return "Unsafe"
}
}
public var debugDescription : String {
return self.description
}
// some typealias for the default recommended Objects
typealias LightAndFastSyncType = OSSpinLockSynchronization
typealias SlowOrComplexSyncType = QueueBarrierSynchronization
}
public class QueueBarrierSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
self.q = QosCompatible.Default.createQueue("QueueBarrierSynchronization", q_attr: DISPATCH_QUEUE_CONCURRENT, relative_priority: 0)
}
public init(type : dispatch_queue_attr_t!, _ q: QosCompatible = .Default, _ p :Int32 = 0) {
self.q = q.createQueue("QueueBarrierSynchronization", q_attr: type, relative_priority: p)
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if (wait) {
dispatch_barrier_sync(self.q) {
let r = modifyBlock()
then?(r)
}
}
else {
dispatch_barrier_async(self.q) {
let r = modifyBlock()
then?(r)
}
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
if (wait) {
dispatch_sync(self.q) {
let r = readBlock()
then?(r)
}
}
else {
dispatch_async(self.q) {
let r = readBlock()
then?(r)
}
}
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
public class QueueSerialSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
self.q = QosCompatible.Default.createQueue("QueueSynchronization", q_attr: DISPATCH_QUEUE_SERIAL, relative_priority: 0)
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if (wait) {
dispatch_sync(self.q) { // should this dispatch_barrier_sync? let's see if there's a performance difference
let r = modifyBlock()
then?( r)
}
}
else {
dispatch_async(self.q) {
let r = modifyBlock()
then?( r)
}
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
if (wait) {
dispatch_sync(self.q) {
let r = readBlock()
then?( r)
}
}
else {
dispatch_async(self.q) {
let r = readBlock()
then?( r)
}
}
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
public class NSObjectLockSynchronization : SynchronizationProtocol {
var lock : AnyObject
required public init() {
self.lock = NSObject()
}
public init(lock l: AnyObject) {
self.lock = l
}
func synchronized<T>(block:() -> T) -> T {
return SYNCHRONIZED(self.lock) { () -> T in
return block()
}
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = self.synchronized(modifyBlock)
then( retVal)
}
else {
self.synchronized(modifyBlock)
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
func synchronizedWithLock<T>(l: NSLocking, @noescape closure: ()->T) -> T {
l.lock()
let retVal: T = closure()
l.unlock()
return retVal
}
public class NSLockSynchronization : SynchronizationProtocol {
var lock = NSLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = self.synchronized(modifyBlock)
then( retVal)
}
else {
self.synchronized(modifyBlock)
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
func synchronizedWithSpinLock<T>(l: UnSafeMutableContainer<OSSpinLock>, @noescape closure: ()->T) -> T {
OSSpinLockLock(l.unsafe_pointer)
let retVal: T = closure()
OSSpinLockUnlock(l.unsafe_pointer)
return retVal
}
public class OSSpinLockSynchronization : SynchronizationProtocol {
var lock = UnSafeMutableContainer<OSSpinLock>(OS_SPINLOCK_INIT)
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(self.lock) { () -> T in
return block()
}
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = self.synchronized(modifyBlock)
then( retVal)
}
else {
self.synchronized(modifyBlock)
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
func synchronizedWithMutexLock<T>(mutex: UnsafeMutablePointer<pthread_mutex_t>, @noescape closure: ()->T) -> T {
pthread_mutex_lock(mutex)
let retVal: T = closure()
pthread_mutex_unlock(mutex)
return retVal
}
public class PThreadMutexSynchronization : SynchronizationProtocol {
var mutex_container: UnSafeMutableContainer<pthread_mutex_t>
var mutex: UnsafeMutablePointer<pthread_mutex_t> {
return self.mutex_container.unsafe_pointer
}
required public init() {
self.mutex_container = UnSafeMutableContainer<pthread_mutex_t>()
pthread_mutex_init(self.mutex, nil)
}
deinit {
pthread_mutex_destroy(mutex)
self.mutex.destroy()
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithMutexLock(mutex) { () -> T in
return block()
}
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = self.synchronized(modifyBlock)
then( retVal)
}
else {
self.synchronized(modifyBlock)
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
public class NSRecursiveLockSynchronization : SynchronizationProtocol {
var lock = NSRecursiveLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = self.synchronized(modifyBlock)
then( retVal)
}
else {
self.synchronized(modifyBlock)
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
// this class offers no actual synchronization protection!!
// all blocks are executed immediately in the current calling thread.
// Useful for implementing a muteable-to-immuteable design pattern in your objects.
// You replace the Synchroniztion object once your object reaches an immutable state.
// USE WITH CARE.
public class UnsafeSynchronization : SynchronizationProtocol {
required public init() {
}
public final func lockAndModify<T>(
waitUntilDone wait: Bool = false,
modifyBlock:() -> T,
then : ((T) -> Void)? = nil) {
if let then = then {
let retVal = modifyBlock()
then( retVal)
}
else {
modifyBlock()
}
}
public final func lockAndRead<T>(
waitUntilDone wait: Bool = false,
readBlock:() -> T,
then : ((T) -> Void)? = nil) {
self.lockAndModify(waitUntilDone: wait, modifyBlock: readBlock, then: then)
}
// this should be in the swift 2.0 protocol extension, for now we do a big cut/paste
public final func lockAndModify(modifyBlock:() -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: nil)
}
public final func lockAndModifyAsync<T>(modifyBlock:() -> T, then : (T) -> Void) {
self.lockAndModify(waitUntilDone: false, modifyBlock: modifyBlock, then: then)
}
public final func lockAndModifySync<T>(modifyBlock:() -> T) -> T {
var retVal : T?
self.lockAndModify(waitUntilDone: true, modifyBlock: modifyBlock) { (modifyBlockReturned) -> Void in
retVal = modifyBlockReturned
}
return retVal!
}
public final func lockAndRead(readBlock:() -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: nil)
}
public final func lockAndReadAsync<T>(readBlock:() -> T, then : (T) -> Void) {
self.lockAndRead(waitUntilDone: false, readBlock: readBlock, then: then)
}
public final func lockAndReadSync<T>(readBlock:() -> T) -> T {
var retVal : T?
self.lockAndRead(waitUntilDone: true, readBlock: readBlock) { (readBlockReturned) -> Void in
retVal = readBlockReturned
}
return retVal!
}
public final func readFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndRead(waitUntilDone: false, readBlock: block) { (readBlockReturned) -> Void in
p.completeWithSuccess(readBlockReturned)
}
return p.future
}
public final func modifyFuture<T>(executor executor : Executor = .Primary, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.lockAndModify(waitUntilDone: false, modifyBlock: block) { (modifyBlockReturned) -> Void in
p.completeWithSuccess(modifyBlockReturned)
}
return p.future
}
}
public class CollectionAccessControl<C : MutableCollectionType, S: SynchronizationProtocol> {
public typealias Index = C.Index
public typealias Element = C.Generator.Element
var syncObject : S
var collection : C
public init(c : C, _ s: S) {
self.collection = c
self.syncObject = s
}
public func getValue(key : Index) -> Future<Element> {
return self.syncObject.readFuture(executor: .Primary) { () -> Element in
return self.collection[key]
}
}
/* subscript (key: Index) -> Element {
get {
return self.syncObject.readSync { () -> Element in
return self.collection[key]
}
}
set(newValue) {
self.syncObject.lockAndModifySync {
self.collection[key] = newValue
}
}
} */
}
public class DictionaryWithSynchronization<Key : Hashable, Value, S: SynchronizationProtocol> {
public typealias Index = Key
public typealias Element = Value
public typealias DictionaryType = Dictionary<Key,Value>
var syncObject : S
var dictionary : DictionaryType
public init() {
self.dictionary = DictionaryType()
self.syncObject = S()
}
public init(_ d : DictionaryType, _ s: S) {
self.dictionary = d
self.syncObject = s
}
public init(_ s: S) {
self.dictionary = DictionaryType()
self.syncObject = s
}
public func getValue(key : Key) -> Future<Value?> {
return self.syncObject.readFuture(executor: .Primary) { () -> Value? in
return self.dictionary[key]
}
}
public func getValueSync(key : Key) -> Value? {
let value = self.syncObject.lockAndReadSync { () -> Element? in
let e = self.dictionary[key]
return e
}
return value
}
public func setValue(value: Value, forKey key: Key) -> Future<Any> {
return self.syncObject.modifyFuture(executor: .Primary) { () -> Any in
self.dictionary[key] = value
}
}
public func updateValue(value: Value, forKey key: Key) -> Future<Value?> {
return self.syncObject.modifyFuture(executor: .Primary) { () -> Value? in
return self.dictionary.updateValue(value, forKey: key)
}
}
public var count: Int {
get {
return self.syncObject.lockAndReadSync { () -> Int in
return self.dictionary.count
}
}
}
public var isEmpty: Bool {
get {
return self.syncObject.lockAndReadSync { () -> Bool in
return self.dictionary.isEmpty
}
}
}
// THIS operation may hang swift 1.2 and CRASHES the Swift 2.0 xcode7.0b1 compiler!
/* subscript (key: Key) -> Value? {
get {
let value = self.syncObject.readSync { () -> Element? in
let e = self.dictionary[key]
return e
}
return value
}
set(newValue) {
// self.syncObject.lockAndModifySync {
// self.dictionary[key] = newValue
// }
}
} */
}
public class ArrayWithSynchronization<T, S: SynchronizationProtocol> : CollectionAccessControl< Array<T> , S> {
var array : Array<T> {
get {
return self.collection
}
}
public init() {
super.init(c: Array<T>(), S())
}
public init(array : Array<T>, _ a: S) {
super.init(c: array, a)
}
public init(a: S) {
super.init(c: Array<T>(), a)
}
public var count: Int {
get {
return self.syncObject.lockAndReadSync { () -> Int in
return self.collection.count
}
}
}
public var isEmpty: Bool {
get {
return self.syncObject.lockAndReadSync { () -> Bool in
return self.collection.isEmpty
}
}
}
public var first: T? {
get {
return self.syncObject.lockAndReadSync { () -> T? in
return self.collection.first
}
}
}
public var last: T? {
get {
return self.syncObject.lockAndReadSync { () -> T? in
return self.collection.last
}
}
}
/* subscript (future index: Int) -> Future<T> {
return self.syncObject.readFuture { () -> T in
return self.collection[index]
}
} */
public func getValue(atIndex i: Int) -> Future<T> {
return self.syncObject.readFuture(executor: .Primary) { () -> T in
return self.collection[i]
}
}
public func append(newElement: T) {
self.syncObject.lockAndModify {
self.collection.append(newElement)
}
}
public func removeLast() -> T {
return self.syncObject.lockAndModifySync {
self.collection.removeLast()
}
}
public func insert(newElement: T, atIndex i: Int) {
self.syncObject.lockAndModify {
self.collection.insert(newElement,atIndex: i)
}
}
public func removeAtIndex(index: Int) -> T {
return self.syncObject.lockAndModifySync {
self.collection.removeAtIndex(index)
}
}
}
public class DictionaryWithFastLockAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,SynchronizationType.LightAndFastSyncType> {
typealias LockObjectType = SynchronizationType.LightAndFastSyncType
public override init() {
super.init(LockObjectType())
}
public init(d : Dictionary<Key,Value>) {
super.init(d,LockObjectType())
}
}
public class DictionaryWithBarrierAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,QueueBarrierSynchronization> {
typealias LockObjectType = QueueBarrierSynchronization
public init(queue : dispatch_queue_t) {
super.init(LockObjectType(queue: queue))
}
public init(d : Dictionary<Key,Value>,queue : dispatch_queue_t) {
super.init(d,LockObjectType(queue: queue))
}
}
public class ArrayWithFastLockAccess<T> : ArrayWithSynchronization<T,SynchronizationType.LightAndFastSyncType> {
}
/* func dispatch_queue_create_compatibleIOS8(label : String,
attr : dispatch_queue_attr_t,
qos_class : dispatch_qos_class_t,relative_priority : Int32) -> dispatch_queue_t
{
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority)
let queue = dispatch_queue_create(label, c_attr)
return queue;
} */
/* class DispatchQueue: NSObject {
enum QueueType {
case Serial
case Concurrent
}
enum QueueClass {
case Main
case UserInteractive // QOS_CLASS_USER_INTERACTIVE
case UserInitiated // QOS_CLASS_USER_INITIATED
case Default // QOS_CLASS_DEFAULT
case Utility // QOS_CLASS_UTILITY
case Background // QOS_CLASS_BACKGROUND
}
var q : dispatch_queue_t
var type : QueueType
init(name : String, type : QueueType, relative_priority : Int32) {
var attr = (type == .Concurrent) ? DISPATCH_QUEUE_CONCURRENT : DISPATCH_QUEUE_SERIAL
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority);
dispatch_queue_t queue = dispatch_queue_create(label, c_attr);
return queue;
}
} */
|
mit
|
8e76ea846ded8638831e461282c66760
| 31.339937 | 150 | 0.591503 | 4.386136 | false | false | false | false |
deadcoda/swiftactoe
|
Sources/Multiplayer.swift
|
1
|
2212
|
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Nanomsg
class Multiplayer {
internal var game: Game
internal var sock: Socket
init(game: Game, proto: Proto) throws {
sock = try Socket(proto)
self.game = game
}
func recieve() -> String? {
do {
sock.rcvtimeo = 100
let buf = try sock.recv()
return String(cString: buf.baseAddress!)
} catch NanomsgError.Err(let errno, _) {
// timeout
assert(errno == 60)
return nil
} catch _ {
return nil
}
}
func send(value: String) -> Bool {
do {
let nBytes = try sock.send(value)
return Int(nBytes) == value.characters.count
} catch _ {
return false
}
}
}
class Client: Multiplayer, InputSource {
init(game: Game) throws {
try super.init(game: game, proto: .SUB)
}
func connect(addr: String) -> Bool {
do {
if game.currentPlayer == Game.PlayerX {
let eid = try sock.bind(addr)
return eid != 0
} else {
let eid = try sock.connect(addr)
return eid != 0
}
} catch _ {
return false
}
}
private func readln() -> String? {
var buf: String = String()
while(true) {
let line = recieve()
if (line == nil) {
return nil;
}
let pos = line!.characters.index(of: "\n")
if (pos != nil) {
let str = line!.characters.prefix(upTo: pos!)
buf.append(String(str));
return buf;
} else {
buf.append(line!)
}
}
}
func readPlayer() -> Int? {
if let str = readln() {
let c = str[str.startIndex]
if c == "X" || c == "x" {
return Game.PlayerX
} else if c == "O" || c == "o" {
return Game.PlayerO
}
}
return nil
}
func readPoint() -> Point? {
if let str = recieve() {
return Point.parse(str: str)
}
return nil
}
}
|
unlicense
|
a8308fd7e49cfd3fffff8be2afa15dd0
| 20.90099 | 59 | 0.458409 | 4.103896 | false | false | false | false |
Frgallah/MasterTransitions
|
Sources/MTTransitions/PushTransition2.swift
|
1
|
5976
|
//
// MTPushTransition2.swift
// Pods
//
// Created by Frgallah on 4/11/17.
//
// Copyright (c) 2017 Mohammed Frgallah. All rights reserved.
//
// Licensed under the MIT license, can be found at: https://github.com/Frgallah/MasterTransitions/blob/master/LICENSE or https://opensource.org/licenses/MIT
//
// For last updated version of this code check the github page at https://github.com/Frgallah/MasterTransitions
//
//
/* Transition's Directions as Transition SubType
RightToLeft
LeftToRight
BottomToTop
TopToBottom
*/
import UIKit
class PushTransition2: TransitionAnimator {
override func setupTranisition(containerView: UIView, fromView: UIView, toView: UIView, fromViewFrame: CGRect, toViewFrame: CGRect) {
var fromFrame: CGRect = CGRect.zero
var toFrame: CGRect = CGRect.zero
var toFrame1: CGRect = CGRect.zero
var toFrame2: CGRect = CGRect.zero
var toFrame3: CGRect = CGRect.zero
switch transitionSubType {
case .RightToLeft:
fromFrame = fromViewFrame.offsetBy(dx: -(fromViewFrame.width), dy: 0)
let width = toViewFrame.width
toFrame = toViewFrame.offsetBy(dx: width, dy: 0)
toFrame1 = toViewFrame.offsetBy(dx: (width * 0.03), dy: 0)
toFrame2 = toViewFrame.offsetBy(dx: (width * 0.015), dy: 0)
toFrame3 = toViewFrame.offsetBy(dx: (width * 0.01), dy: 0)
case .LeftToRight:
fromFrame = fromViewFrame.offsetBy(dx: fromViewFrame.width, dy: 0)
let width = toViewFrame.width
toFrame = toViewFrame.offsetBy(dx: -(width), dy: 0)
toFrame1 = toViewFrame.offsetBy(dx: -(width * 0.03), dy: 0)
toFrame2 = toViewFrame.offsetBy(dx: -(width * 0.015), dy: 0)
toFrame3 = toViewFrame.offsetBy(dx: -(width * 0.01), dy: 0)
case .TopToBottom:
fromFrame = fromViewFrame.offsetBy(dx: 0, dy: fromViewFrame.height)
let height = toViewFrame.height
toFrame = toViewFrame.offsetBy(dx: 0, dy: -(height))
toFrame1 = toViewFrame.offsetBy(dx: 0, dy: -(height * 0.03))
toFrame2 = toViewFrame.offsetBy(dx: 0, dy: -(height * 0.015))
toFrame3 = toViewFrame.offsetBy(dx: 0, dy: -(height * 0.01))
case .BottomToTop:
fromFrame = fromViewFrame.offsetBy(dx: 0, dy: -(fromViewFrame.height))
let height = toViewFrame.height
toFrame = toViewFrame.offsetBy(dx: 0, dy: (height))
toFrame1 = toViewFrame.offsetBy(dx: 0, dy: (height * 0.03))
toFrame2 = toViewFrame.offsetBy(dx: 0, dy: (height * 0.015))
toFrame3 = toViewFrame.offsetBy(dx: 0, dy: (height * 0.01))
default:
fromFrame = fromViewFrame.offsetBy(dx: -(fromViewFrame.width), dy: 0)
let width = toViewFrame.width
toFrame = toViewFrame.offsetBy(dx: width, dy: 0)
toFrame1 = toViewFrame.offsetBy(dx: (width * 0.03), dy: 0)
toFrame2 = toViewFrame.offsetBy(dx: (width * 0.015), dy: 0)
toFrame3 = toViewFrame.offsetBy(dx: (width * 0.01), dy: 0)
}
containerView.backgroundColor = UIColor.lightGray
fromView.frame = fromViewFrame
toView.frame = toFrame
containerView.addSubview(toView)
toView.alpha = 0
let animator: UIViewPropertyAnimator = UIViewPropertyAnimator.init(duration: duration, curve: .linear, animations: {
fromView.alpha = 0
toView.alpha = 1
UIView.animateKeyframes(withDuration: self.duration, delay: 0, options: .calculationModeLinear, animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.76, animations: {
fromView.frame = fromFrame
toView.frame = toViewFrame
})
UIView.addKeyframe(withRelativeStartTime: 0.76, relativeDuration: 0.06, animations: {
toView.frame = toFrame1
toView.transform = CGAffineTransform.init(rotationAngle: -0.008)
})
UIView.addKeyframe(withRelativeStartTime: 0.82, relativeDuration: 0.06, animations: {
toView.frame = toViewFrame
toView.transform = CGAffineTransform.init(rotationAngle: 0.006)
})
UIView.addKeyframe(withRelativeStartTime: 0.88, relativeDuration: 0.04, animations: {
toView.frame = toFrame2
toView.transform = CGAffineTransform.init(rotationAngle: -0.004)
})
UIView.addKeyframe(withRelativeStartTime: 0.92, relativeDuration: 0.04, animations: {
toView.frame = toViewFrame
toView.transform = CGAffineTransform.init(rotationAngle: 0.002)
})
UIView.addKeyframe(withRelativeStartTime: 0.96, relativeDuration: 0.02, animations: {
toView.frame = toFrame3
toView.transform = CGAffineTransform.init(rotationAngle: -0.0008)
})
UIView.addKeyframe(withRelativeStartTime: 0.98, relativeDuration: 0.02, animations: {
toView.frame = toViewFrame
toView.transform = CGAffineTransform.init(rotationAngle: 0.0)
})
}, completion: nil)
})
animator.addCompletion({ [unowned self] (position) in
if self.transitionCompletion != nil {
let completed = position == .end
self.transitionCompletion!(completed)
}
})
animator.isUserInteractionEnabled = false
propertyAnimator = animator
}
}
|
mit
|
9c54c1beea21c73038da14b10e650293
| 41.382979 | 160 | 0.581995 | 4.62181 | false | false | false | false |
randallli/material-components-ios
|
catalog/MDCCatalog/MDCCatalogComponentsController.swift
|
1
|
18097
|
/*
Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import CatalogByConvention
import MaterialCatalog
import MaterialComponents.MaterialFlexibleHeader
import MaterialComponents.MaterialFlexibleHeader_ColorThemer
import MaterialComponents.MaterialIcons_ic_arrow_back
import MaterialComponents.MaterialInk
import MaterialComponents.MaterialLibraryInfo
import MaterialComponents.MaterialShadowElevations
import MaterialComponents.MaterialShadowLayer
import MaterialComponents.MaterialThemes
import MaterialComponents.MaterialTypography
import UIKit
class MDCCatalogComponentsController: UICollectionViewController, MDCInkTouchControllerDelegate {
fileprivate struct Constants {
static let headerScrollThreshold: CGFloat = 30
static let inset: CGFloat = 16
static let menuTopVerticalSpacing: CGFloat = 38
static let logoWidthHeight: CGFloat = 30
static let menuButtonWidthHeight: CGFloat = 24
static let spacing: CGFloat = 1
}
fileprivate lazy var headerViewController = MDCFlexibleHeaderViewController()
private lazy var inkController: MDCInkTouchController = {
let controller = MDCInkTouchController(view: self.collectionView!)
controller.delaysInkSpread = true
controller.delegate = self
return controller
}()
private lazy var logo: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
private lazy var menuButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
let dotsImage = MDCIcons.imageFor_ic_more_horiz()?.withRenderingMode(.alwaysTemplate)
button.setImage(dotsImage, for: .normal)
button.adjustsImageWhenHighlighted = false
button.tintColor = .white
return button
}()
private let node: CBCNode
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.adjustsFontSizeToFitWidth = true
return titleLabel
}()
private var logoLeftPaddingConstraint: NSLayoutConstraint?
private var menuButtonRightPaddingConstraint: NSLayoutConstraint?
private var menuTopPaddingConstraint: NSLayoutConstraint?
init(collectionViewLayout ignoredLayout: UICollectionViewLayout, node: CBCNode) {
self.node = node
let layout = UICollectionViewFlowLayout()
let sectionInset: CGFloat = Constants.spacing
layout.sectionInset = UIEdgeInsets(top: sectionInset,
left: sectionInset,
bottom: sectionInset,
right: sectionInset)
layout.minimumInteritemSpacing = Constants.spacing
layout.minimumLineSpacing = Constants.spacing
super.init(collectionViewLayout: layout)
title = "Material Components for iOS"
addChildViewController(headerViewController)
headerViewController.headerView.minMaxHeightIncludesSafeArea = false
headerViewController.headerView.maximumHeight = 128
headerViewController.headerView.minimumHeight = 56
collectionView?.register(MDCCatalogCollectionViewCell.self,
forCellWithReuseIdentifier: "MDCCatalogCollectionViewCell")
collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
MDCIcons.ic_arrow_backUseNewStyle(true)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.themeDidChange),
name: AppTheme.didChangeGlobalThemeNotificationName,
object: nil)
}
func themeDidChange(notification: NSNotification) {
guard let colorScheme = notification.userInfo?[AppTheme.globalThemeNotificationColorSchemeKey]
as? MDCColorScheming else {
return
}
MDCFlexibleHeaderColorThemer.applySemanticColorScheme(colorScheme,
to: headerViewController.headerView)
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
convenience init(node: CBCNode) {
self.init(collectionViewLayout: UICollectionViewLayout(), node: node)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
inkController.addInkView()
let containerView = UIView(frame: headerViewController.headerView.bounds)
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.text = title!
titleLabel.textColor = AppTheme.globalTheme.colorScheme.onPrimaryColor
titleLabel.textAlignment = .center
titleLabel.font = AppTheme.globalTheme.typographyScheme.headline1
titleLabel.sizeToFit()
let titleInsets = UIEdgeInsets(top: 0,
left: Constants.inset,
bottom: Constants.inset,
right: Constants.inset)
let titleSize = titleLabel.sizeThatFits(containerView.bounds.size)
containerView.addSubview(titleLabel)
headerViewController.headerView.addSubview(containerView)
headerViewController.headerView.forwardTouchEvents(for: containerView)
containerView.addSubview(logo)
let colorScheme = AppTheme.globalTheme.colorScheme
let image = MDCDrawImage(CGRect(x:0,
y:0,
width: Constants.logoWidthHeight,
height: Constants.logoWidthHeight),
{ MDCCatalogDrawMDCLogoLight($0, $1) },
colorScheme)
logo.image = image
menuButton.addTarget(self.navigationController,
action: #selector(navigationController?.presentMenu),
for: .touchUpInside)
containerView.addSubview(menuButton)
setupFlexibleHeaderContentConstraints()
constrainLabel(label: titleLabel,
containerView: containerView,
insets: titleInsets,
height: titleSize.height)
MDCFlexibleHeaderColorThemer.applySemanticColorScheme(colorScheme,
to: headerViewController.headerView)
headerViewController.headerView.trackingScrollView = collectionView
headerViewController.headerView.setShadowLayer(MDCShadowLayer()) { (layer, intensity) in
let shadowLayer = layer as? MDCShadowLayer
CATransaction.begin()
CATransaction.setDisableActions(true)
shadowLayer!.elevation = ShadowElevation(intensity * ShadowElevation.appBar.rawValue)
CATransaction.commit()
}
view.addSubview(headerViewController.view)
headerViewController.didMove(toParentViewController: self)
collectionView?.accessibilityIdentifier = "collectionView"
#if swift(>=3.2)
if #available(iOS 11.0, *) {
collectionView?.contentInsetAdjustmentBehavior = .always
}
#endif
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView?.collectionViewLayout.invalidateLayout()
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func willAnimateRotation(
to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
collectionView?.collectionViewLayout.invalidateLayout()
}
override var childViewControllerForStatusBarStyle: UIViewController? {
return headerViewController
}
override var childViewControllerForStatusBarHidden: UIViewController? {
return headerViewController
}
#if swift(>=3.2)
@available(iOS 11, *)
override func viewSafeAreaInsetsDidChange() {
// Re-constraint the title label to account for changes in safeAreaInsets's left and right.
logoLeftPaddingConstraint?.constant = Constants.inset + view.safeAreaInsets.left
menuButtonRightPaddingConstraint?.constant = -1 * (Constants.inset + view.safeAreaInsets.right)
menuTopPaddingConstraint?.constant = Constants.inset + view.safeAreaInsets.top
}
#endif
func setupFlexibleHeaderContentConstraints() {
logoLeftPaddingConstraint = NSLayoutConstraint(item: logo,
attribute: .leading,
relatedBy: .equal,
toItem: logo.superview,
attribute: .leading,
multiplier: 1,
constant: Constants.inset)
logoLeftPaddingConstraint?.isActive = true
menuButtonRightPaddingConstraint = NSLayoutConstraint(item: menuButton,
attribute: .trailing,
relatedBy: .equal,
toItem: menuButton.superview,
attribute: .trailing,
multiplier: 1,
constant: -1 * Constants.inset)
menuButtonRightPaddingConstraint?.isActive = true
menuTopPaddingConstraint = NSLayoutConstraint(item: menuButton,
attribute: .top,
relatedBy: .equal,
toItem: menuButton.superview,
attribute: .top,
multiplier: 1,
constant: Constants.menuTopVerticalSpacing)
menuTopPaddingConstraint?.isActive = true
NSLayoutConstraint(item: logo,
attribute: .centerY,
relatedBy: .equal,
toItem: menuButton,
attribute: .centerY,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: logo,
attribute: .width,
relatedBy: .equal,
toItem: logo,
attribute: .height,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: logo,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.logoWidthHeight).isActive = true
NSLayoutConstraint(item: menuButton,
attribute: .width,
relatedBy: .equal,
toItem: menuButton,
attribute: .height,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: menuButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.menuButtonWidthHeight).isActive = true
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return node.children.count
}
func inkViewForView(_ view: UIView) -> MDCInkView {
let foundInkView = MDCInkView.injectedInkView(for: view)
foundInkView.inkStyle = .bounded
foundInkView.inkColor = UIColor(white:0.957, alpha: 0.2)
return foundInkView
}
// MARK: MDCInkTouchControllerDelegate
func inkTouchController(_ inkTouchController: MDCInkTouchController,
shouldProcessInkTouchesAtTouchLocation location: CGPoint) -> Bool {
return self.collectionView!.indexPathForItem(at: location) != nil
}
func inkTouchController(_ inkTouchController: MDCInkTouchController,
inkViewAtTouchLocation location: CGPoint) -> MDCInkView? {
if let indexPath = self.collectionView!.indexPathForItem(at: location) {
let cell = self.collectionView!.cellForItem(at: indexPath)
return inkViewForView(cell!)
}
return MDCInkView()
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier: "MDCCatalogCollectionViewCell",
for: indexPath)
cell.backgroundColor = UIColor.white
let componentName = node.children[indexPath.row].title
if let catalogCell = cell as? MDCCatalogCollectionViewCell {
catalogCell.populateView(componentName)
}
// Ensure that ink animations aren't recycled.
MDCInkView.injectedInkView(for: view).cancelAllAnimations(animated: false)
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let dividerWidth: CGFloat = 1
var safeInsets: CGFloat = 0
#if swift(>=3.2)
if #available(iOS 11, *) {
safeInsets = view.safeAreaInsets.left + view.safeAreaInsets.right
}
#endif
var cellWidthHeight: CGFloat
// iPhones have 2 columns in portrait and 3 in landscape
if UI_USER_INTERFACE_IDIOM() == .phone {
cellWidthHeight = (view.frame.size.width - 3 * dividerWidth - safeInsets) / 2
if view.frame.size.width > view.frame.size.height {
cellWidthHeight = (view.frame.size.width - 4 * dividerWidth - safeInsets) / 3
}
} else {
// iPads have 4 columns
cellWidthHeight = (view.frame.size.width - 5 * dividerWidth - safeInsets) / 4
}
return CGSize(width: cellWidthHeight, height: cellWidthHeight)
}
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
let node = self.node.children[indexPath.row]
var vc: UIViewController
if node.isExample() {
vc = node.createExampleViewController()
} else {
vc = MDCNodeListViewController(node: node)
}
self.navigationController?.setMenuBarButton(for: vc)
self.navigationController?.pushViewController(vc, animated: true)
}
// MARK: Private
func constrainLabel(label: UILabel,
containerView: UIView,
insets: UIEdgeInsets,
height: CGFloat) {
NSLayoutConstraint(item: label,
attribute: .leading,
relatedBy: .equal,
toItem: logo,
attribute: .trailing,
multiplier: 1.0,
constant: insets.left).isActive = true
NSLayoutConstraint(item: label,
attribute: .trailing,
relatedBy: .equal,
toItem: menuButton,
attribute: .leading,
multiplier: 1.0,
constant: -insets.right).isActive = true
NSLayoutConstraint(item: label,
attribute: .bottom,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1.0,
constant: -insets.bottom).isActive = true
NSLayoutConstraint(item: label,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: height).isActive = true
}
}
// UIScrollViewDelegate
extension MDCCatalogComponentsController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidScroll()
}
}
override func scrollViewDidEndDragging(
_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == headerViewController.headerView.trackingScrollView {
self.headerViewController.headerView.trackingScrollDidEndDecelerating()
}
}
override func scrollViewWillEndDragging(
_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let headerView = headerViewController.headerView
if scrollView == headerView.trackingScrollView {
headerView.trackingScrollWillEndDragging(
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
}
}
|
apache-2.0
|
5711d817ace1b6156551263b9c1fcf01
| 37.179325 | 99 | 0.635796 | 5.904405 | false | false | false | false |
YifengBai/YuDou
|
YuDou/YuDou/Classes/Home/View/AmuseGameCell.swift
|
1
|
1759
|
//
// AmuseGameCell.swift
// YuDou
//
// Created by Bemagine on 2017/1/23.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
class AmuseGameCell: UICollectionViewCell {
lazy var iconView : UIImageView = UIImageView()
lazy var title : UILabel = {
let title = UILabel()
title.font = UIFont.systemFont(ofSize: 14)
title.textAlignment = .center
return title
}()
var gameModel: BaseGroupRoomModel? {
didSet {
guard let gameModel = gameModel else { return }
title.text = gameModel.tag_name
let url = URL(string: gameModel.icon_url!)
iconView.kf.setImage(with: url, placeholder: UIImage(named: "Img_default"))
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension AmuseGameCell {
fileprivate func setupUI() {
for subv in contentView.subviews {
subv.removeFromSuperview()
}
iconView.frame = CGRect(x: contentView.frame.width / 4, y: contentView.frame.width / 4, width: contentView.frame.width / 2, height: contentView.frame.width / 2)
iconView.layer.cornerRadius = iconView.frame.width / 2.0
iconView.layer.masksToBounds = true
contentView.addSubview(iconView)
title.frame = CGRect(x: 0, y: iconView.frame.height + iconView.frame.origin.y + 5, width: contentView.frame.width, height: 20)
contentView.addSubview(title)
}
}
|
mit
|
e90dcf985c65a6e9b32a1ce552dfd926
| 25.606061 | 168 | 0.581435 | 4.479592 | false | false | false | false |
barisarsan/ScreenSceneController
|
ScreenSceneController/ScreenSceneController/ScreenSceneController.swift
|
1
|
5476
|
//
// ScreenSceneController.swift
// ScreenSceneController
//
// Copyright (c) 2014 Ruslan Shevchuk
//
// 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
@objc public protocol ScreenSceneControllerDelegate {
optional func screenSceneController(screenSceneController: ScreenSceneController, willShowViewController viewController: UIViewController, animated: Bool)
optional func screenSceneController(screenSceneController: ScreenSceneController, didShowViewController viewController: UIViewController, animated: Bool)
}
@objc public class ScreenSceneController: UIViewController, UINavigationControllerDelegate {
// MARK: - Initial Screen Scene Controller Setup
public override func viewDidLoad() {
super.viewDidLoad()
addChildScreenSceneNavigationController()
}
lazy var screenSceneNavigationController : UINavigationController = {
let screenSceneNavigationController = UINavigationController()
screenSceneNavigationController.delegate = self
screenSceneNavigationController.navigationBarHidden = true
return screenSceneNavigationController
}()
func addChildScreenSceneNavigationController() {
adoptChildViewController(screenSceneNavigationController)
screenSceneNavigationController.view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.insertSubview(screenSceneNavigationController.view, atIndex: 0)
view.addConstraints(screenSceneNavigationController.view.scaleToFillContraints(forView: view))
}
// MARK: - Screen Scene Navigation Controller Transition Effect
var transitionEffect = ScreenSceneControllerTransition()
public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation != .None {
transitionEffect.navigationControllerOperation = operation
return transitionEffect
} else {
return nil
}
}
// MARK: - Screen Scene Navigation Delegate
public weak var delegate: ScreenSceneControllerDelegate?
public func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
delegate?.screenSceneController?(self, willShowViewController: viewController, animated: animated)
}
public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
delegate?.screenSceneController?(self, didShowViewController: viewController, animated: animated)
}
// MARK: - Scene Managment
public var topViewController: ScreenScene? {
get {
if let topViewController = screenSceneNavigationController.topViewController as? ScreenScene {
return topViewController
}
return nil
}
}
public var viewControllers: [ScreenScene] {
get {
return screenSceneNavigationController.viewControllers as [ScreenScene]
}
set {
setViewControllers(newValue, animated: false)
}
}
public func setViewControllers(viewControllers: [AnyObject]!, animated: Bool) {
screenSceneNavigationController.setViewControllers(viewControllers, animated: animated)
}
// MARK: - Push
public func pushScreenScene(screenScene: ScreenScene, animated: Bool) {
screenSceneNavigationController.pushViewController(screenScene, animated: animated)
}
// MARK: - Pops
public func popViewControllerAnimated(animated: Bool) -> UIViewController? {
return screenSceneNavigationController.popViewControllerAnimated(animated)
}
public func popToViewController(viewController: UIViewController, animated: Bool) -> [AnyObject]? {
return screenSceneNavigationController.popToViewController(viewController, animated: animated)
}
public func popToRootViewControllerAnimated(animated: Bool) -> [AnyObject]? {
return screenSceneNavigationController.popToRootViewControllerAnimated(animated)
}
}
|
mit
|
d5cac7ee04b6657ac54cb00d29e29783
| 41.457364 | 288 | 0.739591 | 6.057522 | false | false | false | false |
subarnas-repo/CameraButton
|
CameraButton/Classes/CameraButton.swift
|
1
|
26172
|
//
// CameraButton.swift
// CameraButton
//
// Created by Subarna Santra on 8/13/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
/**
Delegates for camera button to allow greater control over the selected image
*/
@objc public protocol CameraButtonDelegate {
/**
Optional delegate method to know if the image is selected and to get the selected image
*/
@objc optional func imagePickerDismissed(imagePicked : Bool, withImage : UIImage?)
/**
Optional delegate method to know if the existing image is deleted
*/
@objc optional func targetImageDeleted()
}
/**
A subclass of UIButton to make image capturing easy
- uses UIImagePickerController for image selection
*/
public class CameraButton: UIButton, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
public weak var delegate : CameraButtonDelegate?
/**
Image type to be provided when getting the image type as NSData
- PNG: For UIImagePNGRepresentation.
- JPEG: For UIImageJPEGRepresentation.
*/
public enum ImageDataType {
case PNG
case JPEG
}
/**
Option types to be shown for the camera option menu.
- Camera: To open the camera
- PhotoLibrary: To open the photo library.
- PhotoAlbum: To open the photo album.
- DeleteExistingImage: To delete the image that is already in the targetImageView.
*/
public enum MenuOptonTypes {
case Camera
case PhotoLibrary
case PhotoAlbum
case DeleteExistingImage
case Cancel
}
/**
Available setting options for the menu.
- type: Defines the what the option does (e.g. if the type is .Camera the option should open up the device camera
- name: The name of the option to be shown to the user in menu list
- show: Defines if the option is shown to the user when the menu list is opened
- allowsEditing: Determines if the user should be allowed to edit the selected photo ( does not effect the option .DeleteExistingImage)
- presentWithAnimation: Show the camera/photo library/photo album image picker is to be shown with animation ( does not effect the option .DeleteExistingImage)
- dismissWithAnimation: Dismiss the camera/photo library/photo album image picker is to be shown with animation ( does not effect the option .DeleteExistingImage)
- notAvailableMessage: If the camera option is not available in the message, this message can be shown to user ( does not effect the option .DeleteExistingImage)
*/
public struct MenuSettings {
var type : MenuOptonTypes
var name: String
var show: Bool = true
var allowsEditing : Bool = false
var presentWithAnimation : Bool = true
var dismissWithAnimation : Bool = true
var notAvailableMessage : String = ""
}
///Keeps track of the current selected option
var currentlySelectedOptionSettings : MenuSettings?
///a custom imagepicker which has to be a subclass of UIImagePickerController can be used if necessary
public lazy var imagePicker : UIImagePickerController = UIImagePickerController()
///a required option, generally this is the view controller where the Camera Button is placed
public weak var targetViewController : UIViewController?
///if not provided, a dummy one would be created
public var targetImageView : UIImageView?
///a image name that could be placed in targetImageView after the image has been deleted
public var placeHolderImageName : String = ""
///if true, indicates the targetImageView contains a image, and the delete option is shown if not otherwise disabled
public var imageViewHasImage : Bool = false
/**
* Settings for different camera action,
*
* can be disabled by setting show = false
* if not available a message can be shown
* no message would be shown if notAvailableMessage is kept empty
*
*/
public var cameraMenuSettings : MenuSettings = MenuSettings(type : .Camera, name: "Camera", show: true, allowsEditing : false, presentWithAnimation : true, dismissWithAnimation : true, notAvailableMessage : "Unable to find camera in this device")
///settings for photo library action
public var photoLibraryMenuSettings : MenuSettings = MenuSettings(type : .PhotoLibrary, name: "Photo Library", show: true, allowsEditing : false, presentWithAnimation : true, dismissWithAnimation : true, notAvailableMessage : "Unable to find photo library in this device")
///settings for photo album action
public var photoAlbumMenuSettings : MenuSettings = MenuSettings(type : .PhotoAlbum, name: "Photo Album", show: true, allowsEditing : false, presentWithAnimation : true, dismissWithAnimation : true, notAvailableMessage : "Unable to find photo album in this device")
///the allowsEditing, prsentWithAnimation and dismissWithAnimation, notAvailableMessage does not really effect this menu
public var deleteMenuSettings : MenuSettings = MenuSettings(type : .DeleteExistingImage, name: "Delete", show: true, allowsEditing : false, presentWithAnimation : true, dismissWithAnimation : true, notAvailableMessage : "")
///settings for cancel action
public var cancelMenuSettings : MenuSettings = MenuSettings(type : .Cancel, name: "Cancel", show: true, allowsEditing : false, presentWithAnimation : true, dismissWithAnimation : true, notAvailableMessage : "")
///The header of the menu
public var optinMenuHeaderTitle : String = ""
///this option should be used to change the order of availabel options, can also be used to not show an option
public var optionMenuList : Array<MenuOptonTypes> = [
.Camera, .PhotoLibrary, .PhotoAlbum, .DeleteExistingImage
]
///user can choose to show the option menu popover from other places
public weak var showOptionMenuFromView : UIView?
///user can choose to show the option menu popover from bar button item
public weak var showOptionFromBarButtonItem : UIBarButtonItem?
///setup image picker first
func setupImagePicker() {
imagePicker.delegate = self
}
/**
* Image picker setup is initiated if the target view controller is availabel.
- Returns: true if the targetViewController is availabel.
*/
func checkSettings()->Bool {
/// if target view controller is not given, would not work
if (targetViewController == nil) {
return false;
}
/// image picker setup is initiated
self.setupImagePicker()
return true;
}
/**
Initializes the options depnding on the settings in optionMenuList
- Parameters:
- alertController: Alert view to show the menu
*/
func createCameraOptionMenu(alertController : UIAlertController) {
for (currentOption) in self.optionMenuList {
switch currentOption {
/// option to get image from camera
case .Camera:
//check settings
if (self.cameraMenuSettings.show == false) {
continue
}
//attach action to the menu
let cameraAction = UIAlertAction(title: self.cameraMenuSettings.name, style: .default) { (action) in
//action to open camera
self.openCamera(withSettings: self.cameraMenuSettings)
}
//added to the list
alertController.addAction(cameraAction)
/// option to select image from photo library
case .PhotoLibrary:
//check settings
if (self.photoLibraryMenuSettings.show == false) {
continue
}
//attach action to the menu
let photoLibraryAction = UIAlertAction(title: self.photoLibraryMenuSettings.name, style: .default) { (action) in
//action to open photo library
self.openPhotoLibary(withSettings: self.photoLibraryMenuSettings)
}
//added to the list
alertController.addAction(photoLibraryAction)
/// option to select image from photo albums
case .PhotoAlbum:
//check settings
if (self.photoAlbumMenuSettings.show == false) {
continue
}
let photoAlbumAction = UIAlertAction(title: self.photoAlbumMenuSettings.name, style: .default) { (action) in
//action to open photo album
self.openPhotoAlbum(withSettings: self.photoAlbumMenuSettings)
}
//added to the list
alertController.addAction(photoAlbumAction)
/// option to delete existing image in target image view
case .DeleteExistingImage:
//check settings
if (self.deleteMenuSettings.show == false) {
continue
}
//if there is any iamge in target image view
if (self.imageViewHasImage == true) {
let deleteImageAction = UIAlertAction(title: self.deleteMenuSettings.name, style: .default) { (action) in
//action to delete the existing image
self.deleteExistingImage(withSettings: self.deleteMenuSettings)
}
//added to the list
alertController.addAction(deleteImageAction)
}
case .Cancel:
//check settings
if (self.cancelMenuSettings.show == false) {
continue
}
///cancel action to cancel the camera option menu
let cancelAction = UIAlertAction(title: self.cancelMenuSettings.name, style: .cancel) { (action) in
}
/// cancel action is added to the list
alertController.addAction(cancelAction)
}
}
}
/**
* Shows menu to open up options depending on the settings in optionMenuList
*/
public func openCameraOptionMenu() {
let totalOptions = self.optionMenuList.count
///if there is no option the menu would not come up
if (totalOptions < 1) {
return;
}
self.optionMenuList.append(.Cancel)
let alertController = UIAlertController(title: nil, message: self.optinMenuHeaderTitle, preferredStyle: .actionSheet)
///add the option menus
self.createCameraOptionMenu(alertController: alertController);
//if the target view controller is avialble
if let givenViewController = targetViewController {
// checks to show where the menu is to be shown from ( IMPORTANT FOR IPAD)
if ( self.showOptionMenuFromView != nil || self.showOptionFromBarButtonItem != nil || UIDevice.current.userInterfaceIdiom == .pad) {
alertController.popoverPresentationController?.sourceView = self.targetViewController!.view
/// camera option is shown from bar button item if given
if (self.showOptionFromBarButtonItem != nil) {
alertController.popoverPresentationController?.barButtonItem = self.showOptionFromBarButtonItem!
} else {
/// if for no view is given to show the menu from, the menu is given from the camera button in case of IPAD
if (self.showOptionMenuFromView == nil) {
self.showOptionMenuFromView = self
}
alertController.popoverPresentationController?.sourceRect = self.showOptionMenuFromView!.frame
}
}
/// the option list is shown
givenViewController.present(alertController, animated: true) { }
}
}
/*if an image exists in the given target image view that has been selected from photo picker its deleted*/
/**
Delete existing image in target image view
- Parameters:
- settings: the settings for this menu options ( does not do anything actually)
*/
public func deleteExistingImage(withSettings settings : MenuSettings) {
if (self.imageViewHasImage == true && targetImageView != nil) {
// image is removed
targetImageView?.image = nil
// flag = false to indicate there is no existing image in target image view
imageViewHasImage = false
/// place holder image is placed if the name is provided in place of the deleted image
/// place holder image is not considered as an existing image
if (!self.placeHolderImageName.isEmpty) {
if let placeHolderImage : UIImage = UIImage(named: self.placeHolderImageName) {
targetImageView?.image = placeHolderImage
}
}
//the delegate method to indicat image deletiion is called
self.delegate?.targetImageDeleted?()
}
}
/**
Opens camera, if available
- Parameters:
- settings: the settings for this menu options
*/
public func openCamera(withSettings settings : MenuSettings) {
//check the settings type
if (settings.type == .Camera) {
//if camer available in device
if UIImagePickerController.isSourceTypeAvailable(.camera){
// if the image picker is setup properly
if (checkSettings() == true) {
//set the currently selected option as camera
self.currentlySelectedOptionSettings = settings
//allows editing of captured depending on the settings
imagePicker.allowsEditing = settings.allowsEditing
//source type is camera
imagePicker.sourceType = .camera
//show the camera to user ( with or without animation depending on the menu settings)
targetViewController!.present(imagePicker, animated: settings.presentWithAnimation, completion: nil)
}
} else {
//shows the alert message ( if the notAvailableMessage is given)
self.showAlertMessage(message: settings.notAvailableMessage)
}
}
}
/**
Opens photo library, if available
- Parameters:
- settings: the settings for this menu options
*/
public func openPhotoLibary(withSettings settings : MenuSettings) {
if (settings.type == .PhotoLibrary) {
//if the photo library is available
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
if (checkSettings() == true) {
//set the currently selected option as photo library
self.currentlySelectedOptionSettings = settings
//allows editing of selected depending on the settings
imagePicker.allowsEditing = settings.allowsEditing
//source type is photo library
imagePicker.sourceType = .photoLibrary
//show the camera to user ( with or without animation depending on the menu settings)
targetViewController!.present(imagePicker, animated: settings.presentWithAnimation, completion: nil)
}
} else {
//shows the alert message ( if the notAvailableMessage is given)
self.showAlertMessage(message: settings.notAvailableMessage)
}
}
}
/**
Opens photo album, if available
- Parameters:
- settings: the settings for this menu options
*/
public func openPhotoAlbum(withSettings settings : MenuSettings) {
//if the photo album is available
if (settings.type == .PhotoAlbum) {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
if (checkSettings() == true) {
//set the currently selected option as photo album
self.currentlySelectedOptionSettings = settings
//allows editing of selected depending on the settings
imagePicker.allowsEditing = settings.allowsEditing
//source type is photo album
imagePicker.sourceType = .savedPhotosAlbum
//show the camera to user ( with or without animation depending on the menu settings)
targetViewController!.present(imagePicker, animated: settings.presentWithAnimation, completion: nil)
}
} else {
//shows the alert message ( if the notAvailableMessage is given)
self.showAlertMessage(message: settings.notAvailableMessage)
}
}
}
/**
Shows the alert message if the selected image source is not available in the device
- Parameters:
- message: The message to be shown to user
- title: Title of the message
*/
public func showAlertMessage(message : String, title : String = "" ) {
// show the alert, if target view controller is there
if (targetViewController != nil && !message.isEmpty) {
//alert view controller is created with the given message and title
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
//dismiss action is added to the view
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
//message is shown to the user
self.targetViewController!.present(alert, animated: true, completion: nil)
}
}
///if target image view is not already supplied, a new one is created
public func getTargetImageView()->UIImageView? {
if (targetImageView == nil) {
targetImageView = UIImageView()
//targetImageView!.contentMode = .ScaleAspectFit
}
return targetImageView!
}
//MARK : get selected image
/**
To get the image currently in target image view (if there is any)
- Returns: the existing image in target image view
*/
public func getSelectedImage()-> UIImage? {
if (self.imageViewHasImage == true && self.targetImageView != nil) {
if let selectedImage = self.targetImageView?.image {
return selectedImage
}
}
return nil
}
/**
To get the image currently in target image view (if there is any) as NSData
- Parameters:
- type: .JPEG or .PNG
- compressionFactor: Value between 1 & 0, if set to 1 the image is uncompressed
in case of PNG representation of the data, compression factor is not used
- Returns: the existing image as NSData
*/
public func getSelectedImageAsData(type : ImageDataType, compressionFactor : CGFloat = 1.0)-> Data? {
if self.imageViewHasImage == true, let selectedImage = self.targetImageView?.image {
if (type == .JPEG) {
return selectedImage.jpegData(compressionQuality: compressionFactor)
} else if (type == .PNG) {
return selectedImage.pngData()
}
}
return nil
}
/**
To get the image currently in target image view (if there is any) as as base64 encoded string
- Parameters:
- type: .JPEG or .PNG
- compressionFactor: Value between 1 & 0, if set to 1 the image is uncompressed
in case of PNG representation of the data, compression factor is not used
- Returns: the existing image as as base64 encoded string
*/
public func getImageAsBase64EncodedString(type : ImageDataType, compressionFactor : CGFloat = 1.0) -> String? {
//existing image is converted to image data
if let imageData = self.getSelectedImageAsData(type: type, compressionFactor: compressionFactor) {
//image data converted to the base64 encoded string
return imageData.base64EncodedString(options: .lineLength64Characters)
}
return nil
}
//MARK : UIImagePickerController delegate methods
/**
* Accepts photos from picker view and add the selected image to target uiiimage
*
* calls the delegate method for indicating image picker is dismissed after image selection
*/
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
///get the target image view
if let imageView = self.getTargetImageView() {
/// if the target image view is available, the image is placed
imageView.image = pickedImage
///flag = true to indicate there is an image in target image view now
self.imageViewHasImage = true
// the delegate method for indicating image picker is dismissed after image selection
self.delegate?.imagePickerDismissed?(imagePicked: true, withImage: pickedImage)
}
}
///dismiss the image picker
self.dismissImagePicker(cancelled : false, imagePicked: true);
}
/**
* Dismiss picker view.
*
* calls the delegate method for indicating image picker cancelled by user is implemented
*/
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// the delegate method for indicating image picker is dismissed without image selection
self.delegate?.imagePickerDismissed?(imagePicked: false, withImage: nil)
///dismiss the image picker
self.dismissImagePicker(cancelled : true, imagePicked: false);
}
/**
Dismiss picker view (with or without animation depending on the menu option settings
- Parameters:
- cancelled: True if the image picker is dismissed after user has cancelled the image picker
- imagePicked: True if the image picker is dismissed after image is selected
- Returns: None.
*/
public func dismissImagePicker(cancelled: Bool, imagePicked : Bool) {
if (targetViewController != nil) {
var withAnimation : Bool = true
if (self.currentlySelectedOptionSettings != nil) {
withAnimation = self.currentlySelectedOptionSettings!.dismissWithAnimation
}
///no option is currently selected
self.currentlySelectedOptionSettings = nil
///dismiss image picker
targetViewController!.dismiss(animated: withAnimation, completion: nil)
}
}
}
|
mit
|
d41536e2130e0d1e89733186233342db
| 34.46206 | 276 | 0.561729 | 6.176776 | false | false | false | false |
volodg/iAsync.utils
|
Sources/String/String+PathExtensions.swift
|
1
|
3498
|
//
// String+PathExtensions.swift
// iAsync_utils
//
// Created by Vlafimir Gorbenko on 06.06.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
//todo remove
public protocol FilePath {
var filePath: URL { get }
var folder: URL { get }
}
extension FilePath {
public var folder: URL {
let result = filePath.deletingLastPathComponent()
return result
}
public var fileName: String {
let result = filePath.lastPathComponent
return result
}
public func stringContent() -> String? {
let data = dataContent()
let result = data?.toString()
return result
}
public func dictionaryContent() -> NSDictionary? {
let result = NSDictionary(contentsOf: filePath)
return result
}
public func dataContent() -> Data? {
let result = try? Data(contentsOf: filePath)
return result
}
public func removeItem(logError: Bool = true) -> Bool {
do {
try FileManager.default.removeItem(at: filePath)
return true
} catch let error as NSError {
if logError {
iAsync_utils_logger.logError("can not remove file error: \(error) filePath: \(filePath)", context: #function)
}
return false
} catch _ {
if logError {
iAsync_utils_logger.logError("can not remove file: \(filePath)", context: #function)
}
return false
}
}
public func addSkipBackupAttribute() {
var filePath_ = filePath
filePath_.addSkipBackupAttribute()
}
func writeToFile(str: String) -> Bool {
do {
try str.write(to: filePath, atomically: true, encoding: String.Encoding.utf8)
return true
} catch _ {
return false
}
}
public func writeToFile(dict: NSDictionary) -> Bool {
let result = dict.write(to: filePath, atomically: true)
return result
}
public func writeToFile(data: Data) -> Bool {
let result = (try? data.write(to: filePath, options: [.atomic])) != nil
return result
}
}
public extension URL {
func filePath() -> FilePath {
struct FilePath_: FilePath {
var filePath: URL
}
assert(self.isFileURL)
return FilePath_(filePath: self)
}
}
public struct DocumentPath: FilePath {
static var docDirectory = URL.pathWith(searchDirecory: .documentDirectory)
public let filePath: URL
fileprivate init(path: String) {
assert(!path.hasPrefix(DocumentPath.docDirectory.path))
let docPath = DocumentPath.docDirectory.appendingPathComponent(path)
self.filePath = docPath
}
}
public extension URL {
fileprivate static func pathWith(searchDirecory: FileManager.SearchPathDirectory) -> URL {
let pathes = FileManager.default.urls(for: searchDirecory, in: .userDomainMask)
return pathes.last!
}
static func cachesPathByAppending(pathComponent: String?) -> URL {
struct Static {
static var instance = URL.pathWith(searchDirecory: .cachesDirectory)
}
guard let str = pathComponent else { return Static.instance }
return Static.instance.appendingPathComponent(str)
}
}
public extension String {
public var documentsPath: DocumentPath {
return DocumentPath(path: self)
}
}
|
mit
|
8b85ed2cfa6fb7b29397c60f3357f2f8
| 22.006579 | 125 | 0.612239 | 4.681392 | false | false | false | false |
samodom/FoundationSwagger
|
FoundationSwagger/MethodSwizzling/MethodSurrogate.swift
|
1
|
1841
|
//
// MethodSurrogate.swift
// FoundationSwagger
//
// Created by Sam Odom on 10/24/16.
// Copyright © 2016 Swagger Soft. All rights reserved.
//
/// Enumerated type representing the two basic types of methods that a class can define.
public enum MethodType {
case `class`, instance
}
/// An association of two swappable (swizzlable) methods of a class
public class MethodSurrogate {
/// The class implementing the class or instance methods designated
/// by the original and alternate selectors.
public let owningClass: AnyClass
/// They type of methods designated by the original and alternate selectors.
public let methodType: MethodType
/// The original selector whose implementation is replaced by the implementation
/// of the method desginated by the alternate selector.
public let originalSelector: Selector
/// The alternate selector whose implementation is replaced by the implementation
/// of the method desginated by the original selector.
public let alternateSelector: Selector
/// Creates a method surrogate for the provided class and methods
/// - parameter forClass: The class implementing both the original and alternate methods.
/// - parameter ofType: The type of method: class or instance.
/// - parameter originalSelector: The selector designating the original method to replace.
/// - parameter alternateSelector: The selector designating the alternate method to use.
public init(
forClass `class`: AnyClass,
ofType type: MethodType,
originalSelector: Selector,
alternateSelector: Selector
) {
owningClass = `class`
methodType = type
self.originalSelector = originalSelector
self.alternateSelector = alternateSelector
}
var isSwizzled = false
}
|
mit
|
45604d721e9482586b4c9cddfca84007
| 30.724138 | 94 | 0.714674 | 5.242165 | false | false | false | false |
movabletype/smartphone-app
|
MT_iOS/MT_iOS/Classes/ViewController/PrimaryCategorySelectorTableViewController.swift
|
1
|
5536
|
//
// PrimaryCategorySelectorTableViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/17.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
protocol PrimaryCategorySelectorDelegate {
func primaryCategorySelectorDone(controller: PrimaryCategorySelectorTableViewController, selected: String)
}
class PrimaryCategorySelectorTableViewController: BaseTableViewController {
var items = [Category]()
var selected = ""
var delegate: PrimaryCategorySelectorDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.title = NSLocalizedString("Select a primary category", comment: "Select a primary category")
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
if selected.isEmpty {
selected = items[0].id
}
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_close"), left: true, target: self, action: "closeButtonPushed:")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.adjustCellLayoutMargins(cell)
// Configure the cell...
let item = items[indexPath.row]
var path = item.path
path = path.stringByReplacingOccurrencesOfString("/", withString: " > ", options: [], range: nil)
cell.textLabel?.text = path
cell.selectionStyle = UITableViewCellSelectionStyle.None
if item.id == selected {
cell.accessoryView = UIImageView(image: UIImage(named: "btn_primary"))
} else {
cell.accessoryView = nil
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 62.0
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = items[indexPath.row]
selected = item.id
self.tableView.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@IBAction func closeButtonPushed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveButtonPushed(sender: AnyObject) {
self.delegate?.primaryCategorySelectorDone(self, selected: selected)
}
@IBAction func backButtonPushed(sender: UIBarButtonItem) {
self.navigationController?.popViewControllerAnimated(true)
}
}
|
mit
|
2682accc76d697912fe2f0e4340982f5
| 35.893333 | 157 | 0.681605 | 5.556225 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Base/Vender/XLPagerTabStrip/ButtonBarViewCell.swift
|
3
|
1907
|
// ButtonBarViewCell.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class ButtonBarViewCell: UICollectionViewCell {
@IBOutlet open var imageView: UIImageView!
@IBOutlet open lazy var label: UILabel! = { [unowned self] in
let label = UILabel(frame: self.contentView.bounds)
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 14.0)
return label
}()
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if label.superview != nil {
contentView.addSubview(label)
}
}
}
|
mit
|
b66b0a6d5aa334c6b29491547b18d2dc
| 41.377778 | 80 | 0.722077 | 4.743781 | false | false | false | false |
brave/browser-ios
|
brave/src/data/MigrateData.swift
|
1
|
12973
|
/* 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 Storage
import CoreData
class MigrateData: NSObject {
fileprivate var files: FileAccessor!
fileprivate var db: OpaquePointer? = nil
enum ProcessOrder: Int {
case bookmarks = 0
case history = 1
case domains = 2
case favicons = 3
case tabs = 4
case delete = 5
}
var completedCalls: [ProcessOrder: Bool] = [.bookmarks: false, .history: false, .domains: false, .favicons: false, .tabs: false] {
didSet {
checkCompleted()
}
}
var completedCallback: ((_ success: Bool) -> Void)?
required convenience init(completed: ((_ success: Bool) -> Void)?) {
self.init()
self.files = ProfileFileAccessor(localName: "profile")
completedCallback = completed
process()
}
override init() {
super.init()
}
fileprivate func process() {
if hasOldDb() {
debugPrint("Found old database...")
migrateDomainData { (success) in
debugPrint("Migrate domains... \(success ? "Done" : "Failed")")
self.completedCalls[ProcessOrder.domains] = success
}
migrateFavicons { (success) in
debugPrint("Migrate favicons... \(success ? "Done" : "Failed")")
self.completedCalls[ProcessOrder.favicons] = success
}
migrateHistory { (success) in
debugPrint("Migrate history... \(success ? "Done" : "Failed")")
self.completedCalls[ProcessOrder.history] = success
}
migrateBookmarks { (success) in
debugPrint("Migrate bookmarks... \(success ? "Done" : "Failed")")
self.completedCalls[ProcessOrder.bookmarks] = success
}
migrateTabs { (success) in
debugPrint("Migrate tabs... \(success ? "Done" : "Failed")")
self.completedCalls[ProcessOrder.tabs] = success
}
}
}
fileprivate func hasOldDb() -> Bool {
let file = ((try! files.getAndEnsureDirectory()) as NSString).appendingPathComponent("browser.db")
let status = sqlite3_open_v2(file.cString(using: String.Encoding.utf8)!, &db, SQLITE_OPEN_READONLY, nil)
if status != SQLITE_OK || status == 0 {
debugPrint("Error: Opening Database with Flags")
return false
}
return true
}
internal var domainHash: [Int32: Domain] = [:]
fileprivate func migrateDomainData(_ completed: (_ success: Bool) -> Void) {
let query: String = "SELECT id, domain, showOnTopSites FROM domains"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
while sqlite3_step(results) == SQLITE_ROW {
let id = sqlite3_column_int(results, 0)
let domain = String(cString: sqlite3_column_text(results, 1))
let showOnTopSites = sqlite3_column_int(results, 2)
if let d = Domain.getOrCreateForUrl(URL(string: domain)!, context: DataController.newBackgroundContext()) {
d.topsite = (showOnTopSites == 1)
domainHash[id] = d
}
}
DataController.save(context: DataController.newBackgroundContext())
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
completed(true)
}
fileprivate func migrateHistory(_ completed: (_ success: Bool) -> Void) {
let query: String = "SELECT url, title FROM history WHERE is_deleted = 0"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
while sqlite3_step(results) == SQLITE_ROW {
let url = String(cString: sqlite3_column_text(results, 0))
let title = String(cString: sqlite3_column_text(results, 1))
History.add(title, url: URL(string: url)!)
}
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
completed(true)
}
internal var domainFaviconHash: [Int32: Domain] = [:]
fileprivate func buildDomainFaviconHash() {
let query: String = "SELECT siteID, faviconID FROM favicon_sites"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
while sqlite3_step(results) == SQLITE_ROW {
let domainId = sqlite3_column_int(results, 0)
let faviconId = sqlite3_column_int(results, 1)
if let domain = domainHash[domainId] {
domainFaviconHash[faviconId] = domain
}
}
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(describing: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
}
fileprivate func migrateFavicons(_ completed: (_ success: Bool) -> Void) {
buildDomainFaviconHash()
let query: String = "SELECT id, url, width, height, type FROM favicons"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
while sqlite3_step(results) == SQLITE_ROW {
let id = sqlite3_column_int(results, 0)
let url = String(cString: sqlite3_column_text(results, 1))
let width = sqlite3_column_int(results, 2)
let height = sqlite3_column_int(results, 3)
let type = sqlite3_column_int(results, 4)
let favicon = Favicon(url: url, type: IconType(rawValue: Int(type))!)
favicon.width = Int(width)
favicon.height = Int(height)
if let domain = domainFaviconHash[id] {
if let url = domain.url {
FaviconMO.add(favicon, forSiteUrl: URL(string: url)!)
}
}
}
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(describing: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
completed(true)
}
internal var bookmarkOrderHash: [String: Int16] = [:]
fileprivate func buildBookmarkOrderHash() {
let query: String = "SELECT child, idx FROM bookmarksLocalStructure"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
while sqlite3_step(results) == SQLITE_ROW {
let child = String(cString: sqlite3_column_text(results, 0))
let idx = sqlite3_column_int(results, 1)
bookmarkOrderHash[child] = Int16(idx)
}
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(describing: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
}
fileprivate func migrateBookmarks(_ completed: (_ success: Bool) -> Void) {
buildBookmarkOrderHash()
let query: String = "SELECT guid, type, parentid, title, description, bmkUri, faviconID FROM bookmarksLocal WHERE (id > 4 AND is_deleted = 0) ORDER BY type DESC"
var results: OpaquePointer? = nil
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
var relationshipHash: [String: Bookmark] = [:]
while sqlite3_step(results) == SQLITE_ROW {
let guid = String(cString: sqlite3_column_text(results, 0))
let type = sqlite3_column_int(results, 1)
let parentid = String(cString: sqlite3_column_text(results, 2))
let title = String(cString: sqlite3_column_text(results, 3))
let description = String(cString: sqlite3_column_text(results, 4))
let url = String(cString: sqlite3_column_text(results, 5))
if let bk = Bookmark.addForMigration(url: url, title: title, customTitle: description, parentFolder: relationshipHash[parentid] ?? nil, isFolder: (type == 2)) {
let parent = relationshipHash[parentid]
bk.parentFolder = parent
bk.syncParentUUID = parent?.syncUUID
if let baseUrl = URL(string: url)?.baseURL {
bk.domain = Domain.getOrCreateForUrl(baseUrl, context: DataController.newBackgroundContext())
}
if let order = bookmarkOrderHash[guid] {
bk.order = order
debugPrint("__ order set \(order) for \((type == 2) ? "folder" : "bookmark")")
}
relationshipHash[guid] = bk
}
}
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(describing: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
completed(true)
}
fileprivate func migrateTabs(_ completed: (_ success: Bool) -> Void) {
let query: String = "SELECT url, title, history FROM tabs ORDER BY last_used"
var results: OpaquePointer? = nil
let context = DataController.viewContext
if sqlite3_prepare_v2(db, query, -1, &results, nil) == SQLITE_OK {
var order: Int16 = 0
while sqlite3_step(results) == SQLITE_ROW {
let url = String(cString: sqlite3_column_text(results, 0))
let title = String(cString: sqlite3_column_text(results, 1))
let history = String(cString: sqlite3_column_text(results, 2))
let historyData = history.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "\\", with: "")
let historyList: [String] = historyData.characters.split{$0 == ","}.map(String.init)
guard let tabId = TabMO.create().syncUUID else { continue }
let tab = SavedTab(id: tabId, title: title, url: url, isSelected: false, order: order, screenshot: nil, history: historyList, historyIndex: Int16(historyList.count-1))
debugPrint("History restored [\(historyList)]")
TabMO.update(tabData: tab)
order = order + 1
}
DataController.save(context: context)
}
if sqlite3_finalize(results) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(db))
debugPrint("Error finalizing prepared statement: \(error)")
}
results = nil
completed(true)
}
fileprivate func removeOldDb(_ completed: (_ success: Bool) -> Void) {
do {
let documentDirectory = URL(fileURLWithPath: self.files.rootPath as String)
let originPath = documentDirectory.appendingPathComponent("browser.db")
let destinationPath = documentDirectory.appendingPathComponent("old-browser.db")
try FileManager.default.moveItem(at: originPath, to: destinationPath)
completed(true)
} catch let error as NSError {
debugPrint("Cannot clear profile data: \(error)")
completed(false)
}
}
fileprivate func checkCompleted() {
var completedAllCalls = true
for (_, value) in completedCalls {
if value == false {
completedAllCalls = false
break
}
}
// All migrations completed, delete the db.
if completedAllCalls {
removeOldDb { (success) in
debugPrint("Delete old database... \(success ? "Done" : "Failed")")
if let callback = self.completedCallback {
callback(success)
}
}
}
}
}
|
mpl-2.0
|
f4ce3342d2ca1fcc62d1e3f071ea715d
| 41.12013 | 203 | 0.552147 | 4.714026 | false | false | false | false |
EXXETA/JSONPatchSwift
|
JsonPatchSwiftTests/JPSTestOperationTests.swift
|
1
|
4739
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the JSONPatchSwift open source project.
//
// Copyright (c) 2015 EXXETA AG
// Licensed under Apache License v2.0
//
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
@testable import JsonPatchSwift
import SwiftyJSON
// http://tools.ietf.org/html/rfc6902#section-4.6
// 4. Operations
// 4.6. test
class JPSTestOperationTests: XCTestCase {
func testIfBasicStringCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : \"2\" }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo/1\", \"value\": \"2\" }")
let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTAssertEqual(resultingJson, json)
}
func testIfInvalidBasicStringCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : \"2\" }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo/1\", \"value\": \"3\" }")
do {
let result = try JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTFail(result.rawString()!)
} catch JPSJsonPatcher.JPSJsonPatcherApplyError.ValidationError(let message) {
// Expected behaviour.
XCTAssertNotNil(message)
} catch {
XCTFail("Unexpected error.")
}
}
func testIfBasicIntCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : 2 }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo/1\", \"value\": 2 }")
let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTAssertEqual(resultingJson, json)
}
func testIfInvalidBasicIntCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : 2 }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo/1\", \"value\": 3 }")
do {
let result = try JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTFail(result.rawString()!)
} catch JPSJsonPatcher.JPSJsonPatcherApplyError.ValidationError(let message) {
// Expected behaviour.
XCTAssertNotNil(message)
} catch {
XCTFail("Unexpected error.")
}
}
func testIfBasicObjectCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : 2 }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo\", \"value\": { \"1\" : 2 } }")
let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTAssertEqual(resultingJson, json)
}
func testIfInvalidBasicObjectCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : { \"1\" : \"2\" }} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo\", \"value\": { \"1\" : 3 } }")
do {
let result = try JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTFail(result.rawString()!)
} catch JPSJsonPatcher.JPSJsonPatcherApplyError.ValidationError(let message) {
// Expected behaviour.
XCTAssertNotNil(message)
} catch {
XCTFail("Unexpected error.")
}
}
func testIfBasicArrayCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : [1, 2, 3, 4, 5]} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo\", \"value\": [1, 2, 3, 4, 5] }")
let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTAssertEqual(resultingJson, json)
}
func testIfInvalidBasicArrayCheckReturnsExpectedResult() {
let json = JSON(data: " { \"foo\" : [1, 2, 3, 4, 5]} ".dataUsingEncoding(NSUTF8StringEncoding)!)
let jsonPatch = try! JPSJsonPatch("{ \"op\": \"test\", \"path\": \"/foo\", \"value\": [1, 2, 3, 4, 5, 6, 7, 42] }")
do {
let result = try JPSJsonPatcher.applyPatch(jsonPatch, toJson: json)
XCTFail(result.rawString()!)
} catch JPSJsonPatcher.JPSJsonPatcherApplyError.ValidationError(let message) {
// Expected behaviour.
XCTAssertNotNil(message)
} catch {
XCTFail("Unexpected error.")
}
}
}
|
apache-2.0
|
241f8806279df8dedfda4e154dd15d0d
| 44.133333 | 123 | 0.577337 | 4.335773 | false | true | false | false |
Jnosh/SwiftBinaryHeapExperiments
|
BinaryHeap/ManagedBufferHeap.swift
|
1
|
3976
|
//
// ManagedBufferHeap.swift
// BinaryHeap
//
// Created by Janosch Hildebrand on 02/04/15.
// Copyright © 2015 Janosch Hildebrand. All rights reserved.
//
/// Binary heap backed by a ManagedBuffer
public struct ManagedBufferHeap<Element : Comparable> {
private var buffer: ManagedArrayBuffer<Element>
private mutating func reserveCapacity(minimumCapacity: Int) {
buffer.reserveCapacity(minimumCapacity)
}
}
// MARK: BinaryHeapType conformance
extension ManagedBufferHeap : BinaryHeapType, BinaryHeapType_Fast {
public init() {
buffer = ManagedArrayBuffer()
}
public var count: Int {
return buffer.count
}
public var first: Element? {
return count > 0 ? buffer.withUnsafeMutablePointer { $0.memory } : nil
}
public mutating func insert(element: Element) {
// Optimization to prevent uneccessary copy
// If we need to resize our element buffer we are guaranteed to have a unique copy afterwards
let count = self.count
if count == buffer.capacity {
buffer.grow(count + 1)
} else {
buffer.ensureHoldsUniqueReference()
}
buffer.count = count + 1
buffer.withUnsafeMutablePointer { elements in
elements.advancedBy(count).initialize(element)
var index = count
while index > 0 && (element < elements[parentIndex(index)]) {
swap(&elements[index], &elements[parentIndex(index)])
index = parentIndex(index)
}
}
}
public mutating func fastInsert(element: Element) {
// Optimization to prevent uneccessary copy
// If we need to resize our element buffer we are guaranteed to have a unique copy afterwards
let count = self.count
if count == buffer.capacity {
buffer.grow(count + 1)
} else {
buffer.ensureHoldsUniqueReference()
}
// FIXME: Workaround for http://www.openradar.me/23412050
// Essentially buffer is retained for the closure call which costs us quite a bit of perf.
buffer.count = count + 1
var elements: UnsafeMutablePointer<Element> = nil
buffer.withUnsafeMutablePointer {
$0.advancedBy(count).initialize(element)
elements = $0
}
var index = count
while index > 0 && (element < elements[parentIndex(index)]) {
swap(&elements[index], &elements[parentIndex(index)])
index = parentIndex(index)
}
}
public mutating func removeFirst() -> Element {
precondition(!isEmpty, "Heap may not be empty.")
buffer.ensureHoldsUniqueReference()
let count = self.count
buffer.count = count - 1
return buffer.withUnsafeMutablePointer { elements in
if count > 1 {
swap(&elements[0], &elements[count - 1])
heapify(elements, startIndex: 0, endIndex: count - 1)
}
return elements.advancedBy(count - 1).move()
}
}
public mutating func fastRemoveFirst() -> Element {
precondition(!isEmpty, "Heap may not be empty.")
buffer.ensureHoldsUniqueReference()
// See fastInsert.
let count = self.count
buffer.count = count - 1
var elements: UnsafeMutablePointer<Element> = nil
buffer.withUnsafeMutablePointer { elements = $0 }
if count > 1 {
swap(&elements[0], &elements[count - 1])
heapify(elements, startIndex: 0, endIndex: count - 1)
}
return elements.advancedBy(count - 1).move()
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
buffer.removeAll(keepCapacity: keepCapacity)
}
}
extension ManagedBufferHeap : CustomDebugStringConvertible, CustomStringConvertible { }
|
mit
|
a8ecfcc55db8785e9e81a75044ce96f8
| 31.85124 | 101 | 0.60805 | 4.901356 | false | false | false | false |
icylydia/PlayWithLeetCode
|
213. House Robber II/solution.swift
|
1
|
851
|
class Solution {
func rob(nums: [Int]) -> Int {
if nums.count < 1 {
return 0
}
var RaR = [nums[0], nums[0]]
var RaN = [nums[0], nums[0]]
if nums.count >= 3 {
for i in 2..<nums.count {
let rob = RaN.last! + nums[i]
let non = max(RaR.last!, RaN.last!)
RaR.append(rob)
RaN.append(non)
}
}
let maxRa = RaN.last!
var NaR = [0]
var NaN = [0]
if nums.count >= 2 {
for i in 1..<nums.count {
let rob = NaN.last! + nums[i]
let non = max(NaR.last!, NaN.last!)
NaR.append(rob)
NaN.append(non)
}
}
let maxNa = max(NaR.last!, NaN.last!)
return max(maxRa, maxNa)
}
}
|
mit
|
9f8134a58282d3800168edb5719e90f7
| 27.4 | 51 | 0.39953 | 3.417671 | false | false | false | false |
rgkobashi/RMTostada
|
RMTostada/RMTostada.swift
|
1
|
19373
|
//
// RMTostada.swift
// RMTostada
//
// Created by Rogelio Martinez Kobashi on 11/13/16.
// Copyright © 2016 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
import UIKit
/**
Completion handler used on all the `showSelfDismissingWithText` methods.
*/
public typealias CompletionHandler = () -> ()
private class RMClosureWrapper<T>
{
fileprivate let value: T
fileprivate init(value: T)
{
self.value = value
}
}
/**
Define the look and feel for the tostada view.
*/
public struct RMTostadaStyle
{
/**
Creates an instance of `RMTostadaStyle` with the default values.
- returns: An instance of RMTostadaStyle.
*/
public init()
{
}
/**
The background color. Default is `UIColor.blackColor()` at 80% opacity.
*/
public var backgroundColor = UIColor.black.withAlphaComponent(0.8)
/**
The text color. Default is `UIColor.whiteColor()`.
*/
public var textColor = UIColor.white
/**
A percentage value from 0.0 to 1.0, representing the maximum width of the tostada
view relative to it's superview. Default is 0.8 (80% of the superview's width).
*/
public var maxWidthPercentage: CGFloat = 0.8 {
didSet {
maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
}
}
/**
The spacing from the vertical edge of the tostada superview to the tostada view.
Default is 10.0.
*/
public var tostadaVerticalPadding: CGFloat = 10.0
/**
The spacing from the horizontal edge of the tostada view to the content.
If the tostada has `UIActivityIndicatorView` this value will be used as padding
between the text and the `UIActivityIndicatorView`.
Default is 10.0.
*/
public var contentHorizontalPadding: CGFloat = 10.0
/**
The spacing from the vertical edge of the tostada view to the content.
Default is 10.0.
*/
public var contentVerticalPadding: CGFloat = 10.0
/**
The corner radius. Default is 10.0.
*/
public var cornerRadius: CGFloat = 10.0;
/**
The text font. Default is `UIFont.systemFontOfSize(16.0)`.
*/
public var font = UIFont.systemFont(ofSize: 16.0)
/**
Enable or disable a shadow on the tostada view. Default is `false`.
*/
public var displayShadow = false;
/**
The shadow color. Default is `UIColor.blackColor()`.
*/
public var shadowColor = UIColor.black
/**
A value from 0.0 to 1.0, representing the opacity of the shadow.
Default is 0.8 (80% opacity).
*/
public var shadowOpacity: Float = 0.8 {
didSet {
shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
}
}
/**
The shadow radius. Default is 6.0.
*/
public var shadowRadius: CGFloat = 6.0
/**
The shadow offset. The default is 4 x 4.
*/
public var shadowOffset = CGSize(width: 4.0, height: 4.0)
/**
The fade in/out animation duration. Default is 0.2.
*/
public var fadeDuration: TimeInterval = 0.2
/**
The shift animation duration. This animation will be executed when
a tostada view has been dismissed and there are more on the queue (on the screen),
the subsequent tostadas will be shifted. Default is 0.2.
*/
public var shiftDuration: TimeInterval = 0.2
/**
The style of the `UIActivityIndicatorView` that will be used on
`showActivityWithText` method. Default is `UIActivityIndicatorViewStyle.White`.
*/
public var activityIndicatorViewStyle: UIActivityIndicatorViewStyle = .white
}
/**
The `RMTostada` class provides static methods to display tostadas views with different
styles. `RMTostada` is capable to display more than one tostada view at the same time,
every tostada view will be appended to a queue. When a tostada view will be dismissed,
all the subsequent tostadas views on the queue (on the screen), will be shifted.
Basically there are three different tostadas views:
- Self dismissed: These tostadas views will be dismissed automatically after a time interval.
- Manually dismissed: These tostadas needs to be dismissed manually calling `dismissWithId`
and sending the id of the tostada to dismiss.
- Manually dismissed with activity indicator: Same as `Manually dismissed` just
that these will include an `UIActivityIndicatorView` at the end of the text.
All the tostadas will be displayed on the rootViewController view, if there is one
(`UIApplication.sharedApplication().windows.first?.rootViewController`) so it can be used on
an UITabBarController based application and all the tostadas views will be visible from every tab.
The styles were based on Toast-Swift pod by Charles Scalesse (https://github.com/scalessec/Toast-Swift).
*/
open class RMTostada
{
/**
The default duration that the tostada view will remain on the screen. This applies only
on the self dismissed tostada. Default is 3.0.
*/
open static var duration: TimeInterval = 3.0
/**
The default style that all the tostadas views will have if no style is specified.
*/
open static var style = RMTostadaStyle()
fileprivate static let sharedInstance = RMTostada()
fileprivate var queue = [RMTostadaView]()
fileprivate let screenSize = UIScreen.main.bounds
fileprivate init()
{
}
// MARK: - Exposed methods
/**
Shows a tostada view with the given text and the default style that will be dismissed automatically after the default duration.
If the param `completion` is specified, it will be executed after the tostada view is dismissed.
- parameter text: The text that the tostada view will have
- parameter completion: Code that will be executed after the tostada view is dismissed
*/
open class func showSelfDismissingWithText(_ text: String, completion: CompletionHandler? = nil)
{
showSelfDismissingWithText(text, duration: duration, style: style, completion: completion)
}
/**
Shows a tostada view with the given text and the default style that will be dismissed automatically after the given duration.
If the param `completion` is specified, it will be executed after the tostada view is dismissed.
- parameter text: The text that the tostada view will have
- parameter duration: The duration that the tostada view will remain on the screen.
- parameter completion: Code that will be executed after the tostada view is dismissed
*/
open class func showSelfDismissingWithText(_ text: String, duration: TimeInterval, completion: CompletionHandler? = nil)
{
showSelfDismissingWithText(text, duration: duration, style: style, completion: completion)
}
/**
Shows a tostada view with the given text and the given style that will be dismissed automatically after the default duration.
If the param `completion` is specified, it will be executed after the tostada view is dismissed.
- parameter text: The text that the tostada view will have
- parameter style: The style that the tostada view will have
- parameter completion: Code that will be executed after the tostada view is dismissed
*/
open class func showSelfDismissingWithText(_ text: String, style: RMTostadaStyle, completion: CompletionHandler? = nil)
{
showSelfDismissingWithText(text, duration: duration, style: style, completion: completion)
}
/**
Shows a tostada view with the given text and the given style that will be dismissed automatically after the given duration.
If the param `completion` is specified, it will be executed after the tostada view is dismissed.
- parameter text: The text that the tostada view will have
- parameter duration: The duration that the tostada view will remain on the screen.
- parameter style: The style that the tostada view will have
- parameter completion: Code that will be executed after the tostada view is dismissed
*/
open class func showSelfDismissingWithText(_ text: String, duration: TimeInterval, style: RMTostadaStyle, completion: CompletionHandler? = nil)
{
let tostada = sharedInstance.createTostadaWithText(text, style: style, activityIndicator: false)
objc_sync_enter(sharedInstance)
sharedInstance.displayTostada(tostada, selfDismissing: true, duration: duration, completion: completion)
objc_sync_exit(sharedInstance)
}
/**
Shows a tostada view with the given text and the given style (if it is specified, otherwise the default style will be used) and returns its id.
To dismiss the tostada view showed a call to `dismissWithId` will be needed.
- parameter text: The text that the tostada view will have
- parameter style: The style that the tostada view will have
- returns: The id of the tostada view showed.
*/
open class func showWithText(_ text: String, style: RMTostadaStyle = style) -> String
{
let tostada = sharedInstance.createTostadaWithText(text, style: style, activityIndicator: false)
objc_sync_enter(sharedInstance)
sharedInstance.displayTostada(tostada, selfDismissing: false, duration: nil, completion: nil)
objc_sync_exit(sharedInstance)
return tostada.identifier()
}
/**
Shows a tostada view with the given text and the given style (if it is specified, otherwise the default style will be used) with an
`UIActivityIndicatorView` at the end of the text and returns its id. To dismiss the tostada view showed a call to `dismissWithId` will be needed.
- parameter text: The text that the tostada view will have
- parameter style: The style that the tostada view will have
- returns: The id of the tostada view showed.
*/
open class func showActivityWithText(_ text: String, style: RMTostadaStyle = style) -> String
{
let tostada = sharedInstance.createTostadaWithText(text, style: style, activityIndicator: true)
objc_sync_enter(sharedInstance)
sharedInstance.displayTostada(tostada, selfDismissing: false, duration: nil, completion: nil)
objc_sync_exit(sharedInstance)
return tostada.identifier()
}
/**
Dismiss the tostada view with the id given.
- parameter id: The id of the tostada view that will be dismissed
*/
open class func dismissWithId(_ id: String)
{
let filtered = sharedInstance.queue.filter { $0.identifier() == id }
if let first = filtered.first
{
objc_sync_enter(sharedInstance)
sharedInstance.hideTostada(first, completion: nil)
objc_sync_exit(sharedInstance)
}
}
// MARK: - Helper methods
fileprivate func topView() -> UIView?
{
if let view = UIApplication.shared.windows.first?.rootViewController?.view
{
return view
}
return nil
}
// MARK: - Create tostada
fileprivate func createTostadaWithText(_ text: String, style: RMTostadaStyle, activityIndicator: Bool) -> RMTostadaView
{
// Setup wrapper view
let wrapperView = RMTostadaView(frame: CGRect.zero, fadeDuration: style.fadeDuration, shiftDuration: style.shiftDuration, verticalPadding: style.tostadaVerticalPadding)
wrapperView.backgroundColor = style.backgroundColor
wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
wrapperView.layer.cornerRadius = style.cornerRadius
if style.displayShadow
{
wrapperView.layer.shadowColor = style.shadowColor.cgColor
wrapperView.layer.shadowOpacity = style.shadowOpacity
wrapperView.layer.shadowRadius = style.shadowRadius
wrapperView.layer.shadowOffset = style.shadowOffset
}
// Setup label
let textLabel = UILabel()
textLabel.text = text
textLabel.numberOfLines = 1
textLabel.font = style.font
textLabel.lineBreakMode = .byTruncatingTail;
textLabel.textColor = style.textColor
textLabel.backgroundColor = UIColor.clear
textLabel.sizeToFit()
textLabel.frame = CGRect(x: style.contentHorizontalPadding, y: style.contentVerticalPadding, width: textLabel.frame.width, height: textLabel.frame.height)
// Setup wrapper view size
let wrapperHeight = (textLabel.frame.height + (style.contentVerticalPadding * 2))
var wrapperWidth = (textLabel.frame.width + (style.contentHorizontalPadding * 2))
// Setup activity indicator
var activityView: UIActivityIndicatorView?
var activityXPos: CGFloat?
var activityYPos: CGFloat?
if activityIndicator
{
activityView = UIActivityIndicatorView(activityIndicatorStyle: style.activityIndicatorViewStyle)
activityXPos = style.contentHorizontalPadding + textLabel.frame.width + style.contentHorizontalPadding
activityYPos = (wrapperHeight - activityView!.frame.size.height) / 2
activityView!.frame = CGRect(x: activityXPos!, y: activityYPos!, width: activityView!.frame.size.width, height: activityView!.frame.size.height)
wrapperView.addSubview(activityView!)
activityView!.startAnimating()
wrapperWidth += activityView!.frame.size.width + style.contentHorizontalPadding
}
// Handler if the wrapper view exceeds the maxWidthPercentage
let wrapperMaxWidth = screenSize.size.width * style.maxWidthPercentage
if wrapperWidth > wrapperMaxWidth
{
if activityIndicator
{
let labelMaxWidth = wrapperMaxWidth - (style.contentHorizontalPadding * 3) - activityView!.frame.size.width
textLabel.frame = CGRect(x: textLabel.frame.origin.x, y: textLabel.frame.origin.y, width: labelMaxWidth, height: textLabel.frame.size.height)
activityXPos = style.contentHorizontalPadding + textLabel.frame.width + style.contentHorizontalPadding
activityYPos = (wrapperHeight - activityView!.frame.size.height) / 2
activityView!.frame = CGRect(x: activityXPos!, y: activityYPos!, width: activityView!.frame.size.width, height: activityView!.frame.size.height)
}
else
{
let labelMaxWidth = wrapperMaxWidth - (style.contentHorizontalPadding * 2)
textLabel.frame = CGRect(x: textLabel.frame.origin.x, y: textLabel.frame.origin.y, width: labelMaxWidth, height: textLabel.frame.size.height)
}
wrapperWidth = wrapperMaxWidth
}
// Place wrapper view
let wrapperXPos = (screenSize.size.width - wrapperWidth) / 2
var wrapperYPos: CGFloat = 0.0
for view in queue
{
wrapperYPos += view.verticalPadding + view.frame.size.height
}
wrapperYPos += style.tostadaVerticalPadding
wrapperView.frame = CGRect(x: wrapperXPos, y: wrapperYPos, width: wrapperWidth, height: wrapperHeight)
wrapperView.addSubview(textLabel)
return wrapperView
}
// MARK: - Tostadas queue
fileprivate func appendTostada(_ tostada: RMTostadaView)
{
queue.append(tostada)
}
fileprivate func removeTostada(_ tostada: RMTostadaView) -> Int?
{
objc_sync_enter(self)
if let index = queue.index(of: tostada)
{
queue.remove(at: index)
objc_sync_exit(queue)
return index
}
objc_sync_exit(self)
return nil
}
// MARK: - Display/hide tostada
fileprivate func displayTostada(_ tostada: RMTostadaView, selfDismissing: Bool, duration: TimeInterval?, completion: CompletionHandler?)
{
if let topView = self.topView()
{
var dict = [String: AnyObject]()
dict["RMTostadaView"] = tostada
if let completion = completion
{
dict["completion"] = RMClosureWrapper(value: completion)
}
tostada.alpha = 0.0
topView.addSubview(tostada)
appendTostada(tostada)
DispatchQueue.main.async(execute: { () -> Void in
UIView.animate(withDuration: tostada.fadeDuration, delay: 0.0, options: [.curveEaseOut], animations: { () -> Void in
tostada.alpha = 1.0
}) { (finished) -> Void in
if let duration = duration, selfDismissing
{
Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(RMTostada.tostadaTimerDidFinish(_:)), userInfo: dict, repeats: false)
}
}
})
}
}
@objc fileprivate func tostadaTimerDidFinish(_ timer: Timer)
{
if let dict = timer.userInfo as? [String: AnyObject]
{
let tostada = dict["RMTostadaView"] as! RMTostadaView
if let closureWrapper = dict["completion"] as? RMClosureWrapper<CompletionHandler>
{
objc_sync_enter(self)
hideTostada(tostada, completion: closureWrapper.value)
objc_sync_exit(self)
}
else
{
objc_sync_enter(self)
hideTostada(tostada, completion: nil)
objc_sync_exit(self)
}
}
}
fileprivate func hideTostada(_ tostada: RMTostadaView, completion: CompletionHandler?)
{
DispatchQueue.main.async(execute: { () -> Void in
UIView.animate(withDuration: tostada.fadeDuration, delay: 0.0, options: [.curveEaseIn], animations: { () -> Void in
tostada.alpha = 0.0
}) { [unowned self] (didFinish: Bool) -> Void in
tostada.removeFromSuperview()
completion?()
if let index = self.removeTostada(tostada)
{
objc_sync_enter(self)
self.shiftTostadasFromIndex(index)
objc_sync_exit(self)
}
}
})
}
// MARK: - Move tostadas which are on the queue
fileprivate func shiftTostadasFromIndex(_ index: Int)
{
for index in index ..< queue.count
{
let tostada = queue[index]
shiftTostada(tostada)
}
}
fileprivate func shiftTostada(_ tostada: RMTostadaView)
{
DispatchQueue.main.async(execute: { () -> Void in
UIView.animate(withDuration: tostada.shiftDuration, animations: {
let yPos = tostada.frame.origin.y - tostada.verticalPadding - tostada.frame.size.height
let frame = CGRect(x: tostada.frame.origin.x, y: yPos, width: tostada.frame.size.width, height: tostada.frame.size.height)
tostada.frame = frame
})
})
}
}
|
mit
|
144fd635ca9d6a8b6151d8e201525cc2
| 38.294118 | 176 | 0.649855 | 4.571024 | false | false | false | false |
SuPair/firefox-ios
|
Client/Frontend/Widgets/GradientProgressBar.swift
|
4
|
6485
|
/* 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/. */
// ADAPTED FROM:
//
// GradientProgressBar.swift
// GradientProgressBar
//
// Created by Felix Mau on 01.03.17.
// Copyright © 2017 Felix Mau. All rights reserved.
//
import UIKit
open class GradientProgressBar: UIProgressView {
private struct DefaultValues {
static let backgroundColor = UIColor.clear
static let animationDuration = 0.2 // CALayer default animation duration
}
var gradientColors: [CGColor] = []
// Alpha mask for visible part of gradient.
private var alphaMaskLayer: CALayer = CALayer()
// Gradient layer.
open var gradientLayer: CAGradientLayer = CAGradientLayer()
// Duration for "setProgress(animated: true)"
open var animationDuration = DefaultValues.animationDuration
// Workaround to handle orientation change, as "layoutSubviews()" gets triggered each time
// the progress value is changed.
override open var bounds: CGRect {
didSet {
updateAlphaMaskLayerWidth()
}
}
// Update layer mask on direct changes to progress value.
override open var progress: Float {
didSet {
updateAlphaMaskLayerWidth()
}
}
func setGradientColors(startColor: UIColor, endColor: UIColor) {
gradientColors = [startColor, endColor, startColor, endColor, startColor, endColor, startColor].map { $0.cgColor }
gradientLayer.colors = gradientColors
}
func commonInit() {
setupProgressViewColors()
setupAlphaMaskLayer()
setupGradientLayer()
layer.insertSublayer(gradientLayer, at: 0)
updateAlphaMaskLayerWidth()
}
override public init(frame: CGRect) {
gradientColors = []
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Setup UIProgressView
private func setupProgressViewColors() {
backgroundColor = DefaultValues.backgroundColor
trackTintColor = .clear
progressTintColor = .clear
}
// MARK: - Setup layers
private func setupAlphaMaskLayer() {
alphaMaskLayer.frame = bounds
alphaMaskLayer.cornerRadius = 3
alphaMaskLayer.anchorPoint = .zero
alphaMaskLayer.position = .zero
alphaMaskLayer.backgroundColor = UIColor.Photon.White100.cgColor
}
private func setupGradientLayer() {
// Apply "alphaMaskLayer" as a mask to the gradient layer in order to show only parts of the current "progress"
gradientLayer.mask = alphaMaskLayer
gradientLayer.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height)
gradientLayer.colors = gradientColors
gradientLayer.locations = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0]
gradientLayer.startPoint = .zero
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
gradientLayer.drawsAsynchronously = true
}
func hideProgressBar() {
guard progress == 1 else {
return
}
CATransaction.begin()
let moveAnimation = CABasicAnimation(keyPath: "position")
moveAnimation.duration = DefaultValues.animationDuration
moveAnimation.fromValue = gradientLayer.position
moveAnimation.toValue = CGPoint(x: gradientLayer.frame.width, y: gradientLayer.position.y)
moveAnimation.fillMode = kCAFillModeForwards
moveAnimation.isRemovedOnCompletion = false
CATransaction.setCompletionBlock {
self.resetProgressBar()
}
gradientLayer.add(moveAnimation, forKey: "position")
CATransaction.commit()
}
func resetProgressBar() {
// Call on super instead so no animation layers are created
super.setProgress(0, animated: false)
isHidden = true // The URLBar will unhide the view before starting the next animation.
}
override open func layoutSubviews() {
super.layoutSubviews()
self.gradientLayer.frame = CGRect(x: bounds.origin.x - 4, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height)
}
func animateGradient() {
let gradientChangeAnimation = CABasicAnimation(keyPath: "locations")
gradientChangeAnimation.duration = DefaultValues.animationDuration * 4
gradientChangeAnimation.toValue = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0]
gradientChangeAnimation.fromValue = [0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8]
gradientChangeAnimation.fillMode = kCAFillModeForwards
gradientChangeAnimation.isRemovedOnCompletion = false
gradientChangeAnimation.repeatCount = .infinity
gradientLayer.add(gradientChangeAnimation, forKey: "colorChange")
}
// MARK: - Update gradient
open func updateAlphaMaskLayerWidth(animated: Bool = false) {
CATransaction.begin()
// Workaround for non animated progress change
// Source: https://stackoverflow.com/a/16381287/3532505
CATransaction.setAnimationDuration(animated ? DefaultValues.animationDuration : 0.0)
alphaMaskLayer.frame = bounds.updateWidth(byPercentage: CGFloat(progress))
if progress == 1 {
// Delay calling hide until the last animation has completed
CATransaction.setCompletionBlock({
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DefaultValues.animationDuration, execute: {
self.hideProgressBar()
})
})
}
CATransaction.commit()
}
override open func setProgress(_ progress: Float, animated: Bool) {
if progress < self.progress && self.progress != 1 {
return
}
// Setup animations
gradientLayer.removeAnimation(forKey: "position")
if gradientLayer.animation(forKey: "colorChange") == nil {
animateGradient()
}
super.setProgress(progress, animated: animated)
updateAlphaMaskLayerWidth(animated: animated)
}
}
extension CGRect {
func updateWidth(byPercentage percentage: CGFloat) -> CGRect {
return CGRect(x: origin.x, y: origin.y, width: size.width * percentage, height: size.height)
}
}
|
mpl-2.0
|
3b8d3a9d0eea189c41904d8ca2f45f1a
| 33.860215 | 143 | 0.662708 | 4.84242 | false | false | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/NCFittingModuleDamageChartTableViewCell.swift
|
2
|
7961
|
//
// NCFittingModuleDamageChartTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 03.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import Dgmpp
class NCFittingModuleDamageChartTableViewCell: NCTableViewCell {
// @IBOutlet weak var damageChartView: NCFittingModuleDamageChartView!
@IBOutlet weak var damageChartView: ChartView!
@IBOutlet weak var optimalLabel: UILabel!
@IBOutlet weak var falloffLabel: UILabel!
@IBOutlet weak var rawDpsLabel: UILabel!
@IBOutlet weak var dpsLabel: UILabel!
@IBOutlet weak var dpsAccuracyView: UIView!
@IBOutlet weak var stepper: UIStepper!
}
extension Prototype {
enum NCFittingModuleDamageChartTableViewCell {
static let `default` = Prototype(nib: nil, reuseIdentifier: "NCFittingModuleDamageChartTableViewCell")
}
}
class NCFittingModuleDamageChartRow: TreeRow {
let module: DGMModule
let ship: DGMShip?
let count: Int
lazy var hullTypes: [NCDBDgmppHullType]? = {
let request = NSFetchRequest<NCDBDgmppHullType>(entityName: "DgmppHullType")
request.sortDescriptors = [NSSortDescriptor(key: "signature", ascending: true), NSSortDescriptor(key: "hullTypeName", ascending: true)]
return (try? NCDatabase.sharedDatabase!.viewContext.fetch(request))
}()
lazy var hullType: NCDBDgmppHullType? = {
guard let ship = self.ship else {return nil}
return NCDatabase.sharedDatabase?.invTypes[ship.typeID]?.hullType
}()
init(module: DGMModule, count: Int) {
self.module = module
self.ship = module.parent as? DGMShip
self.count = count
super.init(prototype: Prototype.NCFittingModuleDamageChartTableViewCell.default)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCFittingModuleDamageChartTableViewCell else {return}
// cell.damageChartView.module = self.module
cell.stepper.maximumValue = Double(hullTypes?.count ?? 1) - 1
cell.object = self
if let hullType = hullType {
cell.stepper.value = Double(hullTypes?.index(of: hullType) ?? 0)
}
cell.dpsLabel.text = NSLocalizedString("DPS AGAINST", comment: "") + " " + (hullType?.hullTypeName?.uppercased() ?? "")
let targetSignature = DGMMeter(hullType?.signature ?? 0)
// cell.damageChartView.targetSignature = targetSignature
let n = Double(round((treeController?.tableView?.bounds.size.width ?? 320) / 5))
guard n > 0 else {return}
guard let ship = ship else {return}
let module = self.module
var hitChanceData = [(x: Double, y: Double)]()
var dpsData = [(x: Double, y: Double)]()
// let hitChancePath = UIBezierPath()
// let dpsPath = UIBezierPath()
let optimal = module.optimal
let falloff = module.falloff
let maxX = ceil((optimal + max(falloff * 2, optimal * 0.5)) / 10000) * 10000
guard maxX > 0 else {return}
let dx = maxX / n
func dps(at range: Double, signature: Double = 0) -> Double {
let angularVelocity = signature > 0 ? ship.maxVelocityInOrbit(range) * DGMSeconds(1) / range : 0
let dps = module.dps(target: DGMHostileTarget(angularVelocity: DGMRadiansPerSecond(angularVelocity), velocity: DGMMetersPerSecond(0), signature: signature, range: range))
return (dps * DGMSeconds(1)).total
}
let maxDPS = dps(at: optimal * 0.1)
guard maxDPS > 0 else {return}
var x: Double = dx
hitChanceData.append((x: 0, y: maxDPS))
hitChanceData.append((x: dx, y: maxDPS))
dpsData.append((x: x, y: dps(at:x, signature: targetSignature)))
x += dx
while x < maxX {
hitChanceData.append((x: x, y: dps(at: x)))
dpsData.append((x: x, y: dps(at:x, signature: targetSignature)))
x += dx
}
x = optimal
let optimalData = [(x: x, y: 0), (x: x, y: dps(at: x))]
x = optimal + falloff
let falloffData = [(x: x, y: 0), (x: x, y: dps(at: x))]
let accuracy = module.accuracy(targetSignature: targetSignature)
let totalDPS = (module.dps() * DGMSeconds(1)).total
// DispatchQueue.main.async {
// guard (cell.object as? NCFittingModuleDamageChartRow) == self else {return}
let xRange = 0...maxX
let yRange = 0...maxDPS
if cell.damageChartView.charts.isEmpty {
let dpsChart = LineChart()
dpsChart.color = accuracy.color
dpsChart.data = dpsData
dpsChart.xRange = xRange
dpsChart.yRange = yRange
let accuracyChart = LineChart()
accuracyChart.color = .caption
accuracyChart.data = hitChanceData
accuracyChart.xRange = xRange
accuracyChart.yRange = yRange
let optimalChart = LineChart()
optimalChart.color = UIColor(white: 1.0, alpha: 0.3)
optimalChart.data = optimalData
optimalChart.xRange = xRange
optimalChart.yRange = yRange
let falloffChart = LineChart()
falloffChart.color = UIColor(white: 1.0, alpha: 0.3)
falloffChart.data = falloffData
falloffChart.xRange = xRange
falloffChart.yRange = yRange
cell.damageChartView.addChart(dpsChart, animated: true)
cell.damageChartView.addChart(accuracyChart, animated: true)
cell.damageChartView.addChart(optimalChart, animated: true)
cell.damageChartView.addChart(falloffChart, animated: true)
}
else {
var chart = (cell.damageChartView.charts[0] as? LineChart)
chart?.color = accuracy.color
chart?.xRange = xRange
chart?.yRange = yRange
chart?.data = dpsData
chart = (cell.damageChartView.charts[1] as? LineChart)
chart?.xRange = xRange
chart?.yRange = yRange
chart?.data = hitChanceData
chart = (cell.damageChartView.charts[2] as? LineChart)
chart?.xRange = xRange
chart?.yRange = yRange
chart?.data = optimalData
chart = (cell.damageChartView.charts[3] as? LineChart)
chart?.xRange = xRange
chart?.yRange = yRange
chart?.data = falloffData
}
cell.dpsAccuracyView.backgroundColor = accuracy.color
if self.count > 1 {
cell.rawDpsLabel.text = NSLocalizedString("RAW DPS:", comment: "") + " " + NCUnitFormatter.localizedString(from: totalDPS, unit: .none, style: .full) + " x \(self.count) = " + NCUnitFormatter.localizedString(from: totalDPS * Double(self.count), unit: .none, style: .full)
}
else {
cell.rawDpsLabel.text = NSLocalizedString("RAW DPS:", comment: "") + " " + NCUnitFormatter.localizedString(from: totalDPS * Double(self.count), unit: .none, style: .full)
}
cell.optimalLabel.text = NSLocalizedString("Optimal", comment: "") + "\n" + NCUnitFormatter.localizedString(from: optimal, unit: .meter, style: .full)
if falloff > 0 {
cell.falloffLabel.text = NSLocalizedString("Falloff", comment: "") + "\n" + NCUnitFormatter.localizedString(from: optimal + falloff, unit: .meter, style: .full)
}
else {
cell.falloffLabel.isHidden = true
}
if let constraint = cell.optimalLabel.superview?.constraints.first(where: {$0.firstItem === cell.optimalLabel && $0.secondItem === cell.optimalLabel.superview && $0.firstAttribute == .centerX}) {
let m = maxX > 0 ? max(0.01, optimal / maxX) : 0.01
constraint.isActive = false
let other = NSLayoutConstraint(item: cell.optimalLabel, attribute: .centerX, relatedBy: .equal, toItem: cell.optimalLabel.superview, attribute: .trailing, multiplier: CGFloat(m), constant: 0)
other.priority = constraint.priority
other.isActive = true
}
if let constraint = cell.falloffLabel.superview?.constraints.first(where: {$0.firstItem === cell.falloffLabel && $0.secondItem === cell.falloffLabel.superview && $0.firstAttribute == .centerX}) {
let m = maxX > 0 ? max(0.01, (optimal + falloff) / maxX) : 0.01
constraint.isActive = false
let other = NSLayoutConstraint(item: cell.falloffLabel, attribute: .centerX, relatedBy: .equal, toItem: cell.falloffLabel.superview, attribute: .trailing, multiplier: CGFloat(m), constant: 0)
other.priority = constraint.priority
other.isActive = true
}
// }
}
override var hash: Int {
return module.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
return (object as? NCFittingModuleDamageChartRow)?.hashValue == hashValue
}
}
|
lgpl-2.1
|
9ca5d69682a1854bbec9d9d095de2885
| 36.023256 | 274 | 0.706281 | 3.420713 | false | false | false | false |
edx/edx-app-ios
|
Source/ServerChangedChecker.swift
|
2
|
1021
|
//
// ServerChangedChecker.swift
// edX
//
// Created by Akiva Leffert on 2/26/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
@objc class ServerChangedChecker : NSObject {
private let defaultsKey = "OEXLastUsedAPIHostURL"
private var lastUsedAPIHostURL : NSURL? {
get {
return UserDefaults.standard.url(forKey: defaultsKey) as NSURL?
}
set {
UserDefaults.standard.set(newValue as URL?, forKey: defaultsKey)
}
}
func logoutIfServerChanged(config: OEXConfig, logoutAction : () -> Void) {
if let lastURL = lastUsedAPIHostURL, let currentURL = config.apiHostURL(), lastURL as URL != currentURL {
logoutAction()
OEXFileUtility.nukeUserData()
}
lastUsedAPIHostURL = config.apiHostURL()! as NSURL
}
@objc func logoutIfServerChanged() {
logoutIfServerChanged(config: OEXConfig(appBundleData: ())) {
OEXSession().closeAndClear()
}
}
}
|
apache-2.0
|
72ab89c3caa7c18916c1b46d61e79f2c
| 26.567568 | 113 | 0.633333 | 4.322034 | false | true | false | false |
edx/edx-app-ios
|
Source/CourseAnnouncementsViewController.swift
|
1
|
6831
|
//
// CourseAnnouncementsViewController.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 07/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
import edXCore
private func announcementsDeserializer(response: HTTPURLResponse, json: JSON) -> Result<[OEXAnnouncement]> {
return json.array.toResult().map {
return $0.map {
return OEXAnnouncement(dictionary: $0.dictionaryObject ?? [:])
}
}
}
class CourseAnnouncementsViewController: OfflineSupportViewController, LoadStateViewReloadSupport, InterfaceOrientationOverriding {
typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & DataManagerProvider & NetworkManagerProvider & OEXRouterProvider & OEXInterfaceProvider & ReachabilityProvider & OEXSessionProvider & OEXStylesProvider
@objc let courseID: String
private let loadController = LoadStateViewController()
private let announcementsLoader = BackedStream<[OEXAnnouncement]>()
private let webView: WKWebView
private let environment: Environment
private let fontStyle = OEXTextStyle(weight : .normal, size: .base, color: OEXStyles.shared().neutralBlack())
private let switchStyle = OEXStyles.shared().standardSwitchStyle()
@objc init(environment: Environment, courseID: String) {
self.courseID = courseID
self.environment = environment
self.webView = WKWebView(frame: .zero, configuration: environment.config.webViewConfiguration())
super.init(env: environment)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.courseAnnouncements
addSubviews()
setConstraints()
view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
webView.backgroundColor = OEXStyles.shared().standardBackgroundColor()
webView.isOpaque = false
webView.navigationDelegate = self
loadController.setupInController(controller: self, contentView: webView)
announcementsLoader.listen(self) {[weak self] in
switch $0 {
case let Result.success(announcements):
self?.useAnnouncements(announcements: announcements)
case let Result.failure(error):
if !(self?.announcementsLoader.active ?? false) {
self?.loadController.state = LoadState.failed(error: error)
}
}
}
setAccessibilityIdentifiers()
}
private func setAccessibilityIdentifiers() {
view.accessibilityIdentifier = "CourseAnnouncementsViewController:view"
webView.accessibilityIdentifier = "CourseAnnouncementsViewController:web-view"
}
private static func requestForCourse(course: OEXCourse) -> NetworkRequest<[OEXAnnouncement]> {
let announcementsURL = course.course_updates ?? "".oex_format(withParameters: [:])
return NetworkRequest(method: .GET,
path: announcementsURL,
requiresAuth: true,
deserializer: .jsonResponse(announcementsDeserializer)
)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadContent()
environment.analytics.trackScreen(withName: OEXAnalyticsScreenAnnouncements, courseID: courseID, value: nil)
}
override func reloadViewData() {
loadContent()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func loadContent() {
if !announcementsLoader.active {
loadController.state = .Initial
let courseStream = environment.dataManager.enrollmentManager.streamForCourseWithID(courseID: courseID)
let announcementStream = courseStream.transform {[weak self] enrollment in
return self?.environment.networkManager.streamForRequest(CourseAnnouncementsViewController.requestForCourse(course: enrollment.course), persistResponse: true) ?? OEXStream<Array>(error : NSError.oex_courseContentLoadError())
}
announcementsLoader.backWithStream((courseStream.value != nil) ? announcementStream : OEXStream<Array>(error : NSError.oex_courseContentLoadError()))
}
}
//MARK: - Setup UI
private func addSubviews() {
view.addSubview(webView)
}
private func setConstraints() {
webView.snp.makeConstraints { make in
make.edges.equalTo(safeEdges)
}
}
//MARK: - Presenter
private func useAnnouncements(announcements: [OEXAnnouncement]) {
guard announcements.count > 0 else {
loadController.state = LoadState.empty(icon: nil, message: Strings.announcementUnavailable)
return
}
var html:String = String()
for (index,announcement) in announcements.enumerated() {
html += "<div class=\"announcement-header\">\(announcement.heading ?? "")</div>"
html += "<hr class=\"announcement\"/>"
html += announcement.content ?? ""
if(index + 1 < announcements.count)
{
html += "<div class=\"announcement-separator\"/></div>"
}
}
let displayHTML = OEXStyles.shared().styleHTMLContent(html, stylesheet: "handouts-announcements") ?? ""
let baseURL = environment.config.apiHostURL()
webView.loadHTMLString(displayHTML, baseURL: baseURL)
}
//MARK:- LoadStateViewReloadSupport method
func loadStateViewReload() {
loadContent()
}
}
extension CourseAnnouncementsViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .linkActivated, .formSubmitted, .formResubmitted:
if let URL = navigationAction.request.url, UIApplication.shared.canOpenURL(URL){
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
default:
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
loadController.state = .Loaded
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
loadController.state = LoadState.failed(error: error as NSError)
}
}
|
apache-2.0
|
b725589f03d84201cf6a2b660a988551
| 37.8125 | 240 | 0.662275 | 5.544643 | false | false | false | false |
SagarSDagdu/SDDownloadManager
|
SDDownloadManager/Classes/SDDownloadManager.swift
|
1
|
12190
|
//
// SDDownloadManager.swift
// SDDownloadManager
//
// Created by Sagar Dagdu on 8/4/17.
// Copyright © 2017 Sagar Dagdu. 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
import UserNotifications
final public class SDDownloadManager: NSObject {
public typealias DownloadCompletionBlock = (_ error : Error?, _ fileUrl:URL?) -> Void
public typealias DownloadProgressBlock = (_ progress : CGFloat) -> Void
public typealias BackgroundDownloadCompletionHandler = () -> Void
// MARK :- Properties
private var session: URLSession!
private var ongoingDownloads: [String : SDDownloadObject] = [:]
private var backgroundSession: URLSession!
public var backgroundCompletionHandler: BackgroundDownloadCompletionHandler?
public var showLocalNotificationOnBackgroundDownloadDone = true
public var localNotificationText: String?
public static let shared: SDDownloadManager = { return SDDownloadManager() }()
//MARK:- Public methods
public func downloadFile(withRequest request: URLRequest,
inDirectory directory: String? = nil,
withName fileName: String? = nil,
shouldDownloadInBackground: Bool = false,
onProgress progressBlock:DownloadProgressBlock? = nil,
onCompletion completionBlock:@escaping DownloadCompletionBlock) -> String? {
guard let url = request.url else {
debugPrint("Request url is empty")
return nil
}
if let _ = self.ongoingDownloads[url.absoluteString] {
debugPrint("Already in progress")
return nil
}
var downloadTask: URLSessionDownloadTask
if shouldDownloadInBackground {
downloadTask = self.backgroundSession.downloadTask(with: request)
} else{
downloadTask = self.session.downloadTask(with: request)
}
let download = SDDownloadObject(downloadTask: downloadTask,
progressBlock: progressBlock,
completionBlock: completionBlock,
fileName: fileName,
directoryName: directory)
let key = self.getDownloadKey(withUrl: url)
self.ongoingDownloads[key] = download
downloadTask.resume()
return key;
}
public func getDownloadKey(withUrl url: URL) -> String {
return url.absoluteString
}
public func currentDownloads() -> [String] {
return Array(self.ongoingDownloads.keys)
}
public func cancelAllDownloads() {
for (_, download) in self.ongoingDownloads {
let downloadTask = download.downloadTask
downloadTask.cancel()
}
self.ongoingDownloads.removeAll()
}
public func cancelDownload(forUniqueKey key:String?) {
let downloadStatus = self.isDownloadInProgress(forUniqueKey: key)
let presence = downloadStatus.0
if presence {
if let download = downloadStatus.1 {
download.downloadTask.cancel()
self.ongoingDownloads.removeValue(forKey: key!)
}
}
}
public func pause(forUniqueKey key:String?) {
let downloadStatus = self.isDownloadInProgress(forUniqueKey: key)
let presence = downloadStatus.0
if presence {
if let download = downloadStatus.1 {
let downloadTask = download.downloadTask
downloadTask.suspend()
}}
}
public func resume(forUniqueKey key:String?) {
let downloadStatus = self.isDownloadInProgress(forUniqueKey: key)
let presence = downloadStatus.0
if presence {
if let download = downloadStatus.1 {
let downloadTask = download.downloadTask
downloadTask.resume()
}}
}
public func isDownloadInProgress(forKey key:String?) -> Bool {
let downloadStatus = self.isDownloadInProgress(forUniqueKey: key)
return downloadStatus.0
}
public func alterDownload(withKey key: String?,
onProgress progressBlock:DownloadProgressBlock?,
onCompletion completionBlock:@escaping DownloadCompletionBlock) {
let downloadStatus = self.isDownloadInProgress(forUniqueKey: key)
let presence = downloadStatus.0
if presence {
if let download = downloadStatus.1 {
download.progressBlock = progressBlock
download.completionBlock = completionBlock
}
}
}
//MARK:- Private methods
private override init() {
super.init()
let sessionConfiguration = URLSessionConfiguration.default
self.session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier!)
self.backgroundSession = URLSession(configuration: backgroundConfiguration, delegate: self, delegateQueue: OperationQueue())
}
private func isDownloadInProgress(forUniqueKey key:String?) -> (Bool, SDDownloadObject?) {
guard let key = key else { return (false, nil) }
for (uniqueKey, download) in self.ongoingDownloads {
if key == uniqueKey {
return (true, download)
}
}
return (false, nil)
}
private func showLocalNotification(withText text:String) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getNotificationSettings { (settings) in
guard settings.authorizationStatus == .authorized else {
debugPrint("Not authorized to schedule notification")
return
}
let content = UNMutableNotificationContent()
content.title = text
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1,
repeats: false)
let identifier = "SDDownloadManagerNotification"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { (error) in
if let error = error {
debugPrint("Could not schedule notification, error : \(error)")
}
})
}
}
}
extension SDDownloadManager : URLSessionDelegate, URLSessionDownloadDelegate {
// MARK:- Delegates
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
let key = (downloadTask.originalRequest?.url?.absoluteString)!
if let download = self.ongoingDownloads[key] {
if let response = downloadTask.response {
let statusCode = (response as! HTTPURLResponse).statusCode
guard statusCode < 400 else {
let error = NSError(domain:"HttpError", code:statusCode, userInfo:[NSLocalizedDescriptionKey : HTTPURLResponse.localizedString(forStatusCode: statusCode)])
OperationQueue.main.addOperation({
download.completionBlock(error,nil)
})
return
}
let fileName = download.fileName ?? downloadTask.response?.suggestedFilename ?? (downloadTask.originalRequest?.url?.lastPathComponent)!
let directoryName = download.directoryName
let fileMovingResult = SDFileUtils.moveFile(fromUrl: location, toDirectory: directoryName, withName: fileName)
let didSucceed = fileMovingResult.0
let error = fileMovingResult.1
let finalFileUrl = fileMovingResult.2
OperationQueue.main.addOperation({
(didSucceed ? download.completionBlock(nil,finalFileUrl) : download.completionBlock(error,nil))
})
}
}
self.ongoingDownloads.removeValue(forKey:key)
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
guard totalBytesExpectedToWrite > 0 else {
debugPrint("Could not calculate progress as totalBytesExpectedToWrite is less than 0")
return;
}
if let download = self.ongoingDownloads[(downloadTask.originalRequest?.url?.absoluteString)!],
let progressBlock = download.progressBlock {
let progress : CGFloat = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite)
OperationQueue.main.addOperation({
progressBlock(progress)
})
}
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
if let error = error {
let downloadTask = task as! URLSessionDownloadTask
let key = (downloadTask.originalRequest?.url?.absoluteString)!
if let download = self.ongoingDownloads[key] {
OperationQueue.main.addOperation({
download.completionBlock(error,nil)
})
}
self.ongoingDownloads.removeValue(forKey:key)
}
}
public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
if downloadTasks.count == 0 {
OperationQueue.main.addOperation({
if let completion = self.backgroundCompletionHandler {
completion()
}
if self.showLocalNotificationOnBackgroundDownloadDone {
var notificationText = "Download completed"
if let userNotificationText = self.localNotificationText {
notificationText = userNotificationText
}
self.showLocalNotification(withText: notificationText)
}
self.backgroundCompletionHandler = nil
})
}
}
}
}
|
mit
|
6bc1483c238d6b6b608bbadd989854b4
| 41.618881 | 175 | 0.603085 | 6.052135 | false | false | false | false |
KrishMunot/swift
|
test/expr/unary/selector/selector.swift
|
1
|
4078
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -parse %s -verify
import ObjectiveC
// REQUIRES: objc_interop
@objc class A { }
@objc class B { }
class C1 {
@objc init(a: A, b: B) { }
@objc func method1(_ a: A, b: B) { }
@objc(someMethodWithA:B:) func method2(_ a: A, b: B) { }
@objc class func method3(_ a: A, b: B) { } // expected-note{{found this candidate}}
@objc class func method3(a: A, b: B) { } // expected-note{{found this candidate}}
@objc var a: A = A() // expected-note{{'a' declared here}}
@objc func getC1() -> AnyObject { return self }
@objc func testUnqualifiedSelector(_ a: A, b: B) {
_ = #selector(testUnqualifiedSelector(_:b:))
let testUnqualifiedSelector = 1
_ = #selector(testUnqualifiedSelector(_:b:))
_ = testUnqualifiedSelector // suppress unused warning
}
@objc func testParam(_ testParam: A) { // expected-note{{'testParam' declared here}}
_ = #selector(testParam) // expected-error{{argument of '#selector' cannot refer to a parameter}}
}
@objc func testVariable() {
let testVariable = 1 // expected-note{{'testVariable' declared here}}
_ = #selector(testVariable) // expected-error{{argument of '#selector' cannot refer to a variable}}
}
}
@objc protocol P1 {
func method4(_ a: A, b: B)
static func method5(_ a: B, b: B)
}
extension C1 {
final func method6() { } // expected-note{{add '@objc' to expose this method to Objective-C}}{{3-3=@objc }}
}
func testSelector(_ c1: C1, p1: P1, obj: AnyObject) {
// Instance methods on an instance
let sel1 = #selector(c1.method1)
_ = #selector(c1.method1(_:b:))
_ = #selector(c1.method2)
// Instance methods on a class.
_ = #selector(C1.method1)
_ = #selector(C1.method1(_:b:))
_ = #selector(C1.method2)
// Class methods on a class.
_ = #selector(C1.method3(_:b:))
_ = #selector(C1.method3(a:b:))
// Methods on a protocol.
_ = #selector(P1.method4)
_ = #selector(P1.method4(_:b:))
_ = #selector(P1.method5) // FIXME: expected-error{{static member 'method5' cannot be used on instance of type 'P1.Protocol'}}
_ = #selector(P1.method5(_:b:)) // FIXME: expected-error{{static member 'method5(_:b:)' cannot be used on instance of type 'P1.Protocol'}}
_ = #selector(p1.method4)
_ = #selector(p1.method4(_:b:))
_ = #selector(p1.dynamicType.method5)
_ = #selector(p1.dynamicType.method5(_:b:))
// Interesting expressions that refer to methods.
_ = #selector(Swift.AnyObject.method1)
_ = #selector(AnyObject.method1!)
_ = #selector(obj.getC1?().method1)
// Initializers
_ = #selector(C1.init(a:b:))
// Make sure the result has type "ObjectiveC.Selector"
let sel2: Selector
sel2 = sel1
_ = sel2
}
func testAmbiguity() {
_ = #selector(C1.method3) // expected-error{{ambiguous use of 'method3(_:b:)'}}
}
func testUnusedSelector() {
#selector(C1.getC1) // expected-warning{{result of '#selector' is unused}}
}
func testProperties(_ c1: C1) {
_ = #selector(c1.a) // expected-error{{argument of '#selector' cannot refer to a property}}
_ = #selector(C1.a) // FIXME poor diagnostic: expected-error{{instance member 'a' cannot be used on type 'C1'}}
}
func testNonObjC(_ c1: C1) {
_ = #selector(c1.method6) // expected-error{{argument of '#selector' refers to a method that is not exposed to Objective-C}}
}
func testParseErrors1() {
_ = #selector foo // expected-error{{expected '(' following '#selector'}}
}
func testParseErrors2() {
_ = #selector( // expected-error{{expected expression naming a method within '#selector(...)'}}
}
func testParseErrors3(_ c1: C1) {
_ = #selector( // expected-note{{to match this opening '('}}
c1.method1(_:b:) // expected-error{{expected ')' to complete '#selector' expression}}
}
func testParseErrors4() {
// Subscripts
_ = #selector(C1.subscript) // expected-error{{expected member name following '.'}}
// expected-error@-1{{consecutive statements on a line must be separated by ';'}}
// expected-error@-2{{expected '(' for subscript parameters}}
}
|
apache-2.0
|
3db3a68b9d611a455bf19a7f2acf05f8
| 32.42623 | 140 | 0.652771 | 3.280772 | false | true | false | false |
blackspotbear/MMDViewer
|
MMDViewer/WireframeDrawer.swift
|
1
|
3116
|
import Foundation
import Metal
import simd
import GLKit
private struct WireframeModelMatrices {
var mvpMatrix: GLKMatrix4
}
private struct FloorModel {
let vertexBuffer: MTLBuffer
let indexBuffer: MTLBuffer
let indexCount: Int
}
private func MakeFloor(_ device: MTLDevice) -> FloorModel {
let xsize: Float = 20
let zsize: Float = 20
let gridNum: Int16 = 20
let xstep = xsize / Float(gridNum)
let zstep = zsize / Float(gridNum)
var vdata = [GLKVector4]()
for zi in 0...gridNum {
for xi in 0...gridNum {
let x = -xsize / 2 + Float(xi) * xstep
let z = -zsize / 2 + Float(zi) * zstep
let vtx = GLKVector4Make(x, 0, z, 1)
vdata.append(vtx)
}
}
var tindices = [Int16]()
for zi in 0..<gridNum {
for xi in 0..<gridNum {
let lefttop = Int16((gridNum + 1) * zi + xi)
tindices.append(lefttop)
tindices.append(lefttop + (gridNum + 1))
tindices.append(lefttop + 1)
tindices.append(lefttop + 1)
tindices.append(lefttop + (gridNum + 1))
tindices.append(lefttop + (gridNum + 1) + 1)
}
}
let vertexBuffer = device.makeBuffer(
bytes: vdata,
length: vdata.count * MemoryLayout<GLKVector4>.stride,
options: [])
vertexBuffer?.label = "wireframe vertices"
let indexBuffer = device.makeBuffer(
bytes: tindices,
length: tindices.count * MemoryLayout<Int16>.stride,
options: [])
indexBuffer?.label = "wireframe indicies"
let model = FloorModel(vertexBuffer: vertexBuffer!, indexBuffer: indexBuffer!, indexCount: tindices.count)
return model
}
class WireFrameDrawer: Drawer {
let matrixBufferProvider: BufferProvider
private let model: FloorModel
init(device: MTLDevice) {
matrixBufferProvider = BufferProvider(
device: device,
inflightBuffersCount: 3,
sizeOfUniformsBuffer: MemoryLayout<WireframeModelMatrices>.stride)
model = MakeFloor(device)
}
func draw(_ renderer: Renderer) {
guard let renderEncoder = renderer.renderCommandEncoder else {
return
}
let matrixBuffer = matrixBufferProvider.nextBuffer()
let matrixData = matrixBuffer.contents().bindMemory(
to: WireframeModelMatrices.self,
capacity: 1)
var matrices = WireframeModelMatrices(
mvpMatrix: renderer.projectionMatrix.multiply(renderer.viewMatrix))
memcpy(matrixData, &matrices, MemoryLayout<WireframeModelMatrices>.size)
renderEncoder.pushDebugGroup("wireframe")
renderEncoder.setVertexBuffer(model.vertexBuffer, offset: 0, index: 0)
renderEncoder.setVertexBuffer(matrixBuffer, offset: 0, index: 1)
renderEncoder.drawIndexedPrimitives(
type: .triangle,
indexCount: model.indexCount,
indexType: .uint16,
indexBuffer: model.indexBuffer,
indexBufferOffset: 0)
renderEncoder.popDebugGroup()
}
}
|
mit
|
21e016bdd5cb407e1e6eb5240d495217
| 29.252427 | 110 | 0.62837 | 4.358042 | false | false | false | false |
insidegui/WWDC
|
Packages/ConfCore/ConfCore/Track.swift
|
1
|
1912
|
//
// Track.swift
// WWDC
//
// Created by Guilherme Rambo on 06/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
/// Tracks represent a specific are of interest (ex: "System Frameworks", "Graphics and Games")
public class Track: Object, Decodable {
/// Unique identifier
@objc public dynamic var identifier = ""
/// The name of the track
@objc public dynamic var name = ""
/// The order in which the track should be listed
@objc public dynamic var order = 0
/// Dark theme color
@objc public dynamic var darkColor = ""
/// Color for light backgrounds
@objc public dynamic var lightBackgroundColor = ""
/// Color for light contexts
@objc public dynamic var lightColor = ""
/// Theme title color
@objc public dynamic var titleColor = ""
/// Sessions related to this track
public let sessions = List<Session>()
/// Instances related to this track
public let instances = List<SessionInstance>()
public override class func primaryKey() -> String? {
return "name"
}
// MARK: - Decodable
private enum CodingKeys: String, CodingKey {
case name, color, darkColor, titleColor, lightBGColor, ordinal
case identifier = "id"
}
public convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
identifier = String(try container.decode(Int.self, forKey: .identifier))
name = try container.decode(key: .name)
darkColor = try container.decode(key: .darkColor)
lightBackgroundColor = try container.decode(key: .lightBGColor)
lightColor = try container.decode(key: .color)
titleColor = try container.decode(key: .titleColor)
order = try container.decodeIfPresent(key: .ordinal) ?? 0
}
}
|
bsd-2-clause
|
110df589a0d0859310c9fa6103f75146
| 27.954545 | 95 | 0.661957 | 4.59375 | false | false | false | false |
wonderkiln/WKAwesomeMenu
|
Pods/SnapKit/Source/ConstraintMakerExtendable.swift
|
1
|
4943
|
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMakerExtendable: ConstraintMakerRelatable {
public var left: ConstraintMakerExtendable {
self.description.attributes += .left
return self
}
public var top: ConstraintMakerExtendable {
self.description.attributes += .top
return self
}
public var bottom: ConstraintMakerExtendable {
self.description.attributes += .bottom
return self
}
public var right: ConstraintMakerExtendable {
self.description.attributes += .right
return self
}
public var leading: ConstraintMakerExtendable {
self.description.attributes += .leading
return self
}
public var trailing: ConstraintMakerExtendable {
self.description.attributes += .trailing
return self
}
public var width: ConstraintMakerExtendable {
self.description.attributes += .width
return self
}
public var height: ConstraintMakerExtendable {
self.description.attributes += .height
return self
}
public var centerX: ConstraintMakerExtendable {
self.description.attributes += .centerX
return self
}
public var centerY: ConstraintMakerExtendable {
self.description.attributes += .centerY
return self
}
@available(*, deprecated:0.40.0, message:"Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
self.description.attributes += .lastBaseline
return self
}
public var lastBaseline: ConstraintMakerExtendable {
self.description.attributes += .lastBaseline
return self
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
self.description.attributes += .firstBaseline
return self
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
self.description.attributes += .leftMargin
return self
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
self.description.attributes += .rightMargin
return self
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
self.description.attributes += .bottomMargin
return self
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
self.description.attributes += .leadingMargin
return self
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
self.description.attributes += .trailingMargin
return self
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerXWithinMargins
return self
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerYWithinMargins
return self
}
public var edges: ConstraintMakerExtendable {
self.description.attributes += .edges
return self
}
public var size: ConstraintMakerExtendable {
self.description.attributes += .size
return self
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
self.description.attributes += .margins
return self
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
self.description.attributes += .centerWithinMargins
return self
}
}
|
mit
|
73d0ec3bee15e3d964f0743199db52bb
| 29.325153 | 81 | 0.668015 | 5.280983 | false | false | false | false |
eric1202/LZJ_Coin
|
LZJ_Coin/Pods/Spruce/Sources/Classes/Full View/DefaultFullViewAnimations.swift
|
1
|
9853
|
//
// DefaultFullViewAnimations.swift
// Spruce
//
// Copyright (c) 2017 WillowTree, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public extension Spruce {
/// Run a spruce style animation on this view. This method is the most basic form of a spruce animation and allows you to setup your view with stock spruce animations. Feel free to chain together animations that would work nicely together.
///
/// - Note: Possible animations include
/// - Fading
/// - Scaling
/// - Translating
/// - Rotating
/// - Note: Default animation type is `StandardAnimation` and SortFunction is `LinearSortFunction(direction: .topToBottom, interObjectDelay: 0.05)`
///
/// See `StockAnimation` for more details
///
/// - Parameters:
/// - animations: an array of stock animations
/// - duration: duration of each individual animation
/// - completion: a closure that is called upon the final animation completing. A `Bool` is passed into the closure letting you know if the animation has completed. **Note:** If you stop animations on the whole animating view, then `false` will be passed into the completion closure. However, if the final animation is allowed to proceed then `true` will be the value passed into the completion closure.
public func animate(_ animations: [StockAnimation], duration: TimeInterval = 0.3, completion: CompletionHandler? = nil ) {
let animation = StandardAnimation(duration: duration)
self.animate(animations, duration: duration, animationType: animation, completion: completion)
}
/// Run a spruce style animation on this view. This allows you to setup your view with stock spruce animations. Feel free to chain together animations that would work nicely together.
///
/// - Note: Possible animations include
/// - Fading
/// - Scaling
/// - Translating
/// - Rotating
/// - Note: Default animation type is `StandardAnimation`
///
/// See `StockAnimation` for more details
///
/// - Parameters:
/// - animations: an array of stock animations
/// - duration: duration of each individual animation
/// - sortFunction: the `sortFunction` to be used when setting the offsets for each subviews animation
/// - completion: a closure that is called upon the final animation completing. A `Bool` is passed into the closure letting you know if the animation has completed. **Note:** If you stop animations on the whole animating view, then `false` will be passed into the completion closure. However, if the final animation is allowed to proceed then `true` will be the value passed into the completion closure.
public func animate(_ animations: [StockAnimation], sortFunction: SortFunction, duration: TimeInterval = 0.3, completion: CompletionHandler? = nil ) {
let animation = StandardAnimation(duration: duration)
self.animate(animations, duration: duration, animationType: animation, sortFunction: sortFunction, completion: completion)
}
/// Run a spruce style animation on this view. This method allows you to setup your view with stock spruce animations. Feel free to chain together animations that would work nicely together.
///
/// - Note: Default SortFunction is `LinearSortFunction(direction: .topToBottom, interObjectDelay: 0.05)`
/// - Parameters:
/// - animations: an array of stock animations
/// - duration: duration of each individual animation
/// - animationType: style of animation that each view should follow. Don't worry about setting the `changeFunction`. We will set that using the stock animations that you provide. If you have a value there it will be overwritten. (ex: SpringAnimation)
/// - completion: a closure that is called upon the final animation completing. A `Bool` is passed into the closure letting you know if the animation has completed. **Note:** If you stop animations on the whole animating view, then `false` will be passed into the completion closure. However, if the final animation is allowed to proceed then `true` will be the value passed into the completion closure.
public func animate(_ animations: [StockAnimation], duration: TimeInterval = 0.3, animationType: Animation, completion: CompletionHandler? = nil) {
let sortFunction = LinearSortFunction(direction: .topToBottom, interObjectDelay: 0.05)
self.animate(animations, duration: duration, animationType: animationType, sortFunction: sortFunction, completion: completion)
}
/// Run a spruce style animation on this view. This method allows you to setup your view with stock spruce animations. Feel free to chain together animations that would work nicely together.
///
/// - Parameters:
/// - animations: an array of stock animations
/// - duration: duration of each individual animation
/// - animationType: style of animation that each view should follow. Don't worry about setting the `changeFunction`. We will set that using the stock animations that you provide. If you have a value there it will be overwritten. (ex: SpringAnimation)
/// - sortFunction: the `sortFunction` to be used when setting the offsets for each subviews animation
/// - prepare: a `bool` as to whether we should run `prepare` on your view for you. If set to `true`, then we will run `prepare` right before the animation using the stock animations that you provided. If `false`, then `prepare` will not run. (default is `true`)
/// - completion: a closure that is called upon the final animation completing. A `Bool` is passed into the closure letting you know if the animation has completed. **Note:** If you stop animations on the whole animating view, then `false` will be passed into the completion closure. However, if the final animation is allowed to proceed then `true` will be the value passed into the completion closure.
public func animate(_ animations: [StockAnimation], duration: TimeInterval = 0.3, animationType: Animation, sortFunction: SortFunction, prepare: Bool = true, completion: CompletionHandler? = nil) {
if prepare {
self.prepare(with: animations)
}
/* Create the animations */
var animationType = animationType
animationType.changeFunction = { view in
for animation in animations {
let animationFunc = animation.animationFunction
animationFunc(view)
}
}
self.animate(withSortFunction: sortFunction, animation: animationType, completion: completion)
}
/// Use this method to setup all of your views before the animation occurs. This could include hiding, fading, translating them, etc...
/// Given the array of stock animations, the change functions required to prepare those animations will automatically be run for you. No need to specify your own custom change function here.
/// - Note: If you run this after the views are visible, then this would cause a slight stutter of the viewport. This could cause UX issues since the views would flash on the screen.
///
/// - Parameters:
/// - animations: an array of stock animations
/// - recursiveDepth: an int describing how deep into the view hiearchy the subview search should go
public func prepare(with animations: [StockAnimation], recursiveDepth: Int = 0) {
/* Reset the views to prepare for the animations */
let clearFunction: ChangeFunction = { view in
for animation in animations {
let clearFunc = animation.prepareFunction
clearFunc(view)
}
}
let subviews = self.subviews(withRecursiveDepth: recursiveDepth)
UIView.performWithoutAnimation {
for subview in subviews {
guard let animatedView = subview.view else {
continue
}
clearFunction(animatedView)
}
}
}
/// Quick method to hide all of the subviews of a view. Use this if you want to make sure that none of the views that will be animated will be shown on screen before you transition them.
///
/// - Parameter recursiveDepth: an int describing how deep into the view hiearchy the subview search should go
public func hideAllSubviews(recursiveDepth: Int = 0) {
let subviews = self.subviews(withRecursiveDepth: recursiveDepth)
UIView.performWithoutAnimation {
for subview in subviews {
guard let animatedView = subview.view else {
continue
}
animatedView.isHidden = true
}
}
}
}
|
mit
|
ef2d2c9ad805d7d2afe811c8ef2d4520
| 64.251656 | 409 | 0.699685 | 4.892254 | false | false | false | false |
brentsimmons/Evergreen
|
Shared/ExtensionPoints/TwitterFeedProvider-Extensions.swift
|
1
|
869
|
//
// TwitterFeedProvider+Extensions.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/7/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
extension TwitterFeedProvider: ExtensionPoint {
static var isSinglton = false
static var isDeveloperBuildRestricted = true
static var title = NSLocalizedString("Twitter", comment: "Twitter")
static var image = AppAssets.extensionPointTwitter
static var description: NSAttributedString = {
return TwitterFeedProvider.makeAttrString("This extension enables you to subscribe to Twitter URLs as if they were RSS feeds. It only works with \(Account.defaultLocalAccountName) or iCloud accounts.")
}()
var extensionPointID: ExtensionPointIdentifer {
return ExtensionPointIdentifer.twitter(screenName)
}
var title: String {
return "@\(screenName)"
}
}
|
mit
|
e86cd0d571e5367e0f77fccecd2d7c54
| 27.933333 | 203 | 0.774194 | 4.234146 | false | false | false | false |
brentsimmons/Evergreen
|
Mac/MainWindow/NNW3/NNW3ImportController.swift
|
1
|
3609
|
//
// NNW3ImportController.swift
// NetNewsWire
//
// Created by Brent Simmons on 10/14/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
struct NNW3ImportController {
/// Import NNW3 subscriptions if they exist.
/// Return true if Subscriptions.plist was found and subscriptions were imported.
static func importSubscriptionsIfFileExists(account: Account) -> Bool {
guard let subscriptionsPlistURL = defaultFileURL else {
return false
}
if !FileManager.default.fileExists(atPath: subscriptionsPlistURL.path) {
return false
}
NNW3ImportController.importSubscriptionsPlist(subscriptionsPlistURL, into: account)
return true
}
/// Run an NSOpenPanel and import subscriptions (if the user chooses to).
static func askUserToImportNNW3Subscriptions(window: NSWindow) {
chooseFile(window)
}
}
private extension NNW3ImportController {
/// URL to ~/Library/Application Support/NetNewsWire/Subscriptions.plist
static var defaultFileURL: URL? {
guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
return nil
}
let folderURL = applicationSupportURL.appendingPathComponent("NetNewsWire", isDirectory: true)
return folderURL.appendingPathComponent("Subscriptions.plist", isDirectory: false)
}
/// Import Subscriptions.plist file. Convert to OPML and then import into specified Account.
static func importSubscriptionsPlist(_ subscriptionsPlistURL: URL, into account: Account) {
guard let opmlURL = convertToOPMLFile(subscriptionsPlistURL: subscriptionsPlistURL) else {
return
}
account.importOPML(opmlURL) { result in
try? FileManager.default.removeItem(at: opmlURL)
switch result {
case .success:
break
case .failure(let error):
NSApplication.shared.presentError(error)
}
}
}
/// Run the NSOpenPanel. On success, import subscriptions to the selected account.
static func chooseFile(_ window: NSWindow) {
let accessoryViewController = NNW3OpenPanelAccessoryViewController()
let panel = NSOpenPanel()
panel.canDownloadUbiquitousContents = true
panel.canResolveUbiquitousConflicts = true
panel.canChooseFiles = true
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.resolvesAliases = true
panel.directoryURL = NNW3ImportController.defaultFileURL
panel.allowedFileTypes = ["plist"]
panel.allowsOtherFileTypes = false
panel.accessoryView = accessoryViewController.view
panel.isAccessoryViewDisclosed = true
panel.title = NSLocalizedString("Choose a Subscriptions.plist file:", comment: "NNW3 Import")
panel.beginSheetModal(for: window) { modalResult in
guard modalResult == .OK, let subscriptionsPlistURL = panel.url else {
return
}
guard let account = accessoryViewController.selectedAccount else {
return
}
AppDefaults.shared.importOPMLAccountID = account.accountID
NNW3ImportController.importSubscriptionsPlist(subscriptionsPlistURL, into: account)
}
}
/// Convert Subscriptions.plist on disk to a temporary OPML file.
static func convertToOPMLFile(subscriptionsPlistURL url: URL) -> URL? {
guard let document = NNW3Document(subscriptionsPlistURL: url) else {
return nil
}
let opml = document.OPMLString(indentLevel: 0)
let opmlURL = FileManager.default.temporaryDirectory.appendingPathComponent("NNW3.opml")
do {
try opml.write(to: opmlURL, atomically: true, encoding: .utf8)
} catch let error as NSError {
NSApplication.shared.presentError(error)
return nil
}
return opmlURL
}
}
|
mit
|
5cbd3d9c9dc11bf8140693c68c18878e
| 32.407407 | 129 | 0.768847 | 4.040314 | false | false | false | false |
jsmerola/DiagnosticReportGenerator
|
DiagnosticReportGenerator/DiagnosticReportGenerator.swift
|
1
|
12740
|
//
// DiagnosticReportGenerator.swift
//
// Created by Jeff Merola on 6/16/15.
// Copyright © 2015 Jeff Merola. All rights reserved.
//
import Foundation
import SystemConfiguration
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
import IOKit.ps
#endif
@available (iOS 8.0, OSX 10.10, *)
public class DiagnosticReportGenerator: NSObject {
/**
Possible errors that can be thrown by generateWithIdentifier(_:extraInfo:includeDefaults:)
- TemplateNotFound: The diagnostic report template file is missing from the project.
- TemplateParseError: The contents of the report template could not be read.
*/
public enum ReportError: ErrorType {
case TemplateNotFound
case TemplateParseError
}
/**
Generates a diagnostic report.
:param: identifer The identifier to use for the generated report. If nil, a random UUID will be generated.
:param: extraInfo An optional dictionary of additional information to be included in the report. The keys and values are printed using Swift's string interpolation feature.
:param: includeDefaults A boolean specifying whether to include NSUserDefaults in the report or not. Defaults to true.
:returns: A diagnostic report as a String, formatted as html.
*/
public func generateWithIdentifier(identifier: String?, extraInfo: [String: AnyObject]?, includeDefaults: Bool = true) throws -> String {
guard let path = NSBundle(forClass: self.dynamicType).pathForResource("DiagnosticReportTemplate", ofType: "html") else {
throw ReportError.TemplateNotFound
}
let reportTemplate: String
do {
reportTemplate = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch {
throw ReportError.TemplateParseError
}
let args: [CVarArgType] = [
Timestamp(),
identifier ?? NSUUID().UUIDString,
DeviceName(),
Model(),
SystemVersion(),
CPUCountString(),
BatteryStateString(),
BatteryLevelString(),
SystemUptime(),
TotalDiskSpaceString(),
FreeDiskSpaceString(),
ScreenInformation(),
SystemLocale(),
Timezone(),
ApplicationName(),
ApplicationBundleID(),
ApplicationVersion(),
ApplicationBuild(),
BuildAdditionalAppInfoStringFromDictionary(extraInfo),
includeDefaults ? UserDefaults() : "Not Included",
].map { (value: CVarArgType) -> CVarArgType in
if let value = value as? String {
return value.htmlRepresentation() as CVarArgType
} else {
return "" as CVarArgType
}
}
return withVaList(args, { (pointer: CVaListPointer) -> String in
NSString(format: reportTemplate, arguments: pointer) as String
})
}
}
// MARK: - Hardware Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func GetSystemInfoByName(name: String) -> String? {
var size: Int = 0
sysctlbyname(name, nil, &size, nil, 0)
var info = [CChar](count: size, repeatedValue: 0)
sysctlbyname(name, &info, &size, nil, 0)
return String.fromCString(info)
}
func Model() -> String {
let machine = GetSystemInfoByName("hw.machine") ?? "?"
let model = GetSystemInfoByName("hw.model") ?? "?"
return "\(model) - \(machine)"
}
func CPUCount() -> Int {
return NSProcessInfo.processInfo().processorCount
}
func CPUCountString() -> String {
return "\(CPUCount())"
}
func ScreenInformation() -> String {
#if os(iOS)
return "\(NSStringFromCGSize(UIScreen.mainScreen().bounds.size))@\(UIScreen.mainScreen().scale)x"
#elseif os(OSX)
var screenStrings = Array<String>()
if let screens = NSScreen.screens() {
var index = 0
for screen in screens {
screenStrings.append("[ Screen #\(++index): {\(Int(screen.frame.size.width)), \(Int(screen.frame.size.height))}@\(screen.backingScaleFactor)x ]")
}
}
return (screenStrings as NSArray).componentsJoinedByString(", ")
#else
return "?"
#endif
}
}
// MARK: - Disk Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func TotalDiskSpace() -> Int64 {
do {
if let totalSpace = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory())[NSFileSystemSize] as? Int {
return Int64(totalSpace)
} else {
return -1
}
} catch {
return -1
}
}
func TotalDiskSpaceString() -> String {
let space = TotalDiskSpace()
if space < 0 {
return "?"
} else {
let formatter = NSByteCountFormatter()
formatter.countStyle = .File
formatter.includesActualByteCount = true
return formatter.stringFromByteCount(space)
}
}
func FreeDiskSpace() -> Int64 {
do {
if let freeSpace = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory())[NSFileSystemFreeSize] as? Int {
return Int64(freeSpace)
} else {
return -1
}
} catch {
return -1
}
}
func FreeDiskSpaceString() -> String {
let space = FreeDiskSpace()
if space < 0 {
return "?"
} else {
let formatter = NSByteCountFormatter()
formatter.countStyle = .File
formatter.includesActualByteCount = true
return formatter.stringFromByteCount(space)
}
}
}
// MARK: - Battery Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
enum ChargeState: CustomStringConvertible {
case Charging, Charged, Draining, Unknown
var description: String {
switch self {
case .Charging:
return "Charging"
case .Charged:
return "Fully Charged"
case .Draining:
return "Draining"
case .Unknown:
return "Unknown"
}
}
}
#if os(OSX)
func PowerSource() -> NSDictionary {
let powerSourceInfoDict = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let powerSources = IOPSCopyPowerSourcesList(powerSourceInfoDict).takeRetainedValue() as Array
if powerSources.count > 0 {
return IOPSGetPowerSourceDescription(powerSourceInfoDict, powerSources[0]).takeUnretainedValue() as NSDictionary
}
return [:]
}
#endif
func BatteryState() -> ChargeState {
#if os(iOS)
UIDevice.currentDevice().batteryMonitoringEnabled = true
let state: ChargeState
switch UIDevice.currentDevice().batteryState {
case .Unknown:
state = .Unknown
case .Unplugged:
state = .Draining
case .Charging:
state = .Charging
case .Full:
state = .Charged
}
UIDevice.currentDevice().batteryMonitoringEnabled = false
return state
#elseif os(OSX)
let powerSource = PowerSource()
let state = powerSource[kIOPSPowerSourceStateKey] as! String
switch state {
case kIOPSACPowerValue:
if powerSource[kIOPSIsChargingKey] as! Bool == true {
return .Charging
} else if powerSource[kIOPSIsChargedKey] as! Bool == true {
return .Charged
} else {
return .Unknown
}
case kIOPSBatteryPowerValue:
return .Draining
default:
return .Unknown
}
#else
return .Unknown
#endif
}
func BatteryStateString() -> String {
return "\(BatteryState())"
}
func BatteryLevel() -> Float {
#if os(iOS)
UIDevice.currentDevice().batteryMonitoringEnabled = true
let batteryLevel = UIDevice.currentDevice().batteryLevel * 100
UIDevice.currentDevice().batteryMonitoringEnabled = false
return batteryLevel
#elseif os(OSX)
let powerSource = PowerSource()
let state = BatteryState()
switch state {
case .Draining, .Charging:
let currentCapacity = powerSource[kIOPSCurrentCapacityKey] as! Float
let maxCapacity = powerSource[kIOPSMaxCapacityKey] as! Float
return currentCapacity / maxCapacity * 100
case .Charged:
return 100
case .Unknown:
return -1
}
#else
return -1
#endif
}
func BatteryLevelString() -> String {
let level = BatteryLevel()
if level < 0 {
return "?"
} else {
return "\(level)%"
}
}
}
// MARK: - Software Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func DeviceName() -> String {
#if os(iOS)
return UIDevice.currentDevice().name
#elseif os(OSX)
if let name = SCDynamicStoreCopyComputerName(nil, nil) {
return name as String
} else {
return "?"
}
#else
return "?"
#endif
}
private func SystemVersion() -> String {
return NSProcessInfo.processInfo().operatingSystemVersionString
}
private func SystemUptime() -> String {
let uptime = NSProcessInfo.processInfo().systemUptime
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Short
return formatter.stringFromTimeInterval(uptime) ?? "?"
}
}
// MARK: - Application Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func ApplicationName() -> String {
return NSBundle.mainBundle().applicationName ?? "?"
}
func ApplicationBundleID() -> String {
return NSBundle.mainBundle().bundleIdentifier ?? "?"
}
func ApplicationVersion() -> String {
return NSBundle.mainBundle().applicationVersion ?? "?"
}
func ApplicationBuild() -> String {
return NSBundle.mainBundle().applicationBuild ?? "?"
}
}
// MARK: - Locale/Time Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func Timestamp() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
return dateFormatter.stringFromDate(NSDate())
}
func SystemLocale() -> String {
return NSLocale.currentLocale().localeIdentifier
}
func Timezone() -> String {
return NSTimeZone.localTimeZone().name
}
}
// MARK: - Additional Info
@available(iOS 8.0, OSX 10.10, *)
private extension DiagnosticReportGenerator {
func BuildAdditionalAppInfoStringFromDictionary(info: [String: AnyObject]?) -> String {
guard let appInfo = info else { return "" }
var result = ""
for (key, value) in appInfo {
result += "\(key): \(value)\n"
}
return result
}
func UserDefaults() -> String {
return "\(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())"
}
}
// MARK: - NSBundle Convenience Methods
private extension NSBundle {
var applicationName: String? {
return objectForInfoDictionaryKey("CFBundleName") as? String
}
var applicationVersion: String? {
return objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
}
var applicationBuild: String? {
return objectForInfoDictionaryKey("CFBundleVersion") as? String
}
}
// MARK: HTML String
private extension String {
func htmlRepresentation() -> String {
var result = self.stringByReplacingOccurrencesOfString("&", withString: "&")
result = result.stringByReplacingOccurrencesOfString("<", withString: "<")
return result.stringByReplacingOccurrencesOfString(">", withString: ">") ?? ""
}
}
|
mit
|
de6513aff6cf9f74f1129c42fcecd838
| 30.8475 | 182 | 0.583013 | 5.184778 | false | false | false | false |
plushcube/Learning
|
Swift/Functional Swift Book/Diagrams.playground/Contents.swift
|
1
|
6483
|
//: Playground - noun: a place where people can play
import UIKit
enum Attribute {
case fillColor(UIColor)
}
enum Primitive {
case ellipse
case rectangle
case text(String)
}
indirect enum Diagram {
case primitive(CGSize, Primitive)
case beside(Diagram, Diagram)
case below(Diagram, Diagram)
case attributed(Attribute, Diagram)
case align(CGPoint, Diagram)
}
extension Diagram {
init() {
self = rect(width: 0.0, height: 0.0)
}
var size: CGSize {
switch self {
case .primitive(let size, _):
return size
case .attributed(_, let x), .align(_, let x):
return x.size
case .beside(let left, let right):
return CGSize(width: left.size.width + right.size.width, height: max(left.size.height, right.size.height))
case .below(let left, let right):
return CGSize(width: max(left.size.width, right.size.width), height: left.size.height + right.size.height)
}
}
func filled(_ color: UIColor) -> Diagram {
return .attributed(.fillColor(color), self)
}
func aligned(to position: CGPoint) -> Diagram {
return .align(position, self)
}
}
extension Sequence where Iterator.Element == Diagram {
var hcat: Diagram {
return reduce(Diagram(), |||)
}
}
extension CGSize {
func fit(into rect: CGRect, alignment: CGPoint) -> CGRect {
let scale = min(rect.width / width, rect.height / height)
let targetSize = scale * self
let spacerSize = alignment.size * (rect.size - targetSize)
return CGRect(origin: rect.origin + spacerSize.point, size: targetSize)
}
var point: CGPoint {
return CGPoint(x: width, y: height)
}
}
extension CGPoint {
var size: CGSize {
return CGSize(width: x, height: y)
}
static let bottom = CGPoint(x: 0.5, y: 1.0)
static let top = CGPoint(x: 0.5, y: 0.0)
static let center = CGPoint(x: 0.5, y: 0.5)
}
func * (scale: CGFloat, size: CGSize) -> CGSize {
return CGSize(width: size.width * scale, height: size.height * scale)
}
func * (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height)
}
func - (lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height)
}
func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
//let center = CGPoint(x: 0.5, y: 0.5)
//let target = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 100.0)
//CGSize(width: 1.0, height: 1.0).fit(into: target, alignment: center)
//let topLeft = CGPoint(x: 0.0, y: 0.0)
//CGSize(width: 1.0, height: 1.0).fit(into: target, alignment: topLeft)
extension CGRectEdge {
var isHorizontal: Bool {
return self == .maxXEdge || self == .minXEdge
}
}
extension CGRect {
func split(ratio: CGFloat, edge: CGRectEdge) -> (CGRect, CGRect) {
let length = edge.isHorizontal ? width : height
return divided(atDistance: length * ratio, from: edge)
}
}
extension CGContext {
func draw(_ primitive: Primitive, in frame: CGRect) {
switch primitive {
case .rectangle:
fill(frame)
case .ellipse:
fillEllipse(in: frame)
case .text(let text):
let font = UIFont.systemFont(ofSize: 12.0)
let attributes = [NSFontAttributeName: font]
let attributedText = NSAttributedString(string: text, attributes: attributes)
attributedText.draw(in: frame)
}
}
func draw(_ diagram: Diagram, in bounds: CGRect) {
switch diagram {
case .primitive(let size, let primitive):
let bounds = size.fit(into: bounds, alignment: .center)
draw(primitive, in: bounds)
case .align(let alignment, let diagram):
let bounds = diagram.size.fit(into: bounds, alignment: alignment)
draw(diagram, in: bounds)
case .beside(let lhs, let rhs):
let (lBounds, rBounds) = bounds.split(ratio: lhs.size.width / diagram.size.width, edge: .minXEdge)
draw(lhs, in: lBounds)
draw(rhs, in: rBounds)
case .below(let ths, let bhs):
let (tBounds, bBounds) = bounds.split(ratio: ths.size.height / diagram.size.height, edge: .minYEdge)
draw(ths, in: tBounds)
draw(bhs, in: bBounds)
case .attributed(.fillColor(let color), let diagram):
saveGState()
color.set()
draw(diagram, in: bounds)
restoreGState()
}
}
}
func rect(width: CGFloat, height: CGFloat) -> Diagram {
return .primitive(CGSize(width: width, height: height), .rectangle)
}
func circle(diameter: CGFloat) -> Diagram {
return .primitive(CGSize(width: diameter, height: diameter), .ellipse)
}
func square(side: CGFloat) -> Diagram {
return .primitive(CGSize(width: side, height: side), .rectangle)
}
func text(_ text: String, width: CGFloat, height: CGFloat) -> Diagram {
return .primitive(CGSize(width: width, height: height), .text(text))
}
precedencegroup VerticalCombination {
associativity: left
}
precedencegroup HorizontalCombination {
higherThan: VerticalCombination
associativity: left
}
infix operator |||: HorizontalCombination
infix operator ---: VerticalCombination
func ||| (lhs: Diagram, rhs: Diagram) -> Diagram {
return .beside(lhs, rhs)
}
func --- (lhs: Diagram, rhs: Diagram) -> Diagram {
return .below(lhs, rhs)
}
let bounds = CGRect(origin: .zero, size: CGSize(width: 300, height: 200))
let renderer = UIGraphicsImageRenderer(bounds: bounds)
renderer.image { context in
UIColor.blue.setFill()
context.fill(CGRect(x: 0.0, y: 37.5, width: 75.0, height: 75.0))
UIColor.red.setFill()
context.fill(CGRect(x: 75.0, y: 0.0, width: 150.0, height: 150.0))
UIColor.green.setFill()
context.cgContext.fillEllipse(in: CGRect(x: 225.0, y: 37.5, width: 75.0, height: 75.0))
}
let blueSquare = square(side: 1.0).filled(.blue)
let redSquare = square(side: 2.0).filled(.red)
let greenCircle = circle(diameter: 1.0).filled(.green)
let example1 = blueSquare ||| redSquare ||| greenCircle
let cyanCircle = circle(diameter: 1.0).filled(.cyan)
let example2 = blueSquare ||| cyanCircle ||| redSquare ||| greenCircle
renderer.image { context in
context.cgContext.draw(example2, in: bounds)
}
|
mit
|
e992768b7159880d83531def394e9e8e
| 28.875576 | 118 | 0.630418 | 3.625839 | false | false | false | false |
LouisLWang/curly-garbanzo
|
weibo-swift/Classes/Module/Main/Controller/LWMainViewController.swift
|
1
|
2645
|
//
// LWMainViewController.swift
// weibo-swift
//
// Created by Louis on 10/27/15.
// Copyright © 2015 louis. All rights reserved.
//
import UIKit
class LWMainViewController: UITabBarController {
func composeButtonClick() {
print(__FUNCTION__)
}
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = UIColor.orangeColor()
let homeVC = LWHomeViewController()
self.addChildViewController(homeVC, title: "首页", imageName: "tabbar_home")
let messageVC = LWMessageViewController()
self.addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center")
let controller = UIViewController()
self.addChildViewController(controller, title: "", imageName: "abc")
let discoverVC = LWDiscoverViewController()
self.addChildViewController(discoverVC, title: "发现", imageName: "tabbar_discover")
let profileVC = LWProfileViewController()
self.addChildViewController(profileVC, title: "我", imageName: "tabbar_profile")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func addChildViewController(controller: UIViewController, title: String, imageName: String) {
controller.title = title
controller.tabBarItem.image = UIImage(named: imageName)
addChildViewController(UINavigationController(rootViewController: controller))
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let width = tabBar.bounds.width / CGFloat(5)
composeButton.frame = CGRect(x: width * 2, y: 0, width: width, height: tabBar.bounds.height)
tabBar.addSubview(composeButton)
}
lazy var composeButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
|
apache-2.0
|
b24a6df5e26b0596076149e739656301
| 32.291139 | 124 | 0.660456 | 5.228628 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/TakeOrder/器械信息/Model/OMSBrandViewModel.swift
|
1
|
17457
|
//
// OMSBrandViewModel.swift
// OMS-WH
//
// Created by xuech on 2017/9/14.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
import ObjectMapper
class OMSBrandViewModel: NSObject {
func checkMaterialInKit(paramters:[String:Any],_ finished: @escaping (_ data: [String:Any],_ error: NSError?)->Void) {
XCHRefershUI.show()
let api = "oms-api-v3/businessData/medicalDevice/checkMaterialInKit"
moyaNetWork.request(.commonRequst(paramters: paramters, api: api)) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
finished(data,nil)
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
func queryKitInventory(paramters:[String:Any],_ finished: @escaping (_ data: [[String : AnyObject]],_ error: NSError?)->Void) {
InventoryNetWork.request(.commonRequest(api: "oms-api-v3/businessData/medicalDevice/queryKitInventory", paramters: paramters)) { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [[String : AnyObject]]{
finished(resultValue,nil)
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
func requestKitData(oIOrgCode:String, _ finished: @escaping (_ data: [KitModel],_ error: NSError?)->Void) {
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: ["oIOrgCode":oIOrgCode], api: "oms-api-v3/businessData/medicalDevice/kitList")) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [String : AnyObject]{
if let res = resultValue["list"] as? [[String : AnyObject]]{
let kitsModels = Mapper<KitModel>().mapArray(JSONArray: res)
// var kitsModels = [KitModel]()
// for dict in res{
// kitsModels.append(KitModel.parse(dict: dict as NSDictionary))
// }
finished(kitsModels,nil)
}
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
func requestData(soNo:String,api:String, _ finished: @escaping (_ data: [OMSOrderMetailsModel]?,_ error: NSError?)->Void) {
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: ["soNo":soNo],api:api)) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [[String : AnyObject]]{
var orderMetailsModels = [OMSOrderMetailsModel]()
for dict in resultValue{
orderMetailsModels.append(OMSOrderMetailsModel(dict: dict))
}
finished(orderMetailsModels,nil)
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
//转换模糊和精确订单返回的物料数据
func changeData(data:[OMSOrderMetailsModel]) -> [TempleBrandModel]{
var brands = [TempleBrandModel]()
let filterBrands = data.filterDuplicates({$0.medBrandCode})
for item in filterBrands{
let brand = TempleBrandModel()
brand.medBrandCode = item.medBrandCode
brand.medBrandName = item.medBrandName
brands.append(brand)
}
var dataSoure = [TempleBrandModel]()
for item in brands{
var medprolns = [TempleProlns]()
let prolns = data.filter({$0.medBrandCode == item.medBrandCode})
for item2 in prolns{
let proln = TempleProlns()
proln.medProdLnCodeWithTool = item2.medProdLnCodeWithTool
proln.medProdLnCode = item2.medProdLnCode
proln.diseaseInfo = item2.diseaseInfo
proln.medProdLnName = item2.medProdLnName
proln.medProdLnCodeWithToolName = item2.medProdLnCodeWithToolName ?? ""
proln.remark = item2.remark
proln.medMaterialList = item2.medMaterialList
// print(proln)
medprolns.append(proln)
}
let a = TempleBrandModel()
a.medBrandCode = item.medBrandCode
a.medBrandName = item.medBrandName
a.prolns = medprolns
dataSoure.append(a)
}
MedLog(message: dataSoure)
return dataSoure
}
func notificationData(dictoryArray:[[String:AnyObject]],templeData:[TempleBrandModel]) -> [TempleBrandModel]? {
var medBrandCode = false
var prdouctLines = templeData
MedLog(message: dictoryArray)
for dictory in dictoryArray {
for prdouctLine in prdouctLines {
//存在相同的品牌
if dictory["medBrandCode"] as? String == prdouctLine.medBrandCode {
medBrandCode = true
var medProdLnCode = false
guard var prolns = prdouctLine.prolns else { return nil }
for proln in prolns {
if dictory["medProdLnCode"] as? String == proln.medProdLnCode{
medProdLnCode = true
}
}
if !medProdLnCode {
let proln = TempleProlns()
proln.medProdLnCode = dictory["medProdLnCode"] as! String
proln.medProdLnName = dictory["medProdLnName"] as! String
proln.medProdLnCodeWithTool = "Y"
proln.diseaseInfo = ""
proln.medProdLnCodeWithToolName = "配工具"
proln.remark = ""
proln.medMaterialList = [MedMaterialList]()
prolns.append(proln)
MedLog(message: prolns)
}
prdouctLine.prolns = prolns
}
}
if !medBrandCode {
let brand = TempleBrandModel()
brand.medBrandCode = dictory["medBrandCode"] as! String
brand.medBrandName = dictory["medBrandName"] as! String
var prolns = [TempleProlns]()
let proln = TempleProlns()
proln.medProdLnCode = dictory["medProdLnCode"] as! String
proln.medProdLnName = dictory["medProdLnName"] as! String
proln.medProdLnCodeWithTool = "Y"
proln.diseaseInfo = ""
proln.medProdLnCodeWithToolName = "配工具"
proln.remark = ""
proln.medMaterialList = [MedMaterialList]()
prolns.append(proln)
brand.prolns = prolns
prdouctLines.append(brand)
}
}
return prdouctLines
}
// func templateNotificationData(medMaterialList:[MedMaterialList],templeData:[TempleBrandModel]) -> [TempleBrandModel]?{
//
//
// }
func templateNotificationData(medMaterialList:[MedMaterialList],orialData:[TempleBrandModel]) -> [TempleBrandModel]? {
var prdouctLines = orialData
if orialData.count == 0 {
let brandsArray = medMaterialList.filterDuplicates({$0.medBrandCode})
var dataSoure = [TempleBrandModel]()
for brand in brandsArray{
let templeBrand = TempleBrandModel()
templeBrand.medBrandCode = brand.medBrandCode
templeBrand.medBrandName = brand.medBrandName
var medprolns = [TempleProlns]()
let bs = medMaterialList.filter({$0.medBrandCode == brand.medBrandCode})
let prolns = bs.filterDuplicates({$0.medProdLnCode})
for proln in prolns{
let templeProln = TempleProlns()
templeProln.medProdLnCode = proln.medProdLnCode
templeProln.medProdLnName = proln.medProdLnName
let list = medMaterialList.filter({$0.medProdLnCode == proln.medProdLnCode && $0.medBrandCode == proln.medBrandCode})
templeProln.medMaterialList = list
medprolns.append(templeProln)
}
templeBrand.prolns = medprolns
dataSoure.append(templeBrand)
}
prdouctLines = dataSoure
}else{
for material in medMaterialList {
let templeBrandArray = prdouctLines.filter({$0.medBrandName == material.medBrandName})
if templeBrandArray.count > 0 {
//存在相同的品牌
for templeProln in templeBrandArray{
let templeProlnsArray = templeProln.prolns.filter({$0.medProdLnCode == material.medProdLnCode})
if templeProlnsArray.count > 0 {
//存在相同的产品线
for templeProln in templeProlnsArray {
var materialCode = false
guard let templeMedMaterialList = templeProln.medMaterialList else { return nil }
for templeMedMaterial in templeMedMaterialList {
//存在相同的物料
if material.medMIInternalNo == templeMedMaterial.medMIInternalNo {
materialCode = true
let addCount = Int(truncating: material.reqQty) + Int(truncating: templeMedMaterial.reqQty)
templeMedMaterial.reqQty = NSNumber.init(value: addCount)
}
}
if !materialCode {
if let _ = templeProln.medMaterialList {
templeProln.medMaterialList!.append(material)
break
}
}
}
}else{
let proln = TempleProlns()
proln.medProdLnCode = material.medProdLnCode
proln.medProdLnName = material.medProdLnName
proln.remark = material.remark
proln.medMaterialList = [material]
MedLog(message: proln)
templeProln.prolns.append(proln)
}
}
}else{
let material = filterMedMaterialListModel(kitProdLnsModel: material)
prdouctLines.append(material)
}
}
}
return prdouctLines
}
private func filterMedMaterialListModel(kitProdLnsModel: MedMaterialList) -> TempleBrandModel{
let templeBrand = TempleBrandModel()
templeBrand.medBrandCode = kitProdLnsModel.medBrandCode
templeBrand.medBrandName = kitProdLnsModel.medBrandName
let templeProln = TempleProlns()
templeProln.medProdLnCode = kitProdLnsModel.medProdLnCode
templeProln.medProdLnName = kitProdLnsModel.medProdLnName
templeProln.medMaterialList = [kitProdLnsModel]
templeBrand.prolns = [templeProln]
return templeBrand
}
//请求模版、套件详情数据
func requestKitProdLnsData(withParamters paramters:[String:Any] ,_ api : String, _ finished: @escaping (_ data: [TempleBrandModel],_ error: NSError?)->Void){
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: paramters, api: api)) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [String : AnyObject]{
if let prolns = resultValue["prodLns"] as? [[String : AnyObject]] {
var childs = [KitProdLnsModel]()
for proln in prolns {
childs.append(KitProdLnsModel(dict:proln))
}
let filterBrand = self.filterKitModel(kitProdLnsModel: childs)
finished(filterBrand,nil)
}
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
private func filterKitModel(kitProdLnsModel: [KitProdLnsModel]) -> [TempleBrandModel]{
var brands = [TempleBrandModel]()
for kitProdLn in kitProdLnsModel{
if brands.count > 0{
var isexist = false
for item2 in brands{
if item2.medBrandCode == kitProdLn.medBrandCode {
isexist = true
}
}
if !isexist{
let brand = TempleBrandModel()
brand.medBrandCode = kitProdLn.medBrandCode
brand.medBrandName = kitProdLn.medBrandName
brands.append(brand)
}
}else{
let brand = TempleBrandModel()
brand.medBrandCode = kitProdLn.medBrandCode
brand.medBrandName = kitProdLn.medBrandName
brands.append(brand)
}
}
var dataSoure = [TempleBrandModel]()
for brand in brands{
var medprolns = [TempleProlns]()
let prolns = kitProdLnsModel.filter({$0.medBrandCode == brand.medBrandCode})
for proln in prolns{
let templeProln = TempleProlns()
templeProln.medProdLnCode = proln.medProdLnCode
templeProln.medProdLnName = proln.medProdLnName
templeProln.medMaterialList = proln.materials
medprolns.append(templeProln)
}
let templeBrand = TempleBrandModel()
templeBrand.medBrandCode = brand.medBrandCode
templeBrand.medBrandName = brand.medBrandName
templeBrand.prolns = medprolns
dataSoure.append(templeBrand)
}
MedLog(message: dataSoure)
return dataSoure
}
}
|
mit
|
d1c3fa561a27cb950891674699e7e0fd
| 43.282051 | 161 | 0.504574 | 5.042336 | false | false | false | false |
sstanic/Shopfred
|
Shopfred/Shopfred/View Controller/ItemsListViewController.swift
|
1
|
4773
|
//
// ItemsListViewController.swift
// Shopfred
//
// Created by Sascha Stanic on 6/24/17.
// Copyright © 2017 Sascha Stanic. All rights reserved.
//
import UIKit
import CoreData
/**
Shows a list of items in a shopping list.
The view controller is used by the **SearchItemViewController** to
show the list of items in the currently selected shopping list.
*/
class ItemsListViewController: UIViewController {
// MARK: - Private Attributes
private var fetchedResultsController: NSFetchedResultsController<Item>!
private var tableView: UITableView!
convenience init() {
self.init(nibName:nil, bundle:nil)
}
convenience init(shoppingList: ShoppingList?, tableView: UITableView) {
self.init()
if let shoppingList = shoppingList {
self.fetchedResultsController = ShoppingListItemsDataSource(shoppingList: shoppingList, delegate: nil).fetchedResultsController
self.fetchedResultsController.delegate = self
}
self.tableView = tableView
self.tableView.dataSource = self
self.tableView.delegate = self
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension ItemsListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "addItemTableViewCell", for: indexPath) as! AddItemTableViewCell
guard let object = self.fetchedResultsController?.object(at: indexPath)
else {
return cell
}
if let txtLbl = cell.textLabel {
txtLbl.text = object.name
}
cell.setStyle()
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = self.fetchedResultsController?.sections
else {
return 0
}
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
func numberOfSections(in tableView: UITableView) -> Int {
guard let sections = self.fetchedResultsController?.sections
else {
return 0
}
return sections.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let sectionInfo = self.fetchedResultsController?.sections?[section]
else {
return nil
}
return sectionInfo.name
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
if let bckgrView = header.backgroundView {
bckgrView.backgroundColor = UIColor.clear
}
}
}
// MARK: - NSFetchedResultsControllerDelegate
extension ItemsListViewController : NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
case .delete:
self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic)
break
case .move:
break
case .update:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .update:
self.tableView.reloadRows(at: [indexPath!], with: .automatic)
case .insert:
self.tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .delete:
self.tableView.deleteRows(at: [indexPath!], with: .automatic)
case .move:
self.tableView.deleteRows(at: [indexPath!], with: .automatic)
self.tableView.insertRows(at: [indexPath!], with: .automatic)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.endUpdates()
}
}
|
mit
|
043a9d52a4b256d7173d42abb459e091
| 28.825 | 209 | 0.639983 | 5.884094 | false | false | false | false |
bhajian/raspi-remote
|
Carthage/Checkouts/ios-sdk/Source/SpeechToTextV1/SpeechToText.swift
|
1
|
7364
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import AVFoundation
import RestKit
/**
The IBM Watson Speech to Text service enables you to add speech transcription capabilities to
your application. It uses machine intelligence to combine information about grammar and language
structure to generate an accurate transcription. Transcriptions are supported for various audio
formats and languages.
*/
public class SpeechToText {
private let restToken: RestToken
private let websocketsURL: String
private let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1"
/**
Create a `SpeechToText` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter serviceURL: The base URL of the Speech to Text service.
- parameter tokenURL: The URL that shall be used to obtain a token.
- parameter websocketsURL: The URL that shall be used to stream audio for transcription.
*/
public init(
username: String,
password: String,
serviceURL: String = "https://stream.watsonplatform.net/speech-to-text/api",
tokenURL: String = "https://stream.watsonplatform.net/authorization/api/v1/token",
websocketsURL: String = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize")
{
self.restToken = RestToken(
tokenURL: tokenURL + "?url=" + serviceURL,
username: username,
password: password
)
self.websocketsURL = websocketsURL
}
/** A function that, when executed, stops streaming audio to Speech to Text. */
public typealias StopStreaming = Void -> Void
/**
Transcribe an audio file.
- parameter file: The audio file to transcribe.
- parameter settings: The configuration for this transcription request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func transcribe(
file: NSURL,
settings: TranscriptionSettings,
failure: (NSError -> Void)? = nil,
success: [TranscriptionResult] -> Void)
{
guard let audio = NSData(contentsOfURL: file) else {
let failureReason = "Could not load audio data from \(file)."
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
transcribe(audio, settings: settings, failure: failure, success: success)
}
/**
Transcribe audio data.
- parameter audio: The audio data to transcribe.
- parameter settings: The configuration for this transcription request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func transcribe(
audio: NSData,
settings: TranscriptionSettings,
failure: (NSError -> Void)? = nil,
success: [TranscriptionResult] -> Void)
{
guard let socket = SpeechToTextWebSocket(
websocketsURL: websocketsURL,
restToken: restToken,
settings: settings,
failure: failure,
success: success) else { return }
do {
let start = try settings.toJSON().serializeString()
let stop = try TranscriptionStop().toJSON().serializeString()
socket.connect()
socket.writeString(start)
socket.writeData(audio)
socket.writeString(stop)
socket.disconnect()
} catch {
let failureReason = "Failed to serialize start and stop instructions to JSON."
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
}
/**
Stream audio from the microphone to the Speech to Text service. The microphone will stop
recording after an end-of-speech event is detected by the Speech to Text service or the
returned function is executed.
- parameter settings: The configuration for this transcription request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
- returns: A function that, when executed, stops streaming audio to Speech to Text.
*/
public func transcribe(
settings: TranscriptionSettings,
failure: (NSError -> Void)? = nil,
success: [TranscriptionResult] -> Void)
-> StopStreaming
{
guard let audioStreamer = SpeechToTextAudioStreamer(
websocketsURL: websocketsURL,
restToken: restToken,
settings: settings,
failure: failure,
success: success) else { return { } }
guard audioStreamer.startStreaming() else {
audioStreamer.stopStreaming()
return { }
}
return audioStreamer.stopStreaming
}
/**
Create an `AVCaptureAudioDataOutput` that streams audio to the Speech to Text service.
- parameter settings: The configuration for this transcription request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
- returns: A tuple with two elements. The first element is an `AVCaptureAudioDataOutput` that
streams audio to the Speech to Text service when set as the output of an `AVCaptureSession`.
The second element is a function that, when executed, stops streaming to Speech to Text.
*/
public func createTranscriptionOutput(
settings: TranscriptionSettings,
failure: (NSError -> Void)? = nil,
success: [TranscriptionResult] -> Void)
-> (AVCaptureAudioDataOutput, StopStreaming)?
{
guard let audioStreamer = SpeechToTextAudioStreamer(
websocketsURL: websocketsURL,
restToken: restToken,
settings: settings,
failure: failure,
success: success) else { return nil }
audioStreamer.startRecognitionRequest()
return (audioStreamer.createTranscriptionOutput(), audioStreamer.stopRecognitionRequest)
}
}
|
mit
|
289765225a47d96e740c131c5811ebf5
| 39.240437 | 100 | 0.670288 | 5.160477 | false | false | false | false |
ParsePlatform/Parse-SDK-iOS-OSX
|
ParseUI/ParseUIDemo/Swift/CustomViewControllers/QueryTableViewController/SectionedTableViewController.swift
|
1
|
3216
|
/*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
import UIKit
import Parse
import ParseUI
class SectionedTableViewController: PFQueryTableViewController {
var sections: [Int: [PFObject]] = Dictionary()
var sectionKeys: [Int] = Array()
// MARK: Init
convenience init(className: String?) {
self.init(style: .plain, className: className)
title = "Sectioned Table"
pullToRefreshEnabled = true
}
// MARK: Data
override func objectsDidLoad(_ error: Error?) {
super.objectsDidLoad(error)
sections.removeAll(keepingCapacity: false)
if let objects = objects {
for object in objects {
let priority = (object["priority"] as? Int) ?? 0
var array = sections[priority] ?? Array()
array.append(object)
sections[priority] = array
}
}
sectionKeys = sections.keys.sorted(by: <)
tableView.reloadData()
}
override func object(at indexPath: IndexPath?) -> PFObject? {
if let indexPath = indexPath {
let array = sections[sectionKeys[indexPath.section]]
return array?[indexPath.row]
}
return nil
}
}
extension SectionedTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let array = sections[sectionKeys[section]]
return array?.count ?? 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Priority \(sectionKeys[section])"
}
override func tableView(_ tableView: UITableView, cellForRowAt: IndexPath, object: PFObject?) -> PFTableViewCell? {
let cellIdentifier = "cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? PFTableViewCell
if cell == nil {
cell = PFTableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
cell?.textLabel?.text = object?["title"] as? String
return cell
}
}
|
bsd-3-clause
|
fe189d3991a8c3a26e758dcf9324d99c
| 32.154639 | 119 | 0.670087 | 4.694891 | false | false | false | false |
Foild/TextDrawer
|
TextDrawer/TextDrawer/TextEditView.swift
|
2
|
4624
|
//
// TextEditView.swift
//
//
// Created by Remi Robert on 11/07/15.
//
//
import UIKit
import Masonry
protocol TextEditViewDelegate {
func textEditViewFinishedEditing(text: String)
}
public class TextEditView: UIView {
private var textView: UITextView!
private var textContainer: UIView!
public var topOffset: CGFloat = 0 {
didSet {
self.updateTextTopOffset()
}
}
var delegate: TextEditViewDelegate?
var textSize: Int! = 42
var textEntry: String! {
set {
textView.text = newValue
}
get {
return textView.text
}
}
var isEditing: Bool! {
didSet {
if isEditing == true {
textContainer.hidden = false;
userInteractionEnabled = true;
backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.65)
textView.becomeFirstResponder()
}
else {
backgroundColor = UIColor.clearColor()
textView.resignFirstResponder()
textContainer.hidden = true;
userInteractionEnabled = false;
delegate?.textEditViewFinishedEditing(textView.text)
}
}
}
init() {
super.init(frame: CGRectZero)
isEditing = false
textContainer = UIView()
textContainer.layer.masksToBounds = true
addSubview(textContainer)
textContainer.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in
make.edges.equalTo()(self)
}
textView = UITextView()
textView.tintColor = UIColor.whiteColor()
textView.font = UIFont.systemFontOfSize(44)
textView.textColor = UIColor.whiteColor()
textView.backgroundColor = UIColor.clearColor()
textView.returnKeyType = UIReturnKeyType.Done
textView.clipsToBounds = true
textView.delegate = self
textContainer.addSubview(textView)
textView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in
make.left.equalTo()(self.textContainer)
make.right.equalTo()(self.textContainer)
make.bottom.equalTo()(self.textContainer)
make.top.equalTo()(self.textContainer).offset()(self.topOffset)
}
textContainer.hidden = true
userInteractionEnabled = false
keyboardNotification()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func updateTextTopOffset() {
textView.mas_updateConstraints { (make: MASConstraintMaker!) -> Void in
make.top.equalTo()(self.textContainer).offset()(self.topOffset)
}
}
}
extension TextEditView: UITextViewDelegate {
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
isEditing = false
return false
}
if textView.text.characters.count + text.characters.count > textSize {
return false
}
return true
}
}
extension TextEditView {
func keyboardNotification() {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) { (notification: NSNotification) -> Void in
if let userInfo = notification.userInfo {
self.textContainer.layer.removeAllAnimations()
if let keyboardRectEnd = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey]?.floatValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.textContainer.mas_updateConstraints({ (make: MASConstraintMaker!) -> Void in
make.bottom.offset()(-CGRectGetHeight(keyboardRectEnd))
})
UIView.animateWithDuration(NSTimeInterval(duration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
self.textContainer.layoutIfNeeded()
}, completion: nil)
})
}
}
}
}
}
|
mit
|
14a02b7015d3a2ccd1ae62b776a2edf2
| 31.56338 | 173 | 0.582396 | 5.794486 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Post/PostEditorNavigationBarManager.swift
|
1
|
7607
|
import Gridicons
protocol PostEditorNavigationBarManagerDelegate: AnyObject {
var publishButtonText: String { get }
var isPublishButtonEnabled: Bool { get }
var uploadingButtonSize: CGSize { get }
var savingDraftButtonSize: CGSize { get }
func navigationBarManager(_ manager: PostEditorNavigationBarManager, closeWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, moreWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, blogPickerWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, publishButtonWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, displayCancelMediaUploads sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, reloadTitleView view: UIView)
}
// A class to share the navigation bar UI of the Post Editor.
// Currenly shared between Aztec and Gutenberg
//
class PostEditorNavigationBarManager {
weak var delegate: PostEditorNavigationBarManagerDelegate?
// MARK: - Buttons
/// Dismiss Button
///
lazy var closeButton: WPButtonForNavigationBar = {
let cancelButton = WPStyleGuide.buttonForBar(with: Assets.closeButtonModalImage, target: self, selector: #selector(closeWasPressed))
cancelButton.leftSpacing = Constants.cancelButtonPadding.left
cancelButton.rightSpacing = Constants.cancelButtonPadding.right
cancelButton.setContentHuggingPriority(.required, for: .horizontal)
cancelButton.accessibilityIdentifier = "editor-close-button"
return cancelButton
}()
private lazy var moreButton: UIButton = {
let image = UIImage.gridicon(.ellipsis)
let button = UIButton(type: .system)
button.setImage(image, for: .normal)
button.frame = CGRect(origin: .zero, size: image.size)
button.accessibilityLabel = NSLocalizedString("More Options", comment: "Action button to display more available options")
button.accessibilityIdentifier = "more_post_options"
button.addTarget(self, action: #selector(moreWasPressed), for: .touchUpInside)
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
/// Blog Picker's Button
///
lazy var blogPickerButton: WPBlogSelectorButton = {
let button = WPBlogSelectorButton(frame: .zero, buttonStyle: .typeSingleLine)
button.addTarget(self, action: #selector(blogPickerWasPressed), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.setContentHuggingPriority(.defaultLow, for: .horizontal)
return button
}()
/// Blog TitleView Label
lazy var blogTitleViewLabel: UILabel = {
let label = UILabel()
label.textColor = .appBarText
label.font = Fonts.blogTitle
return label
}()
/// Publish Button
private(set) lazy var publishButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(publishButtonTapped(sender:)), for: .touchUpInside)
button.setTitle(delegate?.publishButtonText ?? "", for: .normal)
button.sizeToFit()
button.isEnabled = delegate?.isPublishButtonEnabled ?? false
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
/// Media Uploading Button
///
private lazy var mediaUploadingButton: WPUploadStatusButton = {
let button = WPUploadStatusButton(frame: CGRect(origin: .zero, size: delegate?.uploadingButtonSize ?? .zero))
button.setTitle(NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server"), for: .normal)
button.addTarget(self, action: #selector(displayCancelMediaUploads), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.setContentHuggingPriority(.defaultLow, for: .horizontal)
return button
}()
/// Preview Generating Button
///
private lazy var previewGeneratingView: LoadingStatusView = {
let view = LoadingStatusView(title: NSLocalizedString("Generating Preview", comment: "Message to indicate progress of generating preview"))
return view
}()
// MARK: - Bar button items
/// Negative Offset BarButtonItem: Used to fine tune navigationBar Items
///
private lazy var separatorButtonItem: UIBarButtonItem = {
let separator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
return separator
}()
/// NavigationBar's Close Button
///
lazy var closeBarButtonItem: UIBarButtonItem = {
let cancelItem = UIBarButtonItem(customView: self.closeButton)
cancelItem.accessibilityLabel = NSLocalizedString("Close", comment: "Action button to close edior and cancel changes or insertion of post")
cancelItem.accessibilityIdentifier = "Close"
return cancelItem
}()
/// Publish Button
private(set) lazy var publishBarButtonItem: UIBarButtonItem = {
let button = UIBarButtonItem(customView: self.publishButton)
return button
}()
/// NavigationBar's More Button
///
lazy var moreBarButtonItem: UIBarButtonItem = {
let moreItem = UIBarButtonItem(customView: self.moreButton)
return moreItem
}()
// MARK: - Selectors
@objc private func closeWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, closeWasPressed: sender)
}
@objc private func moreWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, moreWasPressed: sender)
}
@objc private func blogPickerWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, blogPickerWasPressed: sender)
}
@objc private func publishButtonTapped(sender: UIButton) {
delegate?.navigationBarManager(self, publishButtonWasPressed: sender)
}
@objc private func displayCancelMediaUploads(sender: UIButton) {
delegate?.navigationBarManager(self, displayCancelMediaUploads: sender)
}
// MARK: - Public
var leftBarButtonItems: [UIBarButtonItem] {
return [separatorButtonItem, closeBarButtonItem]
}
var uploadingMediaTitleView: UIView {
mediaUploadingButton
}
var generatingPreviewTitleView: UIView {
previewGeneratingView
}
var rightBarButtonItems: [UIBarButtonItem] {
return [moreBarButtonItem, publishBarButtonItem, separatorButtonItem]
}
func reloadPublishButton() {
publishButton.setTitle(delegate?.publishButtonText ?? "", for: .normal)
publishButton.sizeToFit()
publishButton.isEnabled = delegate?.isPublishButtonEnabled ?? true
}
func reloadBlogTitleView(text: String) {
blogTitleViewLabel.text = text
}
func reloadTitleView(_ view: UIView) {
delegate?.navigationBarManager(self, reloadTitleView: view)
}
}
extension PostEditorNavigationBarManager {
private enum Constants {
static let cancelButtonPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5)
}
private enum Fonts {
static let semiBold = WPFontManager.systemSemiBoldFont(ofSize: 16)
static var blogTitle: UIFont {
WPStyleGuide.navigationBarStandardFont
}
}
private enum Assets {
static let closeButtonModalImage = UIImage.gridicon(.cross)
}
}
|
gpl-2.0
|
cab02ff3dec86bbe87b29d4603c1208d
| 37.419192 | 147 | 0.70961 | 5.297354 | false | false | false | false |
appnexus/mobile-sdk-ios
|
examples/Swift/SimpleIntegration/SimpleIntegrationSwift/MultiAdRequest/MultiAdViewController.swift
|
1
|
5755
|
/* Copyright 2020 APPNEXUS INC
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 AppNexusSDK
import UIKit
class MultiAdViewController: UITableViewController , ANMultiAdRequestDelegate , ANBannerAdViewDelegate , ANInstreamVideoAdPlayDelegate , ANInterstitialAdDelegate , ANNativeAdRequestDelegate , ANNativeAdDelegate , ANInstreamVideoAdLoadDelegate {
var bannerAd: ANBannerAdView?
var interstitialAd: ANInterstitialAd?
var videoAd = ANInstreamVideoAd()
var nativeAdRequest: ANNativeAdRequest?
var nativeAdResponse: ANNativeAdResponse?
var marAdRequest: ANMultiAdRequest?
@IBOutlet weak var bannerAdView: UIView!
@IBOutlet weak var videoAdView: UIView!
@IBOutlet weak var nativeAdView: UIView!
@IBOutlet weak var nativeIconImageView: UIImageView!
@IBOutlet weak var nativeMainImageView: UIImageView!
@IBOutlet weak var nativeTitleLabel: UILabel!
@IBOutlet weak var nativeBodyLabel: UILabel!
@IBOutlet weak var nativesponsoredLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Multi Ad Request"
// Init ANMultiAdRequest
marAdRequest = ANMultiAdRequest(memberId: 10094, andDelegate: self as ANMultiAdRequestDelegate)
// Add Ad Units
marAdRequest?.addAdUnit(createBannerAd(adView: bannerAdView))
marAdRequest?.addAdUnit(createVideoAd(adView: videoAdView))
marAdRequest?.addAdUnit(createInterstitialAd())
marAdRequest?.addAdUnit(createNativeAd())
// Load Ad Units
marAdRequest?.load()
}
// Create InstreamVideo Ad Object
func createVideoAd(adView : UIView) -> ANInstreamVideoAd {
videoAd = ANInstreamVideoAd(placementId: "17058950")
videoAd.loadDelegate = self
return videoAd
}
// Create Interstitial Ad Object
func createInterstitialAd() -> ANInterstitialAd{
interstitialAd = ANInterstitialAd(placementId: "17058950")
interstitialAd!.delegate = self
return interstitialAd!
}
// Create Native Ad Object
func createNativeAd() -> ANNativeAdRequest{
nativeAdRequest = ANNativeAdRequest()
nativeAdRequest!.placementId = "17058950"
nativeAdRequest!.shouldLoadIconImage = true
nativeAdRequest!.shouldLoadMainImage = true
nativeAdRequest!.delegate = self
return nativeAdRequest!
}
// Create Banner Ad Object
func createBannerAd(adView : UIView) -> ANBannerAdView {
// Needed for when we create our ad view.
let size = CGSize(width: 320, height: 50)
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: self.bannerAdView.frame.size.width , height: self.bannerAdView.frame.size.height))
// Make a banner ad view.
self.bannerAd = ANBannerAdView(frame: rect, placementId: "17058950", adSize: size)
self.bannerAd!.rootViewController = self
self.bannerAd!.delegate = self
self.bannerAd!.shouldResizeAdToFitContainer = true
bannerAdView.addSubview(self.bannerAd!)
return self.bannerAd!
}
// MARK: - ANMultiAdRequest Delegate
func multiAdRequestDidComplete(_ mar: ANMultiAdRequest) {
print("Multi Ad Request Did Complete")
}
func multiAdRequest(_ mar: ANMultiAdRequest, didFailWithError error: Error) {
print("MultiAdRequest failed with error : \(error)")
}
// MARK: - Ad Delegate
func adDidReceiveAd(_ ad: Any) {
if(ad is ANInstreamVideoAd){
print("Video Ad did Receive");
videoAd.play(withContainer: videoAdView, with: self)
}else if(ad is ANInterstitialAd && interstitialAd!.isReady){
print("Interstitial Ad did Receive");
interstitialAd!.display(from: self)
}else if(ad is ANBannerAdView) {
print("Banner Ad did Receive");
}
}
func ad(_ ad: Any, requestFailedWithError error: Error) {
print("requestFailedWithError \(error)")
}
// Native Ad delegate
func adRequest(_ request: ANNativeAdRequest, didReceive response: ANNativeAdResponse) {
print("Native Ad did Receive");
self.nativeAdResponse = response
self.nativeIconImageView.image = nativeAdResponse?.iconImage
self.nativeMainImageView.image = nativeAdResponse?.mainImage
self.nativeTitleLabel.text = nativeAdResponse?.title
self.nativeBodyLabel.text = nativeAdResponse?.body
self.nativesponsoredLabel.text = nativeAdResponse?.sponsoredBy
do {
try nativeAdResponse?.registerView(forTracking: nativeAdView!, withRootViewController: self, clickableViews: [ nativeAdView! as Any])
} catch {
print("Failed to registerView for Tracking")
}
}
func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error, with adResponseInfo: ANAdResponseInfo?) {
print("requestFailedWithError \(error)")
}
func adDidComplete(_ ad: ANAdProtocol, with state: ANInstreamVideoPlaybackStateType) {
print("Video Ad did Complete")
}
}
|
apache-2.0
|
15e554d47d9c03684a2e8fde84681c99
| 36.129032 | 247 | 0.684101 | 4.799833 | false | false | false | false |
AdaptiveMe/adaptive-arp-darwin
|
adaptive-arp-rt/AdaptiveArpRtiOS/NavigationProperties.swift
|
1
|
1924
|
/*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 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 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.
*
* 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]>
*
* =====================================================================================================================
*/
import Foundation
import AdaptiveArpApi
class NavigationProperties {
/// Navigation property fields
var navigationBarHidden : Bool = false
var navigationBarTitle : String = "Browser"
var navigationBarBackLabel : String = "Back"
var navigationUrl : NSURL?
/// Default constructor
init(navigationBarHidden: Bool, navigationBarTitle: String, navigationBarBackLabel: String, navigationUrl: NSURL) {
self.navigationBarHidden = navigationBarHidden
self.navigationBarTitle = navigationBarTitle
self.navigationBarBackLabel = navigationBarBackLabel
self.navigationUrl = navigationUrl
}
}
|
apache-2.0
|
40818c352e816eb678953bb22d7fd146
| 37.5 | 119 | 0.614865 | 4.834171 | false | false | false | false |
cseduardorangel/Cantina
|
Cantina/Class/Cell/ProductCell.swift
|
1
|
2253
|
//
// ProductCell.swift
// Cantina
//
// Created by Eduardo Rangel on 8/26/15.
// Copyright © 2015 Concrete Solutions. All rights reserved.
//
import UIKit
protocol ProductCellDelegate {
func addProductToBuy(product:Product)
func removeProductToBuy(product:Product)
}
class ProductCell: UITableViewCell {
@IBOutlet weak var buttonAddProduct: UIButton!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var productPriceLabel: UILabel!
@IBOutlet weak var productQuantityLabel: UILabel!
var product:Product!
var delegate:ProductCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configureCell(product:Product, delegate:ProductCellDelegate) {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "pt_BR")
self.buttonAddProduct.layer.cornerRadius = buttonAddProduct.frame.size.width / 2
self.buttonAddProduct.clipsToBounds = true
self.productPriceLabel.text = formatter.stringFromNumber(product.price)
self.productNameLabel?.text = product.name
self.delegate = delegate
self.product = product
}
@IBAction func decreaseProduct(sender: AnyObject) {
if self.productQuantityLabel.text == "0" {
return
}
var productQuantity = Int(self.productQuantityLabel.text!)
print("\(productQuantity!--)")
self.productQuantityLabel.text = "\(productQuantity!--)"
self.delegate?.removeProductToBuy(self.product)
}
@IBAction func increaseProduct(sender: AnyObject) {
if self.productQuantityLabel.text == "10" {
return
}
var productQuantity = Int(self.productQuantityLabel.text!)
print("\(productQuantity!++)")
self.productQuantityLabel.text = "\(productQuantity!++)"
self.delegate?.addProductToBuy(self.product)
}
}
|
mit
|
4d9faa838401acda8a5c1ad59276b3b9
| 25.505882 | 88 | 0.637211 | 4.960352 | false | false | false | false |
lorentey/GlueKit
|
Tests/GlueKitTests/UpdatableValueTests.swift
|
1
|
5258
|
//
// UpdatableValueTests.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-27.
// Copyright © 2015–2017 Károly Lőrentey.
//
import XCTest
@testable import GlueKit
class UpdatableValueTests: XCTestCase {
func test_anyUpdatable_fromUpdatableValue() {
let test = TestUpdatableValue<Int>(0)
let any = test.anyUpdatableValue
XCTAssertEqual(any.value, 0)
let updateSink = MockValueUpdateSink<Int>(any.updates)
let changeSink = TransformedMockSink<ValueChange<Int>, String>({ "\($0.old) -> \($0.new)" })
changeSink.subscribe(to: any.changes)
let valuesSink = MockSink<Int>()
valuesSink.expecting(0) {
valuesSink.subscribe(to: any.values)
}
let futureValuesSink = MockSink<Int>(any.futureValues)
updateSink.expecting("begin") {
test.beginTransaction()
}
updateSink.expecting("0 -> 1") {
test.value = 1
}
updateSink.expecting("end") {
changeSink.expecting("0 -> 1") {
valuesSink.expecting(1) {
futureValuesSink.expecting(1) {
test.endTransaction()
}
}
}
}
updateSink.expecting(["begin", "1 -> 2", "end"]) {
changeSink.expecting("1 -> 2") {
valuesSink.expecting(2) {
futureValuesSink.expecting(2) {
any.value = 2
}
}
}
}
updateSink.expecting(["begin", "end"]) {
any.withTransaction {}
}
updateSink.expecting(["begin", "2 -> 3", "3 -> 4", "end"]) {
changeSink.expecting("2 -> 4") {
valuesSink.expecting(4) {
futureValuesSink.expecting(4) {
any.withTransaction {
any.value = 3
any.value = 4
}
}
}
}
}
}
func test_anyUpdatable_fromClosures() {
var value = 0
let signal = Signal<ValueUpdate<Int>>()
var transactions = 0
let begin = {
transactions += 1
if transactions == 1 {
signal.send(.beginTransaction)
}
}
let end = {
transactions -= 1
if transactions == 0 {
signal.send(.endTransaction)
}
}
let test = AnyUpdatableValue(
getter: { value },
apply: { (update: ValueUpdate<Int>) -> Void in
switch update {
case .beginTransaction: begin()
case .change(let change):
value = change.new
signal.send(update)
case .endTransaction: end()
}
},
updates: signal.anySource)
let any = test.anyUpdatableValue
XCTAssertEqual(any.value, 0)
let updateSink = MockValueUpdateSink<Int>(any.updates)
let changeSink = TransformedMockSink<ValueChange<Int>, String>({ "\($0.old) -> \($0.new)" })
changeSink.subscribe(to: any.changes)
let valuesSink = MockSink<Int>()
valuesSink.expecting(0) {
valuesSink.subscribe(to: any.values)
}
let futureValuesSink = MockSink<Int>(any.futureValues)
updateSink.expecting("begin") {
begin()
}
updateSink.expecting("0 -> 1") {
test.value = 1
}
updateSink.expecting("end") {
changeSink.expecting("0 -> 1") {
valuesSink.expecting(1) {
futureValuesSink.expecting(1) {
end()
}
}
}
}
updateSink.expecting(["begin", "1 -> 2", "end"]) {
changeSink.expecting("1 -> 2") {
valuesSink.expecting(2) {
futureValuesSink.expecting(2) {
any.value = 2
}
}
}
}
updateSink.expecting(["begin", "end"]) {
any.withTransaction {}
}
updateSink.expecting(["begin", "2 -> 3", "3 -> 4", "end"]) {
changeSink.expecting("2 -> 4") {
valuesSink.expecting(4) {
futureValuesSink.expecting(4) {
any.withTransaction {
any.value = 3
any.value = 4
}
}
}
}
}
}
func test_anyObservable_fromAnyUpdatable() {
let test = TestUpdatableValue<Int>(0)
let any = test.anyUpdatableValue.anyObservableValue
XCTAssertEqual(any.value, 0)
let updateSink = MockValueUpdateSink<Int>(any.updates)
updateSink.expecting("begin") {
test.beginTransaction()
}
updateSink.expecting("0 -> 1") {
test.value = 1
}
updateSink.expecting("end") {
test.endTransaction()
}
}
}
|
mit
|
7ddca37ada6ea4422985236246c9ed4b
| 27.080214 | 100 | 0.463912 | 4.804209 | false | true | false | false |
gsaslis/Rocket.Chat.iOS
|
Rocket.Chat.iOS/ViewControllers/RegisterViewController.swift
|
2
|
11591
|
//
// RegisterViewController.swift
// Rocket.Chat.iOS
//
// Created by Kornelakis Michael on 8/24/15.
// Copyright © 2015 Rocket.Chat. All rights reserved.
//
import UIKit
import JSQCoreDataKit
class RegisterViewController: UIViewController, UIPopoverPresentationControllerDelegate {
@IBOutlet var nameTextField: UITextField!
@IBOutlet var emailTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var confirmPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Setting the password and confirm password as secure text
passwordTextField.secureTextEntry = true
confirmPasswordTextField.secureTextEntry = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
//Function to return popovers as modals to all devices.
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
//Registration
@IBAction func submitToRegister(sender: AnyObject) {
//Boolean to check text inputs
var checkOK = false
//Check inputs
//Reset text input borders
nameTextField.layer.borderColor = UIColor.blackColor().CGColor
nameTextField.layer.borderWidth = 0
emailTextField.layer.borderColor = UIColor.blackColor().CGColor
emailTextField.layer.borderWidth = 0
passwordTextField.layer.borderColor = UIColor.blackColor().CGColor
passwordTextField.layer.borderWidth = 0
//Name check
if (nameTextField.text!.isEmpty){
nameTextField.layer.borderColor = UIColor.redColor().CGColor
nameTextField.layer.borderWidth = 1
//Create View Controller
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("namePopover")
//Set it as popover
popoverVC!.modalPresentationStyle = .Popover
//Set the size
popoverVC!.preferredContentSize = CGSizeMake(250, 50)
if let popoverController = popoverVC!.popoverPresentationController {
//Specify the anchor location
popoverController.sourceView = nameTextField
popoverController.sourceRect = nameTextField.bounds
//Popover above the textfield
popoverController.permittedArrowDirections = .Down
//Set the delegate
popoverController.delegate = self
}
//Show the popover
presentViewController(popoverVC!, animated: true, completion: nil)
}
//then email check
else if emailTextField.text!.isEmpty || !isValidEmail(emailTextField.text!) {
emailTextField.layer.borderColor = UIColor.redColor().CGColor
emailTextField.layer.borderWidth = 1
//Create View Controller
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("emailPopover")
//Set it as popover
popoverVC!.modalPresentationStyle = .Popover
//Set the size
popoverVC!.preferredContentSize = CGSizeMake(250, 50)
if let popoverController = popoverVC!.popoverPresentationController {
//Specify the anchor location
popoverController.sourceView = emailTextField
popoverController.sourceRect = emailTextField.bounds
//Popover above the textfield
popoverController.permittedArrowDirections = .Down
//Set the delegate
popoverController.delegate = self
}
//Show the popover
presentViewController(popoverVC!, animated: true, completion: nil)
}
//then password check
else if (passwordTextField.text!.characters.count < 8) {
passwordTextField.layer.borderColor = UIColor.redColor().CGColor
passwordTextField.layer.borderWidth = 1
//Create View Controller
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("passwordPopover")
//Set it as popover
popoverVC!.modalPresentationStyle = .Popover
//Set the size
popoverVC!.preferredContentSize = CGSizeMake(250, 55)
if let popoverController = popoverVC!.popoverPresentationController {
//Specify the anchor location
popoverController.sourceView = passwordTextField
popoverController.sourceRect = passwordTextField.bounds
//Popover above the textfield
popoverController.permittedArrowDirections = .Down
//Set the delegate
popoverController.delegate = self
}
//Show the popover
presentViewController(popoverVC!, animated: true, completion: nil)
}
//Do we want the password and confirmPassword trimmed?
//Confirm password
else if passwordTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) != confirmPasswordTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) {
// let alert = UIAlertView(title: "Confirm Password", message: "Please Confirm Your Password", delegate: self, cancelButtonTitle: "Dismiss")
// alert.show()
//Create View Controller
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("confirmPopover")
//Set it as popover
popoverVC!.modalPresentationStyle = .Popover
//Set the size
popoverVC!.preferredContentSize = CGSizeMake(250, 55)
if let popoverController = popoverVC!.popoverPresentationController {
//Specify the anchor location
popoverController.sourceView = confirmPasswordTextField
popoverController.sourceRect = confirmPasswordTextField.bounds
//Popover above the textfield
popoverController.permittedArrowDirections = .Down
//Set the delegate
popoverController.delegate = self
}
//Show the popover
presentViewController(popoverVC!, animated: true, completion: nil)
}
//All good
else
{
checkOK = true
}
//everything is good so let's register
if checkOK {
//get the appdelegate and store it in a variable
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.stack!.context
//Check for already logged in user
let ent = entity(name: "User", context: context)
//Create the request
let request = FetchRequest<User>(entity: ent)
//Users that we have password for only
request.predicate = NSPredicate(format: "password != nil")
//Array to keep the users
var users = [User]()
//Fetch the users and store them in the array
do{
users = try fetch(request: request, inContext: context)
}catch{
print("Error fetching users \(error)")
}
//Check if the username exists
var exists = false
for i in users {
if i.username == nameTextField.text{
exists = true
print("Name Exists")
}
}
//If it doesn't exist
if !exists{
//Create the user
let user = User(context: context, id: "NON-YET", username: nameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()), avatar: UIImage(named: "Default-Avatar")!, status: .ONLINE, timezone: NSTimeZone.systemTimeZone())
//Set the password
user.password = passwordTextField.text!
//User is automatically is added to CoreData, but not saved, so we need to call
//save context next.
//Save the user
saveContext(context, wait: true, completion:{(error: NSError?) -> Void in
if let err = error {
let alert = UIAlertController(title: "Alert", message: "Error \(err.userInfo)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
})
//Go back to login screen
self.performSegueWithIdentifier("returnToLogin", sender: self)
//Inform the registered user
let alert = UIAlertView(title: "Registered", message: "Registration Completed! You can log in now!", delegate: self, cancelButtonTitle: "Dismiss")
alert.show()
}
//If the user exists
else{
//Inform the not-registered user
let alert = UIAlertView(title: "Name Exists", message: "Username not available", delegate: self, cancelButtonTitle: "Dismiss")
alert.show()
}
}
}
//Dismissing the keyboard
@IBAction func dismissKeyboard(sender: AnyObject) {
self.resignFirstResponder()
}
//Email validation
func isValidEmail(email:String) -> Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailCheck = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailCheck.evaluateWithObject(email)
}
}
|
mit
|
3a8a82d83d77cbe6ff0270e28c29eb8f
| 34.121212 | 267 | 0.540725 | 6.825677 | false | false | false | false |
tjw/swift
|
stdlib/public/core/Filter.swift
|
1
|
13977
|
//===--- Filter.swift -----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence whose elements consist of the elements of some base
/// sequence that also satisfy a given predicate.
///
/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,
/// is a `LazyFilterSequence`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct LazyFilterSequence<Base: Sequence> {
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base
/// The predicate used to determine which elements produced by
/// `base` are also produced by `self`.
@usableFromInline // FIXME(sil-serialize-all)
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance consisting of the elements `x` of `base` for
/// which `isIncluded(x) == true`.
@inlinable // FIXME(sil-serialize-all)
public // @testable
init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = base
self._predicate = isIncluded
}
}
extension LazyFilterSequence {
/// An iterator over the elements traversed by some base iterator that also
/// satisfy a given predicate.
///
/// - Note: This is the associated `Iterator` of `LazyFilterSequence`
/// and `LazyFilterCollection`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator {
/// The underlying iterator whose elements are being filtered.
public var base: Base.Iterator { return _base }
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base.Iterator
@usableFromInline // FIXME(sil-serialize-all)
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance that produces the elements `x` of `base`
/// for which `isIncluded(x) == true`.
@inlinable // FIXME(sil-serialize-all)
internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = _base
self._predicate = isIncluded
}
}
}
extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence {
public typealias Element = Base.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
while let n = _base.next() {
if _predicate(n) {
return n
}
}
return nil
}
}
extension LazyFilterSequence: LazySequenceProtocol {
public typealias Element = Base.Element
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), _predicate)
}
@inlinable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
// optimization to check the element first matches the predicate
guard _predicate(element) else { return false }
return _base._customContainsEquatableElement(element)
}
}
/// A lazy `Collection` wrapper that includes the elements of an
/// underlying collection that satisfy a predicate.
///
/// - Note: The performance of accessing `startIndex`, `first`, any methods
/// that depend on `startIndex`, or of advancing an index depends
/// on how sparsely the filtering predicate is satisfied, and may not offer
/// the usual performance given by `Collection`. Be aware, therefore, that
/// general operations on `LazyFilterCollection` instances may not have the
/// documented complexity.
@_fixed_layout // FIXME(sil-serialize-all)
public struct LazyFilterCollection<Base : Collection> {
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base
@usableFromInline // FIXME(sil-serialize-all)
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance containing the elements of `base` that
/// satisfy `isIncluded`.
@inlinable // FIXME(sil-serialize-all)
public // @testable
init(_base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = _base
self._predicate = isIncluded
}
}
extension LazyFilterCollection : LazySequenceProtocol {
public typealias Element = Base.Element
public typealias Iterator = LazyFilterSequence<Base>.Iterator
public typealias SubSequence = LazyFilterCollection<Base.SubSequence>
// Any estimate of the number of elements that pass `_predicate` requires
// iterating the collection and evaluating each element, which can be costly,
// is unexpected, and usually doesn't pay for itself in saving time through
// preventing intermediate reallocations. (SR-4164)
@inlinable // FIXME(sil-serialize-all)
public var underestimatedCount: Int { return 0 }
@inlinable // FIXME(sil-serialize-all)
public func _copyToContiguousArray() -> ContiguousArray<Base.Element> {
// The default implementation of `_copyToContiguousArray` queries the
// `count` property, which evaluates `_predicate` for every element --
// see the note above `underestimatedCount`. Here we treat `self` as a
// sequence and only rely on underestimated count.
return _copySequenceToContiguousArray(self)
}
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), _predicate)
}
@inlinable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
guard _predicate(element) else { return false }
return _base._customContainsEquatableElement(element)
}
}
extension LazyFilterCollection : LazyCollectionProtocol {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
///
/// - Complexity: O(*n*), where *n* is the ratio between unfiltered and
/// filtered collection counts.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
var index = _base.startIndex
while index != _base.endIndex && !_predicate(_base[index]) {
_base.formIndex(after: &index)
}
return index
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _base.endIndex
}
// TODO: swift-3-indexing-model - add docs
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
var i = i
formIndex(after: &i)
return i
}
@inlinable // FIXME(sil-serialize-all)
public func formIndex(after i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.endIndex, "Can't advance past endIndex")
repeat {
_base.formIndex(after: &index)
} while index != _base.endIndex && !_predicate(_base[index])
i = index
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal func _advanceIndex(_ i: inout Index, step: Int) {
repeat {
_base.formIndex(&i, offsetBy: step)
} while i != _base.endIndex && !_predicate(_base[i])
}
@inline(__always)
@inlinable // FIXME(sil-serialize-all)
internal func _ensureBidirectional(step: Int) {
// FIXME: This seems to be the best way of checking whether _base is
// forward only without adding an extra protocol requirement.
// index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return
// nil when the resulting index lands outside the collection boundaries,
// and therefore likely does not trap in these cases.
if step < 0 {
_ = _base.index(
_base.endIndex, offsetBy: step, limitedBy: _base.startIndex)
}
}
@inlinable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
// The following line makes sure that distance(from:to:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ = _base.distance(from: start, to: end)
var _start: Index
let _end: Index
let step: Int
if start > end {
_start = end
_end = start
step = -1
}
else {
_start = start
_end = end
step = 1
}
var count = 0
while _start != _end {
count += step
formIndex(after: &_start)
}
return count
}
@inlinable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // FIXME(sil-serialize-all)
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
@inlinable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:limitedBy:) is
// invoked on the _base at least once, to trigger a _precondition in
// forward only collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
if i == limit {
return nil
}
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // FIXME(sil-serialize-all)
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Accesses the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _base[position]
}
@inlinable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> SubSequence {
return SubSequence(_base: _base[bounds], _predicate)
}
}
extension LazyFilterCollection : BidirectionalCollection
where Base : BidirectionalCollection {
@inlinable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
@inlinable // FIXME(sil-serialize-all)
public func formIndex(before i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.startIndex, "Can't retreat before startIndex")
repeat {
_base.formIndex(before: &index)
} while !_predicate(_base[index])
i = index
}
}
extension LazySequenceProtocol {
/// Returns the elements of `self` that satisfy `isIncluded`.
///
/// - Note: The elements of the result are computed on-demand, as
/// the result is used. No buffering storage is allocated and each
/// traversal step invokes `predicate` on one or more underlying
/// elements.
@inlinable // FIXME(sil-serialize-all)
public func filter(
_ isIncluded: @escaping (Elements.Element) -> Bool
) -> LazyFilterSequence<Self.Elements> {
return LazyFilterSequence(_base: self.elements, isIncluded)
}
}
extension LazyCollectionProtocol {
/// Returns the elements of `self` that satisfy `predicate`.
///
/// - Note: The elements of the result are computed on-demand, as
/// the result is used. No buffering storage is allocated and each
/// traversal step invokes `predicate` on one or more underlying
/// elements.
@inlinable // FIXME(sil-serialize-all)
public func filter(
_ isIncluded: @escaping (Elements.Element) -> Bool
) -> LazyFilterCollection<Self.Elements> {
return LazyFilterCollection(_base: self.elements, isIncluded)
}
}
extension LazyFilterSequence {
@available(swift, introduced: 5)
public func filter(
_ isIncluded: @escaping (Element) -> Bool
) -> LazyFilterSequence<Base> {
return LazyFilterSequence(_base: _base) {
isIncluded($0) && self._predicate($0)
}
}
}
extension LazyFilterCollection {
@available(swift, introduced: 5)
public func filter(
_ isIncluded: @escaping (Element) -> Bool
) -> LazyFilterCollection<Base> {
return LazyFilterCollection(_base: _base) {
isIncluded($0) && self._predicate($0)
}
}
}
// @available(*, deprecated, renamed: "LazyFilterSequence.Iterator")
public typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator
// @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use Base.Index")
public typealias LazyFilterIndex<Base: Collection> = Base.Index
@available(*, deprecated, renamed: "LazyFilterCollection")
public typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T : BidirectionalCollection
|
apache-2.0
|
19332b729bca3e88cbe87ac5e37cba17
| 32.924757 | 113 | 0.671818 | 4.213747 | false | false | false | false |
chayelheinsen/GamingStreams-tvOS-App
|
StreamCenter/TwitchChatView.swift
|
3
|
2492
|
//
// TwitchChatView.swift
// GamingStreamsTVApp
//
// Created by Olivier Boucher on 2015-09-23.
import UIKit
import Foundation
class TwitchChatView : UIView {
let channel : TwitchChannel!
var chatMgr : TwitchChatManager? = nil
var shouldConsume = false
var messageViews = [ChatMessageView]()
init(frame: CGRect, channel: TwitchChannel) {
self.channel = channel
super.init(frame: frame)
self.chatMgr = TwitchChatManager(consumer: self)
self.backgroundColor = UIColor(hexString: "#19191F")
let topView = ChatTopView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 75), title: "#\(self.channel.name)")
self.addSubview(topView)
}
required init?(coder aDecoder: NSCoder) {
self.channel = nil
self.chatMgr = nil
super.init(coder: aDecoder)
}
func startDisplayingMessages() {
Logger.Debug("Attempting to connect and display chat messages")
self.shouldConsume = true
self.chatMgr!.connectAnonymously()
self.chatMgr!.joinTwitchChannel(self.channel)
}
func stopDisplayingMessages() {
Logger.Debug("Disconnecting from chat")
self.shouldConsume = false
self.chatMgr!.disconnect()
}
}
extension TwitchChatView : ChatManagerConsumer {
func messageReadyForDisplay(message: NSAttributedString) {
if self.shouldConsume {
dispatch_async(dispatch_get_main_queue(),{
let view = ChatMessageView(message: message, width: self.bounds.width-40, position: CGPoint(x: 20, y: 0))
var newFrame = view.frame
newFrame.origin.y = self.frame.height - view.frame.height
view.frame = newFrame
for messageView in self.messageViews {
newFrame = messageView.frame
newFrame.origin.y = newFrame.origin.y - view.frame.height
messageView.frame = newFrame
if messageView.frame.origin.y < -100 { //Looks better than 0
self.messageViews.removeFirst()
messageView.removeFromSuperview()
}
}
self.messageViews.append(view)
self.insertSubview(view, atIndex: 0)
})
}
}
}
|
mit
|
80b9e9269491ad27b8ba708743602fd3
| 30.556962 | 130 | 0.570225 | 4.829457 | false | false | false | false |
zehrer/SOGraphDB
|
Sources/SOGraphDB_old/Model/Values/PropertyAccess.swift
|
1
|
7529
|
//
// PropertyAccess.swift
// SOGraphDB
//
// Created by Stephan Zehrer on 05.07.15.
// Copyright © 2015 Stephan Zehrer. All rights reserved.
//
import Foundation
/**
// Exampled how to use
var a = Node() // <- auto default context (not implemented yet !!!)
var b = Node() // <- auto default context
var keyNode = Node()
a[keyNode].value = 1
b[keyNode].value = "Test"
var result = a[keyNode].value
a[keyNode].valueInt = 1
b[keyNode].valueString = "Test"
*/
public protocol CRUD {
// create and read missing :)
mutating func update()
mutating func delete()
}
public protocol PropertyAccess : Identiy, Context, CRUD {
var nextPropertyID: UID {get set} // internal link to the property
//var propertiesArray: [Property] {get} //
//var propertiesDictionary:[UID: Property] {get}
subscript(keyNode: Node) -> Property { mutating get}
func propertyByKey(_ keyNode:Node) -> Property?
//func containsProperty(keyNode:Node) -> Bool
}
extension PropertyAccess {
public subscript(keyNode: Node) -> Property {
mutating get {
//assert(context != nil, "No GraphContext available")
let result = propertyByKey(keyNode)
if let result = result {
return result
} else {
return createPropertyFor(keyNode)
}
}
}
// Create a new property and add it to this element
// This methode update
// - the new property (twice, 1. create 2. update)
// - (optional) the lastProperty -> the property was appended directly
// - (optional) the element -> the property was appended
// PreConditions: Element is in a context
mutating func createPropertyFor(_ keyNode : Node) -> Property {
assert(context != nil, "No GraphContext available")
assert(keyNode.uid != nil, "KeyNode without a uid")
var property = Property(related: self)
property.keyNodeID = keyNode.uid!
context.registerProperty(&property)
//context.updateProperty(property)
append(&property)
return property
}
// This methode will update
// - in any case the property itself
// - this element in case of first property
// - the last property in the chain in case it is not the first one
mutating func append(_ property : inout Property) {
if nextPropertyID == 0 {
// first element
// add property to the element (e.g. Node -> Property)
nextPropertyID = property.uid!
// CONTEXT WRITE
// update of self is only required if the id was set
self.update()
} else {
// appent element at the end of the chain
let propertiesArray = readPropertyArray()
var lastProperty = propertiesArray.last
if lastProperty != nil {
// it seems this element has already one or more properties
// add property to the last one
property.previousPropertyID = lastProperty!.uid!;
lastProperty!.nextPropertyID = property.uid!;
// CONTEXT WRITE
// updated of the LAST relationship is only required if
// the is was extended
context.update(&lastProperty!)
} else {
// ERROR: lastProperty is nil even nextPropertyID is not set to zero
assertionFailure("ERROR: Database inconsistent")
}
}
// CONTEXT WRTIE
context.update(&property)
}
// Generic read methode
// The handler is called by all properties of the chain
// Return: true if the while loop can be stopped
func readProperty(_ handler : (_ property : Property) -> Bool) {
var property:Property? = nil
var nextPropertyID = self.nextPropertyID
while (nextPropertyID > 0) {
property = context.readProperty(nextPropertyID)
if (property != nil) {
let stop = handler(property!)
if stop {
break
}
nextPropertyID = property!.nextPropertyID
} else {
// ERROR: nextPropertyID is not zero but readProperty read nil
assertionFailure("ERROR: Database inconsistent")
}
}
}
public func propertyByKey(_ keyNode : Node) -> Property? {
var result : Property? = nil
readProperty({ property in
if property.keyNodeID == keyNode.uid {
result = property
return true
}
return false
})
return result
}
func readPropertyArray() -> [Property] {
var propertiesArray: [Property] = [Property]()
readProperty({ property in
propertiesArray.append(property)
return false
})
return propertiesArray
}
func readPropertyDictionary() -> [UID: Property] {
var propertiesDictionary:[UID: Property] = [UID: Property]()
readProperty({ property in
propertiesDictionary[property.keyNodeID] = property
return false
})
return propertiesDictionary
}
mutating func deleteProperty(_ property:inout Property) {
assert(context != nil, "No GraphContext available")
var previousProperty:Property? = nil
var nextProperty:Property? = nil
let nextPropertyID:UID = property.nextPropertyID
let previousPropertyID = property.previousPropertyID
if (nextPropertyID > 0) {
nextProperty = context.readProperty(nextPropertyID)
if (nextProperty != nil) {
nextProperty!.previousPropertyID = previousPropertyID
// CONTEXT WRITE
context.update(&nextProperty!)
} else {
// ERROR: nextPropertyID is not zero but readProperty return nil
assertionFailure("ERROR: Database inconsistent")
}
}
if (previousPropertyID > 0) {
previousProperty = context!.readProperty(previousPropertyID)
if (nextProperty != nil) {
previousProperty!.nextPropertyID = nextPropertyID
// CONTEXT WRITE
context.update(&previousProperty!)
} else {
// ERROR: previousProperty is not zero but readProperty return nil
assertionFailure("ERROR: Database inconsistent")
}
} else {
// seems this is the first property in the chain
self.nextPropertyID = nextPropertyID
// CONTEXT WRITE
// update of self is only required if the id was set
self.update()
}
// last step delete the property itself
property.delete()
}
}
|
mit
|
ced36e14f3aebf947facf2bc55028ed2
| 28.178295 | 84 | 0.535069 | 5.377143 | false | false | false | false |
lolgear/JWT
|
Example/JWTDesktopSwift/JWTDesktopSwift/ViewController.swift
|
2
|
10947
|
//
// ViewController.swift
// JWTDesktopSwift
//
// Created by Lobanov Dmitry on 01.10.16.
// Copyright © 2016 JWTIO. All rights reserved.
//
import Cocoa
import JWT
import JWTDesktopSwiftToolkit
// MARK: - Supply JWT Methods
extension ViewController {
func tokenDataTransferObject() -> TokenDecoder.DataTransferObject {
let algorithmName = self.algorithmPopUpButton.selectedItem?.title ?? ""
let secret = self.secretTextField.stringValue
let secretData: Data? = self.getSecretData
let isBase64EncodedSecret = self.secretIsBase64EncodedCheckButton.integerValue == 1
let shouldSkipSignatureVerification = self.signatureVerificationCheckButton.integerValue == 1
return .init(algorithmName: algorithmName, secret: secret, secretData: secretData, isBase64EncodedSecret: isBase64EncodedSecret, shouldSkipSignatureVerification: shouldSkipSignatureVerification)
}
func tokenDataTransferObjectShouldCheckSignature() -> TokenDecoder.DataTransferObject {
var result = self.tokenDataTransferObject()
result.shouldSkipSignatureVerification = false
return result
}
var getSecretData: Data? {
let secret = self.secretTextField.stringValue
let isBase64Encoded = self.secretIsBase64EncodedCheckButton.integerValue == 1
guard let result = Data(base64Encoded: secret), isBase64Encoded else {
self.secretIsBase64EncodedCheckButton.integerValue = 0
return nil
}
return result
}
}
// Refresh UI
extension ViewController {
// MARK: - Encoded Text View
func encodedTextAttributes(_ enumerate: (NSRange, [NSAttributedString.Key : Any]) -> ()) {
let textStorage = self.encodedTextView.textStorage!
let string = textStorage.string
let range = NSMakeRange(0, string.count)
if let attributedString = self.model.appearance.encodedAttributedString(text: string) {
attributedString.enumerateAttributes(in: range, options: []) { (attributes, range, bool) in
enumerate(range, attributes)
}
}
}
// MARK: - Refresh UI
func refreshUI() {
let textStorage = self.encodedTextView.textStorage!;
let string = textStorage.string
self.encodedTextAttributes { (range, attributes) in
textStorage.setAttributes(attributes, range: range)
}
// We should add an option to skip verification in decoding section.
// invalid signature doesn't mean that you can't decode JWT.
if let jwtVerified = self.model.decoder.decode(token: string, object: self.tokenDataTransferObjectShouldCheckSignature()) {
let notVerified = jwtVerified.successResult?.headerAndPayloadDictionary?.isEmpty == true
self.signatureReactOnVerifiedToken(verified: !notVerified)
}
else {
self.signatureReactOnVerifiedToken(verified: false)
}
let result = self.model.decoder.decode(token: string, object: self.tokenDataTransferObject())
self.decriptedViewController.resultType = result
}
func refreshSignature() {
self.signatureStatusLabel.backgroundColor = self.model.signatureValidation.color
self.signatureStatusLabel.stringValue = self.model.signatureValidation.title
}
}
// MARK: - Actions
extension ViewController {
@objc func popUpButtonValueChanged(sender : AnyClass) {
self.refreshUI()
}
@objc func checkBoxState(sender : AnyClass) {
self.refreshUI()
}
func signatureReactOnVerifiedToken(verified: Bool) {
self.model.signatureValidation = verified ? .valid : .invalid
self.refreshSignature()
}
}
extension ViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
if (obj.name == NSControl.textDidChangeNotification) {
let textField = obj.object as! NSTextField
if textField == self.secretTextField {
self.refreshUI()
}
}
}
}
extension ViewController: NSTextViewDelegate {
func textDidChange(_ notification: Notification) {
self.refreshUI()
}
// func textViewDidChangeTypingAttributes(_ notification: Notification) {
// self.updateEncodedTextAttributes()
// }
// func textView(_ textView: NSTextView, shouldChangeTypingAttributes oldTypingAttributes: [String : Any] = [:], toAttributes newTypingAttributes: [NSAttributedString.Key : Any] = [:]) -> [NSAttributedString.Key : Any] {
// return newTypingAttributes
// }
// func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
// if (textView == self.encodedTextView) {
//// if let textStore = textView.textStorage {
//// textView.undoManager?.beginUndoGrouping()
//// textStore.replaceCharacters(in: affectedCharRange, with: replacementString!)
//// self.encodedTextAttributes { (range, attributes) in
//// textStore.setAttributes(attributes, range: range)
//// }
//// textView.undoManager?.endUndoGrouping()
//// }
//// self.refreshUI()
// return true
// }
// return false
// }
}
// MARK: - EncodingTextViewDelegate
//extension ViewController : NSTextViewDelegate {
// func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
// if (textView == self.encodedTextView) {
// if let textStore = textView.textStorage {
// textStore.replaceCharacters(in: affectedCharRange, with: replacementString!)
// }
// self.refreshUI()
// return false
// }
// return false
// }
//}
class ViewController: NSViewController {
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
// MARK: - Properties - Outlets
@IBOutlet weak var algorithmLabel : NSTextField!
@IBOutlet weak var algorithmPopUpButton : NSPopUpButton!
@IBOutlet weak var secretLabel : NSTextField!
@IBOutlet weak var secretTextField : NSTextField!
@IBOutlet weak var secretIsBase64EncodedCheckButton : NSButton!
@IBOutlet weak var signatureLabel : NSTextField!
@IBOutlet weak var signatureVerificationCheckButton : NSButton!
@IBOutlet weak var encodedTextView : NSTextView!
@IBOutlet weak var decriptedView : NSView!
var decriptedViewController : DecriptedViewController!
@IBOutlet weak var signatureStatusLabel : NSTextField!
// MARK: - Model
var model: Model!
// MARK: - Setup
func setupModel() {
self.model = Model()
}
func setupTop() {
// top label.
self.algorithmLabel.stringValue = "Algorithm";
// pop up button.
self.algorithmPopUpButton.removeAllItems()
self.algorithmPopUpButton.addItems(withTitles: self.model.availableAlgorithmsNames)
self.algorithmPopUpButton.target = self
self.algorithmPopUpButton.action = #selector(ViewController.popUpButtonValueChanged(sender:))
// secretLabel
self.secretLabel.stringValue = "Secret"
// secretTextField
self.secretTextField.placeholderString = "Secret"
self.secretTextField.delegate = self
// check button
self.secretIsBase64EncodedCheckButton.title = "is Base64Encoded Secret"
self.secretIsBase64EncodedCheckButton.integerValue = 0
self.secretIsBase64EncodedCheckButton.target = self
self.secretIsBase64EncodedCheckButton.action = #selector(ViewController.checkBoxState(sender:))
// signatureLabel
self.signatureLabel.stringValue = "Signature"
// signatureVerificationCheckButton
self.signatureVerificationCheckButton.title = "Skip signature verification"
self.signatureVerificationCheckButton.integerValue = 0
self.signatureVerificationCheckButton.target = self
self.signatureVerificationCheckButton.action = #selector(ViewController.checkBoxState(sender:))
}
func setupBottom() {
self.signatureStatusLabel.alignment = .center
self.signatureStatusLabel.textColor = NSColor.white
self.signatureStatusLabel.drawsBackground = true
self.refreshSignature()
}
func setupEncodingDecodingViews() {
self.encodedTextView.delegate = self;
}
func setupDecorations() {
self.setupTop()
self.setupBottom()
}
func setupDecriptedViews() {
let view = self.decriptedView
self.decriptedViewController = DecriptedViewController()
view?.addSubview(self.decriptedViewController.view)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupModel()
self.setupDecorations()
self.setupEncodingDecodingViews()
self.setupDecriptedViews()
self.defaultDataSetup()
}
func defaultDataSetup(algorithmName: String, secret: String, token: String) {
// algorithm HS256
if let index = self.model.availableAlgorithmsNames.firstIndex(where: {
$0 == algorithmName
}) {
self.algorithmPopUpButton.selectItem(at: index)
}
// secret
self.secretTextField.stringValue = secret
// token
var range = NSRange()
range.location = 0
range.length = token.count
self.encodedTextView.insertText(token, replacementRange: range)
}
func defaultDataSetup() {
let seed: DataSeedType = .hs256
let seedValue = seed.dataSeed
self.defaultDataSetup(algorithmName: seedValue.algorithmName, secret: seedValue.secret, token: seedValue.token)
}
override func viewWillAppear() {
super.viewWillAppear()
guard let view = self.decriptedView else { return }
let subview = self.decriptedViewController.view
view.translatesAutoresizingMaskIntoConstraints = false
subview.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
subview.leftAnchor.constraint(equalTo: view.leftAnchor),
subview.rightAnchor.constraint(equalTo: view.rightAnchor),
subview.topAnchor.constraint(equalTo: view.topAnchor),
subview.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]
NSLayoutConstraint.activate(constraints)
}
}
|
mit
|
aa0f293131613dd6d45ed077633cd02c
| 35.245033 | 223 | 0.660058 | 4.984517 | false | false | false | false |
djwbrown/swift
|
test/Sanitizers/tsan.swift
|
2
|
986
|
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=thread -o %t_tsan-binary
// RUN: not env %env-TSAN_OPTIONS="abort_on_error=0" %target-run %t_tsan-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: tsan_runtime
// Make sure we can handle swifterror and don't bail during the LLVM
// threadsanitizer pass.
enum MyError : Error {
case A
}
public func foobar(_ x: Int) throws {
if x == 0 {
throw MyError.A
}
}
public func call_foobar() {
do {
try foobar(1)
} catch(_) { }
}
// Test ThreadSanitizer execution end-to-end.
import Darwin
var threads: [pthread_t?] = []
var racey_x: Int;
for _ in 1...5 {
var t : pthread_t?
pthread_create(&t, nil, { _ in
print("pthread ran")
racey_x = 5;
return nil
}, nil)
threads.append(t)
}
for t in threads {
if t == nil {
print("nil thread")
continue
}
pthread_join(t!, nil)
}
// CHECK: ThreadSanitizer: data race
|
apache-2.0
|
08f574948543dfa4e3dfbb8f2ac86dbb
| 17.961538 | 104 | 0.634888 | 3.033846 | false | false | false | false |
crazypoo/PTools
|
Pods/CollectionViewPagingLayout/Lib/Snapshot/SnapshotTransformViewOptions.swift
|
1
|
3860
|
//
// SnapshotTransformViewOptions.swift
// CollectionViewPagingLayout
//
// Created by Amir on 15/03/2020.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
public struct SnapshotTransformViewOptions {
// MARK: Properties
/// Ratio for computing the size of each piece in the snapshot
/// width = view.width * `pieceSizeRatio.width`
public var pieceSizeRatio: CGSize
/// Ratio for computing the size of each piece in the snapshot
public var piecesCornerRadiusRatio: PiecesValue<CGFloat>
/// Ratio for computing the opacity of each piece in the snapshot
/// 0 means no opacity change 1 means full opacity change
public var piecesAlphaRatio: PiecesValue<CGFloat>
/// Ratio for the amount of translate for each piece in the snapshot, calculates by each piece size
/// for instance, if piecesTranslationRatio.x = 0.5 and pieceView.width = 100 then
/// translateX = 50 for the pieceView
public var piecesTranslationRatio: PiecesValue<CGPoint>
/// Ratio for the minimum amount of translate for each piece, calculates like `piecesTranslationRatio`
public var minPiecesTranslationRatio: PiecesValue<CGPoint>?
/// Ratio for the maximum amount of translate for each piece, calculates like `piecesTranslationRatio`
public var maxPiecesTranslationRatio: PiecesValue<CGPoint>?
/// Ratio for computing scale of each piece in the snapshot
/// Scale = 1 - abs(progress) * `piecesScaleRatio`
public var piecesScaleRatio: PiecesValue<CGSize>
/// Ratio for computing scale for the snapshot container
/// Scale = 1 - abs(progress) * `scaleRatio`
public var containerScaleRatio: CGFloat
/// Ratio for the amount of translate for container view, calculates by `targetView` size
/// for instance, if containerTranslationRatio.x = 0.5 and targetView.width = 100 then
/// translateX = 50 for the right view and translateX = -50 for the left view
public var containerTranslationRatio: CGPoint
/// The minimum amount of translate for container views, calculates like `containerTranslationRatio`
public var containerMinTranslationRatio: CGPoint?
/// The maximum amount of translate for container views, calculates like `containerTranslationRatio`
public var containerMaxTranslationRatio: CGPoint?
// MARK: Lifecycle
public init(
pieceSizeRatio: CGSize = .init(width: 1, height: 1.0 / 8.0),
piecesCornerRadiusRatio: PiecesValue<CGFloat> = .static(0),
piecesAlphaRatio: PiecesValue<CGFloat> = .static(0),
piecesTranslationRatio: PiecesValue<CGPoint> = .rowOddEven(.init(x: 0, y: -1), .init(x: -1, y: -1)),
minPiecesTranslationRatio: PiecesValue<CGPoint>? = nil,
maxPiecesTranslationRatio: PiecesValue<CGPoint>? = nil,
piecesScaleRatio: PiecesValue<CGSize> = .static(.init(width: 0, height: 1)),
containerScaleRatio: CGFloat = 0.25,
containerTranslationRatio: CGPoint = .init(x: 1, y: 0),
containerMinTranslationRatio: CGPoint? = nil,
containerMaxTranslationRatio: CGPoint? = nil
) {
self.pieceSizeRatio = pieceSizeRatio
self.piecesCornerRadiusRatio = piecesCornerRadiusRatio
self.piecesAlphaRatio = piecesAlphaRatio
self.piecesTranslationRatio = piecesTranslationRatio
self.minPiecesTranslationRatio = minPiecesTranslationRatio
self.maxPiecesTranslationRatio = maxPiecesTranslationRatio
self.piecesScaleRatio = piecesScaleRatio
self.containerScaleRatio = containerScaleRatio
self.containerTranslationRatio = containerTranslationRatio
self.containerMinTranslationRatio = containerMinTranslationRatio
self.containerMaxTranslationRatio = containerMaxTranslationRatio
}
}
|
mit
|
d7341fd4b160fe66166e7d2c786257ee
| 44.940476 | 108 | 0.718839 | 4.706098 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
Swift/LeetCode/Trivial - 不需要看的题目/实现细节题/48_Rotate Image.swift
|
1
|
1681
|
//
// 48. Rotate Image.swift
// https://leetcode.com/problems/rotate-image
//
// Created by Honghao Zhang on 2016-10-27.
// Copyright © 2016 Honghaoz. All rights reserved.
//
//You are given an n x n 2D matrix representing an image.
//
//Rotate the image by 90 degrees (clockwise).
//
//Follow up:
//Could you do this in-place?
import Foundation
class Num48_RotateImage: Solution {
func rotate(_ matrix: inout [[Int]]) {
let d = matrix.count
var rotated: [[Int]] = Array(repeating: Array(repeating: 0, count: d),
count: d)
for i in 0..<d {
for j in 0..<d {
rotated[i][j] = matrix[d - j - 1][i]
}
}
matrix = rotated
}
func rotateInPlace(_ matrix: inout [[Int]]) {
let d = matrix.count
for i in 0..<Int(ceil(Double(d / 2))) {
for j in i..<(d - i - 1) {
let temp = matrix[i][j]
matrix[i][j] = matrix[d - j - 1][i]
matrix[d - j - 1][i] = matrix[d - i - 1][d - j - 1]
matrix[d - i - 1][d - j - 1] = matrix[j][d - i - 1]
matrix[j][d - i - 1] = temp
}
}
}
func rotateInPlace2(_ matrix: inout [[Int]]) {
let d = matrix.count
for i in 0..<Int(ceil(Double(d / 2))) {
for j in i..<(d - i - 1) {
(matrix[i][j], matrix[d - j - 1][i], matrix[d - i - 1][d - j - 1], matrix[j][d - i - 1]) =
(matrix[d - j - 1][i], matrix[d - i - 1][d - j - 1], matrix[j][d - i - 1], matrix[i][j])
}
}
}
func test() {
}
}
|
mit
|
c4e05b3380f4d2cfc3945da8026b3827
| 28.473684 | 108 | 0.446429 | 3.333333 | false | false | false | false |
eljeff/AudioKit
|
Sources/AudioKit/Analysis/AmplitudeTap.swift
|
1
|
1873
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Accelerate
import AVFoundation
/// Tap to do amplitude analysis on any node.
/// start() will add the tap, and stop() will remove it.
public class AmplitudeTap: BaseTap {
private var amp: [Float] = Array(repeating: 0, count: 2)
/// Detected amplitude (average of left and right channels
public var amplitude: Float {
return amp.reduce(0, +) / 2
}
/// Detected left channel amplitude
public var leftAmplitude: Float {
return amp[0]
}
/// Detected right channel amplitude
public var rightAmplitude: Float {
return amp[1]
}
private var handler: (Float) -> Void = { _ in }
/// Initialize the amplitude
///
/// - parameter input: Node to analyze
/// - parameter bufferSize: Size of buffer to analyze
/// - parameter handler: Code to call with new amplitudes
public init(_ input: Node, bufferSize: UInt32 = 1_024, handler: @escaping (Float) -> Void = { _ in }) {
self.handler = handler
super.init(input, bufferSize: bufferSize)
}
// AVAudioNodeTapBlock - time is unused in this case
override internal func doHandleTapBlock(buffer: AVAudioPCMBuffer, at time: AVAudioTime) {
guard let floatData = buffer.floatChannelData else { return }
let channelCount = Int(buffer.format.channelCount)
let length = UInt(buffer.frameLength)
// n is the channel
for n in 0 ..< channelCount {
let data = floatData[n]
var rms: Float = 0
vDSP_rmsqv(data, 1, &rms, UInt(length))
amp[n] = rms
}
handler(amplitude)
}
/// Remove the tap on the input
override public func stop() {
super.stop()
amp[0] = 0
amp[1] = 0
}
}
|
mit
|
2e20d32432ddf199ea8768777a97303d
| 28.730159 | 107 | 0.618793 | 4.345708 | false | false | false | false |
tlax/GaussSquad
|
GaussSquad/Model/LinearEquations/Solution/Strategy/MLinearEquationsSolutionStrategyIndeterminatesLeft.swift
|
1
|
3307
|
import Foundation
class MLinearEquationsSolutionStrategyIndeterminatesLeft:MLinearEquationsSolutionStrategy
{
class func indeterminatesRight(step:MLinearEquationsSolutionStep) -> MLinearEquationsSolutionStrategyIndeterminatesLeft?
{
var indexEquation:Int = 0
for equation:MLinearEquationsSolutionEquation in step.equations
{
if let _:MLinearEquationsSolutionEquationItemPolynomial = equation.result as? MLinearEquationsSolutionEquationItemPolynomial
{
let strategy:MLinearEquationsSolutionStrategyIndeterminatesLeft = MLinearEquationsSolutionStrategyIndeterminatesLeft(
step:step,
indexEquation:indexEquation)
return strategy
}
indexEquation += 1
}
return nil
}
private let indexEquation:Int
private init(
step:MLinearEquationsSolutionStep,
indexEquation:Int)
{
self.indexEquation = indexEquation
super.init(step:step)
}
override func process(delegate:MLinearEquationsSolutionStrategyDelegate)
{
super.process(delegate:delegate)
moveToLeft()
}
//MARK: private
private func moveToLeft()
{
var equations:[MLinearEquationsSolutionEquation] = []
let descr:String = String(
format:NSLocalizedString("MLinearEquationsSolutionStrategyIndeterminatesLeft_descr", comment:""),
"\((indexEquation + 1))")
let countEquations:Int = self.step.equations.count
for indexEquation:Int in 0 ..< countEquations
{
let equation:MLinearEquationsSolutionEquation
let currentEquation:MLinearEquationsSolutionEquation = self.step.equations[indexEquation]
if indexEquation == self.indexEquation
{
guard
let oldResult:MLinearEquationsSolutionEquationItemPolynomial = currentEquation.result as? MLinearEquationsSolutionEquationItemPolynomial
else
{
return
}
var items:[MLinearEquationsSolutionEquationItem] = currentEquation.items
let currentItems:Int = items.count
let inversedResult:MLinearEquationsSolutionEquationItemPolynomial = oldResult.inversed(
newIndex:currentItems)
let newResult:MLinearEquationsSolutionEquationItemConstant = MLinearEquationsSolutionEquationItem.emptyCoefficient(
index:0)
items.append(inversedResult)
equation = MLinearEquationsSolutionEquation(
items:items,
result:newResult,
equationIndex:indexEquation)
}
else
{
equation = currentEquation
}
equations.append(equation)
}
let step:MLinearEquationsSolutionStepProcess = MLinearEquationsSolutionStepProcess(
equations:equations,
descr:descr)
completed(step:step)
}
}
|
mit
|
e2867a2843dd69a1b45422538270ad1a
| 33.810526 | 156 | 0.600847 | 6.484314 | false | false | false | false |
contextio/contextio-ios
|
CIOPlayground.playground/Contents.swift
|
1
|
6090
|
//: Playground - noun: a place where people can play
import CIOAPIClient
import XCPlayground
import WebKit
XCPSetExecutionShouldContinueIndefinitely(true)
let liteSession = CIOLiteClient(consumerKey: "", consumerSecret: "")
if liteSession.valueForKey("OAuthConsumerKey") as? String == "" {
assertionFailure("Please provide your consumer key and consumer secret.")
}
// Uncomment this line and let the playground execute to clear previous
// credentials and authenticate with a new email account:
//liteSession.clearCredentials()
// Load the first email in the current account's inbox, and display it in a WKWebView.
// Open the assistant navigator to the Timeline display to see the webview.
CIOAuthenticator(session: liteSession).withAuthentication{ session in
let folderName = "INBOX"
session.getMessagesForFolderWithPath(folderName, accountLabel: nil).executeWithSuccess({ response in
guard let firstMessage = response.first as? [String: AnyObject] else { return }
guard let messageID = firstMessage["message_id"] as? String else { return }
let request = session.requestForMessageWithID(messageID,
inFolder: folderName, accountLabel: nil, delimiter: nil)
request.include_body = true
request.include_headers = "1"
request.executeWithSuccess({ response in
response
response["headers"]
guard let bodies = response["bodies"] as? [[NSObject: AnyObject]] else { return }
for body in bodies {
if (body["type"] as? String) == "text/html" {
let htmlContent = body["content"] as! String
let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 500, height: 800))
webView.loadHTMLString(htmlContent, baseURL: nil)
XCPShowView("webView", view: webView)
}
}
}, failure: { error in
print("Message load error: \(error)")
})
},
failure: { error in
print("Error: \(error)")
})
}
// Uncomment the following to use Context.IO API V2 rather than lite:
//let s = CIOV2Client(consumerKey: "", consumerSecret: "")
//if s.valueForKey("OAuthConsumerKey") as? String == "" {
// assertionFailure("Please provide your consumer key and consumer secret.")
//}
//
//// Uncomment this line and let the playground execute to clear previous
//// credentials and authenticate with a new email account:
////s.clearCredentials()
//let authenticator = CIOAuthenticator(session: s)
//
//authenticator.withAuthentication() { session in
// session.getContacts().executeWithSuccess({ responseDict in
// print(responseDict)
// let contactsArray = responseDict["matches"] as! [[NSObject: AnyObject]]
// let names = contactsArray.map { $0["name"] as! String }
//// String(format: "Contacts: %@", names.join)
// },
// failure: { error in
// print("\(error)")
// })
//}
//
///////
// Utility classes for authenticating with the CIO API via an OS X WebKit View
final class CIOAuthenticator<Client: CIOAPIClient> {
let delegate = WebViewDelegate()
var session: Client
var window: NSWindow?
init(session: Client) {
self.session = session
}
func withAuthentication(block: Client -> Void) {
if !session.isAuthorized {
let app = NSApplication.sharedApplication()
app.setActivationPolicy(.Regular)
let s = session
delegate.tokenHandler = { token in
s.fetchAccountWithConnectToken(token).executeWithSuccess(
{ responseDict in
self.window?.close()
self.window = nil
if s.completeLoginWithResponse(responseDict, saveCredentials: true) {
block(s)
}
}, failure: { error in
print("token fetch failure: \(error)")
})
}
s.beginAuthForProviderType(.Gmail, callbackURLString: "cio-api-auth://", params: nil)
.executeWithSuccess({ responseDict in
let redirectURL = s.redirectURLFromResponse(responseDict)
let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 400, height: 600))
let window = NSWindow(contentRect: webView.bounds,
styleMask: NSTitledWindowMask | NSClosableWindowMask,
backing: .Buffered,
`defer`: false)
let request = NSURLRequest(URL: redirectURL)
webView.loadRequest(request)
webView.navigationDelegate = self.delegate
window.title = "Authenticate With Context.IO"
window.contentView?.addSubview(webView)
window.makeKeyAndOrderFront(nil)
self.window = window
},
failure: { error in
print(error)
})
} else {
block(session)
}
}
}
public final class WebViewDelegate: NSObject, WKNavigationDelegate {
public var tokenHandler: (String -> Void)? = nil
public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.URL
if url?.scheme == "cio-api-auth" {
if let queryItems = NSURLComponents(URL: url!, resolvingAgainstBaseURL: false)?.queryItems {
for queryItem in queryItems {
if let value = queryItem.value where queryItem.name == "contextio_token" {
tokenHandler?(value)
decisionHandler(.Cancel)
return
}
}
}
}
decisionHandler(.Allow)
}
}
|
apache-2.0
|
3bc634b5958a562d40b574cf3109d65d
| 39.065789 | 168 | 0.588834 | 5.10906 | false | false | false | false |
OpsLabJPL/MarsImagesIOS
|
MarsImagesIOS/MarsImageCatalog.swift
|
1
|
2460
|
//
// MarsImageCatalog.swift
// MarsImagesIOS
//
// Created by Mark Powell on 7/27/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import Foundation
import Reachability
let numImagesetsReturnedKey = "numImagesetsReturnedKey"
let missionKey = "missionKey"
extension Notification.Name {
static let beginImagesetLoading = Notification.Name("BeginImagesetLoading")
static let endImagesetLoading = Notification.Name("EndImagesetLoading")
static let locationsLoaded = Notification.Name("LocationsLoaded")
static let namedLocationsLoaded = Notification.Name("NamedLocationsLoaded")
}
protocol MarsImageCatalog {
func reload()
func hasMoreImages() -> Bool
func loadNextPage()
var mission:String { get }
var searchWords:String { get set }
var imagesetCount:Int { get }
var imagesets:[Imageset] { get }
var captions:[String?] { get }
var marsphotos:[MarsPhoto] { get }
var imagesetsForSol:[Int:[Imageset]] { get }
var sols:[Int] { get }
var solIndices:[Int:Int] { get }
var imagesetCountsBySol:[Int:Int] { get }
func reachability() -> Reachability
func imageName(imageset: Imageset, imageIndexInSet: Int) -> String
func getImagesetCount(imageset: Imageset) -> Int
func changeToImage(imagesetIndex: Int, imageIndexInSet: Int)
func changeToAnaglyph(leftAndRight: (Int,Int), imageIndex: Int)
func stereoForImages(imagesetIndex: Int) -> (Int,Int)?
func getNearestRMC() -> (Int,Int)?
func getNextRMC(rmc:(Int,Int)) -> (Int,Int)?
func getPreviousRMC(rmc:(Int,Int)) -> (Int,Int)?
func getLocations() -> [(Int,Int)]?
func getNamedLocations() -> [String:(Int,Int)]?
func reloadLocations()
func localLevelQuaternion(_ rmc:(Int, Int), completionHandler:@escaping (Quaternion)->(Void))
}
class Imageset: Equatable {
var mission:Mission
var title:String
var rowTitle:String
var subtitle:String
var thumbnailUrl:String?
var sol:Int?
init (title:String) {
self.title = title
self.mission = Mission.currentMission()
self.rowTitle = mission.rowTitle(title)
self.subtitle = mission.subtitle(title)
self.sol = mission.sol(title)
}
static func ==(lhs: Imageset, rhs: Imageset) -> Bool {
return lhs.title == rhs.title
}
}
|
apache-2.0
|
5231ab6422afba5d9c59c223213d959e
| 24.091837 | 97 | 0.649451 | 4.098333 | false | false | false | false |
samuelclay/NewsBlur
|
clients/ios/Widget Extension/WidgetStory.swift
|
1
|
5154
|
//
// WidgetStory.swift
// Widget Extension
//
// Created by David Sinclair on 2019-11-29.
// Copyright © 2021 NewsBlur. All rights reserved.
//
import SwiftUI
/// A story to display in the widget.
struct Story: Codable, Identifiable {
/// The version number.
let version = 1
/// The story hash.
let id: String
/// The feed ID.
let feed: String
/// The date and/or time as a string.
let date: String
/// The author of the story.
let author: String
/// The title of the story.
let title: String
/// The content of the story.
let content: String
/// The thumbnail image data, or `nil` if none.
let imageData: Data?
/// The thumbnail image, or `nil` if none.
let image: UIImage?
/// Keys for the dictionary representation.
struct DictionaryKeys {
static let id = "story_hash"
static let feed = "story_feed_id"
static let date = "short_parsed_date"
static let author = "story_authors"
static let title = "story_title"
static let content = "story_content"
static let imageData = "select_thumbnail_data"
}
/// Initializer from a dictionary.
///
/// - Parameter dictionary: Dictionary from the server.
init(from dictionary: [String : Any]) {
id = dictionary[DictionaryKeys.id] as? String ?? ""
feed = dictionary[DictionaryKeys.feed] as? String ?? "\(dictionary[DictionaryKeys.feed] as? Int ?? 0)"
date = dictionary[DictionaryKeys.date] as? String ?? ""
author = dictionary[DictionaryKeys.author] as? String ?? ""
title = dictionary[DictionaryKeys.title] as? String ?? ""
content = dictionary[DictionaryKeys.content] as? String ?? ""
if let base64 = dictionary[DictionaryKeys.imageData] as? String {
imageData = Data(base64Encoded: base64)
} else {
imageData = nil
}
if let data = imageData {
image = UIImage(data: data)
} else {
image = nil
}
}
/// Initializer for a sample.
///
/// - Parameter title: The title of the sample.
/// - Parameter feed: The feed identifier.
init(sample title: String, feed: String) {
id = UUID().uuidString
self.feed = feed
date = "2021-08-09"
author = "Sample"
self.title = title
content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec ornare dolor. Vivamus porta mi nec libero convallis tempus. Cras semper, ante et pretium vulputate, risus urna venenatis magna, vitae fringilla ipsum ante ut augue. Cras euismod, eros convallis scelerisque congue, massa sem elementum sem, ut condimentum est tortor id mauris."
imageData = nil
image = UIImage(systemName: "globe.americas.fill")
}
/// Keys for the codable representation.
enum CodingKeys: String, CodingKey {
case version = "version"
case id = "id"
case feed = "feed"
case date = "date"
case author = "author"
case title = "title"
case content = "content"
case imageData = "imageData"
}
/// Initializer to load from the JSON data.
///
/// - Parameter decoder: The decoder from which to read data.
/// - Throws: An error if the data is invalid.
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
feed = try container.decode(String.self, forKey: .feed)
date = try container.decode(String.self, forKey: .date)
author = try container.decode(String.self, forKey: .author)
title = try container.decode(String.self, forKey: .title)
content = try container.decode(String.self, forKey: .content)
imageData = try container.decodeIfPresent(Data.self, forKey: .imageData)
if let data = imageData {
image = UIImage(data: data)
} else {
image = nil
}
}
/// Encodes the story into the given encoder.
///
/// - Parameter encoder: The encoder to which to write data.
/// - Throws: An error if the data is invalid.
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(version, forKey: .version)
try container.encode(id, forKey: .id)
try container.encode(feed, forKey: .feed)
try container.encode(date, forKey: .date)
try container.encode(author, forKey: .author)
try container.encode(title, forKey: .title)
try container.encode(content, forKey: .content)
try container.encodeIfPresent(imageData, forKey: .imageData)
}
}
extension Story: Equatable {
static func ==(lhs: Story, rhs: Story) -> Bool {
return lhs.id == rhs.id
}
}
extension Story: CustomStringConvertible {
var description: String {
return "Story \(title) by \(author) (\(id))"
}
}
|
mit
|
8d7888892f19422837a1fc815bc72777
| 32.901316 | 366 | 0.607995 | 4.393009 | false | false | false | false |
Mogendas/ChickenFight
|
ChickenFight/Challenge.swift
|
1
|
986
|
//
// Challenge.swift
// ChickenFight
//
// Created by Johan Wejdenstolpe on 2017-08-07.
// Copyright © 2017 Johan Wejdenstolpe. All rights reserved.
//
import Foundation
class Challenge {
var challengeID: Int?
var attacker: String?
var defender: String?
var attackerMoves: Moves?
var defenderMoves: Moves?
var watched: Bool = false
init(){
}
init(challenge: Challenge) {
if challenge.challengeID != nil {
challengeID = challenge.challengeID
}
if challenge.attacker != nil {
attacker = challenge.attacker
}
if challenge.defender != nil {
defender = challenge.defender
}
if challenge.attackerMoves != nil {
attackerMoves = challenge.attackerMoves
}
if challenge.defenderMoves != nil {
defenderMoves = challenge.defenderMoves
}
watched = challenge.watched
}
}
|
gpl-3.0
|
89f822dd63b2fd2ab2ba069149b4ad88
| 21.906977 | 61 | 0.582741 | 4.539171 | false | false | false | false |
Marquis103/RecipeFinder
|
RecipeFinder/RecipeTableViewController.swift
|
1
|
4103
|
//
// RecipeTableViewController.swift
// RecipeFinder
//
// Created by Marquis Dennis on 5/8/16.
// Copyright © 2016 Marquis Dennis. All rights reserved.
//
import UIKit
class RecipeTableViewController: UITableViewController {
//MARK: Properties
var dataSource:RecipeTableViewControllerDataSource!
var loadingView = ActivityIndicatorLoadingView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0))
var recipeAPI = RecipeAPI.sharedAPI
private var isUpdating = false
var selectedRecipe:Recipe?
//MARK: Outlets
@IBOutlet weak var recipeSearchBar: UISearchBar!
//MARK: View Controller LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
dataSource = RecipeTableViewControllerDataSource()
tableView.dataSource = dataSource
tableView.delegate = self
loadingView.center = view.center
view.addSubview(loadingView)
recipeSearchBar.showsCancelButton = true
recipeSearchBar.delegate = self
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "recipeDetailSegue" {
let destinationController = segue.destinationViewController as! RecipeDetailViewController
if let recipe = selectedRecipe {
destinationController.recipe = recipe
}
}
}
//MARK: Methods
func updateRecipes() {
guard Reachability.connectedToNetwork() == true else {
let alert = getUIAlertController(withActvityTitle: "Internet Connection Required", message: "An Internet connection is required to search for recipes.", actionTitle: "OK")
presentViewController(alert, animated: true, completion: nil)
return
}
//perform search
recipeAPI.getRecipes(forFoodWithName: recipeSearchBar.text!, isUpdatingQuery: true) { (error) in
self.isUpdating = false
performUIUpdatesOnMain({
self.tableView.reloadData()
})
}
}
}
extension RecipeTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
guard Reachability.connectedToNetwork() == true else {
let alert = getUIAlertController(withActvityTitle: "Internet Connection Required", message: "An Internet connection is required to search for recipes.", actionTitle: "OK")
presentViewController(alert, animated: true, completion: nil)
return
}
loadingView.show()
//perform search
recipeAPI.getRecipes(forFoodWithName: searchBar.text!, isUpdatingQuery: false) { (error) in
guard error == nil else {
performUIUpdatesOnMain({
self.loadingView.hide()
let alert = getUIAlertController(withActvityTitle: "Query Error", message: "Sorry! There was an error performing your query. Please try again.", actionTitle: "OK")
self.presentViewController(alert, animated: true, completion: nil)
})
return
}
performUIUpdatesOnMain({
if self.recipeAPI.recipes.count > 0 {
self.loadingView.hide()
self.tableView.reloadData()
} else {
self.loadingView.hide()
let alert = getUIAlertController(withActvityTitle: "Results Not Found", message: "Ooops! It appears we could not find any results for \(searchBar.text!)", actionTitle: "OK")
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
loadingView.hide()
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
extension RecipeTableViewController {
override func scrollViewDidScroll(scrollView: UIScrollView) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
let deltaOffset = maximumOffset - currentOffset
if deltaOffset <= 0 && !isUpdating {
isUpdating = true
updateRecipes()
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
view.endEditing(true)
selectedRecipe = recipeAPI.recipes[indexPath.row]
performSegueWithIdentifier("recipeDetailSegue", sender: nil)
}
}
|
gpl-3.0
|
786d5554cdcda3a2b206b41803a88683
| 29.392593 | 179 | 0.745734 | 4.259605 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Nodes/Generators/Physical Models/Metal Bar/AKMetalBar.swift
|
1
|
8960
|
//
// AKMetalBar.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
///
///
/// - Parameters:
/// - leftBoundaryCondition: Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - rightBoundaryCondition: Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - decayDuration: 30db decay time (in seconds).
/// - scanSpeed: Speed of scanning the output location.
/// - position: Position along bar that strike occurs.
/// - strikeVelocity: Normalized strike velocity
/// - strikeWidth: Spatial width of strike.
/// - stiffness: Dimensionless stiffness parameter
/// - highFrequencyDamping: High-frequency loss parameter. Keep this small
///
public class AKMetalBar: AKNode {
// MARK: - Properties
internal var internalAU: AKMetalBarAudioUnit?
internal var token: AUParameterObserverToken?
private var leftBoundaryConditionParameter: AUParameter?
private var rightBoundaryConditionParameter: AUParameter?
private var decayDurationParameter: AUParameter?
private var scanSpeedParameter: AUParameter?
private var positionParameter: AUParameter?
private var strikeVelocityParameter: AUParameter?
private var strikeWidthParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
public var leftBoundaryCondition: Double = 1 {
willSet {
if leftBoundaryCondition != newValue {
leftBoundaryConditionParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
public var rightBoundaryCondition: Double = 1 {
willSet {
if rightBoundaryCondition != newValue {
rightBoundaryConditionParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// 30db decay time (in seconds).
public var decayDuration: Double = 3 {
willSet {
if decayDuration != newValue {
decayDurationParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Speed of scanning the output location.
public var scanSpeed: Double = 0.25 {
willSet {
if scanSpeed != newValue {
scanSpeedParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Position along bar that strike occurs.
public var position: Double = 0.2 {
willSet {
if position != newValue {
positionParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Normalized strike velocity
public var strikeVelocity: Double = 500 {
willSet {
if strikeVelocity != newValue {
strikeVelocityParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Spatial width of strike.
public var strikeWidth: Double = 0.05 {
willSet {
if strikeWidth != newValue {
strikeWidthParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this Bar node
///
/// - Parameters:
/// - leftBoundaryCondition: Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - rightBoundaryCondition: Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free
/// - decayDuration: 30db decay time (in seconds).
/// - scanSpeed: Speed of scanning the output location.
/// - position: Position along bar that strike occurs.
/// - strikeVelocity: Normalized strike velocity
/// - strikeWidth: Spatial width of strike.
/// - stiffness: Dimensionless stiffness parameter
/// - highFrequencyDamping: High-frequency loss parameter. Keep this small
///
public init(
leftBoundaryCondition: Double = 1,
rightBoundaryCondition: Double = 1,
decayDuration: Double = 3,
scanSpeed: Double = 0.25,
position: Double = 0.2,
strikeVelocity: Double = 500,
strikeWidth: Double = 0.05,
stiffness: Double = 3,
highFrequencyDamping: Double = 0.001) {
self.leftBoundaryCondition = leftBoundaryCondition
self.rightBoundaryCondition = rightBoundaryCondition
self.decayDuration = decayDuration
self.scanSpeed = scanSpeed
self.position = position
self.strikeVelocity = strikeVelocity
self.strikeWidth = strikeWidth
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x6d626172 /*'mbar'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKMetalBarAudioUnit.self,
asComponentDescription: description,
name: "Local AKMetalBar",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKMetalBarAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
leftBoundaryConditionParameter = tree.valueForKey("leftBoundaryCondition") as? AUParameter
rightBoundaryConditionParameter = tree.valueForKey("rightBoundaryCondition") as? AUParameter
decayDurationParameter = tree.valueForKey("decayDuration") as? AUParameter
scanSpeedParameter = tree.valueForKey("scanSpeed") as? AUParameter
positionParameter = tree.valueForKey("position") as? AUParameter
strikeVelocityParameter = tree.valueForKey("strikeVelocity") as? AUParameter
strikeWidthParameter = tree.valueForKey("strikeWidth") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.leftBoundaryConditionParameter!.address {
self.leftBoundaryCondition = Double(value)
} else if address == self.rightBoundaryConditionParameter!.address {
self.rightBoundaryCondition = Double(value)
} else if address == self.decayDurationParameter!.address {
self.decayDuration = Double(value)
} else if address == self.scanSpeedParameter!.address {
self.scanSpeed = Double(value)
} else if address == self.positionParameter!.address {
self.position = Double(value)
} else if address == self.strikeVelocityParameter!.address {
self.strikeVelocity = Double(value)
} else if address == self.strikeWidthParameter!.address {
self.strikeWidth = Double(value)
}
}
}
internalAU?.leftBoundaryCondition = Float(leftBoundaryCondition)
internalAU?.rightBoundaryCondition = Float(rightBoundaryCondition)
internalAU?.decayDuration = Float(decayDuration)
internalAU?.scanSpeed = Float(scanSpeed)
internalAU?.position = Float(position)
internalAU?.strikeVelocity = Float(strikeVelocity)
internalAU?.strikeWidth = Float(strikeWidth)
}
// MARK: - Control
/// Trigger the sound with an optional set of parameters
///
public func trigger() {
self.internalAU!.start()
self.internalAU!.trigger()
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
mit
|
271295cede79731c30c0c19c8728259e
| 36.966102 | 111 | 0.626563 | 5.143513 | false | false | false | false |
Nikita2k/Himotoki
|
HimotokiTests/DecodableTest.swift
|
1
|
7406
|
//
// DecodableTest.swift
// Himotoki
//
// Created by Syo Ikeda on 5/2/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
import XCTest
import Himotoki
class DecodableTest: XCTestCase {
lazy var personJSON: [String: AnyObject] = {
let gruopJSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]
var JSON: [String: AnyObject] = [
"first_name": "ABC",
"last_name": "DEF",
"age": 20,
"int64": NSNumber(longLong: INT64_MAX),
"height": 175.9,
"float": 32.1 as Float,
"bool": true,
"number": NSNumber(long: 123456789),
"raw_value": "RawValue",
"nested": [
"value": "The nested value",
"dict": [ "key": "The nested value" ]
],
"array": [ "123", "456" ],
"arrayOption": NSNull(),
"dictionary": [ "A": 1, "B": 2 ],
// "dictionaryOption" key is missing
"group": gruopJSON,
]
JSON["groups"] = [ gruopJSON, gruopJSON ]
return JSON
}()
func testPerson() {
var JSON = personJSON
// Succeeding case
let person: Person? = try? decode(JSON)
XCTAssert(person != nil)
XCTAssert(person?.firstName == "ABC")
XCTAssert(person?.lastName == "DEF")
XCTAssert(person?.age == 20)
XCTAssert(person?.int64 == INT64_MAX)
XCTAssert(person?.height == 175.9)
XCTAssert(person?.float == 32.1)
XCTAssert(person?.bool == true)
XCTAssert(person?.number == NSNumber(long: 123456789))
XCTAssert(person?.rawValue as? String == "RawValue")
XCTAssert(person?.nested == "The nested value")
XCTAssert(person?.nestedDict["key"] == "The nested value")
XCTAssert(person?.array.count == 2)
XCTAssert(person?.array.first == "123")
XCTAssert(person?.arrayOption == nil)
XCTAssert(person?.dictionary.count == 2)
XCTAssert(person?.dictionary["A"] == 1)
XCTAssert(person?.dictionaryOption == nil)
XCTAssert(person?.group.name == "Himotoki")
XCTAssert(person?.group.floor == 12)
XCTAssert(person?.group.optional == nil)
XCTAssert(person?.groups.count == 2)
// Failing cases
do {
JSON["bool"] = nil
JSON["group"] = nil
try decode(JSON) as Person
} catch let DecodeError.MissingKeyPath(keyPath) {
XCTAssert(keyPath == "bool")
} catch {
XCTFail()
}
do {
JSON["age"] = "32"
try decode(JSON) as Person
} catch let DecodeError.TypeMismatch(expected, actual, keyPath) {
XCTAssert(keyPath == "age")
XCTAssert(actual == "32")
XCTAssert(expected == "Int")
} catch {
XCTFail()
}
}
func testPerformanceByPersons() {
let peopleJSON = Array(count: 500, repeatedValue: personJSON)
measureBlock {
let _: [Person]? = try? decodeArray(peopleJSON)
}
}
func testGroup() {
var JSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]
let g: Group? = try? decode(JSON)
XCTAssert(g != nil)
XCTAssert(g?.name == "Himotoki")
XCTAssert(g?.floor == 12)
XCTAssert(g?.optional == nil)
JSON["name"] = nil
do {
try decode(JSON) as Group
} catch let DecodeError.MissingKeyPath(keyPath) {
XCTAssert(keyPath == "name")
} catch {
XCTFail()
}
}
func testDecodeArray() {
let JSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]
let JSONArray = [ JSON, JSON ]
let values: [Group]? = try? decodeArray(JSONArray)
XCTAssert(values != nil)
XCTAssert(values?.count == 2)
}
func testDecodeDictionary() {
let JSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]
let JSONDict = [ "1": JSON, "2": JSON ]
let values: [String: Group]? = try? decodeDictionary(JSONDict)
XCTAssert(values != nil)
XCTAssert(values?.count == 2)
}
func testDecodeNumbers() {
let JSON: [String: AnyObject] = [
"int": Int.min,
"uint": UInt.max,
"int8": NSNumber(char: Int8.min),
"uint8": NSNumber(unsignedChar: UInt8.max),
"int16": NSNumber(short: Int16.min),
"uint16": NSNumber(unsignedShort: UInt16.max),
"int32": NSNumber(int: Int32.min),
"uint32": NSNumber(unsignedInt: UInt32.max),
"int64": NSNumber(longLong: Int64.min),
"uint64": NSNumber(unsignedLongLong: UInt64.max),
]
let numbers: Numbers? = try? decode(JSON)
XCTAssert(numbers != nil)
XCTAssert(numbers?.int == Int.min)
XCTAssert(numbers?.uint == UInt.max)
XCTAssert(numbers?.int8 == Int8.min)
XCTAssert(numbers?.uint8 == UInt8.max)
XCTAssert(numbers?.int16 == Int16.min)
XCTAssert(numbers?.uint16 == UInt16.max)
XCTAssert(numbers?.int32 == Int32.min)
XCTAssert(numbers?.uint32 == UInt32.max)
XCTAssert(numbers?.int64 == Int64.min)
XCTAssert(numbers?.uint64 == UInt64.max)
}
}
struct Person: Decodable {
let firstName: String
let lastName: String
let age: Int
let int64: Int64
let height: Double
let float: Float
let bool: Bool
let number: NSNumber
let rawValue: AnyObject
let nested: String
let nestedDict: [String: String]
let array: [String]
let arrayOption: [String]?
let dictionary: [String: Int]
let dictionaryOption: [String: Int]?
let group: Group
let groups: [Group]
static func decode(e: Extractor) throws -> Person {
return try build(Person.init)(
e <| "first_name",
e <| "last_name",
e <| "age",
e <| "int64",
e <| "height",
e <| "float",
e <| "bool",
e <| "number",
(e <| "raw_value" as Extractor).rawValue,
e <| [ "nested", "value" ],
e <|-| [ "nested", "dict" ],
e <|| "array",
e <||? "arrayOption",
e <|-| "dictionary",
e <|-|? "dictionaryOption",
e <| "group",
e <|| "groups"
)
}
}
struct Group: Decodable {
let name: String
let floor: Int
let optional: [String]?
static func decode(e: Extractor) throws -> Group {
return try build(Group.init)(
e <| "name",
e <| "floor",
e <||? "optional"
)
}
}
struct Numbers: Decodable {
let int: Int
let uint: UInt
let int8: Int8
let uint8: UInt8
let int16: Int16
let uint16: UInt16
let int32: Int32
let uint32: UInt32
let int64: Int64
let uint64: UInt64
static func decode(e: Extractor) throws -> Numbers {
return try build(Numbers.init)(
e <| "int",
e <| "uint",
e <| "int8",
e <| "uint8",
e <| "int16",
e <| "uint16",
e <| "int32",
e <| "uint32",
e <| "int64",
e <| "uint64"
)
}
}
|
mit
|
e81a6efc9d7670471b32accca419ca95
| 28.043137 | 80 | 0.517283 | 4.062534 | false | false | false | false |
rsaenzi/MyWeatherForecastApp
|
MyWeatherForecastApp/MyWeatherForecastApp/CitySelectionVC.swift
|
1
|
1729
|
//
// CitySelectionVC.swift
// MyWeatherForecastApp
//
// Created by Rigoberto Sáenz Imbacuán on 2/3/16.
// Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved.
//
import UIKit
import KVNProgress
class CitySelectionVC: UITableViewController {
// Countries Data [Name: [latitude: longitude]]
var countries: [String] = []
var cities: [Array<String>] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Model.instance.getSelectedCountryCities()!.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Obtenemos una copia de la celda prototipo
let currentCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cellCity")!
// Colomamos el nombre del pais en la celda
currentCell.textLabel?.text = Model.instance.getSelectedCountryCities()![indexPath.row]
// Retornamos la celda ya configurada
return currentCell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
// Obtenemos los datos de la ciudad seleccionada
let name: String = Model.instance.getSelectedCountryCities()![indexPath.row]
// Guardamos la data del pais seleccionado
Model.instance.setSelectedCity(name)
// Quitamos la pantalla actual
self.navigationController?.popViewControllerAnimated(true)
self.navigationController?.popViewControllerAnimated(true)
}
}
|
mit
|
1d6187dd7058fb551de2055e2c940000
| 31.566038 | 118 | 0.681924 | 4.974063 | false | false | false | false |
polymr/polymyr-api
|
Sources/App/Models/Tag.swift
|
1
|
1096
|
//
// Tag.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/4/17.
//
//
import Vapor
import Fluent
import FluentProvider
import Node
final class Tag: Model, Preparation, JSONConvertible, NodeConvertible, Sanitizable {
let storage = Storage()
static var permitted: [String] = ["name"]
var id: Identifier?
var exists = false
let name: String
init(node: Node) throws {
id = try? node.extract("id")
name = try node.extract("name")
}
func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"name" : name
]).add(objects: [
"id" : id
])
}
static func prepare(_ database: Database) throws {
try database.create(Tag.self) { tag in
tag.id()
tag.string("name")
}
}
static func revert(_ database: Database) throws {
try database.delete(Tag.self)
}
}
extension Tag {
func products() -> Siblings<Tag, Product, Pivot<Tag, Product>> {
return siblings()
}
}
|
mit
|
5669bc20577d5cd7074eb01e2ecaa7a5
| 18.927273 | 84 | 0.555657 | 4.014652 | false | false | false | false |
darren90/Gankoo_Swift
|
Gankoo/Gankoo/Lib/Vendor/TFCycleScrollView/TFCycleScrollView.swift
|
1
|
3716
|
//
// TFCycleScrollView.swift
// Gankoo
//
// Created by Fengtf on 2017/2/7.
// Copyright © 2017年 ftf. All rights reserved.
//
import UIKit
let TFSection = 100
protocol TFCycleScrollViewDelegate {
// func cycleScrollViewDidSelectAtIndex
}
class TFCycleScrollView: UIView {
var imgsArray:[String]?{
didSet{
}
}
var dataArray:[String]?
lazy var waterView:UICollectionView = UICollectionView(frame: self.frame, collectionViewLayout: UICollectionViewFlowLayout())
lazy var pageControl:UIPageControl = UIPageControl()
var timer : Timer?
override init(frame: CGRect) {
super.init(frame: frame)
initSubViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubViews(){
self .addSubview(waterView)
waterView.isPagingEnabled = true
waterView.delegate = self
waterView.dataSource = self
waterView.showsHorizontalScrollIndicator = false
waterView.backgroundColor = UIColor.white
waterView.frame = self.bounds
let flowLayout = waterView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.itemSize = self.frame.size
flowLayout.scrollDirection = .horizontal
}
override func layoutSubviews() {
super.layoutSubviews()
}
func addTimer(){
if timer == nil {
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.goToNext), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
}
func destroyTimer(){
if let timer = timer{
timer.invalidate()
}
}
func resetIndexPath() -> IndexPath{
let currentIndexPath = waterView.indexPathsForVisibleItems.last
let currentIndexPathReset = IndexPath(item: (currentIndexPath?.item)!, section: TFSection/2)
waterView.scrollToItem(at: currentIndexPathReset, at: .left, animated: false)
return currentIndexPathReset
}
func goToNext(){
if timer == nil {
return
}
let currentIndexPath = resetIndexPath()
var nexItem = currentIndexPath.item + 1
var nexSection = currentIndexPath.section
if nexItem == dataArray?.count {
nexItem = 0
nexSection = nexSection + 1
}
let nexIndexPath = IndexPath(item: nexItem, section: nexSection)
waterView.scrollToItem(at: nexIndexPath, at: .left, animated: true)
pageControl.currentPage = nexItem
}
}
extension TFCycleScrollView : UICollectionViewDataSource,UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return TFSection
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (dataArray?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// let pageNum = Float(((Float(scrollView.contentOffset.x) / Float(self.frame.width)) + 0.5)) % (Float(dataArray!.count))
// pageControl.currentPage = Int(pageNum)
}
}
|
apache-2.0
|
582db6419a9aa0f860e7ba7d83560cdb
| 24.965035 | 137 | 0.656612 | 4.963904 | false | false | false | false |
ShawnMoore/Swift1.2-SQLiteFramework
|
SQLiteFramework/SQLite3_Stmt.swift
|
1
|
10706
|
//
// SQLite3_Stmt.swift
// SQLiteFramework
//
// Created by Shawn Moore on 6/2/15.
// Copyright (c) 2015 Shawn Moore. All rights reserved.
//
import UIKit
public class SQLite3_Stmt {
internal var local_sqlite3_stmt: COpaquePointer = nil
private var local_pzTail: UnsafePointer<Int8> = nil
public var returnCode = SQLite.LOCAL_UNKNOWN
public var pzTail: String? {
if local_pzTail == nil {
return nil
} else {
return String.fromCString(UnsafePointer<CChar>(local_pzTail))
}
}
internal init?(ppStmt: COpaquePointer, pzTail: UnsafePointer<Int8>, rc: SQLite) {
if ppStmt == nil { return nil }
self.local_sqlite3_stmt = ppStmt
self.local_pzTail = pzTail
self.returnCode = rc
}
deinit {
self.finalize()
}
//sqlite3_reset(pStmt: COpaquePointer)
public func reset() -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_reset(local_sqlite3_stmt)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//sqlite3_step(COpaquePointer)
public func step() -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_step(local_sqlite3_stmt)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//sqlite3_column_count(COpaquePointer)
public func column_count() -> Int {
return Int(sqlite3_column_count(local_sqlite3_stmt))
}
//sqlite3_column_name(COpaquePointer, N: Int32)
public func column_name(iCol: Int) -> String? {
let charArray = sqlite3_column_name(local_sqlite3_stmt, Int32(iCol))
return String.fromCString(UnsafePointer<CChar>(charArray))
}
//sqlite3_finalize(pStmt: COpaquePointer)
public func finalize() -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_finalize(local_sqlite3_stmt)) {
local_sqlite3_stmt = nil
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
// MARK: BINDING INTERFACE
//int sqlite3_bind_double( sqlite3_stmt *stmt, int pidx, double data )
//sqlite3_bind_double(COpaquePointer, Int32, Double)
public func bind_double(pidx: Int, data: Double) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_double(local_sqlite3_stmt, Int32(pidx), data)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_int( sqlite3_stmt *stmt, int pidx, int data )
//sqlite3_bind_int(COpaquePointer, Int32, Int32)
public func bind_int(pidx: Int, data: Int) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_int(local_sqlite3_stmt, Int32(pidx), Int32(data))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_int64( sqlite3_stmt *stmt, int pidx, sqlite3_int64 )
//sqlite3_bind_int64(COpaquePointer, Int32, sqlite3_int64)
public func bind_int64(pidx: Int, data: Int) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_int64(local_sqlite3_stmt, Int32(pidx), NSNumber(integer: data).longLongValue as sqlite3_int64)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_null( sqlite3_stmt *stmt, int pidx )
//sqlite3_bind_null(COpaquePointer, Int32)
public func bind_null(pidx: Int) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_null(local_sqlite3_stmt, Int32(pidx))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_text( sqlite3_stmt *stmt, int pidx, const char *data, int data_len, mem_callback )
//sqlite3_bind_text(COpaquePointer, Int32, UnsafePointer<Int8>, n: Int32, { (UnsafeMutablePointer<Void>) -> Void in code })
public func bind_text(pidx: Int, data: String) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_text(local_sqlite3_stmt, Int32(pidx), data.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, sqlite3_destructor_type(COpaquePointer(bitPattern: -1)))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_text16( sqlite3_stmt *stmt, int pidx, const void *data, int data_len, mem_callback )
//sqlite3_bind_text16(COpaquePointer, Int32, UnsafePointer<Void>, Int32, { (UnsafeMutablePointer<Void>) -> Void in code })
public func bind_text16(pidx: Int, data: String) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_text16(local_sqlite3_stmt, Int32(pidx), data.cStringUsingEncoding(NSUTF16StringEncoding)!, -1, sqlite3_destructor_type(COpaquePointer(bitPattern: -1)))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_zeroblob( sqlite3_stmt *stmt, int pidx, int len )
public func bind_zeroblob(pidx: Int, len: Int) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_zeroblob(local_sqlite3_stmt, Int32(pidx), Int32(len))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_blob( sqlite3_stmt *stmt, int pidx, const void *data, int data_len, mem_callback )
//sqlite3_bind_blob(COpaquePointer, Int32, UnsafePointer<Void>, n: Int32, { (UnsafeMutablePointer<Void>) -> Void in code })
public func bind_blob(pidx: Int, data: NSData) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_blob(local_sqlite3_stmt, Int32(pidx), data.bytes, Int32(data.length), sqlite3_destructor_type(COpaquePointer(bitPattern: -1)))) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
//int sqlite3_bind_value( sqlite3_stmt *stmt, int pidx, const sqlite3_value *data_value )
//sqlite3_bind_value(COpaquePointer, Int32, COpaquePointer)
public func bind_value(pidx: Int, data_value: SQLite_Value) -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_bind_value(local_sqlite3_stmt, Int32(pidx), data_value.value)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
// MARK: BINDING UTILITY INTERFACE
//int sqlite3_bind_parameter_count( sqlite3_stmt *stmt )
//sqlite3_bind_parameter_count(COpaquePointer)
public func bind_parameter_count() -> Int {
return Int(sqlite3_bind_parameter_count(local_sqlite3_stmt))
}
//int sqlite3_bind_parameter_index( sqlite3_stmt *stmt, const char *name )
//sqlite3_bind_parameter_index(COpaquePointer, zName: UnsafePointer<Int8>)
public func bind_parameter_index(zName: String) -> Int {
return Int(sqlite3_bind_parameter_index(local_sqlite3_stmt, zName.cStringUsingEncoding(NSUTF8StringEncoding)!))
}
//const char* sqlite3_bind_parameter_name( sqlite3_stmt *stmt, int pidx )
public func bind_parameter_name(pidx: Int) -> String? {
return String.fromCString(UnsafePointer<CChar>(sqlite3_bind_parameter_name(local_sqlite3_stmt, Int32(pidx))))
}
//int sqlite3_clear_bindings( sqlite3_stmt *stmt )
//sqlite3_clear_bindings(COpaquePointer)
public func clear_bindings() -> SQLite {
if let returnValue = SQLite(rawValue: sqlite3_clear_bindings(local_sqlite3_stmt)) {
return returnValue
} else {
return SQLite.LOCAL_UNKNOWN
}
}
// MARK: RESULT SET INTERFACE
//sqlite3_column_blob(COpaquePointer, iCol: Int32)
public func column_blob(iCol: Int) -> NSData? {
var blobPointer = sqlite3_column_blob(local_sqlite3_stmt, Int32(iCol))
if blobPointer != nil {
var size = column_bytes(iCol)
return NSData(bytes: blobPointer, length: size)
} else {
return nil
}
}
//sqlite3_column_bytes(COpaquePointer, iCol: Int32)
public func column_bytes(iCol: Int) -> Int {
return Int(sqlite3_column_bytes(local_sqlite3_stmt, Int32(iCol)))
}
//sqlite3_column_bytes16(COpaquePointer, iCol: Int32)
public func column_bytes16(iCol: Int) -> Int {
return Int(sqlite3_column_bytes16(local_sqlite3_stmt, Int32(iCol)))
}
//sqlite3_column_double(COpaquePointer, iCol: Int32)
public func column_double(iCol: Int) -> Double {
return sqlite3_column_double(local_sqlite3_stmt, Int32(iCol))
}
//sqlite3_column_int(COpaquePointer, iCol: Int32)
public func column_int(iCol: Int) -> Int32 {
return sqlite3_column_int(local_sqlite3_stmt, Int32(iCol))
}
//sqlite3_column_int64(COpaquePointer, iCol: Int32)
public func column_int64(iCol: Int) -> Int {
return Int(sqlite3_column_int64(local_sqlite3_stmt, Int32(iCol)))
}
//sqlite3_column_text(COpaquePointer, iCol: Int32)
public func column_text(iCol: Int) -> String? {
let charArray = sqlite3_column_text(local_sqlite3_stmt, Int32(iCol))
return String.fromCString(UnsafePointer<CChar>(charArray))
}
//sqlite3_column_text16(COpaquePointer, iCol: Int32)
public func column_text16(iCol: Int) -> String? {
var charArray = sqlite3_column_text16(local_sqlite3_stmt, Int32(iCol))
if charArray == nil {
return nil
} else {
var size = column_bytes16(iCol)
return NSString(characters: UnsafePointer<unichar>(charArray), length: size) as String
}
}
//sqlite3_column_type(COpaquePointer, iCol: Int32)
public func column_type(iCol: Int) -> SQLite_Type {
let value = sqlite3_column_type(local_sqlite3_stmt, Int32(iCol))
if let returnValue = SQLite_Type(rawValue: value) {
return returnValue
} else {
return SQLite_Type.LOCAL_UNKNOWN
}
}
//sqlite3_column_value(COpaquePointer, iCol: Int32)
//sqlite3_value* sqlite3_column_value( sqlite_stmt *stmt, int cidx )
public func column_value(iCol: Int) -> SQLite_Value {
return SQLite_Value(value: sqlite3_column_value(local_sqlite3_stmt, Int32(iCol)), protected: false)
}
}
public struct SQLite_Value {
internal var value: COpaquePointer
public let protected: Bool
internal init(value: COpaquePointer, protected: Bool) {
self.value = value
self.protected = protected
}
}
|
mit
|
31799f71f3a4928416931227220ec0a6
| 37.239286 | 213 | 0.632636 | 3.783039 | false | false | false | false |
Shun87/OpenAdblock
|
Open Adblock/Open Adblock/SettingsTableViewController.swift
|
2
|
2234
|
//
// SettingsTableViewController.swift
// Open Adblock
//
// Created by Justin on 2015-08-13.
// Copyright © 2015 OpenAdblock. All rights reserved.
//
import SafariServices
import UIKit
class SettingsTableViewController: UITableViewController {
@IBOutlet weak var blockAds: UISwitch! {
didSet {
blockAds.setOn(NSUserDefaults(suiteName: "group.openadblock.openadblock")?.boolForKey("blockAds") ?? false, animated: false)
}
}
@IBOutlet weak var blockAnalytics: UISwitch!
let testAdblockWebView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
testAdblockWebView.scalesPageToFit = true
testAdblockWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.jusleg.com/testOAB")!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func blockAds(sender: AnyObject) {
NSUserDefaults(suiteName: "group.openadblock.openadblock")!.setBool((sender as! UISwitch).on, forKey: "blockAds")
SFContentBlockerManager.reloadContentBlockerWithIdentifier("\(NSBundle.mainBundle().bundleIdentifier!).contentblockerextension", completionHandler: nil)
}
@IBAction func blockAnalytics(sender: AnyObject) {
}
@IBAction func openSettings(sender: AnyObject) {
if let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(settingsURL)
}
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 1 {
return testAdblockWebView
} else {
return super.tableView(tableView, viewForFooterInSection: section)
}
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 1 {
return CGFloat(200)
} else {
return super.tableView(tableView, heightForFooterInSection: section)
}
}
}
|
apache-2.0
|
e504e83233026b00bb961e79bbf5939e
| 33.90625 | 160 | 0.672638 | 5.08656 | false | true | false | false |
tsolomko/SWCompression
|
Sources/GZip/GzipArchive.swift
|
1
|
8838
|
// Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import BitByteData
/// Provides unarchive and archive functions for GZip archives.
public class GzipArchive: Archive {
/// Represents the member of a multi-member GZip archive.
public struct Member {
/// GZip header of a member.
public let header: GzipHeader
/// Unarchived data from a member.
public let data: Data
let crcError: Bool
}
/**
Unarchives GZip archive.
- Note: This function is specification compliant.
- Parameter archive: Data archived with GZip.
- Throws: `DeflateError` or `GzipError` depending on the type of the problem.
It may indicate that either archive is damaged or it might not be archived with GZip
or compressed with Deflate at all.
- Returns: Unarchived data.
*/
public static func unarchive(archive data: Data) throws -> Data {
/// Object with input data which supports convenient work with bit shifts.
let bitReader = LsbBitReader(data: data)
let member = try processMember(bitReader)
guard !member.crcError
else { throw GzipError.wrongCRC([member]) }
return member.data
}
/**
Unarchives multi-member GZip archive.
Multi-member GZip archives are essentially several GZip archives following each other in a single file.
- Parameter archive: GZip archive with one or more members.
- Throws: `DeflateError` or `GzipError` depending on the type of the problem.
It may indicate that one of the members of archive is damaged or
it might not be archived with GZip or compressed with Deflate at all.
- Returns: Unarchived data.
*/
public static func multiUnarchive(archive data: Data) throws -> [Member] {
/// Object with input data which supports convenient work with bit shifts.
let bitReader = LsbBitReader(data: data)
var result = [Member]()
while !bitReader.isFinished {
let member = try processMember(bitReader)
result.append(member)
guard !member.crcError
else { throw GzipError.wrongCRC(result) }
}
return result
}
private static func processMember(_ bitReader: LsbBitReader) throws -> Member {
// Valid GZip archive must contain at least 20 bytes of data (10 for the header, 2 for an empty Deflate block,
// and 8 for checksums). In addition, since GZip format is "byte-oriented" we should ensure that members are
// byte-aligned.
guard bitReader.isAligned && bitReader.bytesLeft >= 20
else { throw GzipError.wrongMagic }
let header = try GzipHeader(bitReader)
let memberData = try Deflate.decompress(bitReader)
bitReader.align()
guard bitReader.bytesLeft >= 8
else { throw GzipError.wrongMagic }
let crc32 = bitReader.uint32()
let isize = bitReader.uint64(fromBytes: 4)
guard UInt64(truncatingIfNeeded: memberData.count) % (UInt64(truncatingIfNeeded: 1) << 32) == isize
else { throw GzipError.wrongISize }
return Member(header: header, data: memberData,
crcError: CheckSums.crc32(memberData) != crc32)
}
/**
Archives `data` into GZip archive, using various specified options.
Data will be also compressed with Deflate algorithm.
It will be also specified in archive's header that the compressor used the slowest Deflate algorithm.
- Note: This function is specification compliant.
- Parameter data: Data to compress and archive.
- Parameter comment: Additional comment, which will be stored as a separate field in archive.
- Parameter fileName: Name of the file which will be archived.
- Parameter writeHeaderCRC: Set to true, if you want to store consistency check for archive's header.
- Parameter isTextFile: Set to true, if the file which will be archived is text file or ASCII-file.
- Parameter osType: Type of the system on which this archive will be created.
- Parameter modificationTime: Last time the file was modified.
- Parameter extraFields: Any extra fields. Note that no extra field is allowed to have second byte of the extra
field (subfield) ID equal to zero. In addition, the length of a field's binary content must be less than
`UInt16.max`, while the total sum of the binary content length of all extra fields plus 4 for each field must also
not exceed `UInt16.max`. See GZip format specification for more details.
- Throws: `GzipError.cannotEncodeISOLatin1` if a file name or a comment cannot be encoded with ISO-Latin-1 encoding
or if the total sum of the binary content length of all extra fields plus 4 for each field exceeds `UInt16.max`.
- Returns: Resulting archive's data.
*/
public static func archive(data: Data, comment: String? = nil, fileName: String? = nil,
writeHeaderCRC: Bool = false, isTextFile: Bool = false,
osType: FileSystemType? = nil, modificationTime: Date? = nil,
extraFields: [GzipHeader.ExtraField] = []) throws -> Data {
var flags: UInt8 = 0
var commentData = Data()
if var comment = comment {
flags |= 1 << 4
if comment.last != "\u{00}" {
comment.append("\u{00}")
}
if let data = comment.data(using: .isoLatin1) {
commentData = data
} else {
throw GzipError.cannotEncodeISOLatin1
}
}
var fileNameData = Data()
if var fileName = fileName {
flags |= 1 << 3
if fileName.last != "\u{00}" {
fileName.append("\u{00}")
}
if let data = fileName.data(using: .isoLatin1) {
fileNameData = data
} else {
throw GzipError.cannotEncodeISOLatin1
}
}
if !extraFields.isEmpty {
flags |= 1 << 2
}
if writeHeaderCRC {
flags |= 1 << 1
}
if isTextFile {
flags |= 1 << 0
}
let os = osType?.osTypeByte ?? 255
var mtimeBytes: [UInt8] = [0, 0, 0, 0]
if let modificationTime = modificationTime {
let timeInterval = Int(modificationTime.timeIntervalSince1970)
for i in 0..<4 {
mtimeBytes[i] = UInt8(truncatingIfNeeded: (timeInterval & (0xFF << (i * 8))) >> (i * 8))
}
}
var headerBytes: [UInt8] = [
0x1f, 0x8b, // 'magic' bytes.
8, // Compression method (DEFLATE).
flags
]
for i in 0..<4 {
headerBytes.append(mtimeBytes[i])
}
headerBytes.append(2) // Extra flags; 2 means that DEFLATE used slowest algorithm.
headerBytes.append(os)
if !extraFields.isEmpty {
let xlen = extraFields.reduce(0) { $0 + 4 + $1.bytes.count }
guard xlen <= UInt16.max
else { throw GzipError.cannotEncodeISOLatin1 }
headerBytes.append((xlen & 0xFF).toUInt8())
headerBytes.append(((xlen >> 8) & 0xFF).toUInt8())
for extraField in extraFields {
headerBytes.append(extraField.si1)
headerBytes.append(extraField.si2)
let len = extraField.bytes.count
headerBytes.append((len & 0xFF).toUInt8())
headerBytes.append(((len >> 8) & 0xFF).toUInt8())
for byte in extraField.bytes {
headerBytes.append(byte)
}
}
}
var outData = Data(headerBytes)
outData.append(fileNameData)
outData.append(commentData)
if writeHeaderCRC {
let headerCRC = CheckSums.crc32(outData)
for i: UInt32 in 0..<2 {
outData.append(UInt8(truncatingIfNeeded: (headerCRC & (0xFF << (i * 8))) >> (i * 8)))
}
}
outData.append(Deflate.compress(data: data))
let crc32 = CheckSums.crc32(data)
var crcBytes = [UInt8]()
for i: UInt32 in 0..<4 {
crcBytes.append(UInt8(truncatingIfNeeded: (crc32 & (0xFF << (i * 8))) >> (i * 8)))
}
outData.append(Data(crcBytes))
let isize = UInt64(data.count) % UInt64(1) << 32
var isizeBytes = [UInt8]()
for i: UInt64 in 0..<4 {
isizeBytes.append(UInt8(truncatingIfNeeded: (isize & (0xFF << (i * 8))) >> (i * 8)))
}
outData.append(Data(isizeBytes))
return outData
}
}
|
mit
|
160e6996bd3b56a875df4cc68d6e64d0
| 35.37037 | 120 | 0.600588 | 4.41018 | false | false | false | false |
gaoleegin/SwiftLianxi
|
SwiftLianxi/SwiftLianxi/Classes/Mudule/Main/BaseTableViewController.swift
|
1
|
4072
|
//
// BaseTableViewController.swift
// SwiftLianxi
//
// Created by 高李军 on 15/10/19.
// Copyright © 2015年 LJLianXi. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController,VisitorViewDelegate{
//这样的话一个UITableViewController变成了一个UIViewController
var visitorView:VisitorView?
override func loadView() {
visitorView = NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).last as? VisitorView
visitorView!.delegate = self
self.view = visitorView
}
func VisitorViewRegiestViewDidSelected() {
}
func VisitorViewLoginViewDidSelected() {
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "leftbarButtonClicked")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "rightbarButtonClicked")
}
///右边的注册
func rightbarButtonClicked(){
let oaVC = UIStoryboard(name: "OAuth", bundle: nil).instantiateInitialViewController() as! UINavigationController
presentViewController(oaVC, animated: true, completion: nil)
}
/// 左边的登录
func leftbarButtonClicked(){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
a5bb243d9771384c073d21e5dee40a45
| 31.893443 | 157 | 0.681535 | 5.452446 | false | false | false | false |
douShu/weiboInSwift
|
weiboInSwift/weiboInSwift/Classes/Tools/UIButton + Extension.swift
|
1
|
1374
|
//
// UIButton + Extension.swift
// weiboInSwift
//
// Created by 逗叔 on 15/9/12.
// Copyright © 2015年 逗叔. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(title: String, imgName: String, fontSize: CGFloat = 12, fontColor: UIColor = UIColor.darkGrayColor()) {
self.init()
setTitle(title, forState: UIControlState.Normal)
setImage(UIImage(named: imgName), forState: UIControlState.Normal)
setTitleColor(fontColor, forState: UIControlState.Normal)
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
}
convenience init(imageName: String) {
self.init()
setImage(imageName)
}
func setImage(imageName: String) {
setImage(UIImage(named: imageName), forState: UIControlState.Normal)
setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
}
convenience init(title: String, fontSize: CGFloat = 14, fontColor: UIColor = UIColor.whiteColor(), backColor: UIColor = UIColor.blackColor()) {
self.init()
setTitle(title, forState: UIControlState.Normal)
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
setTitleColor(fontColor, forState: UIControlState.Normal)
backgroundColor = backColor
}
}
|
mit
|
d787d74a0b737a6801ac7e6bc9a1d134
| 29.288889 | 147 | 0.653705 | 4.765734 | false | false | false | false |
aatalyk/swift-algorithm-club
|
Bit Set/BitSet.swift
|
18
|
6025
|
/*
A fixed-size sequence of n bits. Bits have indices 0 to n-1.
*/
public struct BitSet {
/* How many bits this object can hold. */
private(set) public var size: Int
/*
We store the bits in a list of unsigned 64-bit integers.
The first entry, `words[0]`, is the least significant word.
*/
private let N = 64
public typealias Word = UInt64
fileprivate(set) public var words: [Word]
private let allOnes = ~Word()
/* Creates a bit set that can hold `size` bits. All bits are initially 0. */
public init(size: Int) {
precondition(size > 0)
self.size = size
// Round up the count to the next multiple of 64.
let n = (size + (N-1)) / N
words = [Word](repeating: 0, count: n)
}
/* Converts a bit index into an array index and a mask inside the word. */
private func indexOf(_ i: Int) -> (Int, Word) {
precondition(i >= 0)
precondition(i < size)
let o = i / N
let m = Word(i - o*N)
return (o, 1 << m)
}
/* Returns a mask that has 1s for all bits that are in the last word. */
private func lastWordMask() -> Word {
let diff = words.count*N - size
if diff > 0 {
// Set the highest bit that's still valid.
let mask = 1 << Word(63 - diff)
// Subtract 1 to turn it into a mask, and add the high bit back in.
return mask | (mask - 1)
} else {
return allOnes
}
}
/*
If the size is not a multiple of N, then we have to clear out the bits
that we're not using, or bitwise operations between two differently sized
BitSets will go wrong.
*/
fileprivate mutating func clearUnusedBits() {
words[words.count - 1] &= lastWordMask()
}
/* So you can write bitset[99] = ... */
public subscript(i: Int) -> Bool {
get { return isSet(i) }
set { if newValue { set(i) } else { clear(i) } }
}
/* Sets the bit at the specified index to 1. */
public mutating func set(_ i: Int) {
let (j, m) = indexOf(i)
words[j] |= m
}
/* Sets all the bits to 1. */
public mutating func setAll() {
for i in 0..<words.count {
words[i] = allOnes
}
clearUnusedBits()
}
/* Sets the bit at the specified index to 0. */
public mutating func clear(_ i: Int) {
let (j, m) = indexOf(i)
words[j] &= ~m
}
/* Sets all the bits to 0. */
public mutating func clearAll() {
for i in 0..<words.count {
words[i] = 0
}
}
/* Changes 0 into 1 and 1 into 0. Returns the new value of the bit. */
public mutating func flip(_ i: Int) -> Bool {
let (j, m) = indexOf(i)
words[j] ^= m
return (words[j] & m) != 0
}
/* Determines whether the bit at the specific index is 1 (true) or 0 (false). */
public func isSet(_ i: Int) -> Bool {
let (j, m) = indexOf(i)
return (words[j] & m) != 0
}
/*
Returns the number of bits that are 1. Time complexity is O(s) where s is
the number of 1-bits.
*/
public var cardinality: Int {
var count = 0
for var x in words {
while x != 0 {
let y = x & ~(x - 1) // find lowest 1-bit
x = x ^ y // and erase it
count += 1
}
}
return count
}
/* Checks if all the bits are set. */
public func all1() -> Bool {
for i in 0..<words.count - 1 {
if words[i] != allOnes { return false }
}
return words[words.count - 1] == lastWordMask()
}
/* Checks if any of the bits are set. */
public func any1() -> Bool {
for x in words {
if x != 0 { return true }
}
return false
}
/* Checks if none of the bits are set. */
public func all0() -> Bool {
for x in words {
if x != 0 { return false }
}
return true
}
}
// MARK: - Equality
extension BitSet: Equatable {
}
public func == (lhs: BitSet, rhs: BitSet) -> Bool {
return lhs.words == rhs.words
}
// MARK: - Hashing
extension BitSet: Hashable {
/* Based on the hashing code from Java's BitSet. */
public var hashValue: Int {
var h = Word(1234)
for i in stride(from: words.count, to: 0, by: -1) {
h ^= words[i - 1] &* Word(i)
}
return Int((h >> 32) ^ h)
}
}
// MARK: - Bitwise operations
extension BitSet: BitwiseOperations {
public static var allZeros: BitSet {
return BitSet(size: 64)
}
}
private func copyLargest(_ lhs: BitSet, _ rhs: BitSet) -> BitSet {
return (lhs.words.count > rhs.words.count) ? lhs : rhs
}
/*
Note: In all of these bitwise operations, lhs and rhs are allowed to have a
different number of bits. The new BitSet always has the larger size.
The extra bits that get added to the smaller BitSet are considered to be 0.
That will strip off the higher bits from the larger BitSet when doing &.
*/
public func & (lhs: BitSet, rhs: BitSet) -> BitSet {
let m = max(lhs.size, rhs.size)
var out = BitSet(size: m)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] & rhs.words[i]
}
return out
}
public func | (lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] | rhs.words[i]
}
return out
}
public func ^ (lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] ^ rhs.words[i]
}
return out
}
prefix public func ~ (rhs: BitSet) -> BitSet {
var out = BitSet(size: rhs.size)
for i in 0..<rhs.words.count {
out.words[i] = ~rhs.words[i]
}
out.clearUnusedBits()
return out
}
// MARK: - Debugging
extension UInt64 {
/* Writes the bits in little-endian order, LSB first. */
public func bitsToString() -> String {
var s = ""
var n = self
for _ in 1...64 {
s += ((n & 1 == 1) ? "1" : "0")
n >>= 1
}
return s
}
}
extension BitSet: CustomStringConvertible {
public var description: String {
var s = ""
for x in words {
s += x.bitsToString() + " "
}
return s
}
}
|
mit
|
bd1721f0cab133422dd867f21fc91fb3
| 23.392713 | 82 | 0.588216 | 3.3398 | false | false | false | false |
broadwaylamb/Codable
|
Sources/Measurement+Codable.swift
|
1
|
2671
|
//
// Measurement+Codable.swift
// Codable
//
// Created by Sergej Jaskiewicz on 21/03/2018.
//
import Foundation
#if swift(>=3.2)
#else
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
#endif
|
mit
|
af8477cbb7314daadeb3206e42db6abd
| 36.619718 | 145 | 0.676151 | 4.752669 | false | false | false | false |
danzajork/SwiftForm
|
SwiftForm/SwiftForm.swift
|
1
|
4098
|
//
// SwiftForm.swift
//
// Copyright (c) 2015 Daniel Zajork. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public class SwiftForm : UITableViewController {
public let dataSource = FormTableViewDataSource()
public override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "TextFieldTableViewCell", bundle: NSBundle(forClass: SwiftForm.classForCoder())), forCellReuseIdentifier: FormFieldType.TextField.rawValue)
tableView.registerNib(UINib(nibName: "BooleanFieldTableViewCell", bundle: NSBundle(forClass: SwiftForm.classForCoder())), forCellReuseIdentifier: FormFieldType.Boolean.rawValue)
tableView.registerNib(UINib(nibName: "ButtonFieldTableViewCell", bundle: NSBundle(forClass: SwiftForm.classForCoder())), forCellReuseIdentifier: FormFieldType.Button.rawValue)
tableView.registerNib(UINib(nibName: "DateFieldTableViewCell", bundle: NSBundle(forClass: SwiftForm.classForCoder())), forCellReuseIdentifier: FormFieldType.Date.rawValue)
tableView.registerNib(UINib(nibName: "LabelFieldTableViewCell", bundle: NSBundle(forClass: SwiftForm.classForCoder())), forCellReuseIdentifier: FormFieldType.Label.rawValue)
tableView.keyboardDismissMode = .OnDrag
tableView.dataSource = dataSource
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let formField = dataSource.formFieldForIndexPath(indexPath)
if let buttonFormField = formField as? ButtonFormField {
buttonFormField.buttonAction()
}
if formField is DateFormField {
toggleEditingForIndexPath(indexPath)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
public override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let formField = dataSource.formFieldForIndexPath(indexPath)
if formField is DateFormField || formField is ButtonFormField {
return indexPath
}
return nil
}
private func toggleEditingForIndexPath(indexPath : NSIndexPath) {
tableView.beginUpdates()
let willEnableEditing = !dataSource.editingEnabledFor(indexPath)
if let datePickerIndexPath = dataSource.datePickerIndexPath {
tableView.deleteRowsAtIndexPaths([datePickerIndexPath], withRowAnimation: .Fade)
dataSource.datePickerIndexPath = nil
}
if (willEnableEditing) {
dataSource.enableEditForIndexPath(indexPath)
tableView.insertRowsAtIndexPaths([dataSource.datePickerIndexPath!], withRowAnimation: .Fade)
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
tableView.endUpdates()
}
}
|
mit
|
d04c63791b568dc9f5fa4d4571f37265
| 43.554348 | 185 | 0.707418 | 5.57551 | false | false | false | false |
wftllc/hahastream
|
Haha Stream/Team.swift
|
1
|
1023
|
import Foundation
/*
"id":761,
"name":"Lakers",
"league_id":null,
"location":"Los Angeles",
"abbreviation":"LAL",
"logo":"/images/teams/nba/LAL.svg"
*/
final class Team: NSObject, FromDictable {
public var id: Int;
public var name: String?
public var location: String?
public var abbreviation: String?
static func fromDictionary(_ dict:[String: Any]?) throws -> Self {
return try self.init(dict: dict)
}
required public init(dict: [String: Any]?) throws {
guard let dict = dict else { throw FromDictableError.keyError(key: "<root>") }
self.id = try dict.value("id")
self.name = try? dict.value("name")
self.location = try? dict.value("location")
self.abbreviation = try? dict.value("abbreviation")
}
required init(id: Int, name: String, location: String?, abbreviation: String?) {
self.id = id;
self.name = name
self.location = location
self.abbreviation = abbreviation
}
override var description : String {
let s = name ?? abbreviation ?? "unknown team"
return "\(s)";
}
}
|
mit
|
c3438bb155abd49a07ce83f5f596bd62
| 22.790698 | 81 | 0.676442 | 3.247619 | false | false | false | false |
eoger/firefox-ios
|
Client/Frontend/Widgets/AutocompleteTextField.swift
|
1
|
12494
|
/* 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/. */
// This code is loosely based on https://github.com/Antol/APAutocompleteTextField
import UIKit
import Shared
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: AnyObject {
func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String)
func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidBeginEditing(_ autocompleteTextField: AutocompleteTextField)
func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField)
func autocompletePasteAndGo(_ autocompleteTextField: AutocompleteTextField)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
var autocompleteDelegate: AutocompleteTextFieldDelegate?
// AutocompleteTextLabel repersents the actual autocomplete text.
// The textfields "text" property only contains the entered text, while this label holds the autocomplete text
// This makes sure that the autocomplete doesnt mess with keyboard suggestions provided by third party keyboards.
private var autocompleteTextLabel: UILabel?
private var hideCursor: Bool = false
private let copyShortcutKey = "c"
var isSelectionActive: Bool {
return autocompleteTextLabel != nil
}
// This variable is a solution to get the right behavior for refocusing
// the AutocompleteTextField. The initial transition into Overlay Mode
// doesn't involve the user interacting with AutocompleteTextField.
// Thus, we update shouldApplyCompletion in touchesBegin() to reflect whether
// the highlight is active and then the text field is updated accordingly
// in touchesEnd() (eg. applyCompletion() is called or not)
fileprivate var notifyTextChanged: (() -> Void)?
private var lastReplacement: String?
var textSelectionColor = UIColor.theme.urlbar.textSelectionHighlight
override var text: String? {
didSet {
super.text = text
self.textDidChange(self)
}
}
override var accessibilityValue: String? {
get {
return (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "")
}
set(value) {
super.accessibilityValue = value
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
super.delegate = self
super.addTarget(self, action: #selector(AutocompleteTextField.textDidChange), for: .editingChanged)
notifyTextChanged = debounce(0.1, action: {
if self.isEditing {
self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.normalizeString(self.text ?? ""))
}
})
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
UIKeyCommand(input: UIKeyInputEscape, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
UIKeyCommand(input: copyShortcutKey, modifierFlags: .command, action: #selector(self.handleKeyCommand(sender:)))
]
}
@objc func handleKeyCommand(sender: UIKeyCommand) {
guard let input = sender.input else {
return
}
switch input {
case UIKeyInputLeftArrow:
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-left-arrow"])
if isSelectionActive {
applyCompletion()
// Set the current position to the beginning of the text.
selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument)
} else if let range = selectedTextRange {
if range.start == beginningOfDocument {
break
}
guard let cursorPosition = position(from: range.start, offset: -1) else {
break
}
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
case UIKeyInputRightArrow:
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-right-arrow"])
if isSelectionActive {
applyCompletion()
// Set the current position to the end of the text.
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
} else if let range = selectedTextRange {
if range.end == endOfDocument {
break
}
guard let cursorPosition = position(from: range.end, offset: 1) else {
break
}
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
case UIKeyInputEscape:
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-cancel"])
autocompleteDelegate?.autocompleteTextFieldDidCancel(self)
case copyShortcutKey:
if isSelectionActive {
UIPasteboard.general.string = self.autocompleteTextLabel?.text
} else {
if let selectedTextRange = self.selectedTextRange {
UIPasteboard.general.string = self.text(in: selectedTextRange)
}
}
default:
break
}
}
func highlightAll() {
let text = self.text
self.text = ""
setAutocompleteSuggestion(text ?? "")
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
fileprivate func normalizeString(_ string: String) -> String {
return string.lowercased().stringByTrimmingLeadingCharactersInSet(CharacterSet.whitespaces)
}
/// Commits the completion by setting the text and removing the highlight.
fileprivate func applyCompletion() {
// Clear the current completion, then set the text without the attributed style.
let text = (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "")
removeCompletion()
self.text = text
hideCursor = false
// Move the cursor to the end of the completion.
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
/// Removes the autocomplete-highlighted
fileprivate func removeCompletion() {
autocompleteTextLabel?.removeFromSuperview()
autocompleteTextLabel = nil
}
// `shouldChangeCharactersInRange` is called before the text changes, and textDidChange is called after.
// Since the text has changed, remove the completion here, and textDidChange will fire the callback to
// get the new autocompletion.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
lastReplacement = string
return true
}
func setAutocompleteSuggestion(_ suggestion: String?) {
let text = self.text ?? ""
guard let suggestion = suggestion, isEditing && markedTextRange == nil else {
hideCursor = false
return
}
let normalized = normalizeString(text)
guard suggestion.hasPrefix(normalized) && normalized.count < suggestion.count else {
hideCursor = false
return
}
let suggestionText = String(suggestion[suggestion.index(suggestion.startIndex, offsetBy: normalized.count)...])
let autocompleteText = NSMutableAttributedString(string: suggestionText)
autocompleteText.addAttribute(NSAttributedStringKey.backgroundColor, value: textSelectionColor, range: NSRange(location: 0, length: suggestionText.count))
autocompleteTextLabel?.removeFromSuperview() // should be nil. But just in case
autocompleteTextLabel = createAutocompleteLabelWith(autocompleteText)
if let l = autocompleteTextLabel {
addSubview(l)
hideCursor = true
forceResetCursor()
}
}
override func caretRect(for position: UITextPosition) -> CGRect {
return hideCursor ? CGRect.zero : super.caretRect(for: position)
}
private func createAutocompleteLabelWith(_ autocompleteText: NSAttributedString) -> UILabel {
let label = UILabel()
var frame = self.bounds
label.attributedText = autocompleteText
label.font = self.font
label.accessibilityIdentifier = "autocomplete"
label.backgroundColor = self.backgroundColor
label.textColor = self.textColor
label.textAlignment = .left
let enteredTextSize = self.attributedText?.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
frame.origin.x = (enteredTextSize?.width.rounded() ?? 0)
frame.size.width = self.frame.size.width - frame.origin.x
frame.size.height = self.frame.size.height - 1
label.frame = frame
return label
}
func textFieldDidBeginEditing(_ textField: UITextField) {
autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
applyCompletion()
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
applyCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
removeCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
override func setMarkedText(_ markedText: String?, selectedRange: NSRange) {
// Clear the autocompletion if any provisionally inserted text has been
// entered (e.g., a partial composition from a Japanese keyboard).
removeCompletion()
super.setMarkedText(markedText, selectedRange: selectedRange)
}
func setTextWithoutSearching(_ text: String) {
super.text = text
hideCursor = autocompleteTextLabel != nil
removeCompletion()
}
@objc func textDidChange(_ textField: UITextField) {
hideCursor = autocompleteTextLabel != nil
removeCompletion()
let isAtEnd = selectedTextRange?.start == endOfDocument
let isKeyboardReplacingText = lastReplacement != nil
if isKeyboardReplacingText, isAtEnd, markedTextRange == nil {
notifyTextChanged?()
} else {
hideCursor = false
}
}
// Reset the cursor to the end of the text field.
// This forces `caretRect(for position: UITextPosition)` to be called which will decide if we should show the cursor
// This exists because ` caretRect(for position: UITextPosition)` is not called after we apply an autocompletion.
private func forceResetCursor() {
selectedTextRange = nil
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
override func deleteBackward() {
lastReplacement = ""
hideCursor = false
if isSelectionActive {
removeCompletion()
forceResetCursor()
} else {
super.deleteBackward()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
applyCompletion()
super.touchesBegan(touches, with: event)
}
}
extension AutocompleteTextField: MenuHelperInterface {
@objc func menuHelperPasteAndGo() {
autocompleteDelegate?.autocompletePasteAndGo(self)
}
}
|
mpl-2.0
|
4dfe2f251165bc1cfaa51274eda84125
| 39.303226 | 162 | 0.665599 | 5.4967 | false | false | false | false |
qkrqjadn/SoonChat
|
source/ChatViewController.swift
|
1
|
2621
|
//
// ChatViewController.swift
// soonchat
//
// Created by 박범우 on 2016. 12. 27..
// Copyright © 2016년 bumwoo. All rights reserved.
//
import UIKit
import Firebase
class ChatViewController : UITableViewController
{
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.hidesBarsOnSwipe = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = .red
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
let image = UIImage(named:"new_message_icon")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleNewMessage))
//self.navigationItem.title = FIRAuth.auth()?.currentUser?.email
self.navigationItem.titleView = titleView
titleView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleChatLog)))
}
func handleChatLog()
{
let logView = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
self.navigationController?.pushViewController(logView, animated: true)
}
func handleNewMessage()
{
let newMessageController = NewMessageController()
newMessageController.chatViewController = self
let navController = UINavigationController(rootViewController: newMessageController)
present(navController, animated: true, completion: nil)
}
func checkIfUserIsLoggedIn()
{
if FIRAuth.auth()?.currentUser?.uid == nil
{
perform(#selector(handleLogout), with: nil, afterDelay: 0)
}
else
{
let uid = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String:AnyObject]{
self.navigationItem.title = dictionary["name"] as? String
}
}, withCancel: nil)
}
}
func handleLogout(){
do {
try FIRAuth.auth()?.signOut()
present(LoginController(), animated: true, completion: nil)
}catch let logoutError {
print(logoutError)
}
}
}
|
mit
|
17741d2a849d2c78d017b5c2f9ce8b13
| 31.246914 | 144 | 0.626723 | 5.023077 | false | false | false | false |
TitouanVanBelle/XCUITestHTMLReport
|
XCTestHTMLReport/XCTestHTMLReport/Classes/Models/TestSummary.swift
|
1
|
2166
|
//
// Summary.swift
// XCTestHTMLReport
//
// Created by Titouan van Belle on 21.07.17.
// Copyright © 2017 Tito. All rights reserved.
//
import Foundation
struct TestSummary: HTML
{
var uuid: String
var testName: String
var tests: [Test]
var status: Status {
let currentTests = tests
var status: Status = .unknown
var currentSubtests: [Test] = []
for test in currentTests {
currentSubtests += test.allTestSummaries()
}
if currentSubtests.count == 0 {
return .success
}
status = currentSubtests.reduce(.unknown, { (accumulator: Status, test: Test) -> Status in
if accumulator == .unknown {
return test.status
}
if test.status == .failure {
return .failure
}
if test.status == .success {
return accumulator == .failure ? .failure : .success
}
return .unknown
})
return status
}
init(screenshotsPath: String, dict: [String : Any])
{
Logger.substep("Parsing TestSummary")
uuid = NSUUID().uuidString
testName = dict["TestName"] as! String
let rawTests = dict["Tests"] as! [[String: Any]]
tests = rawTests.map { Test(screenshotsPath: screenshotsPath, dict: $0) }
}
// PRAGMA MARK: - HTML
var htmlTemplate = HTMLTemplates.testSummary
var htmlPlaceholderValues: [String: String] {
return [
"UUID": uuid,
"TESTS": tests.reduce("", { (accumulator: String, test: Test) -> String in
return accumulator + test.html
})
]
}
}
extension Test {
func allTestSummaries() -> [Test] {
if self.objectClass == .testSummary {
return [self]
}
guard let subTests = self.subTests, subTests.isEmpty == false else {
return []
}
var testsToReturn: [Test] = []
for test in subTests {
testsToReturn += test.allTestSummaries()
}
return testsToReturn
}
}
|
mit
|
f3057d3c8018cbac8701fb81ee90fac3
| 24.174419 | 98 | 0.537182 | 4.491701 | false | true | false | false |
A-Kod/vkrypt
|
Pods/SwiftyVK/Library/Sources/Extensions/String+Extensions.swift
|
2
|
549
|
extension String {
static func random(_ length: Int) -> String {
let letters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let lettersLen = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(lettersLen)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
}
|
apache-2.0
|
4062acb76926640e751a9afc00726edf
| 31.294118 | 96 | 0.593807 | 5.278846 | false | false | false | false |
sm-haskell-users-group/sm-haskell-users-group.github.io
|
srcs/TypeClassDemo/TypeClassDemo.swift
|
1
|
920
|
class K { }
// instance Eq K
extension K : Equatable { }
func == (lhs: K, rhs: K) -> Bool { return false }
func != (lhs: K, rhs: K) -> Bool { return false }
let o = K()
println(( o == o, o != o, o === o )) // (false, false, true)
// instance Ord K
extension K : Comparable { }
func < (lhs: K, rhs: K) -> Bool { return true }
let k = K()
println(( o < k, k < o )) // (true, true)
// DIY Monad
// class Monad t
protocol Monad { typealias T; func bind (ƒ: T -> Self) -> Self }
// infixl 1 >>=
infix operator >>= { associativity left precedence 100 }
func >>= <M: Monad> ($: M, ƒ: M.T -> M) -> M { return $.bind(ƒ) }
// instance Monad Array
extension Array : Monad {
func bind (ƒ: T -> Array) -> Array { return reduce([]) { z, x in z + ƒ(x) } }
}
let ra = [1,2,3]
let rb = ra.bind { t in [t * t] }
let rc = ra >>= { t in [t * t * t] }
println(( ra, rb, rc )) // ([1, 2, 3], [1, 4, 9], [1, 8, 27])
|
mit
|
567fab74fdda3a6d878679e631cf457f
| 18.891304 | 79 | 0.521311 | 2.636888 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Field.swift
|
1
|
1406
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** Field. */
public struct Field: Decodable {
/// The type of the field.
public enum FieldType: String {
case nested = "nested"
case string = "string"
case date = "date"
case long = "long"
case integer = "integer"
case short = "short"
case byte = "byte"
case double = "double"
case float = "float"
case boolean = "boolean"
case binary = "binary"
}
/// The name of the field.
public var fieldName: String?
/// The type of the field.
public var fieldType: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case fieldName = "field"
case fieldType = "type"
}
}
|
mit
|
374e18b7fbd47bab7d1d679f6fc1b32e
| 27.693878 | 82 | 0.647226 | 4.299694 | false | false | false | false |
cpmpercussion/microjam
|
Pods/DateToolsSwift/DateToolsSwift/DateTools/TimePeriod.swift
|
2
|
24514
|
//
// TimePeriod.swift
// DateTools
//
// Created by Grayson Webster on 8/17/16.
// Copyright © 2016 Grayson Webster. All rights reserved.
//
import Foundation
/**
* In DateTools, time periods are represented by the TimePeriod protocol.
* Required variables and method impleementations are bound below. An inheritable
* implementation of the TimePeriodProtocol is available through the TimePeriodClass
*
* [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information.
*/
public protocol TimePeriodProtocol {
// MARK: - Variables
/**
* The start date for a TimePeriod representing the starting boundary of the time period
*/
var beginning: Date? {get set}
/**
* The end date for a TimePeriod representing the ending boundary of the time period
*/
var end: Date? {get set}
}
public extension TimePeriodProtocol {
// MARK: - Information
/**
* True if the `TimePeriod`'s duration is zero
*/
public var isMoment: Bool {
return self.beginning == self.end
}
/**
* The duration of the `TimePeriod` in years.
* Returns the max int if beginning or end are nil.
*/
public var years: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.yearsEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in weeks.
* Returns the max int if beginning or end are nil.
*/
public var weeks: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.weeksEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in days.
* Returns the max int if beginning or end are nil.
*/
public var days: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.daysEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in hours.
* Returns the max int if beginning or end are nil.
*/
public var hours: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.hoursEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in minutes.
* Returns the max int if beginning or end are nil.
*/
public var minutes: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.minutesEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in seconds.
* Returns the max int if beginning or end are nil.
*/
public var seconds: Int {
if self.beginning != nil && self.end != nil {
return self.beginning!.secondsEarlier(than: self.end!)
}
return Int.max
}
/**
* The duration of the `TimePeriod` in a time chunk.
* Returns a time chunk with all zeroes if beginning or end are nil.
*/
public var chunk: TimeChunk {
if beginning != nil && end != nil {
return beginning!.chunkBetween(date: end!)
}
return TimeChunk(seconds: 0, minutes: 0, hours: 0, days: 0, weeks: 0, months: 0, years: 0)
}
/**
* The length of time between the beginning and end dates of the
* `TimePeriod` as a `TimeInterval`.
*/
public var duration: TimeInterval {
if self.beginning != nil && self.end != nil {
return abs(self.beginning!.timeIntervalSince(self.end!))
}
return TimeInterval(Double.greatestFiniteMagnitude)
}
// MARK: - Time Period Relationships
/**
* The relationship of the self `TimePeriod` to the given `TimePeriod`.
* Relations are stored in Enums.swift. Formal defnitions available in the provided
* links:
* [GitHub](https://github.com/MatthewYork/DateTools#relationships),
* [CodeProject](http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET)
*
* - parameter period: The time period to compare to self
*
* - returns: The relationship between self and the given time period
*/
public func relation(to period: TimePeriodProtocol) -> Relation {
//Make sure that all start and end points exist for comparison
if (self.beginning != nil && self.end != nil && period.beginning != nil && period.end != nil) {
//Make sure time periods are of positive durations
if (self.beginning!.isEarlier(than: self.end!) && period.beginning!.isEarlier(than: period.end!)) {
//Make comparisons
if (period.end!.isEarlier(than: self.beginning!)) {
return .after
}
else if (period.end!.equals(self.beginning!)) {
return .startTouching
}
else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) {
return .startInside
}
else if (period.beginning!.equals(self.beginning!) && period.end!.isLater(than: self.end!)) {
return .insideStartTouching
}
else if (period.beginning!.equals(self.beginning!) && period.end!.isEarlier(than: self.end!)) {
return .enclosingStartTouching
}
else if (period.beginning!.isLater(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) {
return .enclosing
}
else if (period.beginning!.isLater(than: self.beginning!) && period.end!.equals(self.end!)) {
return .enclosingEndTouching
}
else if (period.beginning!.equals(self.beginning!) && period.end!.equals(self.end!)) {
return .exactMatch
}
else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.end!)) {
return .inside
}
else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.equals(self.end!)) {
return .insideEndTouching
}
else if (period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)) {
return .endInside
}
else if (period.beginning!.equals(self.end!) && period.end!.isLater(than: self.end!)) {
return .endTouching
}
else if (period.beginning!.isLater(than: self.end!)) {
return .before
}
}
}
return .none;
}
/**
* If `self.beginning` and `self.end` are equal to the beginning and end of the
* given `TimePeriod`.
*
* - parameter period: The time period to compare to self
*
* - returns: True if the periods are the same
*/
public func equals(_ period: TimePeriodProtocol) -> Bool {
return self.beginning == period.beginning && self.end == period.end
}
/**
* If the given `TimePeriod`'s beginning is before `self.beginning` and
* if the given 'TimePeriod`'s end is after `self.end`.
*
* - parameter period: The time period to compare to self
*
* - returns: True if self is inside of the given `TimePeriod`
*/
public func isInside(of period: TimePeriodProtocol) -> Bool {
return period.beginning!.isEarlierThanOrEqual(to: self.beginning!) && period.end!.isLaterThanOrEqual(to: self.end!)
}
/**
* If the given Date is after `self.beginning` and before `self.end`.
*
* - parameter period: The time period to compare to self
* - parameter interval: Whether the edge of the date is included in the calculation
*
* - returns: True if the given `TimePeriod` is inside of self
*/
public func contains(_ date: Date, interval: Interval) -> Bool {
if (interval == .open) {
return self.beginning!.isEarlier(than: date) && self.end!.isLater(than: date)
}
else if (interval == .closed){
return (self.beginning!.isEarlierThanOrEqual(to: date) && self.end!.isLaterThanOrEqual(to: date))
}
return false
}
/**
* If the given `TimePeriod`'s beginning is after `self.beginning` and
* if the given 'TimePeriod`'s after is after `self.end`.
*
* - parameter period: The time period to compare to self
*
* - returns: True if the given `TimePeriod` is inside of self
*/
public func contains(_ period: TimePeriodProtocol) -> Bool {
return self.beginning!.isEarlierThanOrEqual(to: period.beginning!) && self.end!.isLaterThanOrEqual(to: period.end!)
}
/**
* If self and the given `TimePeriod` share any sub-`TimePeriod`.
*
* - parameter period: The time period to compare to self
*
* - returns: True if there is a period of time that is shared by both `TimePeriod`s
*/
public func overlaps(with period: TimePeriodProtocol) -> Bool {
//Outside -> Inside
if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.beginning!)) {
return true
}
//Enclosing
else if (period.beginning!.isLaterThanOrEqual(to: self.beginning!) && period.end!.isEarlierThanOrEqual(to: self.end!)){
return true
}
//Inside -> Out
else if(period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)){
return true
}
return false
}
/**
* If self and the given `TimePeriod` overlap or the period's edges touch.
*
* - parameter period: The time period to compare to self
*
* - returns: True if there is a period of time or moment that is shared by both `TimePeriod`s
*/
public func intersects(with period: TimePeriodProtocol) -> Bool {
return self.relation(to: period) != .after && self.relation(to: period) != .before
}
/**
* If self and the given `TimePeriod` have no overlap or touching edges.
*
* - parameter period: The time period to compare to self
*
* - returns: True if there is a period of time between self and the given `TimePeriod` not contained by either period
*/
public func hasGap(between period: TimePeriodProtocol) -> Bool {
return self.isBefore(period: period) || self.isAfter(period: period)
}
/**
* The period of time between self and the given `TimePeriod` not contained by either.
*
* - parameter period: The time period to compare to self
*
* - returns: The gap between the periods. Zero if there is no gap.
*/
public func gap(between period: TimePeriodProtocol) -> TimeInterval {
if (self.end!.isEarlier(than: period.beginning!)) {
return abs(self.end!.timeIntervalSince(period.beginning!));
}
else if (period.end!.isEarlier(than: self.beginning!)){
return abs(period.end!.timeIntervalSince(self.beginning!));
}
return 0
}
/**
* The period of time between self and the given `TimePeriod` not contained by either
* as a `TimeChunk`.
*
* - parameter period: The time period to compare to self
*
* - returns: The gap between the periods, zero if there is no gap
*/
public func gap(between period: TimePeriodProtocol) -> TimeChunk? {
if self.end != nil && period.beginning != nil {
return (self.end?.chunkBetween(date: period.beginning!))!
}
return nil
}
/**
* If self is after the given `TimePeriod` chronologically. (A gap must exist between the two).
*
* - parameter period: The time period to compare to self
*
* - returns: True if self is after the given `TimePeriod`
*/
public func isAfter(period: TimePeriodProtocol) -> Bool {
return self.relation(to: period) == .after
}
/**
* If self is before the given `TimePeriod` chronologically. (A gap must exist between the two).
*
* - parameter period: The time period to compare to self
*
* - returns: True if self is after the given `TimePeriod`
*/
public func isBefore(period: TimePeriodProtocol) -> Bool {
return self.relation(to: period) == .before
}
// MARK: - Shifts
//MARK: In Place
/**
* In place, shift the `TimePeriod` by a `TimeInterval`
*
* - parameter timeInterval: The time interval to shift the period by
*/
public mutating func shift(by timeInterval: TimeInterval) {
self.beginning?.addTimeInterval(timeInterval)
self.end?.addTimeInterval(timeInterval)
}
/**
* In place, shift the `TimePeriod` by a `TimeChunk`
*
* - parameter chunk: The time chunk to shift the period by
*/
public mutating func shift(by chunk: TimeChunk) {
self.beginning = self.beginning?.add(chunk)
self.end = self.end?.add(chunk)
}
// MARK: - Lengthen / Shorten
// MARK: In Place
/**
* In place, lengthen the `TimePeriod`, anchored at the beginning, end or center
*
* - parameter timeInterval: The time interval to lengthen the period by
* - parameter anchor: The anchor point from which to make the change
*/
public mutating func lengthen(by timeInterval: TimeInterval, at anchor: Anchor) {
switch anchor {
case .beginning:
self.end = self.end?.addingTimeInterval(timeInterval)
break
case .center:
self.beginning = self.beginning?.addingTimeInterval(-timeInterval/2.0)
self.end = self.end?.addingTimeInterval(timeInterval/2.0)
break
case .end:
self.beginning = self.beginning?.addingTimeInterval(-timeInterval)
break
}
}
/**
* In place, lengthen the `TimePeriod`, anchored at the beginning or end
*
* - parameter chunk: The time chunk to lengthen the period by
* - parameter anchor: The anchor point from which to make the change
*/
public mutating func lengthen(by chunk: TimeChunk, at anchor: Anchor) {
switch anchor {
case .beginning:
self.end = self.end?.add(chunk)
break
case .center:
// Do not lengthen by TimeChunk at center
print("Mutation via chunk from center anchor is not supported.")
break
case .end:
self.beginning = self.beginning?.subtract(chunk)
break
}
}
/**
* In place, shorten the `TimePeriod`, anchored at the beginning, end or center
*
* - parameter timeInterval: The time interval to shorten the period by
* - parameter anchor: The anchor point from which to make the change
*/
public mutating func shorten(by timeInterval: TimeInterval, at anchor: Anchor) {
switch anchor {
case .beginning:
self.end = self.end?.addingTimeInterval(-timeInterval)
break
case .center:
self.beginning = self.beginning?.addingTimeInterval(timeInterval/2.0)
self.end = self.end?.addingTimeInterval(-timeInterval/2.0)
break
case .end:
self.beginning = self.beginning?.addingTimeInterval(timeInterval)
break
}
}
/**
* In place, shorten the `TimePeriod`, anchored at the beginning or end
*
* - parameter chunk: The time chunk to shorten the period by
* - parameter anchor: The anchor point from which to make the change
*/
public mutating func shorten(by chunk: TimeChunk, at anchor: Anchor) {
switch anchor {
case .beginning:
self.end = self.end?.subtract(chunk)
break
case .center:
// Do not shorten by TimeChunk at center
print("Mutation via chunk from center anchor is not supported.")
break
case .end:
self.beginning = self.beginning?.add(chunk)
break
}
}
}
/**
* In DateTools, time periods are represented by the case TimePeriod class
* and come with a suite of initializaiton, manipulation, and comparison methods
* to make working with them a breeze.
*
* [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information.
*/
open class TimePeriod: TimePeriodProtocol {
// MARK: - Variables
/**
* The start date for a TimePeriod representing the starting boundary of the time period
*/
public var beginning: Date?
/**
* The end date for a TimePeriod representing the ending boundary of the time period
*/
public var end: Date?
// MARK: - Initializers
public init() {
}
public init(beginning: Date?, end: Date?) {
self.beginning = beginning
self.end = end
}
public init(beginning: Date, duration: TimeInterval) {
self.beginning = beginning
self.end = beginning + duration
}
public init(end: Date, duration: TimeInterval) {
self.end = end
self.beginning = end.addingTimeInterval(-duration)
}
public init(beginning: Date, chunk: TimeChunk) {
self.beginning = beginning
self.end = beginning + chunk
}
public init(end: Date, chunk: TimeChunk) {
self.end = end
self.beginning = end - chunk
}
public init(chunk: TimeChunk) {
self.beginning = Date()
self.end = self.beginning?.add(chunk)
}
// MARK: - Shifted
/**
* Shift the `TimePeriod` by a `TimeInterval`
*
* - parameter timeInterval: The time interval to shift the period by
*
* - returns: The new, shifted `TimePeriod`
*/
public func shifted(by timeInterval: TimeInterval) -> TimePeriod {
let timePeriod = TimePeriod()
timePeriod.beginning = self.beginning?.addingTimeInterval(timeInterval)
timePeriod.end = self.end?.addingTimeInterval(timeInterval)
return timePeriod
}
/**
* Shift the `TimePeriod` by a `TimeChunk`
*
* - parameter chunk: The time chunk to shift the period by
*
* - returns: The new, shifted `TimePeriod`
*/
public func shifted(by chunk: TimeChunk) -> TimePeriod {
let timePeriod = TimePeriod()
timePeriod.beginning = self.beginning?.add(chunk)
timePeriod.end = self.end?.add(chunk)
return timePeriod
}
// MARK: - Lengthen / Shorten
// MARK: New
/**
* Lengthen the `TimePeriod` by a `TimeInterval`
*
* - parameter timeInterval: The time interval to lengthen the period by
* - parameter anchor: The anchor point from which to make the change
*
* - returns: The new, lengthened `TimePeriod`
*/
public func lengthened(by timeInterval: TimeInterval, at anchor: Anchor) -> TimePeriod {
let timePeriod = TimePeriod()
switch anchor {
case .beginning:
timePeriod.beginning = self.beginning
timePeriod.end = self.end?.addingTimeInterval(timeInterval)
break
case .center:
timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval)
timePeriod.end = self.end?.addingTimeInterval(timeInterval)
break
case .end:
timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval)
timePeriod.end = self.end
break
}
return timePeriod
}
/**
* Lengthen the `TimePeriod` by a `TimeChunk`
*
* - parameter chunk: The time chunk to lengthen the period by
* - parameter anchor: The anchor point from which to make the change
*
* - returns: The new, lengthened `TimePeriod`
*/
public func lengthened(by chunk: TimeChunk, at anchor: Anchor) -> TimePeriod {
let timePeriod = TimePeriod()
switch anchor {
case .beginning:
timePeriod.beginning = beginning
timePeriod.end = end?.add(chunk)
break
case .center:
print("Mutation via chunk from center anchor is not supported.")
break
case .end:
timePeriod.beginning = beginning?.add(-chunk)
timePeriod.end = end
break
}
return timePeriod
}
/**
* Shorten the `TimePeriod` by a `TimeInterval`
*
* - parameter timeInterval: The time interval to shorten the period by
* - parameter anchor: The anchor point from which to make the change
*
* - returns: The new, shortened `TimePeriod`
*/
public func shortened(by timeInterval: TimeInterval, at anchor: Anchor) -> TimePeriod {
let timePeriod = TimePeriod()
switch anchor {
case .beginning:
timePeriod.beginning = beginning
timePeriod.end = end?.addingTimeInterval(-timeInterval)
break
case .center:
timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval/2)
timePeriod.end = end?.addingTimeInterval(timeInterval/2)
break
case .end:
timePeriod.beginning = beginning?.addingTimeInterval(timeInterval)
timePeriod.end = end
break
}
return timePeriod
}
/**
* Shorten the `TimePeriod` by a `TimeChunk`
*
* - parameter chunk: The time chunk to shorten the period by
* - parameter anchor: The anchor point from which to make the change
*
* - returns: The new, shortened `TimePeriod`
*/
public func shortened(by chunk: TimeChunk, at anchor: Anchor) -> TimePeriod {
let timePeriod = TimePeriod()
switch anchor {
case .beginning:
timePeriod.beginning = beginning
timePeriod.end = end?.subtract(chunk)
break
case .center:
print("Mutation via chunk from center anchor is not supported.")
break
case .end:
timePeriod.beginning = beginning?.add(-chunk)
timePeriod.end = end
break
}
return timePeriod
}
// MARK: - Operator Overloads
/**
* Operator overload for checking if two `TimePeriod`s are equal
*/
public static func ==(leftAddend: TimePeriod, rightAddend: TimePeriod) -> Bool {
return leftAddend.equals(rightAddend)
}
// Default anchor = beginning
/**
* Operator overload for lengthening a `TimePeriod` by a `TimeInterval`
*/
public static func +(leftAddend: TimePeriod, rightAddend: TimeInterval) -> TimePeriod {
return leftAddend.lengthened(by: rightAddend, at: .beginning)
}
/**
* Operator overload for lengthening a `TimePeriod` by a `TimeChunk`
*/
public static func +(leftAddend: TimePeriod, rightAddend: TimeChunk) -> TimePeriod {
return leftAddend.lengthened(by: rightAddend, at: .beginning)
}
// Default anchor = beginning
/**
* Operator overload for shortening a `TimePeriod` by a `TimeInterval`
*/
public static func -(minuend: TimePeriod, subtrahend: TimeInterval) -> TimePeriod {
return minuend.shortened(by: subtrahend, at: .beginning)
}
/**
* Operator overload for shortening a `TimePeriod` by a `TimeChunk`
*/
public static func -(minuend: TimePeriod, subtrahend: TimeChunk) -> TimePeriod {
return minuend.shortened(by: subtrahend, at: .beginning)
}
/**
* Operator overload for checking if a `TimePeriod` is equal to a `TimePeriodProtocol`
*/
public static func ==(left: TimePeriod, right: TimePeriodProtocol) -> Bool {
return left.equals(right)
}
}
|
mit
|
1c61b1ea50718fcff97bc960543a82a9
| 33.140669 | 127 | 0.591482 | 4.527706 | false | false | false | false |
vnu/vTweetz
|
Pods/SwiftDate/SwiftDate_src/NSDate+SwiftDate.swift
|
1
|
27138
|
//
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// Extension for initialisation
extension NSDate {
/**
Initialise a `NSDate` object from a number of date properties.
Parameters are kind of fuzzy; they can overlap functionality and can contradict eachother. In such a case the parameter highest in the parameter list below has priority. All parameters but `fromDate` are optional.
Use this initialiser if you have a source date from which to copy the properties.
- Parameters:
- fromDate: DateInRegion,
- era: era to set (optional)
- year: year number to set (optional)
- month: month number to set (optional)
- day: day number to set (optional)
- hour: hour number to set (optional)
- minute: minute number to set (optional)
- second: second number to set (optional)
- nanosecond: nanosecond number to set (optional)
- calendarID: calendar identifier to set (optional)
- timeZoneID: time zone abbreviation or nameto set (optional)
- localeID: locale identifier to set (optional)
- calType: calendar type to set (optional), renamed to calendarName, will be deprecated in SwiftDate v2.2
- tzName: time zone region to set (optional), renamed to timeZoneRegion, will be deprecated in SwiftDate v2.2
- calendarName: calendar type to set (optional)
- timeZoneRegion: time zone region to set (optional)
- calendar: calendar object to set (optional)
- timeZone: time zone object to set (optional)
- locale: locale object to set (optional)
- region: region to set (optional)
- Note: the properties provided are evaluated for the calendar, time zone and locale data provided. If you have provided none, then the default device settings will be used.
- Remark: Return value is an `NSDate` object that does not remember the calendar, time zone or locale information. If you need that, use `DateinRegion`.
- Returns: An absolute date for the properties provided.
*/
public convenience init?(
fromDate: NSDate,
era: Int? = nil,
year: Int? = nil,
month: Int? = nil,
day: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil,
nanosecond: Int? = nil,
region: Region? = nil) {
if let dateInRegion = DateInRegion(fromDate: fromDate.inRegion(region), era: era, year: year, month: month, day: day, hour: hour, minute: minute, second: second, nanosecond: nanosecond, region: region) {
self.init(timeIntervalSinceReferenceDate: dateInRegion.timeIntervalSinceReferenceDate)
} else {
return nil
}
}
public convenience init?(
era: Int? = nil,
year: Int,
month: Int,
day: Int,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil,
nanosecond: Int? = nil,
calendarID: String = "",
timeZoneID: String = "",
localeID: String = "",
region: Region? = nil) {
if let dateInRegion = DateInRegion(era: era, year: year, month: month, day: day, hour: hour, minute: minute, second: second, nanosecond: nanosecond, region: region) {
self.init(timeIntervalSinceReferenceDate: dateInRegion.timeIntervalSinceReferenceDate)
} else {
return nil
}
}
public convenience init?(
era: Int? = nil,
yearForWeekOfYear: Int,
weekOfYear: Int,
weekday: Int,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil,
nanosecond: Int? = nil,
calendarID: String = "",
timeZoneID: String = "",
localeID: String = "",
region: Region? = nil) {
if let dateInRegion = DateInRegion(era: era, yearForWeekOfYear: yearForWeekOfYear, weekOfYear: weekOfYear, weekday: weekday, hour: hour, minute: minute, second: second, nanosecond: nanosecond, region: region) {
self.init(timeIntervalSinceReferenceDate: dateInRegion.timeIntervalSinceReferenceDate)
} else {
return nil
}
}
public convenience init?(components: NSDateComponents) {
if let dateInRegion = DateInRegion(components) {
let absoluteTime = dateInRegion.absoluteTime
guard absoluteTime != nil else { return nil }
self.init(timeIntervalSinceReferenceDate: absoluteTime!.timeIntervalSinceReferenceDate)
} else {
return nil
}
}
/**
Initialize a new NSDate instance by passing components in a dictionary.
Each key of the component must be an NSCalendarUnit type. All values are supported.
- parameter params: paramters dictionary, each key must be an NSCalendarUnit
- parameter locale: NSLocale instance to assign. If missing current locale will be used instead
- returns: a new NSDate instance
*/
public convenience init?(dateComponentDictionary: DateComponentDictionary) {
let absoluteTime = dateComponentDictionary.absoluteTime()
guard absoluteTime != nil else { return nil }
self.init(timeIntervalSinceReferenceDate: absoluteTime!.timeIntervalSinceReferenceDate)
}
/**
Initialize a new NSDate instance by taking initial components from date object and setting only specified components if != nil
- parameter date: reference date
- parameter era: era to set (nil to ignore)
- parameter year: year to set (nil to ignore)
- parameter month: month to set (nil to ignore)
- parameter day: day to set (nil to ignore)
- parameter yearForWeekOfYear: yearForWeekOfYear to set (nil to ignore)
- parameter weekOfYear: weekOfYear to set (nil to ignore)
- parameter weekday: weekday to set (nil to ignore)
- parameter hour: hour to set (nil to ignore)
- parameter minute: minute to set (nil to ignore)
- parameter second: second to set (nil to ignore)
- parameter nanosecond: nanosecond to set (nil to ignore)
- parameter region: region to set (if not specified Region() will be used instead - Gregorian/UTC/Current Locale)
- returns: a new date instance with components created from refDate and only specified components set by passing input params
*/
@available(*, renamed="init(fromDate, ...)")
public convenience init(refDate date : NSDate,
era : Int? = nil,
year : Int? = nil,
month : Int? = nil,
day : Int? = nil,
yearForWeekOfYear : Int? = nil,
weekOfYear : Int? = nil,
weekday : Int? = nil,
hour : Int? = nil,
minute : Int? = nil,
second : Int? = nil,
nanosecond : Int? = nil,
region : Region = Region()) {
let newComponents = NSDateComponents()
newComponents.era = era ?? date.era ?? 1
newComponents.year = year ?? date.year ?? 2001
newComponents.month = weekOfYear ?? date.weekOfYear ?? 1
newComponents.day = weekday ?? date.weekday ?? 1
newComponents.yearForWeekOfYear = yearForWeekOfYear ?? date.yearForWeekOfYear ?? NSDateComponentUndefined
newComponents.weekOfYear = weekOfYear ?? date.weekOfYear ?? NSDateComponentUndefined
newComponents.weekday = weekday ?? date.weekday ?? NSDateComponentUndefined
newComponents.hour = hour ?? date.hour ?? 0
newComponents.minute = minute ?? date.minute ?? 0
newComponents.second = second ?? date.second ?? 0
newComponents.nanosecond = nanosecond ?? date.nanosecond ?? 0
newComponents.calendar = region.calendar
newComponents.timeZone = region.timeZone
let date = NSCalendar.currentCalendar().dateFromComponents(newComponents)!
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
}
/**
Create a new DateInRegion object. It will represent an absolute time expressed in a particular world region.
- parameter region: region to associate. If not specified defaultRegion() will be used instead. Use Region.setDefaultRegion() to define a default region for your application.
- returns: a new DateInRegion instance representing this date in specified region. You can query for each component and it will be returned taking care of the region components specified.
*/
public func inRegion(region: Region? = nil) -> DateInRegion {
let region = region ?? Region()
let dateInRegion = DateInRegion(absoluteTime: self, region: region)
return dateInRegion
}
/**
This is a shortcut to express the date into the default region of the app.
You can specify a default region by calling Region.setDefaultRegion(). By default default region for you app is Gregorian Calendar/UTC TimeZone and current locale.
- returns: a new DateInRegion instance representing this date in default region
*/
public func inDefaultRegion() -> DateInRegion {
return self.inRegion()
}
/**
Create a new date from self by adding specified component values. All values are optional. Date still remain expressed in UTC.
- parameter years: years to add
- parameter months: months to add
- parameter weekOfYear: week of year to add
- parameter days: days to add
- parameter hours: hours to add
- parameter minutes: minutes to add
- parameter seconds: seconds to add
- parameter nanoseconds: nanoseconds to add
- returns: a new absolute time from self plus passed components
*/
public func add(years years: Int? = nil, months: Int? = nil, weeks: Int? = nil, days: Int? = nil,hours: Int? = nil, minutes: Int? = nil, seconds: Int? = nil, nanoseconds: Int? = nil) -> NSDate {
let date = self.inRegion()
let newDate = date.add(years: years, months: months, weeks: weeks, days: days, hours: hours, minutes: minutes, seconds: seconds, nanoseconds: nanoseconds)
return newDate.absoluteTime
}
/**
Add components to the current absolute time by passing an NSDateComponents intance
- parameter components: components to add
- returns: a new absolute time from self plus passed components
*/
public func add(components :NSDateComponents) -> NSDate {
let date = self.inRegion().add(components)
return date.absoluteTime
}
/**
Add components to the current absolute time by passing NSCalendarUnit dictionary
- parameter params: dictionary of NSCalendarUnit components
- returns: a new absolute time from self plus passed components dictionary
*/
public func add(params :[NSCalendarUnit : AnyObject]) -> NSDate {
let date = self.inRegion().add(components: params)
return date.absoluteTime
}
/**
Diffenence between the receiver and toDate for the units provided
- parameters:
- toDate: date to calculate the difference with
- unitFlags: calendar component flags to express the difference in
- returns: date components with the difference calculated, `nil` on error
*/
public func difference(toDate: NSDate, unitFlags: NSCalendarUnit) -> NSDateComponents? {
return self.inRegion().difference(toDate.inRegion(), unitFlags: unitFlags)
}
/**
Get the NSDateComponents from passed absolute time by converting it into specified region timezone
- parameter region: region of destination
- returns: date components
*/
public func components(inRegion region :Region = Region()) -> NSDateComponents {
return self.inRegion().components
}
/// The same of calling components() without specify a region: current region is used instead
public var components : NSDateComponents {
get {
return components()
}
}
/**
Takes a date unit and returns a date at the start of that unit.
- parameter unit: unit
- parameter region: region of the date
- returns: the date representing that start of that unit
*/
public func startOf(unit :NSCalendarUnit, inRegion region :Region) -> NSDate {
return self.inRegion(region).startOf(unit).absoluteTime
}
/**
Takes a date unit and returns a date at the end of that unit.
- parameter unit: unit
- parameter region: region of the date
- returns: the date representing that end of that unit
*/
public func endOf(unit :NSCalendarUnit, inRegion region :Region) -> NSDate {
return self.inRegion(region).endOf(unit).absoluteTime
}
/**
Return the string representation the date in specified region
- parameter format: format of date
- parameter region: region of destination (Region() is used when argument is not specified)
- returns: string representation of the date into the region
*/
public func toString(format :DateFormat, inRegion region :Region = Region()) -> String? {
return DateInRegion(absoluteTime: self, region: region).toString(format)
}
/**
Convert a DateInRegion date into a date with date & time style specific format style
- parameter style: style to format both date and time (if you specify this you don't need to specify dateStyle,timeStyle)
- parameter dateStyle: style to format the date
- parameter timeStyle: style to format the time
- parameter region: region in which you want to represent self absolute time
- returns: a new string which represent the date expressed into the current region or nil if region does not contain valid date
*/
public func toString(
style: NSDateFormatterStyle? = nil,
dateStyle: NSDateFormatterStyle? = nil,
timeStyle: NSDateFormatterStyle? = nil,
inRegion region :Region = Region(),
relative: Bool = false) -> String? {
let refDateInRegion = DateInRegion(absoluteTime: self, region: region)
return refDateInRegion.toString(style, dateStyle: dateStyle, timeStyle: timeStyle, relative: relative)
}
@available(*, deprecated=2.2, message="Use toString(style:dateStyle:timeStyle:relative:) with relative parameters")
/**
Return relative representation of the date in a specified region
- parameter region: region of destination (Region() is used when argument is not specified)
- paramater style: style used to format the string
- returns: string representation in form of relative date (just now, 3 seconds...)
*/
public func toRelativeCocoaString(inRegion region :Region = Region(), style: NSDateFormatterStyle) -> String? {
return DateInRegion(absoluteTime: self, region: region).toRelativeCocoaString(style: style)
}
@available(*, deprecated=2.2, message="Use toNaturalString() with relative parameters")
/**
Return relative representation of the self absolute time (expressed in region region) compared to another UTC refDate (always expressed in the same region)
- parameter refDate: reference date
- parameter region: region assigned both for reference date and self date
- parameter abbreviated: true to get abbreviated form of the representation
- parameter maxUnits: units details to include in representation (value is from 0 to 7: year = 0, month, weekOfYear, day, hour, minute, second, nanosecond = 7)
- returns: relative string representation
*/
public func toRelativeString(fromDate refDate: NSDate = NSDate(), inRegion region :Region = Region(), abbreviated :Bool = false, maxUnits: Int = 1) -> String? {
let refDateInRegion = DateInRegion(absoluteTime: refDate, region: region)
return DateInRegion(absoluteTime: self, region: region).toRelativeString(refDateInRegion, abbreviated: abbreviated, maxUnits: maxUnits)
}
/**
This method produces a colloquial representation of time elapsed
between this `NSDate` (`self`) and another reference `NSDate` (`refDate`) both expressed in passed `DateInRegion`
- parameter refDate reference date to compare (if not specified current date into `self` region is used)
- parameter style style of the output string
- returns: formatted string or nil if representation cannot be provided
*/
public func toNaturalString(refDate: NSDate, inRegion region :Region = Region(), style: FormatterStyle = FormatterStyle()) -> String? {
let selfInRegion = DateInRegion(absoluteTime: self, region: region)
let refInRegion = DateInRegion(absoluteTime: refDate, region: region)
return selfInRegion.toNaturalString(refInRegion, style: style)
}
}
// MARK: - Adoption of Comparable protocol
extension NSDate : Comparable {}
/**
Compare two dates and return true if the left date is earlier than the right date
- parameter left: left date
- parameter right: right date
- returns: true if left < right
*/
public func < (left: NSDate, right: NSDate) -> Bool {
return (left.compare(right) == NSComparisonResult.OrderedAscending)
}
// MARK: - Date calculations with date components
/**
Subtract from absolute seconds of UTC left date the number of absolute seconds of UTC right date
- parameter lhs: left date
- parameter rhs: right date
- returns: a new date result of the difference between two dates
*/
public func - (lhs: NSDate, rhs: NSDateComponents) -> NSDate {
return lhs + (-rhs)
}
/**
Sum to absolute seconds of UTC left date the number of absolute seconds of UTC right date
- parameter lhs: left date
- parameter rhs: right date
- returns: a new date result of the sum between two dates
*/
public func + (lhs: NSDate, rhs: NSDateComponents) -> NSDate {
return lhs.add(rhs)
}
extension NSDate {
/// Get the year component of the date in current region (use inRegion(...).year to get the year component in specified time zone)
public var year :Int {
return self.inRegion().year!
}
/// Get the month component of the date in current region (use inRegion(...).month to get the month component in specified time zone)
public var month :Int {
return self.inRegion().month!
}
/// Get the month name component of the date in current region (use inRegion(...).monthName to get the month's name component in specified time zone)
public var monthName :String {
return self.inRegion().monthName!
}
/// Get the week of month component of the date in current region (use inRegion(...).weekOfMonth to get the week of month component in specified time zone)
public var weekOfMonth :Int {
return self.inRegion().weekOfMonth!
}
/// Get the year for week of year component of the date in current region (use inRegion(...).yearForWeekOfYear to get the year week of year component in specified time zone)
public var yearForWeekOfYear :Int {
return self.inRegion().yearForWeekOfYear!
}
/// Get the week of year component of the date in current region (use inRegion(...).weekOfYear to get the week of year component in specified time zone)
public var weekOfYear :Int {
return self.inRegion().weekOfYear!
}
/// Get the weekday component of the date in current region (use inRegion(...).weekday to get the weekday component in specified time zone)
public var weekday :Int {
return self.inRegion().weekday!
}
/// Get the weekday ordinal component of the date in current region (use inRegion(...).weekdayOrdinal to get the weekday ordinal component in specified time zone)
public var weekdayOrdinal :Int {
return self.inRegion().weekdayOrdinal!
}
/// Get the day component of the date in current region (use inRegion(...).day to get the day component in specified time zone)
public var day :Int {
return self.inRegion().day!
}
/// Get the number of days of the current date's month in current region (use inRegion(...).monthDays to get it in specified time zone)
public var monthDays :Int {
return self.inRegion().monthDays!
}
/// Get the hour component of the current date's hour in current region (use inRegion(...).hour to get it in specified time zone)
public var hour :Int {
return self.inRegion().hour!
}
/// Get the nearest hour component of the current date's hour in current region (use inRegion(...).nearestHour to get it in specified time zone)
public var nearestHour :Int {
return self.inRegion().nearestHour
}
/// Get the minute component of the current date's minute in current region (use inRegion(...).minute to get it in specified time zone)
public var minute :Int {
return self.inRegion().minute!
}
/// Get the second component of the current date's second in current region (use inRegion(...).second to get it in specified time zone)
public var second :Int {
return self.inRegion().second!
}
/// Get the nanoscend component of the current date's nanosecond in current region (use inRegion(...).nanosecond to get it in specified time zone)
public var nanosecond :Int {
return self.inRegion().nanosecond!
}
/// Get the era component of the current date's era in current region (use inRegion(...).era to get it in specified time zone)
public var era :Int {
return self.inRegion().era!
}
/**
Get the first day of the week in current self absolute time in calendar
- parameter cal: calendar to use. If not specified Gregorian is used instead
- returns: first day of the week in calendar, nil if region is not valid
*/
public func firstDayOfWeek(inRegion region: Region = Region()) -> Int? {
return self.inRegion(region).startOf(.WeekOfYear).day
}
/**
Get the last day of week according to region specified
- parameter cal: calendar to use. If not specified Gregorian is used instead
- returns: last day of the week in calendar, nil if region is not valid
*/
public func lastDayOfWeek(inRegion region: Region = Region()) -> Int? {
return self.inRegion(region).endOf(.WeekOfYear).day
}
public func isIn(unit: NSCalendarUnit, ofDate date: NSDate, inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isIn(unit, ofDate: date.inRegion(region))
}
public func isBefore(unit: NSCalendarUnit, ofDate date: NSDate, inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isBefore(unit, ofDate: date.inRegion(region))
}
public func isAfter(unit: NSCalendarUnit, ofDate date: NSDate, inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isAfter(unit, ofDate: date.inRegion(region))
}
@available(*, deprecated, renamed="isInToday")
public func isToday() -> Bool {
return self.isInToday()
}
public func isInToday(inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isInToday()
}
@available(*, deprecated, renamed="isInYesterday")
public func isYesterday() -> Bool {
return self.isInYesterday()
}
public func isInYesterday(inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isInYesterday()
}
@available(*, deprecated, renamed="isInTomorrow")
public func isTomorrow() -> Bool {
return self.isInTomorrow()
}
public func isInTomorrow(inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isInTomorrow()
}
@available(*, deprecated, renamed="isInSameDayAsDate")
public func inSameDayAsDate(date: NSDate) -> Bool {
return self.isInSameDayAsDate(date)
}
public func isInSameDayAsDate(date: NSDate, inRegion region: Region = Region()) -> Bool {
return self.inRegion(region).isInSameDayAsDate(date.inRegion(region))
}
@available(*, deprecated, renamed="isInWeekend")
public func isWeekend() -> Bool? {
return self.inRegion().isInWeekend()
}
/**
Return true if date is a weekend day into specified region calendar
- returns: true if date is tomorrow into specified region calendar
*/
public func isInWeekend(inRegion region: Region = Region()) -> Bool? {
return self.inRegion(region).isInWeekend()
}
public func isInLeapYear(inRegion region: Region = Region()) -> Bool? {
return self.inRegion(region).leapYear
}
public func isInLeapMonth(inRegion region: Region = Region()) -> Bool? {
return self.inRegion(region).leapMonth
}
}
extension NSDate {
public class func today(inRegion region: Region = Region()) -> NSDate {
return region.today().absoluteTime
}
public class func yesterday(inRegion region: Region = Region()) -> NSDate {
return region.yesterday().absoluteTime
}
public class func tomorrow(inRegion region: Region = Region()) -> NSDate {
return region.tomorrow().absoluteTime
}
}
|
apache-2.0
|
bfc1556da653a9b9261c7264968574dc
| 40.945904 | 222 | 0.657786 | 4.924333 | false | false | false | false |
jacks205/Spots-iOS
|
Spots/Parsing/CSUFParser.swift
|
1
|
2352
|
//
// CSUFParser.swift
// Spots
//
// Created by Mark Jackson on 4/11/16.
// Copyright © 2016 Mark Jackson. All rights reserved.
//
import RxSwift
import ObjectMapper
import Kanna
enum ParsingError : ErrorType {
case Error
}
class CSUFParser {
static func parseCSUFData(data : NSData) -> Observable<SpotsResponse> {
return Observable<SpotsResponse>.create { obs -> Disposable in
let dataString = String(data: data, encoding: NSUTF8StringEncoding)
if let doc = Kanna.HTML(html: dataString!, encoding: NSUTF8StringEncoding) {
let set = doc.css("tr")
let structures = set
.filter { $0.text != nil }
.map { element -> [String : AnyObject] in
return parseXMLElement(element)
}
let json = [
"Structures" : structures
]
if let spotsResponse = Mapper<SpotsResponse>().map(json) {
obs.onNext(spotsResponse)
} else {
obs.onError(ParsingError.Error)
}
} else {
obs.onError(ParsingError.Error)
}
obs.onCompleted()
return AnonymousDisposable { }
}
}
private static func parseXMLElement(element : XMLElement) -> [String : AnyObject] {
let structures = element.text!.characters
.split { $0 == "\r\n" }
.map(String.init)
.filter { !$0.containsString("\t") && !$0.containsString("More") && !$0.containsString("Total") }
.map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }
.filter { $0 != "" }
let name = structures[0]
let total = Int(structures[1])!
let lastUpdated = structures[2]
let date = lastUpdated.dateWithFormat("M/dd/yyyy h:mm:s a", timezone: "PST")
let lastUpdatedISO = "/Date(\(Int(date.timeIntervalSince1970))-700)/"
let available = Int(structures[3])!
let structure : [String : AnyObject] = [
"Name" : name,
"CurrentCount" : available,
"Capacity" : total,
"Timestamp" : lastUpdatedISO
]
return structure
}
}
|
mit
|
8c7cda5f9d16f16d21ed29757caac8f9
| 33.072464 | 109 | 0.538069 | 4.664683 | false | false | false | false |
donald-pinckney/SwiftNum
|
Sources/Linear/MatrixMultiplication.swift
|
1
|
1698
|
//
// MatrixMultiplication.swift
// SwiftNum
//
// Created by Donald Pinckney on 1/1/17.
//
//
import Accelerate
public extension Matrix {
static func *(lhs: Matrix, rhs: Matrix) -> Matrix {
precondition(lhs.width == rhs.height)
var res = Matrix.zeros(lhs.height, rhs.width)
vDSP_mmulD(lhs.data, 1, rhs.data, 1, &res.data, 1, vDSP_Length(lhs.height), vDSP_Length(rhs.width), vDSP_Length(lhs.width))
return res
}
static func *=(lhs: inout Matrix, rhs: Matrix) {
lhs = lhs * rhs
}
static func *(lhs: Matrix, rhs: Double) -> Matrix {
var res = lhs
var rhs = rhs
vDSP_vsmulD(res.data, 1, &rhs, &res.data, 1, vDSP_Length(lhs.data.count))
return res
}
static func *(lhs: Double, rhs: Matrix) -> Matrix {
return rhs * lhs
}
static func *=(lhs: inout Matrix, rhs: Double) {
var rhs = rhs
vDSP_vsmulD(lhs.data, 1, &rhs, &lhs.data, 1, vDSP_Length(lhs.data.count))
}
}
infix operator .*: MultiplicationPrecedence
infix operator .*=: AssignmentPrecedence
public extension Matrix {
static func .*(lhs: Matrix, rhs: Matrix) -> Matrix {
precondition(lhs.width == rhs.width)
precondition(lhs.height == rhs.height)
var res = rhs
vDSP_vmulD(lhs.data, 1, rhs.data, 1, &res.data, 1, vDSP_Length(lhs.data.count))
return res
}
static func .*=(lhs: inout Matrix, rhs: Matrix) {
precondition(lhs.width == rhs.width)
precondition(lhs.height == rhs.height)
vDSP_vmulD(lhs.data, 1, rhs.data, 1, &lhs.data, 1, vDSP_Length(lhs.data.count))
}
}
|
mit
|
cf567fb767ebc5f5c8781a236aca0fdf
| 27.3 | 131 | 0.581861 | 3.559748 | false | false | false | false |
Jerry0523/JWIntent
|
Intent/Transition/SystemTransition.swift
|
1
|
5919
|
//
// SystemTransition.swift
//
// Copyright (c) 2015 Jerry Wong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public enum SystemTransitionStyle {
case translate(factor: CGFloat)
case zoom(factor: CGFloat)
case translateAndZoom(translateFactor: CGFloat, zoomFactor: CGFloat)
func transform(forView: UIView, axis: NSLayoutConstraint.Axis) -> CGAffineTransform {
switch self {
case .translate(let factor):
if axis == .vertical {
return CGAffineTransform(translationX: 0, y: forView.frame.size.height * factor)
} else {
return CGAffineTransform(translationX: forView.frame.size.width * factor, y: 0)
}
case .zoom(let factor):
return CGAffineTransform(scaleX: factor, y: factor)
case .translateAndZoom(let translateFactor, let zoomFactor):
if axis == .vertical {
return CGAffineTransform(scaleX: zoomFactor, y: zoomFactor).translatedBy(x: 0, y: forView.frame.size.height * translateFactor)
} else {
return CGAffineTransform(scaleX: zoomFactor, y: zoomFactor).translatedBy(x: forView.frame.size.width * translateFactor, y: 0)
}
}
}
}
open class SystemTransition: Transition {
public required init(axis: NSLayoutConstraint.Axis, style: SystemTransitionStyle) {
self.axis = axis
self.style = style
super.init()
}
override func present(_ vcToBePresent: UIViewController, fromVC: UIViewController, container: UIView, context: UIViewControllerContextTransitioning) {
super.present(vcToBePresent, fromVC: fromVC, container: container, context: context)
let viewToBePresent = (context.view(forKey: .to) ?? vcToBePresent.view)!
let fromView = (context.view(forKey: .from) ?? fromVC.view)!
if axis == .vertical {
viewToBePresent.transform = CGAffineTransform(translationX: 0, y: viewToBePresent.frame.size.height)
} else {
viewToBePresent.transform = CGAffineTransform(translationX: viewToBePresent.frame.size.width, y: 0)
}
UIView.animate(withDuration: duration, animations: {
viewToBePresent.transform = .identity
fromView.transform = self.style.transform(forView: fromView, axis: self.axis)
self.applyShadow(forView: viewToBePresent)
}) { (complete) in
if context.transitionWasCancelled {
viewToBePresent.removeFromSuperview()
}
viewToBePresent.transform = .identity
fromView.transform = .identity
self.removeShadow(forView: viewToBePresent)
context.completeTransition(!context.transitionWasCancelled)
}
}
override func dismiss(_ vcToBeDismissed: UIViewController, toVC: UIViewController, container: UIView, context: UIViewControllerContextTransitioning) {
super.dismiss(vcToBeDismissed, toVC: toVC, container: container, context: context)
let viewToBeDismissed = (context.view(forKey: .from) ?? vcToBeDismissed.view)!
let toView = (context.view(forKey: .to) ?? toVC.view)!
toView.transform = style.transform(forView: toView, axis: axis)
applyShadow(forView: viewToBeDismissed)
UIView.animate(withDuration: duration, animations: {
toView.transform = .identity
if self.axis == .vertical {
viewToBeDismissed.transform = CGAffineTransform(translationX: 0, y: viewToBeDismissed.frame.size.height)
} else {
viewToBeDismissed.transform = CGAffineTransform(translationX: viewToBeDismissed.frame.size.width, y: 0)
}
}) { (complete) in
toView.transform = .identity
if context.transitionWasCancelled {
toView.removeFromSuperview()
}
self.removeShadow(forView: viewToBeDismissed)
viewToBeDismissed.transform = .identity
context.completeTransition(!context.transitionWasCancelled)
}
}
private func applyShadow(forView: UIView) {
forView.layer.shadowColor = UIColor.black.cgColor
forView.layer.shadowRadius = 10.0
forView.layer.shadowOpacity = 0.5
forView.layer.shadowOffset = CGSize(width: 0, height: 0)
forView.layer.shadowPath = UIBezierPath(rect: forView.bounds).cgPath
}
private func removeShadow(forView: UIView) {
forView.layer.shadowColor = nil
forView.layer.shadowRadius = 0.0
forView.layer.shadowOpacity = 0
forView.layer.shadowPath = nil
}
private var axis : NSLayoutConstraint.Axis
private var style: SystemTransitionStyle
}
|
mit
|
ee546d3707654210746883e992e1e703
| 41.891304 | 154 | 0.661429 | 4.928393 | false | false | false | false |
johnno1962b/swift-corelibs-foundation
|
Foundation/NSKeyedCoderOldStyleArray.swift
|
7
|
3493
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureCoding, NSCoding {
private var _addr : UnsafeMutableRawPointer // free if decoding
private var _count : Int
private var _size : Int
private var _type : _NSSimpleObjCType
private var _decoded : Bool = false
static func sizeForObjCType(_ type: _NSSimpleObjCType) -> Int? {
var size : Int = 0
var align : Int = 0
return _NSGetSizeAndAlignment(type, &size, &align) ? size : nil
}
// TODO: Why isn't `addr` passed as a mutable pointer?
init?(objCType type: _NSSimpleObjCType, count: Int, at addr: UnsafeRawPointer) {
self._addr = UnsafeMutableRawPointer(mutating: addr)
self._count = count
guard let size = _NSKeyedCoderOldStyleArray.sizeForObjCType(type) else {
return nil
}
self._size = size
self._type = type
self._decoded = false
}
deinit {
if self._decoded {
// Cannot deinitialize memory without knowing the element type.
self._addr.deallocate(bytes: self._count * self._size, alignedTo: 1)
}
}
init?(coder aDecoder: NSCoder) {
assert(aDecoder.allowsKeyedCoding)
guard let type = _NSSimpleObjCType(UInt8(aDecoder.decodeInteger(forKey: "NS.type"))) else {
return nil
}
self._count = aDecoder.decodeInteger(forKey: "NS.count")
self._size = aDecoder.decodeInteger(forKey: "NS.size")
self._type = type
self._decoded = true
if self._size != _NSKeyedCoderOldStyleArray.sizeForObjCType(type) {
return nil
}
self._addr = UnsafeMutableRawPointer.allocate(bytes: self._count * self._size, alignedTo: 1)
super.init()
for idx in 0..<self._count {
var type = Int8(self._type)
withUnsafePointer(to: &type) { typep in
let addr = self._addr.advanced(by: idx * self._size)
aDecoder.decodeValue(ofObjCType: typep, at: addr)
}
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self._count, forKey: "NS.count")
aCoder.encode(self._size, forKey: "NS.size")
aCoder.encode(Int(self._type), forKey: "NS.type")
for idx in 0..<self._count {
var type = Int8(self._type)
withUnsafePointer(to: &type) { typep in
aCoder.encodeValue(ofObjCType: typep, at: self._addr + (idx * self._size))
}
}
}
static var supportsSecureCoding: Bool {
return true
}
func fillObjCType(_ type: _NSSimpleObjCType, count: Int, at addr: UnsafeMutableRawPointer) {
if type == self._type && count <= self._count {
addr.copyBytes(from: self._addr, count: count * self._size)
}
}
override func copy() -> Any {
return copy(with: nil)
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
|
apache-2.0
|
b0e1514d30a77f2ec4e0a0b6696f0199
| 31.045872 | 100 | 0.587747 | 4.449682 | false | false | false | false |
ellipse43/v2ex
|
v2ex/HomeViewController.swift
|
1
|
2171
|
//
// HomeViewController.swift
// v2ex
//
// Created by ellipse42 on 15/8/16.
// Copyright (c) 2015年 ellipse42. All rights reserved.
//
import UIKit
import PageMenu
class HomeViewController: UIViewController, CAPSPageMenuDelegate {
@IBOutlet weak var barButton: UIButton!
lazy var pageMenu: CAPSPageMenu = {
var vcs : [UIViewController] = []
for (idx, item) in Config.tabMenus.enumerated() {
var vc = TabViewController()
vc.title = item.0
vc.tabCategory = item.1
vc.parentNavigationController = self.navigationController
vc.currentIdx = idx
vcs.append(vc)
}
var args: [CAPSPageMenuOption] = [
.scrollMenuBackgroundColor(UIColor.white),
.viewBackgroundColor(UIColor.white),
.selectionIndicatorColor(UIColor.black),
.bottomMenuHairlineColor(UIColor.black),
.selectedMenuItemLabelColor(UIColor.black),
.menuItemFont(UIFont(name: "HelveticaNeue", size: 13.0)!),
.menuHeight(40.0),
.menuMargin(20.0),
.menuItemWidth(40.0),
.centerMenuItems(true)
]
// fix: PageMenu Bug
var _height = UIApplication.shared.statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height
var v = CAPSPageMenu(viewControllers: vcs, frame: CGRect(x: 0.0, y: _height, width: self.view.frame.width, height: self.view.frame.height - _height), pageMenuOptions: args)
v.delegate = self
return v
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setNavigationBarItem()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "v2ex"
view.addSubview(pageMenu.view)
}
func willMoveToPage(_ controller: UIViewController, index: Int) {
}
func didMoveToPage(_ controller: UIViewController, index: Int) {
let vc = controller as! TabViewController
if vc.isRefresh == false {
vc.refresh()
}
}
}
|
mit
|
b49b81d2c9c96c172a9f20e4c2e98904
| 30.434783 | 180 | 0.60627 | 4.634615 | false | false | false | false |
narner/AudioKit
|
AudioKit/macOS/AudioKit/User Interface/AKPlaygroundLoop.swift
|
1
|
1357
|
//
// AKPlaygroundLoop.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
/// Class to handle updating via CADisplayLink
public class AKPlaygroundLoop: NSObject {
private var internalHandler: () -> Void = {}
private var duration = 1.0
/// Repeat this loop at a given period with a code block
///
/// - parameter period: Interval between block executions
/// - parameter handler: Code block to execute
///
public init(every period: Double, handler: @escaping () -> Void) {
duration = period
internalHandler = handler
super.init()
update()
}
/// Repeat this loop at a given frequency with a code block
///
/// - parameter frequency: Frequency of block executions in Hz
/// - parameter handler: Code block to execute
///
public init(frequency: Double, handler: @escaping () -> Void) {
duration = 1.0 / frequency
internalHandler = handler
super.init()
update()
}
/// Callback function
@objc func update() {
self.internalHandler()
self.perform(#selector(update),
with: nil,
afterDelay: duration,
inModes: [RunLoopMode.commonModes])
}
}
|
mit
|
40a6eb30a3f628e083dc8d588c180657
| 27.87234 | 70 | 0.604274 | 4.795053 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Rules/RuleConfigurations/NumberSeparatorConfiguration.swift
|
1
|
2043
|
struct NumberSeparatorConfiguration: SeverityBasedRuleConfiguration, Equatable {
private(set) var severityConfiguration = SeverityConfiguration(.warning)
private(set) var minimumLength: Int
private(set) var minimumFractionLength: Int?
private(set) var excludeRanges: [Range<Double>]
var consoleDescription: String {
let minimumFractionLengthDescription: String
if let minimumFractionLength = minimumFractionLength {
minimumFractionLengthDescription = ", minimum_fraction_length: \(minimumFractionLength)"
} else {
minimumFractionLengthDescription = ", minimum_fraction_length: none"
}
return severityConfiguration.consoleDescription
+ ", minimum_length: \(minimumLength)"
+ minimumFractionLengthDescription
}
init(minimumLength: Int, minimumFractionLength: Int?, excludeRanges: [Range<Double>]) {
self.minimumLength = minimumLength
self.minimumFractionLength = minimumFractionLength
self.excludeRanges = excludeRanges
}
mutating func apply(configuration: Any) throws {
guard let configuration = configuration as? [String: Any] else {
throw ConfigurationError.unknownConfiguration
}
if let minimumLength = configuration["minimum_length"] as? Int {
self.minimumLength = minimumLength
}
if let minimumFractionLength = configuration["minimum_fraction_length"] as? Int {
self.minimumFractionLength = minimumFractionLength
}
if let excludeRanges = configuration["exclude_ranges"] as? [[String: Any]] {
self.excludeRanges = excludeRanges.compactMap { dict in
guard let min = dict["min"] as? Double, let max = dict["max"] as? Double else { return nil }
return min ..< max
}
}
if let severityString = configuration["severity"] as? String {
try severityConfiguration.apply(configuration: severityString)
}
}
}
|
mit
|
fee39243686be69ba9090889a3f53d9a
| 40.693878 | 108 | 0.667156 | 5.225064 | false | true | false | false |
yunzixun/V2ex-Swift
|
View/V2ActivityViewController.swift
|
1
|
13011
|
//
// V2ActivityViewController.swift
// V2ex-Swift
//
// Created by huangfeng on 3/7/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
@objc protocol V2ActivityViewDataSource {
/**
获取有几个 ,当前不考虑复用,最多仅支持4个,之后会考虑复用并可以返回Int.max多个。
*/
func V2ActivityView(_ activityView:V2ActivityViewController ,numberOfCellsInSection section: Int) -> Int
/**
返回Activity ,主要是标题和图片
*/
func V2ActivityView(_ activityView:V2ActivityViewController ,ActivityAtIndexPath indexPath:IndexPath) -> V2Activity
/**
有多少组 ,和UITableView 一样。
*/
@objc optional func numberOfSectionsInV2ActivityView(_ activityView:V2ActivityViewController) ->Int
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,heightForHeaderInSection section: Int) -> CGFloat
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,heightForFooterInSection section: Int) -> CGFloat
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,viewForHeaderInSection section: Int) ->UIView?
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,viewForFooterInSection section: Int) ->UIView?
@objc optional func V2ActivityView(_ activityView: V2ActivityViewController, didSelectRowAtIndexPath indexPath: IndexPath)
}
class V2Activity:NSObject {
var title:String
var image:UIImage
init(title aTitle:String , image aImage:UIImage){
title = aTitle
image = aImage
}
}
class V2ActivityButton: UIButton {
var indexPath:IndexPath?
}
/// 一个和UIActivityViewController 一样的弹出框
class V2ActivityViewController: UIViewController ,UIViewControllerTransitioningDelegate {
weak var dataSource:V2ActivityViewDataSource?
var section:Int{
get{
if let _section = dataSource?.numberOfSectionsInV2ActivityView?(self) {
return _section
}
else {
return 1
}
}
}
var panel:UIToolbar = CTToolBar()
/**
当前不考虑复用,每一行最多支持4个cell
*/
func numberOfCellsInSection(_ section:Int) -> Int{
if var cells = dataSource?.V2ActivityView(self, numberOfCellsInSection: section) {
if cells > 5 {
cells = 5
}
return cells
}
else{
return 0
}
}
//MARK: - 页面生命周期事件
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0, alpha: 0)
self.transitioningDelegate = self
self.panel.barStyle = V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault ? .default : .black
self.view.addSubview(self.panel)
self.panel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.view).offset(-90)
make.left.equalTo(self.view).offset(10)
make.right.equalTo(self.view).offset(-10)
}
self.panel.layer.cornerRadius = 6
self.panel.layer.masksToBounds = true
self.setupView()
if let lastView = self.panel.subviews.last {
self.panel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(lastView)
}
}
let cancelPanel = UIToolbar()
cancelPanel.barStyle = self.panel.barStyle
cancelPanel.layer.cornerRadius = self.panel.layer.cornerRadius
cancelPanel.layer.masksToBounds = true
self.view.addSubview(cancelPanel)
cancelPanel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.panel.snp.bottom).offset(10)
make.left.right.equalTo(self.panel);
make.height.equalTo(45)
}
let cancelButton = UIButton()
cancelButton.setTitle(NSLocalizedString("cancel2"), for: UIControlState())
cancelButton.titleLabel?.font = v2Font(18)
cancelButton.setTitleColor(V2EXColor.colors.v2_TopicListTitleColor, for: UIControlState())
cancelPanel.addSubview(cancelButton)
cancelButton.snp.makeConstraints{ (make) -> Void in
make.left.top.right.bottom.equalTo(cancelPanel)
}
cancelButton.addTarget(self, action: #selector(dismiss as () -> Void), for: .touchUpInside)
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss as () -> Void)))
}
@objc func dismiss(){
self.dismiss(animated: true, completion: nil)
}
//#MARK: - 配置视图
fileprivate func setupView(){
for i in 0..<section {
//setupHeaderView
//...
//setupSectionView
let sectionView = self.setupSectionView(i)
self.panel.addSubview(sectionView)
sectionView.snp.makeConstraints{ (make) -> Void in
make.left.right.equalTo(self.panel)
make.height.equalTo(110)
if self.panel.subviews.count > 1 {
make.top.equalTo(self.panel.subviews[self.panel.subviews.count - 1 - 1].snp.bottom)
}
else {
make.top.equalTo(self.panel)
}
}
//setupFoterView
self.setupFooterView(i)
}
}
//配置每组的cell
fileprivate func setupSectionView(_ _section:Int) -> UIView {
let sectionView = UIView()
let margin = (SCREEN_WIDTH-20 - 60 * 5 )/6.0
for i in 0..<self.numberOfCellsInSection(_section) {
let cellView = self.setupCellView(i, currentSection: _section);
sectionView.addSubview(cellView)
cellView.snp.makeConstraints{ (make) -> Void in
make.width.equalTo(60)
make.height.equalTo(80)
make.centerY.equalTo(sectionView)
make.left.equalTo(sectionView).offset( CGFloat((i+1)) * margin + CGFloat(i * 60) )
}
}
return sectionView
}
//配置每组的 footerView
fileprivate func setupFooterView(_ _section:Int) {
if let view = dataSource?.V2ActivityView?(self, viewForFooterInSection: _section) {
var height = dataSource?.V2ActivityView?(self, heightForFooterInSection: _section)
if height == nil {
height = 40
}
self.panel.addSubview(view)
view.snp.makeConstraints{ (make) -> Void in
make.left.right.equalTo(self.panel)
make.height.equalTo(height!)
if self.panel.subviews.count > 1 {
make.top.equalTo(self.panel.subviews[self.panel.subviews.count - 1 - 1].snp.bottom)
}
else {
make.top.equalTo(self.panel)
}
}
}
}
//配置每个cell
fileprivate func setupCellView(_ index:Int , currentSection:Int) -> UIView {
let cellView = UIView()
let buttonBackgoundView = UIImageView()
//用颜色生成图片 切成圆角 并拉伸显示
buttonBackgoundView.image = createImageWithColor(V2EXColor.colors.v2_CellWhiteBackgroundColor, size: CGSize(width: 15, height: 15)).roundedCornerImageWithCornerRadius(5).stretchableImage(withLeftCapWidth: 7, topCapHeight: 7)
cellView.addSubview(buttonBackgoundView)
buttonBackgoundView.snp.makeConstraints{ (make) -> Void in
make.width.height.equalTo(60)
make.top.left.equalTo(cellView)
}
let activity = dataSource?.V2ActivityView(self, ActivityAtIndexPath: IndexPath(row: index, section: currentSection))
let button = V2ActivityButton()
button.setImage(activity?.image.withRenderingMode(.alwaysTemplate), for: UIControlState())
cellView.addSubview(button)
button.tintColor = V2EXColor.colors.v2_TopicListUserNameColor
button.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(buttonBackgoundView)
}
button.indexPath = IndexPath(row: index, section: currentSection)
button.addTarget(self, action: #selector(V2ActivityViewController.cellDidSelected(_:)), for: .touchUpInside)
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 2
titleLabel.text = activity?.title
titleLabel.font = v2Font(12)
titleLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor
cellView.addSubview(titleLabel)
titleLabel.snp.makeConstraints{ (make) -> Void in
make.centerX.equalTo(cellView)
make.left.equalTo(cellView)
make.right.equalTo(cellView)
make.top.equalTo(buttonBackgoundView.snp.bottom).offset(5)
}
return cellView
}
@objc func cellDidSelected(_ sender:V2ActivityButton){
dataSource?.V2ActivityView?(self, didSelectRowAtIndexPath: sender.indexPath!)
}
//MARK: - 转场动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return V2ActivityTransionPresent()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return V2ActivityTransionDismiss()
}
}
/// 显示转场动画
class V2ActivityTransionPresent:NSObject,UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
fromVC?.view.isHidden = true
let screenshotImage = fromVC?.view.screenshot()
let tempView = UIImageView(image: screenshotImage)
tempView.tag = 9988
container.addSubview(tempView)
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
container.addSubview(toVC!.view)
toVC?.view.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 7, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
toVC?.view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
tempView.transform = CGAffineTransform(scaleX: 0.98, y: 0.98);
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
/// 隐藏转场动画
class V2ActivityTransionDismiss:NSObject,UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
container.addSubview(toVC!.view)
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
container.addSubview(fromVC!.view)
let tempView = container.viewWithTag(9988)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
fromVC?.view.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
tempView!.transform = CGAffineTransform(scaleX: 1, y: 1);
}, completion: { (finished) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
toVC?.view.isHidden = false
})
}
}
class CTToolBar: UIToolbar {
override func layoutSubviews() {
super.layoutSubviews()
//Fix iOS11 种 UIToolBar的子View 都不响应点击事件
for view in self.subviews {
print("\(NSStringFromClass(view.classForCoder))")
if NSStringFromClass(view.classForCoder) == "_UIToolbarContentView" {
view.isUserInteractionEnabled = false
}
}
}
}
|
mit
|
95e184490ad724ffc082fa664f80bb87
| 38.113846 | 232 | 0.64089 | 4.904321 | false | false | false | false |
Eiltea/MyWeiBo
|
MyWeiBo/MyWeiBo/Classes/View/Home/EilToolBarView.swift
|
1
|
3814
|
//
// EilToolBarView.swift
// MyWeiBo
//
// Created by Eil.tea on 15/12/11.
// Copyright © 2015年 Eil.tea. All rights reserved.
//
import UIKit
class EilToolBarView: UIView {
var retweetButton: UIButton?
var commentButton: UIButton?
var unlikeButton: UIButton?
var statusViewModel: EilStatusViewModel? {
didSet{
// 取到三个按钮,设置按钮上的文字
retweetButton?.setTitle(statusViewModel?.retweetCountStr, forState: .Normal)
commentButton?.setTitle(statusViewModel?.commentCountStr, forState: .Normal)
unlikeButton?.setTitle(statusViewModel?.attitudeCountStr, forState: .Normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 设置视图
private func setupUI(){
// 添加三个按钮
retweetButton = addChildButton("转发", imgName: "timeline_icon_retweet")
commentButton = addChildButton("评论", imgName: "timeline_icon_comment")
unlikeButton = addChildButton("赞", imgName: "timeline_icon_unlike")
// 添加两个分割线
let sp1 = addSeparator()
let sp2 = addSeparator()
// 添加约束
retweetButton?.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(commentButton!)
}
commentButton?.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(retweetButton!.snp_trailing)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(unlikeButton!)
}
unlikeButton?.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.leading.equalTo(commentButton!.snp_trailing)
}
// 添加分割线的约束
sp1.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(retweetButton!.snp_trailing)
make.centerY.equalTo(self)
}
sp2.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(commentButton!.snp_trailing)
make.centerY.equalTo(self)
}
}
/// 添加三个按钮
///
/// - parameter title: 默认文字
/// - parameter imgName: 图片名字
///
/// - returns: 返回当前添加的按钮
private func addChildButton(title: String, imgName: String) -> UIButton {
let button = UIButton()
// 设置文字,字体大小,不同状态的字体颜色
button.setTitle(title, forState: .Normal)
button.setTitleColor(UIColor.grayColor(), forState: .Normal)
button.setTitleColor(UIColor.darkGrayColor(), forState: .Highlighted)
button.titleLabel?.font = UIFont.systemFontOfSize(14)
// 设置图标
button.setImage(UIImage(named: imgName), forState: .Normal)
// 设置不同状态下的背景图片
button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), forState: UIControlState.Highlighted)
button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), forState: UIControlState.Normal)
addSubview(button)
return button
}
// 添加分割线
private func addSeparator() -> UIView {
let imageView = UIImageView(image: UIImage(named: "timeline_card_bottom_line"))
addSubview(imageView)
return imageView
}
}
|
mit
|
6a68a6ab3f2a8a9663b0ea4b32520a79
| 31.663636 | 134 | 0.607014 | 4.49125 | false | false | false | false |
nessBautista/iOSBackup
|
blackboard.playground/Pages/Basics.xcplaygroundpage/Contents.swift
|
1
|
2272
|
//: [Previous](@previous)
import UIKit
class ElectricVehicle
{
static var count = 0
var passengerCapacity: Int = 4
let zeroTo60: Float
var color: UIColor
init(passengerCapacity:Int, zeroTo60:Float, color:UIColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1))
{
self.passengerCapacity = passengerCapacity
self.zeroTo60 = zeroTo60
self.color = color
ElectricVehicle.count += 1
}
convenience init(zeroTo60:Float)
{
self.init(passengerCapacity:4, zeroTo60:zeroTo60)
}
convenience init()
{
self.init(zeroTo60: 6.0)
}
deinit
{
ElectricVehicle.count -= 1
}
}
let teslaModelS = ElectricVehicle(passengerCapacity: 4, zeroTo60: 2.5)
var teslaModel3: ElectricVehicle? = ElectricVehicle(passengerCapacity: 5, zeroTo60: 1.5)
teslaModel3 = nil
//See how deinitializer modifies counter
ElectricVehicle.count
//The color is changed by reference
let p100d = teslaModelS
teslaModelS.color
p100d.color = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
teslaModelS.color
//Realize how p100d properties can be change even if it's declared as a constant
//Strings
//Passed by copy
let quote = "In the end, we only regrest the chances we didn't take"
var newQuote = quote
newQuote = "In the end, it's not the years in your life that count. It's the life in your years"
print(quote)
//Access string individual characters.
quote.characters.count
let quoteArray = quote.characters.map({$0})
quote.uppercased()
//quote.lowercased()
print(quote.uppercased())
//Repeating
String(repeating: "😀", count: 5)
//Replacing occurences
let verse1 = "I like to eat, eat, eat, apples and bananas!"
let verse2 = verse1.replacingOccurrences(of: "eat", with: "ate")
.replacingOccurrences(of: "ap", with: "ay-")
.replacingOccurrences(of: "bananas", with: "ba-nay-nays")
print(verse1, verse2, separator:"\n")
//Range of operators
let rangeA = 0..<10
rangeA.count
let rangeB = 0...10
rangeB.count
var fibonacciNumbers = [1, 3, 6,10, 15, 21]
let replacement = [1,2,3,5,8,13]
fibonacciNumbers.replaceSubrange(1..<5, with: replacement)
print(fibonacciNumbers)
|
cc0-1.0
|
d8f730b2908dcbf975d97c9c5288d751
| 23.663043 | 148 | 0.696342 | 3.326979 | false | false | false | false |
mrdepth/CloudData
|
CloudData/CloudData/Extensions.swift
|
1
|
7819
|
//
// Extensions.swift
// CloudData
//
// Created by Artem Shimanski on 13.03.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
extension UUID {
init(ubiquityIdentityToken token: NSCoding) {
let data = NSKeyedArchiver.archivedData(withRootObject: token)
let md5 = data.md5()
let uuid = md5.withUnsafeBytes { ptr -> uuid_t in
let b = ptr.bindMemory(to: UInt8.self)
return uuid_t(b[0], b[1], b[2], b[3],
b[4], b[5], b[6], b[7],
b[8], b[9], b[10], b[11],
b[12], b[13], b[14], b[15])
}
self = UUID(uuid: uuid)
}
}
extension NSAttributeDescription {
func transformedValue(_ value: Any?) -> Any? {
if attributeType == .transformableAttributeType {
if let valueTransformerName = valueTransformerName {
return ValueTransformer(forName: NSValueTransformerName(rawValue: valueTransformerName))?.transformedValue(value)
}
else if let value = value {
return NSKeyedArchiver.archivedData(withRootObject: value)
}
}
return value
}
func reverseTransformedValue(_ value: Any?, compressed withAlgorithm: CompressionAlgorithm?) -> Any? {
var value = value
guard !(value is NSNull) else {return nil}
if let data = value as? Data {
if let algorithm = withAlgorithm {
value = (try? data.decompressed(algorithm: algorithm)) ?? data
}
else {
value = data
}
}
switch attributeType {
case .undefinedAttributeType, .objectIDAttributeType:
assert(false, "Invalid attribute type \(attributeType)")
case .integer16AttributeType,
.integer32AttributeType,
.integer64AttributeType,
.decimalAttributeType,
.doubleAttributeType,
.floatAttributeType,
.booleanAttributeType:
return value ?? self.defaultValue
case .stringAttributeType,
.dateAttributeType,
.binaryDataAttributeType,
.UUIDAttributeType,
.URIAttributeType:
return value
case .transformableAttributeType:
if let valueTransformerName = valueTransformerName {
return ValueTransformer(forName: NSValueTransformerName(rawValue: valueTransformerName))?.reverseTransformedValue(value)
}
else if let data = value as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: data)
}
@unknown default:
return value
}
return value
}
func ckRecordValue(from backingObject: NSManagedObject) -> CKRecordValue? {
return transformedValue(backingObject.value(forKey: self.name)) as? CKRecordValue
}
func managedValue(from record: CKRecord, compressed withAlgorithm: CompressionAlgorithm?) -> Any? {
return reverseTransformedValue(record[name], compressed: withAlgorithm)
}
}
extension NSRelationshipDescription {
@nonobjc var shouldSerialize: Bool {
return true
/*if let inverseRelationship = inverseRelationship {
if inverseRelationship.deleteRule == .cascadeDeleteRule {
return true
}
else if deleteRule == .cascadeDeleteRule {
return false
}
else {
if isToMany {
if inverseRelationship.isToMany {
return entity.name! < inverseRelationship.name
}
else {
return false
}
}
else {
if inverseRelationship.isToMany {
return true
}
else {
return entity.name! < inverseRelationship.name
}
}
}
}
else {
return true
}*/
}
@nonobjc func ckReference(from backingObject: NSManagedObject, recordZoneID: CKRecordZone.ID) -> Any? {
var result: Any?
backingObject.managedObjectContext?.performAndWait {
let action: CKRecord.Reference.Action = self.inverseRelationship?.deleteRule == .cascadeDeleteRule ? .deleteSelf : .none
let value = backingObject.value(forKey: self.name)
if self.isToMany {
if self.isOrdered {
guard let value = value as? NSOrderedSet else {return}
var references = [CKRecord.Reference]()
for object in value {
guard let object = object as? NSManagedObject else {continue}
guard let record = object.value(forKey: CloudRecordProperty) as? CloudRecord else {continue}
let reference = CKRecord.Reference(recordID: CKRecord.ID(recordName: record.recordID!, zoneID: recordZoneID), action: action)
references.append(reference)
}
result = references.count > 0 ? references : NSNull()
}
else {
guard let value = value as? Set<NSManagedObject> else {return}
var references = Set<CKRecord.Reference>()
for object in value {
guard let record = object.value(forKey: CloudRecordProperty) as? CloudRecord else {continue}
let reference = CKRecord.Reference(recordID: CKRecord.ID(recordName: record.recordID!, zoneID: recordZoneID), action: action)
references.insert(reference)
}
result = references.count > 0 ? references.sorted(by: {$0.recordID.recordName < $1.recordID.recordName}) : NSNull()
}
}
else if let object = value as? NSManagedObject {
guard let record = object.value(forKey: CloudRecordProperty) as? CloudRecord else {return}
result = CKRecord.Reference(recordID: CKRecord.ID(recordName: record.recordID!, zoneID: recordZoneID), action: action)
}
}
return result
}
@nonobjc func managedReference(from record: CKRecord, store: CloudStore) -> Any? {
let value = record[name]
if isToMany {
guard let value = value as? [CKRecord.Reference] else {return NSNull()}
var set = [NSManagedObjectID]()
for reference in value {
if let objectID = managedReference(from: reference, store: store) {
set.append(objectID)
}
}
return isOrdered ? NSOrderedSet(array: set) : NSSet(array: set)
}
else {
if let reference = value as? CKRecord.Reference ?? (value as? [CKRecord.Reference])?.last {
return managedReference(from: reference, store: store)
}
else {
return NSNull()
}
}
}
@nonobjc func managedReference(from reference: CKRecord.Reference, store: CloudStore) -> NSManagedObjectID? {
return store.backingObjectHelper?.objectID(recordID: reference.recordID.recordName, entityName: destinationEntity!.name!)
}
}
extension NSManagedObject {
}
extension CKRecord {
func changedValues(object: NSManagedObject, entity: NSEntityDescription) -> [String: Any] {
assert(recordType == object.entity.name)
var diff = [String: Any]()
for property in entity.properties {
if let attribute = property as? NSAttributeDescription {
let value1: NSObjectProtocol = attribute.ckRecordValue(from: object) ?? NSNull()
let value2: NSObjectProtocol = self[attribute.name] ?? NSNull()
if !value1.isEqual(value2) {
diff[attribute.name] = value1
}
}
else if let relationship = property as? NSRelationshipDescription {
if relationship.shouldSerialize {
let value1: NSObjectProtocol = relationship.ckReference(from: object, recordZoneID: self.recordID.zoneID) as? NSObjectProtocol ?? NSNull()
let value2: NSObjectProtocol = self[relationship.name] ?? NSNull()
if !value1.isEqual(value2) {
diff[relationship.name] = value1
}
}
}
}
return diff
}
func nodeValues(store: CloudStore, includeToManyRelationships: Bool) -> [String: Any] {
guard let entity = store.entities?[recordType] else {return [:]}
var values = [String: Any]()
for property in entity.properties {
if let attribute = property as? NSAttributeDescription {
if let value = attribute.managedValue(from: self, compressed: store.binaryDataCompressionAlgorithm) {
values[attribute.name] = value
}
}
else if let relationship = property as? NSRelationshipDescription {
if includeToManyRelationships || !relationship.isToMany {
if let value = relationship.managedReference(from: self, store: store) {
values[relationship.name] = value
}
}
}
}
return values
}
}
|
mit
|
6f9557e558fe5277365bd517e4f3c732
| 29.420233 | 143 | 0.69583 | 3.914872 | false | false | false | false |
colemancda/Seam
|
Seam/Seam/SMServerStoreSetupOperation.swift
|
1
|
5143
|
// SMServerStoreSetupOperation.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nofel Mahmood ( https://twitter.com/NofelMahmood )
//
// 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
import CloudKit
let SMStoreCloudStoreCustomZoneName = "SMStoreCloudStore_CustomZone"
let SMStoreCloudStoreSubscriptionName = "SM_CloudStore_Subscription"
class SMServerStoreSetupOperation:NSOperation {
var database:CKDatabase?
var setupOperationCompletionBlock:((customZoneCreated:Bool,customZoneSubscriptionCreated:Bool)->Void)?
init(cloudDatabase:CKDatabase?) {
self.database = cloudDatabase
super.init()
}
override func main() {
let operationQueue = NSOperationQueue()
let zone = CKRecordZone(zoneName: SMStoreCloudStoreCustomZoneName)
var error: NSError?
let modifyRecordZonesOperation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil)
modifyRecordZonesOperation.database = self.database
modifyRecordZonesOperation.modifyRecordZonesCompletionBlock = ({(savedRecordZones, deletedRecordZonesIDs, operationError) -> Void in
error = operationError
let customZoneWasCreated:AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(SMStoreCloudStoreCustomZoneName)
let customZoneSubscriptionWasCreated:AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(SMStoreCloudStoreSubscriptionName)
if ((operationError == nil || customZoneWasCreated != nil) && customZoneSubscriptionWasCreated == nil)
{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: SMStoreCloudStoreCustomZoneName)
let recordZoneID = CKRecordZoneID(zoneName: SMStoreCloudStoreCustomZoneName, ownerName: CKOwnerDefaultName)
let subscription = CKSubscription(zoneID: recordZoneID, subscriptionID: SMStoreCloudStoreSubscriptionName, options: CKSubscriptionOptions(rawValue: 0))
let subscriptionNotificationInfo = CKNotificationInfo()
subscriptionNotificationInfo.alertBody = ""
subscriptionNotificationInfo.shouldSendContentAvailable = true
subscription.notificationInfo = subscriptionNotificationInfo
subscriptionNotificationInfo.shouldBadge = false
let subscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
subscriptionsOperation.database = self.database
subscriptionsOperation.modifySubscriptionsCompletionBlock=({ (modified,created,operationError) -> Void in
if operationError == nil
{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: SMStoreCloudStoreSubscriptionName)
}
error = operationError
})
operationQueue.addOperation(subscriptionsOperation)
}
})
operationQueue.addOperation(modifyRecordZonesOperation)
operationQueue.waitUntilAllOperationsAreFinished()
if self.setupOperationCompletionBlock != nil
{
if error == nil
{
self.setupOperationCompletionBlock!(customZoneCreated: true, customZoneSubscriptionCreated: true)
}
else
{
if NSUserDefaults.standardUserDefaults().objectForKey(SMStoreCloudStoreCustomZoneName) == nil
{
self.setupOperationCompletionBlock!(customZoneCreated: false, customZoneSubscriptionCreated: false)
}
else
{
self.setupOperationCompletionBlock!(customZoneCreated: true, customZoneSubscriptionCreated: false)
}
}
}
}
}
|
mit
|
0cee5b7721a6ed92e70199a3cf69ee35
| 47.528302 | 167 | 0.675481 | 5.746369 | false | false | false | false |
wybosys/n2
|
src.swift/ui/N2Application.swift
|
1
|
2605
|
class Application : UIResponder, UIApplicationDelegate, SignalSlotPattern
{
var window: UIWindow?
var root: UINavigationController!
func bootstrap() -> Bool
{
n2_core_foundation()
// 替换一些标准类的函数
uikit_swizzles()
return true
}
func start()
{
self.root = UINavigationController()
self.root.navigationBarHidden = true
}
func load()
{
}
final
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
// 引导应用
if !self.bootstrap() {
return false
}
// 初始化环境
self.start()
// 建立根window
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.rootViewController = self.root
self.window!.makeKeyAndVisible()
// 加载应用
self.load()
return true
}
final
func applicationWillResignActive(application: UIApplication)
{
log("Application Deactivating")
self.signals().emit(kSignalApplicationDeactivating)
}
final
func applicationDidEnterBackground(application: UIApplication)
{
log("Application Deactivated")
self.signals().emit(kSignalApplicationDeactivated)
}
final
func applicationWillEnterForeground(application: UIApplication)
{
log("Application Activating")
self.signals().emit(kSignalApplicationActivating)
}
final
func applicationDidBecomeActive(application: UIApplication)
{
log("Application Activated")
self.signals().emit(kSignalApplicationActivated)
}
final
func applicationWillTerminate(application: UIApplication)
{
log("terminating")
}
func signals() -> Signals
{
return SignalSlotImpl.signals(self)
}
func siginit()
{
self.signals().add(kSignalApplicationActivating)
self.signals().add(kSignalApplicationActivated)
self.signals().add(kSignalApplicationDeactivating)
self.signals().add(kSignalApplicationDeactivated)
}
}
let kSignalApplicationActivating = "::ui::app::activating";
let kSignalApplicationActivated = "::ui::app::activated";
let kSignalApplicationDeactivating = "::ui::app::deactivating";
let kSignalApplicationDeactivated = "::ui::app::deactivated";
|
bsd-3-clause
|
a546d779c42e4b8c575c49aed3b08671
| 24.029412 | 116 | 0.622405 | 5.065476 | false | false | false | false |
coderMONSTER/ioscelebrity
|
YStar/YStar/Scenes/Controller/ResetPwdVC.swift
|
1
|
5076
|
//
// ResetPwdVC.swift
// YStar
//
// Created by mu on 2017/7/6.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
class ResetPwdVC: BaseTableViewController {
@IBOutlet weak var phoneText: UITextField!
@IBOutlet weak var codeText: UITextField!
@IBOutlet weak var pwdText: UITextField!
@IBOutlet weak var vaildCodeBtn: UIButton!
@IBOutlet weak var sureBtn: UIButton!
@IBOutlet weak var closeBtn: UIButton!
@IBOutlet weak var headerView: UIView!
var codeTime = 60
var timer: Timer?
var timeStamp = ""
var vToken = ""
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.clear
headerView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
closeBtn.setImage(UIImage.imageWith(AppConst.iconFontName.closeIcon.rawValue, fontSize: CGSize.init(width: 33, height: 33), fontColor: UIColor.init(rgbHex: AppConst.ColorKey.label9.rawValue)), for: .normal)
}
// MARK: - 获取验证码
@IBAction func codeBtnTapped(_ sender: UIButton) {
if checkTextFieldEmpty([phoneText]) && isTelNumber(num: phoneText.text!) {
let checkRegisterRequestModel = CheckRegisterRequestModel()
checkRegisterRequestModel.phone = phoneText.text!
AppAPIHelper.commen().CheckRegister(model: checkRegisterRequestModel, complete: {[weak self] (checkRegistResult) in
if let checkRegistResponse = checkRegistResult {
if checkRegistResponse["result"] as! Int == 0 {
SVProgressHUD.showErrorMessage(ErrorMessage: "该用户未注册!!!", ForDuration: 2.0, completion: nil)
self?.vaildCodeBtn.isEnabled = true
return nil
} else {
SVProgressHUD.showProgressMessage(ProgressMessage: "")
let sendVerificationCodeRequestModel = SendVerificationCodeRequestModel()
sendVerificationCodeRequestModel.phone = (self?.phoneText.text)!
AppAPIHelper.commen().SendVerificationCode(model: sendVerificationCodeRequestModel, complete: {[weak self] (result) in
SVProgressHUD.dismiss()
if let response = result {
if response["result"] as! Int == 1 {
self?.timer = Timer.scheduledTimer(timeInterval: 1,target:self!,selector: #selector(self?.updatecodeBtnTitle),userInfo: nil,repeats: true)
self?.timeStamp = String.init(format: "%ld", response["timeStamp"] as! Int)
self?.vToken = String.init(format: "%@", response["vToken"] as! String)
}
}
return nil
}, error: self?.errorBlockFunc())
}
}
return nil
}, error: errorBlockFunc())
}
}
// MARK: - 更新秒数
func updatecodeBtnTitle() {
if codeTime == 0 {
vaildCodeBtn.isEnabled = true
vaildCodeBtn.setTitle("重新发送", for: .normal)
codeTime = 60
timer?.invalidate()
vaildCodeBtn.backgroundColor = UIColor(hexString: "BCE0DA")
return
}
vaildCodeBtn.isEnabled = false
codeTime = codeTime - 1
let title: String = "\(codeTime)秒重新发送"
vaildCodeBtn.setTitle(title, for: .normal)
vaildCodeBtn.backgroundColor = UIColor(hexString: "ECECEC")
}
// MARK: - 重置密码
@IBAction func resetBtnTapped(_ sender: UIButton) {
if checkTextFieldEmpty([phoneText,codeText,pwdText]){
let string = AppConst.pwdKey + self.timeStamp + codeText.text! + phoneText.text!
if string.md5() != self.vToken{
SVProgressHUD.showErrorMessage(ErrorMessage: "验证码不正确", ForDuration: 0.5, completion:nil)
return
}
let model = ResetPwdReqModel()
model.phone = phoneText.text!
model.pwd = pwdText.text!.md5()
AppAPIHelper.commen().Resetpwd(model: model, complete: { (result) in
if let response = result {
if response["result"] as! Int == 1{
// 重置成功
SVProgressHUD.showSuccessMessage(SuccessMessage: "重置成功", ForDuration: 2.0, completion: {
_ = self.navigationController?.popViewController(animated: true)
})
}
}
return nil
}, error: errorBlockFunc())
}
}
// MARK: - 返回
@IBAction func closeBtnTapped(_ sender: UIButton) {
_ = navigationController?.popToRootViewController(animated: true)
}
}
|
mit
|
1c8d317db032a34f54875afb3ed7d579
| 42.347826 | 214 | 0.566299 | 4.960199 | false | false | false | false |
rjalkuino/youtubeApiSample
|
YTSample/AppDelegate.swift
|
1
|
2456
|
//
// AppDelegate.swift
// YTSample
//
// Created by robert john alkuino on 12/28/16.
// Copyright © 2016 thousandminds. All rights reserved.
//
import UIKit
let Env = EnvType.localStaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = .white
let tabBarViewController = ViewController()
self.window?.rootViewController = tabBarViewController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
apache-2.0
|
b332b1035d0284dd674fafb871273735
| 40.610169 | 285 | 0.731976 | 5.617849 | false | false | false | false |
victorchee/CollectionView
|
BookCollectionView/BookCollectionView/BookStore.swift
|
2
|
712
|
//
// BookStore.swift
// BookCollectionView
//
// Created by qihaijun on 11/30/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class BookStore {
static let sharedStore = BookStore()
func loadBooks(_ plist: String) -> [Book] {
var books = [Book]()
guard let path = Bundle.main.path(forResource: plist, ofType: "plist") else {
return books
}
guard let array = NSArray(contentsOfFile: path) as? [NSDictionary] else {
return books
}
for dict in array {
let book = Book(dict: dict)
books.append(book)
}
return books
}
}
|
mit
|
a0986703523bbec331dc9f19a9c690a8
| 21.21875 | 85 | 0.541491 | 4.361963 | false | false | false | false |
hgani/ganilib-ios
|
glib/Classes/View/GWebView.swift
|
1
|
3098
|
import UIKit
import WebKit
open class GWebView: WKWebView {
private var helper: ViewHelper!
private var requestUrl: URL?
fileprivate lazy var refresher: GRefreshControl = {
GRefreshControl().onValueChanged { [unowned self] in
self.refresh()
}
}()
public init() {
super.init(frame: .zero, configuration: WKWebViewConfiguration())
initialize()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
private func initialize() {
helper = ViewHelper(self)
navigationDelegate = self
scrollView.addSubview(refresher)
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
helper.didMoveToSuperview()
}
public func color(bg: UIColor?) -> Self {
if let bgColor = bg {
backgroundColor = bgColor
}
return self
}
public func width(_ width: Int) -> Self {
helper.width(width)
return self
}
public func width(_ width: LayoutSize) -> Self {
helper.width(width)
return self
}
public func width(weight: Float) -> Self {
helper.width(weight: weight)
return self
}
public func height(_ height: Int) -> Self {
helper.height(height)
return self
}
public func height(_ height: LayoutSize) -> Self {
helper.height(height)
return self
}
public func load(url: URL) -> Self {
requestUrl = url
GLog.i("Loading \(url) ...")
refresher.show()
load(URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 30))
return self
}
public func load(url: String) -> Self {
return load(url: URL(string: url)!)
}
public func refresh() {
// It seems that reload() doesn't do anything when the initial load() failed.
if let url = self.requestUrl {
_ = load(url: url)
}
}
public func end() {
// Ends chaining
}
}
extension GWebView: WKNavigationDelegate {
public func webView(_: WKWebView, didFinish _: WKNavigation!) {
refresher.hide()
}
public func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
handle(error: error)
}
// E.g. SSL error
public func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
handle(error: error)
}
private func handle(error: Error) {
refresher.hide()
let alert = UIAlertController(title: nil,
message: error.localizedDescription,
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "Retry", style: .default) { [unowned self] (_) -> Void in
self.refresh()
})
GApp.instance.navigationController.present(alert, animated: true, completion: nil)
}
}
|
mit
|
3591cbca6f7ca141ff57a1301aa0d1a5
| 24.603306 | 110 | 0.584571 | 4.810559 | false | false | false | false |
gtranchedone/FlickrParty
|
FlickrParty/DataSources/PhotosDataSource.swift
|
1
|
3366
|
//
// PhotosDataSource.swift
// FlickrParty
//
// Created by Gianluca Tranchedone on 04/05/2015.
// Copyright (c) 2015 Gianluca Tranchedone. All rights reserved.
//
import UIKit
import Haneke
public class PhotosDataSource: ViewDataSource {
public var photosCache = Cache<Photo>(name: "PhotoObjectsCache")
private var photos: [Photo] = []
private let placeholderPhoto = Photo(identifier: "placeholder", title: "", details: "", ownerName: "", imageURL: nil, thumbnailURL: nil)
override public func invalidateContent() {
photos = []
delegate?.viewDataSourceDidInvalidateContent(self)
}
override public func fetchContent(page: Int = 1) {
loading = true
performFetch(page) { [weak self] response, possibleError in
if let strongSelf = self {
strongSelf.parseAPIResponse(response, error: possibleError)
strongSelf.loading = false
}
}
}
internal func performFetch(page: Int, completionBlock: (APIResponse?, NSError?) -> ()) -> Void {
// TODO: subclassing hook
completionBlock(nil, nil)
}
internal func parseAPIResponse(response: APIResponse?, error: NSError?) {
if let error = error {
delegate?.viewDataSourceDidFailFetchingContent(self, error: error)
}
else {
lastMetadata = response?.metadata
let photos = response?.responseObject as? [Photo] ?? []
let page = lastMetadata?.page ?? 0
if page > 1 {
self.photos = self.photos + photos
}
else {
self.photos = photos
}
delegate?.viewDataSourceDidFetchContent(self)
}
}
public override func numberOfItems() -> Int {
return photos.count
}
public override func numberOfSections() -> Int {
return 1
}
public override func numberOfItemsInSection(section: Int) -> Int {
return self.numberOfItems()
}
override public func itemAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
guard indexPath.item < photos.count else { return nil }
return photos[indexPath.item]
}
override public func itemAtIndexPath(indexPath: NSIndexPath, completion: ((AnyObject?) -> ())) {
guard indexPath.item < photos.count else {
completion(nil)
return
}
let photo = photos[indexPath.item]
if photo === placeholderPhoto {
photosCache.fetch(key: indexPath.description, formatName: HanekeGlobals.Cache.OriginalFormatName, failure: { error in
print("\(error)")
completion(photo)
}, success: { fetchedPhoto in
self.photos[indexPath.item] = fetchedPhoto
completion(fetchedPhoto)
})
}
else {
completion(photo)
}
}
public override func cacheItemAtIndexPath(indexPath: NSIndexPath) {
let photo = photos[indexPath.item]
guard photo !== placeholderPhoto else { return }
photosCache.set(value: photo, key: indexPath.description, formatName: HanekeGlobals.Cache.OriginalFormatName) { _ in
self.photos[indexPath.item] = self.placeholderPhoto
}
}
}
|
mit
|
1f99b12347b8da1d98f91732bd0ca902
| 32 | 140 | 0.598039 | 5.023881 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.