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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
barteljan/RocketChatAdapter | Example/Pods/SwiftWebSocket/Source/WebSocket.swift | 1 | 67541 | /*
* SwiftWebSocket (websocket.swift)
*
* Copyright (C) Josh Baker. All Rights Reserved.
* Contact: @tidwall, [email protected]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
import Foundation
private let windowBufferSize = 0x2000
private class Payload {
var ptr : UnsafeMutablePointer<UInt8>
var cap : Int
var len : Int
init(){
len = 0
cap = windowBufferSize
ptr = UnsafeMutablePointer<UInt8>(malloc(cap))
}
deinit{
free(ptr)
}
var count : Int {
get {
return len
}
set {
if newValue > cap {
while cap < newValue {
cap *= 2
}
ptr = UnsafeMutablePointer<UInt8>(realloc(ptr, cap))
}
len = newValue
}
}
func append(bytes: UnsafePointer<UInt8>, length: Int){
let prevLen = len
count = len+length
memcpy(ptr+prevLen, bytes, length)
}
var array : [UInt8] {
get {
var array = [UInt8](count: count, repeatedValue: 0)
memcpy(&array, ptr, count)
return array
}
set {
count = 0
append(newValue, length: newValue.count)
}
}
var nsdata : NSData {
get {
return NSData(bytes: ptr, length: count)
}
set {
count = 0
append(UnsafePointer<UInt8>(newValue.bytes), length: newValue.length)
}
}
var buffer : UnsafeBufferPointer<UInt8> {
get {
return UnsafeBufferPointer<UInt8>(start: ptr, count: count)
}
set {
count = 0
append(newValue.baseAddress, length: newValue.count)
}
}
}
private enum OpCode : UInt8, CustomStringConvertible {
case Continue = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA
var isControl : Bool {
switch self {
case .Close, .Ping, .Pong:
return true
default:
return false
}
}
var description : String {
switch self {
case Continue: return "Continue"
case Text: return "Text"
case Binary: return "Binary"
case Close: return "Close"
case Ping: return "Ping"
case Pong: return "Pong"
}
}
}
/// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection.
public struct WebSocketEvents {
/// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
public var open : ()->() = {}
/// An event to be called when the WebSocket connection's readyState changes to .Closed.
public var close : (code : Int, reason : String, wasClean : Bool)->() = {(code, reason, wasClean) in}
/// An event to be called when an error occurs.
public var error : (error : ErrorType)->() = {(error) in}
/// An event to be called when a message is received from the server.
public var message : (data : Any)->() = {(data) in}
/// An event to be called when a pong is received from the server.
public var pong : (data : Any)->() = {(data) in}
/// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
public var end : (code : Int, reason : String, wasClean : Bool, error : ErrorType?)->() = {(code, reason, wasClean, error) in}
}
/// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection.
public enum WebSocketBinaryType : CustomStringConvertible {
/// The WebSocket should transmit [UInt8] objects.
case UInt8Array
/// The WebSocket should transmit NSData objects.
case NSData
/// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk.
case UInt8UnsafeBufferPointer
public var description : String {
switch self {
case UInt8Array: return "UInt8Array"
case NSData: return "NSData"
case UInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer"
}
}
}
/// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection.
@objc public enum WebSocketReadyState : Int, CustomStringConvertible {
/// The connection is not yet open.
case Connecting = 0
/// The connection is open and ready to communicate.
case Open = 1
/// The connection is in the process of closing.
case Closing = 2
/// The connection is closed or couldn't be opened.
case Closed = 3
private var isClosed : Bool {
switch self {
case .Closing, .Closed:
return true
default:
return false
}
}
/// Returns a string that represents the ReadyState value.
public var description : String {
switch self {
case Connecting: return "Connecting"
case Open: return "Open"
case Closing: return "Closing"
case Closed: return "Closed"
}
}
}
private let defaultMaxWindowBits = 15
/// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection.
public struct WebSocketCompression {
/// Used to accept compressed messages from the server. Default is true.
public var on = false
/// request no context takeover.
public var noContextTakeover = false
/// request max window bits.
public var maxWindowBits = defaultMaxWindowBits
}
/// The WebSocketService options are used by the services property and manages the underlying socket services.
public struct WebSocketService : OptionSetType {
public typealias RawValue = UInt
var value: UInt = 0
init(_ value: UInt) { self.value = value }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: WebSocketService { return self.init(0) }
static func fromMask(raw: UInt) -> WebSocketService { return self.init(raw) }
public var rawValue: UInt { return self.value }
/// No services.
public static var None: WebSocketService { return self.init(0) }
/// Allow socket to handle VoIP.
public static var VoIP: WebSocketService { return self.init(1 << 0) }
/// Allow socket to handle video.
public static var Video: WebSocketService { return self.init(1 << 1) }
/// Allow socket to run in background.
public static var Background: WebSocketService { return self.init(1 << 2) }
/// Allow socket to handle voice.
public static var Voice: WebSocketService { return self.init(1 << 3) }
}
private let atEndDetails = "streamStatus.atEnd"
private let timeoutDetails = "The operation couldn’t be completed. Operation timed out"
private let timeoutDuration : CFTimeInterval = 30
public enum WebSocketError : ErrorType, CustomStringConvertible {
case Memory
case NeedMoreInput
case InvalidHeader
case InvalidAddress
case Network(String)
case LibraryError(String)
case PayloadError(String)
case ProtocolError(String)
case InvalidResponse(String)
case InvalidCompressionOptions(String)
public var description : String {
switch self {
case .Memory: return "Memory"
case .NeedMoreInput: return "NeedMoreInput"
case .InvalidAddress: return "InvalidAddress"
case .InvalidHeader: return "InvalidHeader"
case let .InvalidResponse(details): return "InvalidResponse(\(details))"
case let .InvalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))"
case let .LibraryError(details): return "LibraryError(\(details))"
case let .ProtocolError(details): return "ProtocolError(\(details))"
case let .PayloadError(details): return "PayloadError(\(details))"
case let .Network(details): return "Network(\(details))"
}
}
public var details : String {
switch self {
case .InvalidResponse(let details): return details
case .InvalidCompressionOptions(let details): return details
case .LibraryError(let details): return details
case .ProtocolError(let details): return details
case .PayloadError(let details): return details
case .Network(let details): return details
default: return ""
}
}
}
private class UTF8 {
var text : String = ""
var count : UInt32 = 0 // number of bytes
var procd : UInt32 = 0 // number of bytes processed
var codepoint : UInt32 = 0 // the actual codepoint
var bcount = 0
init() { text = "" }
func append(byte : UInt8) throws {
if count == 0 {
if byte <= 0x7F {
text.append(UnicodeScalar(byte))
return
}
if byte == 0xC0 || byte == 0xC1 {
throw WebSocketError.PayloadError("invalid codepoint: invalid byte")
}
if byte >> 5 & 0x7 == 0x6 {
count = 2
} else if byte >> 4 & 0xF == 0xE {
count = 3
} else if byte >> 3 & 0x1F == 0x1E {
count = 4
} else {
throw WebSocketError.PayloadError("invalid codepoint: frames")
}
procd = 1
codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6)
return
}
if byte >> 6 & 0x3 != 0x2 {
throw WebSocketError.PayloadError("invalid codepoint: signature")
}
codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6)
if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) {
throw WebSocketError.PayloadError("invalid codepoint: out of bounds")
}
procd++
if procd == count {
if codepoint <= 0x7FF && count > 2 {
throw WebSocketError.PayloadError("invalid codepoint: overlong")
}
if codepoint <= 0xFFFF && count > 3 {
throw WebSocketError.PayloadError("invalid codepoint: overlong")
}
procd = 0
count = 0
text.append(UnicodeScalar(codepoint))
}
return
}
func append(bytes : UnsafePointer<UInt8>, length : Int) throws {
if length == 0 {
return
}
if count == 0 {
var ascii = true
for var i = 0; i < length; i++ {
if bytes[i] > 0x7F {
ascii = false
break
}
}
if ascii {
text += NSString(bytes: bytes, length: length, encoding: NSASCIIStringEncoding) as! String
bcount += length
return
}
}
for var i = 0; i < length; i++ {
try append(bytes[i])
}
bcount += length
}
var completed : Bool {
return count == 0
}
static func bytes(string : String) -> [UInt8]{
let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
return [UInt8](UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
}
static func string(bytes : [UInt8]) -> String{
if let str = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding) {
return str as String
}
return ""
}
}
private class Frame {
var inflate = false
var code = OpCode.Continue
var utf8 = UTF8()
var payload = Payload()
var statusCode = UInt16(0)
var finished = true
static func makeClose(statusCode: UInt16, reason: String) -> Frame {
let f = Frame()
f.code = .Close
f.statusCode = statusCode
f.utf8.text = reason
return f
}
func copy() -> Frame {
let f = Frame()
f.code = code
f.utf8.text = utf8.text
f.payload.buffer = payload.buffer
f.statusCode = statusCode
f.finished = finished
f.inflate = inflate
return f
}
}
private class Delegate : NSObject, NSStreamDelegate {
@objc func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){
manager.signal()
}
}
@asmname("zlibVersion") private func zlibVersion() -> COpaquePointer
@asmname("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt
@asmname("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@asmname("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt
@asmname("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt
@asmname("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt
private func zerror(res : CInt) -> ErrorType? {
var err = ""
switch res {
case 0: return nil
case 1: err = "stream end"
case 2: err = "need dict"
case -1: err = "errno"
case -2: err = "stream error"
case -3: err = "data error"
case -4: err = "mem error"
case -5: err = "buf error"
case -6: err = "version error"
default: err = "undefined error"
}
return WebSocketError.PayloadError("zlib: \(err): \(res)")
}
private struct z_stream {
var next_in : UnsafePointer<UInt8> = nil
var avail_in : CUnsignedInt = 0
var total_in : CUnsignedLong = 0
var next_out : UnsafeMutablePointer<UInt8> = nil
var avail_out : CUnsignedInt = 0
var total_out : CUnsignedLong = 0
var msg : UnsafePointer<CChar> = nil
var state : COpaquePointer = nil
var zalloc : COpaquePointer = nil
var zfree : COpaquePointer = nil
var opaque : COpaquePointer = nil
var data_type : CInt = 0
var adler : CUnsignedLong = 0
var reserved : CUnsignedLong = 0
}
private class Inflater {
var windowBits = 0
var strm = z_stream()
var tInput = [[UInt8]]()
var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF]
var bufferSize = windowBufferSize
var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize))
init?(windowBits : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(sizeof(z_stream)))
if ret != 0 {
return nil
}
}
deinit{
inflateEndG(&strm)
free(buffer)
}
func inflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){
var buf = buffer
var bufsiz = bufferSize
var buflen = 0
for var i = 0; i < 2; i++ {
if i == 0 {
strm.avail_in = CUnsignedInt(length)
strm.next_in = UnsafePointer<UInt8>(bufin)
} else {
if !final {
break
}
strm.avail_in = CUnsignedInt(inflateEnd.count)
strm.next_in = UnsafePointer<UInt8>(inflateEnd)
}
for ;; {
strm.avail_out = CUnsignedInt(bufsiz)
strm.next_out = buf
inflateG(&strm, flush: 0)
let have = bufsiz - Int(strm.avail_out)
bufsiz -= have
buflen += have
if strm.avail_out != 0{
break
}
if bufsiz == 0 {
bufferSize *= 2
let nbuf = UnsafeMutablePointer<UInt8>(realloc(buffer, bufferSize))
if nbuf == nil {
throw WebSocketError.PayloadError("memory")
}
buffer = nbuf
buf = buffer+Int(buflen)
bufsiz = bufferSize - buflen
}
}
}
return (buffer, buflen)
}
}
private class Deflater {
var windowBits = 0
var memLevel = 0
var strm = z_stream()
var bufferSize = windowBufferSize
var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize))
init?(windowBits : Int, memLevel : Int){
if buffer == nil {
return nil
}
self.windowBits = windowBits
self.memLevel = memLevel
let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(sizeof(z_stream)))
if ret != 0 {
return nil
}
}
deinit{
deflateEnd(&strm)
free(buffer)
}
func deflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){
return (nil, 0, nil)
}
}
/// WebSocketDelegate is an Objective-C alternative to WebSocketEvents and is used to delegate the events for the WebSocket connection.
@objc public protocol WebSocketDelegate {
/// A function to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data.
func webSocketOpen()
/// A function to be called when the WebSocket connection's readyState changes to .Closed.
func webSocketClose(code: Int, reason: String, wasClean: Bool)
/// A function to be called when an error occurs.
func webSocketError(error: NSError)
/// A function to be called when a message (string) is received from the server.
optional func webSocketMessageText(text: String)
/// A function to be called when a message (binary) is received from the server.
optional func webSocketMessageData(data: NSData)
/// A function to be called when a pong is received from the server.
optional func webSocketPong()
/// A function to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events.
optional func webSocketEnd(code: Int, reason: String, wasClean: Bool, error: NSError?)
}
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
private class InnerWebSocket: Hashable {
var id : Int
var mutex = pthread_mutex_t()
let request : NSURLRequest!
let subProtocols : [String]!
var frames : [Frame] = []
var delegate : Delegate
var inflater : Inflater!
var deflater : Deflater!
var outputBytes : UnsafeMutablePointer<UInt8>
var outputBytesSize : Int = 0
var outputBytesStart : Int = 0
var outputBytesLength : Int = 0
var inputBytes : UnsafeMutablePointer<UInt8>
var inputBytesSize : Int = 0
var inputBytesStart : Int = 0
var inputBytesLength : Int = 0
var createdAt = CFAbsoluteTimeGetCurrent()
var connectionTimeout = false
var eclose : ()->() = {}
var _eventQueue : dispatch_queue_t? = dispatch_get_main_queue()
var _subProtocol = ""
var _compression = WebSocketCompression()
var _allowSelfSignedSSL = false
var _services = WebSocketService.None
var _event = WebSocketEvents()
var _eventDelegate: WebSocketDelegate?
var _binaryType = WebSocketBinaryType.UInt8Array
var _readyState = WebSocketReadyState.Connecting
var _networkTimeout = NSTimeInterval(-1)
var url : String {
return request.URL!.description
}
var subProtocol : String {
get { return privateSubProtocol }
}
var privateSubProtocol : String {
get { lock(); defer { unlock() }; return _subProtocol }
set { lock(); defer { unlock() }; _subProtocol = newValue }
}
var compression : WebSocketCompression {
get { lock(); defer { unlock() }; return _compression }
set { lock(); defer { unlock() }; _compression = newValue }
}
var allowSelfSignedSSL : Bool {
get { lock(); defer { unlock() }; return _allowSelfSignedSSL }
set { lock(); defer { unlock() }; _allowSelfSignedSSL = newValue }
}
var services : WebSocketService {
get { lock(); defer { unlock() }; return _services }
set { lock(); defer { unlock() }; _services = newValue }
}
var event : WebSocketEvents {
get { lock(); defer { unlock() }; return _event }
set { lock(); defer { unlock() }; _event = newValue }
}
var eventDelegate : WebSocketDelegate? {
get { lock(); defer { unlock() }; return _eventDelegate }
set { lock(); defer { unlock() }; _eventDelegate = newValue }
}
var eventQueue : dispatch_queue_t? {
get { lock(); defer { unlock() }; return _eventQueue; }
set { lock(); defer { unlock() }; _eventQueue = newValue }
}
var binaryType : WebSocketBinaryType {
get { lock(); defer { unlock() }; return _binaryType }
set { lock(); defer { unlock() }; _binaryType = newValue }
}
var readyState : WebSocketReadyState {
get { return privateReadyState }
}
var privateReadyState : WebSocketReadyState {
get { lock(); defer { unlock() }; return _readyState }
set { lock(); defer { unlock() }; _readyState = newValue }
}
func copyOpen(request: NSURLRequest, subProtocols : [String] = []) -> InnerWebSocket{
let ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
ws.eclose = eclose
ws.compression = compression
ws.allowSelfSignedSSL = allowSelfSignedSSL
ws.services = services
ws.event = event
ws.eventQueue = eventQueue
ws.binaryType = binaryType
return ws
}
var hashValue: Int { return id }
init(request: NSURLRequest, subProtocols : [String] = [], stub : Bool = false){
pthread_mutex_init(&mutex, nil)
self.id = manager.nextId()
self.request = request
self.subProtocols = subProtocols
self.outputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize)
self.outputBytesSize = windowBufferSize
self.inputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize)
self.inputBytesSize = windowBufferSize
self.delegate = Delegate()
if stub{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
self
}
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
manager.add(self)
}
}
}
deinit{
if outputBytes != nil {
free(outputBytes)
}
if inputBytes != nil {
free(inputBytes)
}
pthread_mutex_init(&mutex, nil)
}
@inline(__always) private func lock(){
pthread_mutex_lock(&mutex)
}
@inline(__always) private func unlock(){
pthread_mutex_unlock(&mutex)
}
private var dirty : Bool {
lock()
defer { unlock() }
if exit {
return false
}
if connectionTimeout {
return true
}
if stage != .ReadResponse && stage != .HandleFrames {
return true
}
if rd.streamStatus == .Opening && wr.streamStatus == .Opening {
return false;
}
if rd.streamStatus != .Open || wr.streamStatus != .Open {
return true
}
if rd.streamError != nil || wr.streamError != nil {
return true
}
if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 {
return true
}
if outputBytesLength > 0 && wr.hasSpaceAvailable{
return true
}
return false
}
enum Stage : Int {
case OpenConn
case ReadResponse
case HandleFrames
case CloseConn
case End
}
var stage = Stage.OpenConn
var rd : NSInputStream!
var wr : NSOutputStream!
var atEnd = false
var closeCode = UInt16(0)
var closeReason = ""
var closeClean = false
var closeFinal = false
var finalError : ErrorType?
var exit = false
func step(){
if exit {
return
}
do {
try stepBuffers()
try stepStreamErrors()
switch stage {
case .OpenConn:
try openConn()
stage = .ReadResponse
case .ReadResponse:
try readResponse()
privateReadyState = .Open
fire {
self.event.open()
self.eventDelegate?.webSocketOpen()
}
stage = .HandleFrames
case .HandleFrames:
try stepOutputFrames()
if closeFinal {
privateReadyState = .Closing
stage = .CloseConn
return
}
let frame = try readFrame()
switch frame.code {
case .Text:
fire {
self.event.message(data: frame.utf8.text)
self.eventDelegate?.webSocketMessageText?(frame.utf8.text)
}
case .Binary:
fire {
switch self.binaryType {
case .UInt8Array:
self.event.message(data: frame.payload.array)
case .NSData:
self.event.message(data: frame.payload.nsdata)
// The WebSocketDelegate is necessary to add Objective-C compability and it is only possible to send binary data with NSData.
self.eventDelegate?.webSocketMessageData?(frame.payload.nsdata)
case .UInt8UnsafeBufferPointer:
self.event.message(data: frame.payload.buffer)
}
}
case .Ping:
let nframe = frame.copy()
nframe.code = .Pong
lock()
frames += [nframe]
unlock()
case .Pong:
fire {
switch self.binaryType {
case .UInt8Array:
self.event.pong(data: frame.payload.array)
case .NSData:
self.event.pong(data: frame.payload.nsdata)
case .UInt8UnsafeBufferPointer:
self.event.pong(data: frame.payload.buffer)
}
self.eventDelegate?.webSocketPong?()
}
case .Close:
lock()
frames += [frame]
unlock()
default:
break
}
case .CloseConn:
if let error = finalError {
self.event.error(error: error)
self.eventDelegate?.webSocketError(error as NSError)
}
privateReadyState = .Closed
if rd != nil {
closeConn()
fire {
self.eclose()
self.event.close(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
self.eventDelegate?.webSocketClose(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal)
}
}
stage = .End
case .End:
fire {
self.event.end(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError)
self.eventDelegate?.webSocketEnd?(Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError as? NSError)
}
exit = true
manager.remove(self)
}
} catch WebSocketError.NeedMoreInput {
} catch {
if finalError != nil {
return
}
finalError = error
if stage == .OpenConn || stage == .ReadResponse {
stage = .CloseConn
} else {
var frame : Frame?
if let error = error as? WebSocketError{
switch error {
case .Network(let details):
if details == atEndDetails{
stage = .CloseConn
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
atEnd = true
finalError = nil
}
case .ProtocolError:
frame = Frame.makeClose(1002, reason: "Protocol error")
case .PayloadError:
frame = Frame.makeClose(1007, reason: "Payload error")
default:
break
}
}
if frame == nil {
frame = Frame.makeClose(1006, reason: "Abnormal Closure")
}
if let frame = frame {
if frame.statusCode == 1007 {
self.lock()
self.frames = [frame]
self.unlock()
manager.signal()
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), manager.queue){
self.lock()
self.frames += [frame]
self.unlock()
manager.signal()
}
}
}
}
}
}
func stepBuffers() throws {
if rd != nil {
if stage != .CloseConn && rd.streamStatus == NSStreamStatus.AtEnd {
if atEnd {
return;
}
throw WebSocketError.Network(atEndDetails)
}
while rd.hasBytesAvailable {
var size = inputBytesSize
while size-(inputBytesStart+inputBytesLength) < windowBufferSize {
size *= 2
}
if size > inputBytesSize {
let ptr = UnsafeMutablePointer<UInt8>(realloc(inputBytes, size))
if ptr == nil {
throw WebSocketError.Memory
}
inputBytes = ptr
inputBytesSize = size
}
let n = rd.read(inputBytes+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength)
if n > 0 {
inputBytesLength += n
}
}
}
if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 {
let n = wr.write(outputBytes+outputBytesStart, maxLength: outputBytesLength)
if n > 0 {
outputBytesLength -= n
if outputBytesLength == 0 {
outputBytesStart = 0
} else {
outputBytesStart += n
}
}
}
}
func stepStreamErrors() throws {
if finalError == nil {
if connectionTimeout {
throw WebSocketError.Network(timeoutDetails)
}
if let error = rd?.streamError {
throw WebSocketError.Network(error.localizedDescription)
}
if let error = wr?.streamError {
throw WebSocketError.Network(error.localizedDescription)
}
}
}
func stepOutputFrames() throws {
lock()
defer {
frames = []
unlock()
}
if !closeFinal {
for frame in frames {
try writeFrame(frame)
if frame.code == .Close {
closeCode = frame.statusCode
closeReason = frame.utf8.text
closeFinal = true
return
}
}
}
}
@inline(__always) func fire(block: ()->()){
if let queue = eventQueue {
dispatch_sync(queue) {
block()
}
} else {
block()
}
}
var readStateSaved = false
var readStateFrame : Frame?
var readStateFinished = false
var leaderFrame : Frame?
func readFrame() throws -> Frame {
var frame : Frame
var finished : Bool
if !readStateSaved {
if leaderFrame != nil {
frame = leaderFrame!
finished = false
leaderFrame = nil
} else {
frame = try readFrameFragment(nil)
finished = frame.finished
}
if frame.code == .Continue{
throw WebSocketError.ProtocolError("leader frame cannot be a continue frame")
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.NeedMoreInput
}
} else {
frame = readStateFrame!
finished = readStateFinished
if !finished {
let cf = try readFrameFragment(frame)
finished = cf.finished
if cf.code != .Continue {
if !cf.code.isControl {
throw WebSocketError.ProtocolError("only ping frames can be interlaced with fragments")
}
leaderFrame = frame
return cf
}
if !finished {
readStateSaved = true
readStateFrame = frame
readStateFinished = finished
throw WebSocketError.NeedMoreInput
}
}
}
if !frame.utf8.completed {
throw WebSocketError.PayloadError("incomplete utf8")
}
readStateSaved = false
readStateFrame = nil
readStateFinished = false
return frame
}
func closeConn() {
rd.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
wr.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
rd.delegate = nil
wr.delegate = nil
rd.close()
wr.close()
}
func openConn() throws {
let req = request.mutableCopy() as! NSMutableURLRequest
req.setValue("websocket", forHTTPHeaderField: "Upgrade")
req.setValue("Upgrade", forHTTPHeaderField: "Connection")
if req.valueForHTTPHeaderField("User-Agent") == nil {
req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent")
}
req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version")
if req.URL == nil || req.URL!.host == nil{
throw WebSocketError.InvalidAddress
}
if req.URL!.port == nil || req.URL!.port!.integerValue == 80 || req.URL!.port!.integerValue == 443 {
req.setValue(req.URL!.host!, forHTTPHeaderField: "Host")
} else {
req.setValue("\(req.URL!.host!):\(req.URL!.port!.integerValue)", forHTTPHeaderField: "Host")
}
req.setValue(req.URL!.absoluteString, forHTTPHeaderField: "Origin")
if subProtocols.count > 0 {
req.setValue(subProtocols.joinWithSeparator(";"), forHTTPHeaderField: "Sec-WebSocket-Protocol")
}
if req.URL!.scheme != "wss" && req.URL!.scheme != "ws" {
throw WebSocketError.InvalidAddress
}
if compression.on {
var val = "permessage-deflate"
if compression.noContextTakeover {
val += "; client_no_context_takeover; server_no_context_takeover"
}
val += "; client_max_window_bits"
if compression.maxWindowBits != 0 {
val += "; server_max_window_bits=\(compression.maxWindowBits)"
}
req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions")
}
let security: TCPConnSecurity
let port : Int
if req.URL!.scheme == "wss" {
port = req.URL!.port?.integerValue ?? 443
security = .NegoticatedSSL
} else {
port = req.URL!.port?.integerValue ?? 80
security = .None
}
var path = CFURLCopyPath(req.URL!) as String
if path == "" {
path = "/"
}
if let q = req.URL!.query {
if q != "" {
path += "?" + q
}
}
var reqs = "GET \(path) HTTP/1.1\r\n"
for key in req.allHTTPHeaderFields!.keys {
if let val = req.valueForHTTPHeaderField(key) {
reqs += "\(key): \(val)\r\n"
}
}
var keyb = [UInt32](count: 4, repeatedValue: 0)
for var i = 0; i < 4; i++ {
keyb[i] = arc4random()
}
let rkey = NSData(bytes: keyb, length: 16).base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
reqs += "Sec-WebSocket-Key: \(rkey)\r\n"
reqs += "\r\n"
var header = [UInt8]()
for b in reqs.utf8 {
header += [b]
}
let addr = ["\(req.URL!.host!)", "\(port)"]
if addr.count != 2 || Int(addr[1]) == nil {
throw WebSocketError.InvalidAddress
}
var (rdo, wro) : (NSInputStream?, NSOutputStream?)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, addr[0], UInt32(Int(addr[1])!), &readStream, &writeStream);
rdo = readStream!.takeRetainedValue()
wro = writeStream!.takeRetainedValue()
(rd, wr) = (rdo!, wro!)
rd.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey)
wr.setProperty(security.level, forKey: NSStreamSocketSecurityLevelKey)
if services.contains(.VoIP) {
rd.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Video) {
rd.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Background) {
rd.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType)
}
if services.contains(.Voice) {
rd.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType)
wr.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType)
}
if allowSelfSignedSSL {
let prop: Dictionary<NSObject,NSObject> = [kCFStreamSSLPeerName: kCFNull, kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false)]
rd.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String)
wr.setProperty(prop, forKey: kCFStreamPropertySSLSettings as String)
}
rd.delegate = delegate
wr.delegate = delegate
rd.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
wr.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
rd.open()
wr.open()
try write(header, length: header.count)
}
func write(bytes: UnsafePointer<UInt8>, length: Int) throws {
if outputBytesStart+outputBytesLength+length > outputBytesSize {
var size = outputBytesSize
while outputBytesStart+outputBytesLength+length > size {
size *= 2
}
let ptr = UnsafeMutablePointer<UInt8>(realloc(outputBytes, size))
if ptr == nil {
throw WebSocketError.Memory
}
outputBytes = ptr
outputBytesSize = size
}
memcpy(outputBytes+outputBytesStart+outputBytesLength, bytes, length)
outputBytesLength += length
}
func readResponse() throws {
let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ]
let ptr = UnsafeMutablePointer<UInt8>(memmem(inputBytes+inputBytesStart, inputBytesLength, end, 4))
if ptr == nil {
throw WebSocketError.NeedMoreInput
}
let buffer = inputBytes+inputBytesStart
let bufferCount = ptr-(inputBytes+inputBytesStart)
let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: NSUTF8StringEncoding, freeWhenDone: false) as? String
if string == nil {
throw WebSocketError.InvalidHeader
}
let header = string!
var needsCompression = false
var serverMaxWindowBits = 15
let clientMaxWindowBits = 15
var key = ""
let trim : (String)->(String) = { (text) in return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())}
let eqval : (String,String)->(String) = { (line, del) in return trim(line.componentsSeparatedByString(del)[1]) }
let lines = header.componentsSeparatedByString("\r\n")
for var i = 0; i < lines.count; i++ {
let line = trim(lines[i])
if i == 0 {
if !line.hasPrefix("HTTP/1.1 101"){
throw WebSocketError.InvalidResponse(line)
}
} else if line != "" {
var value = ""
if line.hasPrefix("\t") || line.hasPrefix(" ") {
value = trim(line)
} else {
key = ""
if let r = line.rangeOfString(":") {
key = trim(line.substringToIndex(r.startIndex))
value = trim(line.substringFromIndex(r.endIndex))
}
}
switch key.lowercaseString {
case "sec-websocket-subprotocol":
privateSubProtocol = value
case "sec-websocket-extensions":
let parts = value.componentsSeparatedByString(";")
for p in parts {
let part = trim(p)
if part == "permessage-deflate" {
needsCompression = true
} else if part.hasPrefix("server_max_window_bits="){
if let i = Int(eqval(line, "=")) {
serverMaxWindowBits = i
}
}
}
default:
break
}
}
}
if needsCompression {
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.InvalidCompressionOptions("server_max_window_bits")
}
if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 {
throw WebSocketError.InvalidCompressionOptions("client_max_window_bits")
}
inflater = Inflater(windowBits: serverMaxWindowBits)
if inflater == nil {
throw WebSocketError.InvalidCompressionOptions("inflater init")
}
deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8)
if deflater == nil {
throw WebSocketError.InvalidCompressionOptions("deflater init")
}
}
inputBytesLength -= bufferCount+4
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += bufferCount+4
}
}
class ByteReader {
var start : UnsafePointer<UInt8>
var end : UnsafePointer<UInt8>
var bytes : UnsafePointer<UInt8>
init(bytes: UnsafePointer<UInt8>, length: Int){
self.bytes = bytes
start = bytes
end = bytes+length
}
func readByte() throws -> UInt8 {
if bytes >= end {
throw WebSocketError.NeedMoreInput
}
let b = bytes.memory
bytes++
return b
}
var length : Int {
return end - bytes
}
var position : Int {
get {
return bytes - start
}
set {
bytes = start + newValue
}
}
}
var fragStateSaved = false
var fragStatePosition = 0
var fragStateInflate = false
var fragStateLen = 0
var fragStateFin = false
var fragStateCode = OpCode.Continue
var fragStateLeaderCode = OpCode.Continue
var fragStateUTF8 = UTF8()
var fragStatePayload = Payload()
var fragStateStatusCode = UInt16(0)
var fragStateHeaderLen = 0
var buffer = [UInt8](count: windowBufferSize, repeatedValue: 0)
var reusedPayload = Payload()
func readFrameFragment(var leader : Frame?) throws -> Frame {
var inflate : Bool
var len : Int
var fin = false
var code : OpCode
var leaderCode : OpCode
var utf8 : UTF8
var payload : Payload
var statusCode : UInt16
var headerLen : Int
let reader = ByteReader(bytes: inputBytes+inputBytesStart, length: inputBytesLength)
if fragStateSaved {
// load state
reader.position += fragStatePosition
inflate = fragStateInflate
len = fragStateLen
fin = fragStateFin
code = fragStateCode
leaderCode = fragStateLeaderCode
utf8 = fragStateUTF8
payload = fragStatePayload
statusCode = fragStateStatusCode
headerLen = fragStateHeaderLen
fragStateSaved = false
} else {
var b = try reader.readByte()
fin = b >> 7 & 0x1 == 0x1
let rsv1 = b >> 6 & 0x1 == 0x1
let rsv2 = b >> 5 & 0x1 == 0x1
let rsv3 = b >> 4 & 0x1 == 0x1
if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) {
inflate = true
} else if rsv1 || rsv2 || rsv3 {
throw WebSocketError.ProtocolError("invalid extension")
} else {
inflate = false
}
code = OpCode.Binary
if let c = OpCode(rawValue: (b & 0xF)){
code = c
} else {
throw WebSocketError.ProtocolError("invalid opcode")
}
if !fin && code.isControl {
throw WebSocketError.ProtocolError("unfinished control frame")
}
b = try reader.readByte()
if b >> 7 & 0x1 == 0x1 {
throw WebSocketError.ProtocolError("server sent masked frame")
}
var len64 = Int64(b & 0x7F)
var bcount = 0
if b & 0x7F == 126 {
bcount = 2
} else if len64 == 127 {
bcount = 8
}
if bcount != 0 {
if code.isControl {
throw WebSocketError.ProtocolError("invalid payload size for control frame")
}
len64 = 0
for var i = bcount-1; i >= 0; i-- {
b = try reader.readByte()
len64 += Int64(b) << Int64(i*8)
}
}
len = Int(len64)
if code == .Continue {
if code.isControl {
throw WebSocketError.ProtocolError("control frame cannot have the 'continue' opcode")
}
if leader == nil {
throw WebSocketError.ProtocolError("continue frame is missing it's leader")
}
}
if code.isControl {
if leader != nil {
leader = nil
}
if inflate {
throw WebSocketError.ProtocolError("control frame cannot be compressed")
}
}
statusCode = 0
if leader != nil {
leaderCode = leader!.code
utf8 = leader!.utf8
payload = leader!.payload
} else {
leaderCode = code
utf8 = UTF8()
payload = reusedPayload
payload.count = 0
}
if leaderCode == .Close {
if len == 1 {
throw WebSocketError.ProtocolError("invalid payload size for close frame")
}
if len >= 2 {
let b1 = try reader.readByte()
let b2 = try reader.readByte()
statusCode = (UInt16(b1) << 8) + UInt16(b2)
len -= 2
if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) {
throw WebSocketError.ProtocolError("invalid status code for close frame")
}
}
}
headerLen = reader.position
}
let rlen : Int
let rfin : Bool
let chopped : Bool
if reader.length+reader.position-headerLen < len {
rlen = reader.length
rfin = false
chopped = true
} else {
rlen = len-reader.position+headerLen
rfin = fin
chopped = false
}
let bytes : UnsafeMutablePointer<UInt8>
let bytesLen : Int
if inflate {
(bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin)
} else {
(bytes, bytesLen) = (UnsafeMutablePointer<UInt8>(reader.bytes), rlen)
}
reader.bytes += rlen
if leaderCode == .Text || leaderCode == .Close {
try utf8.append(bytes, length: bytesLen)
} else {
payload.append(bytes, length: bytesLen)
}
if chopped {
// save state
fragStateHeaderLen = headerLen
fragStateStatusCode = statusCode
fragStatePayload = payload
fragStateUTF8 = utf8
fragStateLeaderCode = leaderCode
fragStateCode = code
fragStateFin = fin
fragStateLen = len
fragStateInflate = inflate
fragStatePosition = reader.position
fragStateSaved = true
throw WebSocketError.NeedMoreInput
}
inputBytesLength -= reader.position
if inputBytesLength == 0 {
inputBytesStart = 0
} else {
inputBytesStart += reader.position
}
let f = Frame()
(f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin)
return f
}
var head = [UInt8](count: 0xFF, repeatedValue: 0)
func writeFrame(f : Frame) throws {
if !f.finished{
throw WebSocketError.LibraryError("cannot send unfinished frames")
}
var hlen = 0
let b : UInt8 = 0x80
var deflate = false
if deflater != nil {
if f.code == .Binary || f.code == .Text {
deflate = true
// b |= 0x40
}
}
head[hlen++] = b | f.code.rawValue
var payloadBytes : [UInt8]
var payloadLen = 0
if f.utf8.text != "" {
payloadBytes = UTF8.bytes(f.utf8.text)
} else {
payloadBytes = f.payload.array
}
payloadLen += payloadBytes.count
if deflate {
}
var usingStatusCode = false
if f.statusCode != 0 && payloadLen != 0 {
payloadLen += 2
usingStatusCode = true
}
if payloadLen < 126 {
head[hlen++] = 0x80 | UInt8(payloadLen)
} else if payloadLen <= 0xFFFF {
head[hlen++] = 0x80 | 126
for var i = 1; i >= 0; i-- {
head[hlen++] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF)
}
} else {
head[hlen++] = UInt8((0x1 << 7) + 127)
for var i = 7; i >= 0; i-- {
head[hlen++] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF)
}
}
let r = arc4random()
var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)]
for var i = 0; i < 4; i++ {
head[hlen++] = maskBytes[i]
}
if payloadLen > 0 {
if usingStatusCode {
var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)]
for var i = 0; i < 2; i++ {
sc[i] ^= maskBytes[i % 4]
}
head[hlen++] = sc[0]
head[hlen++] = sc[1]
for var i = 2; i < payloadLen; i++ {
payloadBytes[i-2] ^= maskBytes[i % 4]
}
} else {
for var i = 0; i < payloadLen; i++ {
payloadBytes[i] ^= maskBytes[i % 4]
}
}
}
try write(head, length: hlen)
try write(payloadBytes, length: payloadBytes.count)
}
func close(code : Int = 1000, reason : String = "Normal Closure") {
let f = Frame()
f.code = .Close
f.statusCode = UInt16(truncatingBitPattern: code)
f.utf8.text = reason
sendFrame(f)
}
func sendFrame(f : Frame) {
lock()
frames += [f]
unlock()
manager.signal()
}
func send(message : Any) {
let f = Frame()
if let message = message as? String {
f.code = .Text
f.utf8.text = message
} else if let message = message as? [UInt8] {
f.code = .Binary
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.code = .Binary
f.payload.append(message.baseAddress, length: message.count)
} else if let message = message as? NSData {
f.code = .Binary
f.payload.nsdata = message
} else {
f.code = .Text
f.utf8.text = "\(message)"
}
sendFrame(f)
}
func ping() {
let f = Frame()
f.code = .Ping
sendFrame(f)
}
func ping(message : Any){
let f = Frame()
f.code = .Ping
if let message = message as? String {
f.payload.array = UTF8.bytes(message)
} else if let message = message as? [UInt8] {
f.payload.array = message
} else if let message = message as? UnsafeBufferPointer<UInt8> {
f.payload.append(message.baseAddress, length: message.count)
} else if let message = message as? NSData {
f.payload.nsdata = message
} else {
f.utf8.text = "\(message)"
}
sendFrame(f)
}
}
private func ==(lhs: InnerWebSocket, rhs: InnerWebSocket) -> Bool {
return lhs.id == rhs.id
}
private enum TCPConnSecurity {
case None
case NegoticatedSSL
var level: String {
switch self {
case .None: return NSStreamSocketSecurityLevelNone
case .NegoticatedSSL: return NSStreamSocketSecurityLevelNegotiatedSSL
}
}
}
// Manager class is used to minimize the number of dispatches and cycle through network events
// using fewers threads. Helps tremendously with lowing system resources when many conncurrent
// sockets are opened.
private class Manager {
var queue = dispatch_queue_create("SwiftWebSocketInstance", nil)
var once = dispatch_once_t()
var mutex = pthread_mutex_t()
var cond = pthread_cond_t()
var websockets = Set<InnerWebSocket>()
var _nextId = 0
init(){
pthread_mutex_init(&mutex, nil)
pthread_cond_init(&cond, nil)
dispatch_async(dispatch_queue_create("SwiftWebSocket", nil)) {
var wss : [InnerWebSocket] = []
for ;; {
var wait = true
wss.removeAll()
pthread_mutex_lock(&self.mutex)
for ws in self.websockets {
wss.append(ws)
}
for ws in wss {
self.checkForConnectionTimeout(ws)
if ws.dirty {
pthread_mutex_unlock(&self.mutex)
ws.step()
pthread_mutex_lock(&self.mutex)
wait = false
}
}
if wait {
self.wait(250)
}
pthread_mutex_unlock(&self.mutex)
}
}
}
func checkForConnectionTimeout(ws : InnerWebSocket) {
if ws.rd != nil && ws.wr != nil && (ws.rd.streamStatus == .Opening || ws.wr.streamStatus == .Opening) {
let age = CFAbsoluteTimeGetCurrent() - ws.createdAt
if age >= timeoutDuration {
ws.connectionTimeout = true
}
}
}
func wait(timeInMs : Int) -> Int32 {
var ts = timespec()
var tv = timeval()
gettimeofday(&tv, nil)
ts.tv_sec = time(nil) + timeInMs / 1000;
let v1 = Int(tv.tv_usec * 1000)
let v2 = Int(1000 * 1000 * Int(timeInMs % 1000))
ts.tv_nsec = v1 + v2;
ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
ts.tv_nsec %= (1000 * 1000 * 1000);
return pthread_cond_timedwait(&self.cond, &self.mutex, &ts)
}
func signal(){
pthread_mutex_lock(&mutex)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func add(websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.insert(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func remove(websocket: InnerWebSocket) {
pthread_mutex_lock(&mutex)
websockets.remove(websocket)
pthread_cond_signal(&cond)
pthread_mutex_unlock(&mutex)
}
func nextId() -> Int {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
return ++_nextId
}
}
private let manager = Manager()
/// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455.
public class WebSocket: NSObject {
private var ws: InnerWebSocket
private var id = manager.nextId()
private var opened: Bool
public override var hashValue: Int { return id }
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(_ url: String){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public convenience init(url: NSURL){
self.init(request: NSURLRequest(URL: url), subProtocols: [])
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public convenience init(_ url: String, subProtocols : [String]){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols)
}
/// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public convenience init(_ url: String, subProtocol : String){
self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol])
}
/// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols.
public init(request: NSURLRequest, subProtocols : [String] = []){
opened = true
ws = InnerWebSocket(request: request, subProtocols: subProtocols, stub: false)
}
/// Create a WebSocket object with a deferred connection; the connection is not opened until the .open() method is called.
public override init(){
opened = false
ws = InnerWebSocket(request: NSURLRequest(), subProtocols: [], stub: true)
super.init()
ws.eclose = {
self.opened = false
}
}
/// The URL as resolved by the constructor. This is always an absolute URL. Read only.
public var url : String{ return ws.url }
/// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
public var subProtocol : String{ return ws.subProtocol }
/// The compression options of the WebSocket.
public var compression : WebSocketCompression{
get { return ws.compression }
set { ws.compression = newValue }
}
/// Allow for Self-Signed SSL Certificates. Default is false.
public var allowSelfSignedSSL : Bool{
get { return ws.allowSelfSignedSSL }
set { ws.allowSelfSignedSSL = newValue }
}
/// The services of the WebSocket.
public var services : WebSocketService{
get { return ws.services }
set { ws.services = newValue }
}
/// The events of the WebSocket.
public var event : WebSocketEvents{
get { return ws.event }
set { ws.event = newValue }
}
/// The queue for firing off events. default is main_queue
public var eventQueue : dispatch_queue_t?{
get { return ws.eventQueue }
set { ws.eventQueue = newValue }
}
/// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array.
public var binaryType : WebSocketBinaryType{
get { return ws.binaryType }
set { ws.binaryType = newValue }
}
/// The current state of the connection; this is one of the WebSocketReadyState constants. Read only.
public var readyState : WebSocketReadyState{
return ws.readyState
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public func open(url: String){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond.
public func open(nsurl url: NSURL){
open(request: NSURLRequest(URL: url), subProtocols: [])
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols.
public func open(url: String, subProtocols : [String]){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols)
}
/// Opens a deferred or closed WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol.
public func open(url: String, subProtocol : String){
open(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol])
}
/// Opens a deferred or closed WebSocket connection from an NSURLRequest; Also include a list of protocols.
public func open(request request: NSURLRequest, subProtocols : [String] = []){
if opened{
return
}
opened = true
ws = ws.copyOpen(request, subProtocols: subProtocols)
}
/// Opens a closed WebSocket connection from an NSURLRequest; Uses the same request and protocols as previously closed WebSocket
public func open(){
open(request: ws.request, subProtocols: ws.subProtocols)
}
/**
Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing.
:param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed.
:param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).
*/
public func close(code : Int = 1000, reason : String = "Normal Closure"){
if !opened{
return
}
opened = false
ws.close(code, reason: reason)
}
/**
Transmits message to the server over the WebSocket connection.
:param: message The message to be sent to the server.
*/
public func send(message : Any){
if !opened{
return
}
ws.send(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
:param: optional message The data to be sent to the server.
*/
public func ping(message : Any){
if !opened{
return
}
ws.ping(message)
}
/**
Transmits a ping to the server over the WebSocket connection.
*/
public func ping(){
if !opened{
return
}
ws.ping()
}
}
public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool {
return lhs.id == rhs.id
}
extension WebSocket {
/// The events of the WebSocket using a delegate.
public var delegate : WebSocketDelegate? {
get { return ws.eventDelegate }
set { ws.eventDelegate = newValue }
}
/**
Transmits message to the server over the WebSocket connection.
:param: text The message (string) to be sent to the server.
*/
@objc
public func send(text text: String){
send(text)
}
/**
Transmits message to the server over the WebSocket connection.
:param: data The message (binary) to be sent to the server.
*/
@objc
public func send(data data: NSData){
send(data)
}
}
| mit | 71769fde842cca63739197bea395c83a | 36.521667 | 222 | 0.557174 | 4.973051 | false | false | false | false |
ykyouhei/QiitaKit | QiitaKit/Sources/Entities/Group.swift | 1 | 1163 | //
// Group.swift
// QiitaKit
//
// Created by kyo__hei on 2016/07/10.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import Foundation
/// Qiita:Teamのグループを表します
///
/// https://qiita.com/api/v2/docs#グループ
public struct Group: Codable, CustomStringConvertible {
/// データが作成された日時
public let createdAt: Date
/// グループの一意なIDを表します
public let id: Int
/// グループに付けられた表示用の名前を表します
public let name: String
/// グループに付けられた表示用の名前を表します
public let privated: Bool
/// データが最後に更新された日時
public let updatedAt: Date
/// グループのチーム上での一意な名前を表します
public let urlName: String
}
extension Group {
enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
case id = "id"
case name = "name"
case privated = "private"
case updatedAt = "updated_at"
case urlName = "url_name"
}
}
| mit | 7c12e7326829f03c93cf0279892c2a43 | 18.375 | 55 | 0.596774 | 3.369565 | false | false | false | false |
zirinisp/SlackKit | SlackKit/Sources/History.swift | 1 | 1804 | //
// History.swift
//
// Copyright © 2016 Peter Zignego. 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
public struct History {
internal(set) public var latest: Date?
internal(set) public var messages = [Message]()
public let hasMore: Bool?
internal init(history: [String: Any]?) {
if let latestStr = history?["latest"] as? String, let latestDouble = Double(latestStr) {
latest = Date(timeIntervalSince1970: TimeInterval(latestDouble))
}
if let msgs = history?["messages"] as? [[String: Any]] {
for message in msgs {
messages.append(Message(dictionary: message))
}
}
hasMore = history?["has_more"] as? Bool
}
}
| mit | 77afb0de3fe2eb4797a2e576414fe33e | 40.930233 | 96 | 0.701054 | 4.564557 | false | true | false | false |
ahernandezlopez/Preacher | Preacher/Comparison/Comparison.swift | 1 | 7918 | //
// Comparison.swift
// Preacher
//
// Created by Albert Hernández López on 1/6/15.
// Copyright (c) 2015 Albert Hernández López. All rights reserved.
//
import Foundation
/**
Describes all supported comparisons.
- EqualsDate: Equals to a date.
- NotEqualsDate: Not equals to a date.
- GreaterThanDate: Greater than a date.
- GreaterThanOrEqualDate: Greater than or equals a date.
- LessThanDate: Less than a date.
- LessThanOrEqualDate: Less than or equals a date.
- InDates: Contained in the given dates.
- BetweenDates: Between two dates.
- EqualsNumber: Equals to a number.
- NotEqualsNumber: Not equals to a number.
- GreaterThanNumber: Not equals to a number.
- GreaterThanOrEqualNumber: Greater than or equals a number.
- LessThanNumber: Less than a number.
- LessThanOrEqualNumber: Less than or equals a number.
- InNumbers: Contained in the given numbers.
- BetweenNumbers: Between two numbers.
- EqualsString: Equals to a string.
- NotEqualsString: Not equals to a string.
- InStrings: Contained in the given strings.
- BeginsWith: Begins with a substring.
- Contains: Contains a substring.
- EndsWith: Ends with a substring.
- Like: Likes a string.
- Matches: Matches a regular expression.
*/
public enum Comparison: Equatable {
// NSDate
case EqualsDate(NSDate)
case NotEqualsDate(NSDate)
case GreaterThanDate(NSDate)
case GreaterThanOrEqualDate(NSDate)
case LessThanDate(NSDate)
case LessThanOrEqualDate(NSDate)
case InDates(Array<NSDate>)
case BetweenDates(NSDate, NSDate)
// NSNumber
case EqualsNumber(NSNumber)
case NotEqualsNumber(NSNumber)
case GreaterThanNumber(NSNumber)
case GreaterThanOrEqualNumber(NSNumber)
case LessThanNumber(NSNumber)
case LessThanOrEqualNumber(NSNumber)
case InNumbers(Array<NSNumber>)
case BetweenNumbers(NSNumber, NSNumber)
// String
case EqualsString(String)
case NotEqualsString(String)
case InStrings(Array<String>)
case BeginsWith(String, StringComparisonModifier)
case Contains(String, StringComparisonModifier)
case EndsWith(String, StringComparisonModifier)
case Like(String, StringComparisonModifier)
case Matches(String, StringComparisonModifier)
}
// MARK: - Equatable
public func ==(lhs: Comparison, rhs: Comparison) -> Bool {
switch (lhs, rhs) {
// NSDate
case (.EqualsDate(let lValue), .EqualsDate(let rValue)):
return lValue == rValue
case (.NotEqualsDate(let lValue), .NotEqualsDate(let rValue)):
return lValue == rValue
case (.GreaterThanDate(let lValue), .GreaterThanDate(let rValue)):
return lValue == rValue
case (.GreaterThanOrEqualDate(let lValue), .GreaterThanOrEqualDate(let rValue)):
return lValue == rValue
case (.LessThanDate(let lValue), .LessThanDate(let rValue)):
return lValue == rValue
case (.LessThanOrEqualDate(let lValue), .LessThanOrEqualDate(let rValue)):
return lValue == rValue
case (.InDates(let lValue), .InDates(let rValue)):
return lValue == rValue
case (.BetweenDates(let lA, let lB), .BetweenDates(let rA, let rB)):
return lA == rA && lB == rB
// NSNumber
case (.EqualsNumber(let lValue), .EqualsNumber(let rValue)):
return lValue == rValue
case (.NotEqualsNumber(let lValue), .NotEqualsNumber(let rValue)):
return lValue == rValue
case (.GreaterThanNumber(let lValue), .GreaterThanNumber(let rValue)):
return lValue == rValue
case (.GreaterThanOrEqualNumber(let lValue), .GreaterThanOrEqualNumber(let rValue)):
return lValue == rValue
case (.LessThanNumber(let lValue), .LessThanNumber(let rValue)):
return lValue == rValue
case (.LessThanOrEqualNumber(let lValue), .LessThanOrEqualNumber(let rValue)):
return lValue == rValue
case (.InNumbers(let lValue), .InNumbers(let rValue)):
return lValue == rValue
case (.BetweenNumbers(let lA, let lB), .BetweenNumbers(let rA, let rB)):
return lA == rA && lB == rB
// String
case (.EqualsString(let lValue), .EqualsString(let rValue)):
return lValue == rValue
case (.NotEqualsString(let lValue), .NotEqualsString(let rValue)):
return lValue == rValue
case (.InStrings(let lValue), .InStrings(let rValue)):
return lValue == rValue
case (.BeginsWith(let lValue, let lModifier), .BeginsWith(let rValue, let rModifier)):
return lValue == rValue && lModifier == rModifier
case (.Contains(let lValue, let lModifier), .Contains(let rValue, let rModifier)):
return lValue == rValue && lModifier == rModifier
case (.EndsWith(let lValue, let lModifier), .EndsWith(let rValue, let rModifier)):
return lValue == rValue && lModifier == rModifier
case (.Like(let lValue, let lModifier), .Like(let rValue, let rModifier)):
return lValue == rValue && lModifier == rModifier
case (.Matches(let lValue, let lModifier), .Matches(let rValue, let rModifier)):
return lValue == rValue && lModifier == rModifier
default:
return false
}
}
// MARK: - Printable
extension Comparison: Printable {
public var description: String {
switch self {
// NSDate
case EqualsDate(let date):
return "== \(date)"
case NotEqualsDate(let date):
return "!= \(date)"
case GreaterThanDate(let date):
return "> \(date)"
case GreaterThanOrEqualDate(let date):
return ">= \(date)"
case LessThanDate(let date):
return "< \(date)"
case LessThanOrEqualDate(let date):
return "<= \(date)"
case InDates(let array):
var valuesDescription = array.reduce("") { "\($0),\($1)"}
return "IN {\(valuesDescription)}"
case BetweenDates(let min, let max):
return "BETWEEN {\(min), \(max)}"
// NSNumber
case .EqualsNumber(let number):
return "== \(number)"
case NotEqualsNumber(let number):
return "!= \(number)"
case GreaterThanNumber(let number):
return "> \(number)"
case GreaterThanOrEqualNumber(let number):
return ">= \(number)"
case LessThanNumber(let number):
return "< \(number)"
case LessThanOrEqualNumber(let number):
return "<= \(number)"
case InNumbers(let array):
var valuesDescription = array.reduce("") { "\($0),\($1)"}
return "IN {\(valuesDescription)}"
case BetweenNumbers(let min, let max):
return "BETWEEN {\(min), \(max)}"
// String
case .EqualsString(let value):
return "== \(value)"
case .NotEqualsString(let value):
return "!= \(value)"
case .InStrings(let array):
var valuesDescription = array.reduce("") { "\($0),\"\($1)\""}
return "IN {\(valuesDescription)}"
case BeginsWith(let value, let modifiers):
return "BEGINSWITH\(modifiers) \"\(value)\""
case Contains(let value, let modifiers):
return "CONTAINS\(modifiers) \"\(value)\""
case EndsWith(let value, let modifiers):
return "ENDSWITH\(modifiers) \"\(value)\""
case Like(let value, let modifiers):
return "LIKE\(modifiers) \"\(value)\""
case Matches(let value, let modifiers):
return "MATCHES\(modifiers) \"\(value)\""
}
}
} | mit | 8734bca7fc8b7c1a6bc896b89bc8ab64 | 38.974747 | 90 | 0.61069 | 4.816799 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/CharaInfo/Controller/CharFilterSortController.swift | 1 | 8780 | //
// CharFilterSortController.swift
// DereGuide
//
// Created by zzk on 2017/1/13.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
protocol CharFilterSortControllerDelegate: class {
func doneAndReturn(filter: CGSSCharFilter, sorter: CGSSSorter)
}
class CharFilterSortController: BaseFilterSortController {
weak var delegate: CharFilterSortControllerDelegate?
var filter: CGSSCharFilter!
var sorter: CGSSSorter!
var charTypeTitles = ["Cute", "Cool", "Passion"]
var charCVTitles = [NSLocalizedString("已付声", comment: ""), NSLocalizedString("未付声", comment: "")]
var charAgeTitles = [NSLocalizedString("年龄", comment: "") + "<10", "10-19", "20-29", "30~", NSLocalizedString("未知", comment: "")]
var charBloodTitles = [NSLocalizedString("血型", comment: "") + "A", "B", "AB", "O"]
var favoriteTitles = [NSLocalizedString("已收藏", comment: ""),
NSLocalizedString("未收藏", comment: "")]
var sorterMethods = ["sHeight", "sWeight", "BMI", "sAge", "sizeB", "sizeW", "sizeH", "sName", "sCharaId", "sBirthday"]
var sorterTitles = [NSLocalizedString("身高", comment: ""), NSLocalizedString("体重", comment: ""), "BMI", NSLocalizedString("年龄", comment: ""), "B", "W", "H", NSLocalizedString("五十音", comment: ""), NSLocalizedString("游戏编号", comment: ""), NSLocalizedString("生日", comment: "")]
var sorterOrderTitles = [NSLocalizedString("降序", comment: ""), NSLocalizedString("升序", comment: "")]
override func viewDidLoad() {
super.viewDidLoad()
}
func reloadData() {
self.tableView.reloadData()
}
override func doneAction() {
delegate?.doneAndReturn(filter: filter, sorter: sorter)
drawerController?.hide(animated: true)
// 使用自定义动画效果
/*let transition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionReveal
navigationController?.view.layer.addAnimation(transition, forKey: kCATransition)
navigationController?.popViewControllerAnimated(false)*/
}
override func resetAction() {
filter = CGSSCharFilter.init(typeMask: 0b111, ageMask: 0b11111, bloodMask: 0b11111, cvMask: 0b11, favoriteMask: 0b11)
sorter = CGSSSorter.init(property: "sName", ascending: true)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TableViewDelegate & DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 5
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilterCell", for: indexPath) as! FilterTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: charTypeTitles, index: filter.charTypes.rawValue, all: CGSSCharTypes.all.rawValue)
case 1:
cell.setup(titles: charCVTitles, index: filter.charCVTypes.rawValue, all: CGSSCharCVTypes.all.rawValue)
case 2:
cell.setup(titles: charAgeTitles, index: filter.charAgeTypes.rawValue, all: CGSSCharAgeTypes.all.rawValue)
case 3:
cell.setup(titles: charBloodTitles, index: filter.charBloodTypes.rawValue, all: CGSSCharBloodTypes.all.rawValue)
case 4:
cell.setup(titles: favoriteTitles, index: filter.favoriteTypes.rawValue, all: CGSSFavoriteTypes.all.rawValue)
default:
break
}
cell.delegate = self
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SortCell", for: indexPath) as! SortTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: sorterOrderTitles)
cell.presetIndex(index: sorter.ascending ? 1 : 0)
case 1:
cell.setup(titles: sorterTitles)
if let index = sorterMethods.index(of: sorter.property) {
cell.presetIndex(index: UInt(index))
}
default:
break
}
cell.delegate = self
return cell
}
}
}
extension CharFilterSortController: FilterTableViewCellDelegate {
func filterTableViewCell(_ cell: FilterTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.charTypes.insert(CGSSCharTypes.init(type: index))
case 1:
filter.charCVTypes.insert(CGSSCharCVTypes.init(rawValue: 1 << UInt(index)))
case 2:
filter.charAgeTypes.insert(CGSSCharAgeTypes.init(rawValue: 1 << UInt(index)))
case 3:
filter.charBloodTypes.insert(CGSSCharBloodTypes.init(rawValue: 1 << UInt(index)))
case 4:
filter.favoriteTypes.insert(CGSSFavoriteTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func filterTableViewCell(_ cell: FilterTableViewCell, didDeselect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.charTypes.remove(CGSSCharTypes.init(type: index))
case 1:
filter.charCVTypes.remove(CGSSCharCVTypes.init(rawValue: 1 << UInt(index)))
case 2:
filter.charAgeTypes.remove(CGSSCharAgeTypes.init(rawValue: 1 << UInt(index)))
case 3:
filter.charBloodTypes.remove(CGSSCharBloodTypes.init(rawValue: 1 << UInt(index)))
case 4:
filter.favoriteTypes.remove(CGSSFavoriteTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func didSelectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.charTypes = .all
case 1:
filter.charCVTypes = .all
case 2:
filter.charAgeTypes = .all
case 3:
filter.charBloodTypes = .all
case 4:
filter.favoriteTypes = .all
default:
break
}
}
}
}
func didDeselectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.charTypes = CGSSCharTypes.init(rawValue: 0)
case 1:
filter.charCVTypes = CGSSCharCVTypes.init(rawValue: 0)
case 2:
filter.charAgeTypes = CGSSCharAgeTypes.init(rawValue: 0)
case 3:
filter.charBloodTypes = CGSSCharBloodTypes.init(rawValue: 0)
case 4:
filter.favoriteTypes = CGSSFavoriteTypes.init(rawValue: 0)
default:
break
}
}
}
}
}
extension CharFilterSortController: SortTableViewCellDelegate {
func sortTableViewCell(_ cell: SortTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 1 {
switch indexPath.row {
case 0:
sorter.ascending = (index == 1)
case 1:
sorter.property = sorterMethods[index]
sorter.displayName = sorterTitles[index]
default:
break
}
}
}
}
}
| mit | 321566aafa8b3da8059e667c9f67eabd | 38.121622 | 276 | 0.560507 | 5.075979 | false | false | false | false |
coodly/ios-gambrinus | Packages/Sources/KioskUI/Modal/ModalPresentationViewController.swift | 1 | 2865 | //
// ModalPresentationViewController.swift
// KDMUI
//
// Created by Jaanus Siim on 07/12/2018.
// Copyright © 2018 Coodly OU. All rights reserved.
//
import UIKit
private extension Selector {
static let dismissModal = #selector(ModalPresentationViewController.dismissModal)
}
internal extension Notification.Name {
static let modalShowPresented = Notification.Name(rawValue: "modalShowPresented")
static let modalShowDismissed = Notification.Name(rawValue: "modalShowDismissed")
}
internal class ModalPresentationViewController: UIViewController, StoryboardLoaded, UIInjector {
static var storyboardName: String {
return "ModalPresentation"
}
@IBOutlet private var dimView: UIView!
@IBOutlet private var container: UIView!
@IBOutlet private var containerVerticalCenterConstraint: NSLayoutConstraint!
internal var controller: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
let modalPresented: UIViewController = controller
addChild(modalPresented)
container.addSubview(modalPresented.view)
modalPresented.view.pinToSuperviewEdges()
dimView.backgroundColor = UIColor.black
dimView.alpha = 0
let tap = UITapGestureRecognizer(target: self, action: .dismissModal)
dimView.addGestureRecognizer(tap)
container.layer.cornerRadius = 10
guard let navigation = controller as? UINavigationController else {
return
}
navigation.topViewController?.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissModal))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
containerVerticalCenterConstraint.constant = view.frame.height
NotificationCenter.default.post(name: .modalShowPresented, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
containerVerticalCenterConstraint.constant = 0
let animation = {
self.dimView.alpha = 0.4
self.view.layoutIfNeeded()
}
UIView.animate(withDuration: 0.3, animations: animation)
}
@objc fileprivate func dismissModal() {
containerVerticalCenterConstraint.constant = view.frame.height
let animation = {
self.dimView.alpha = 0
self.view.layoutIfNeeded()
}
UIView.animate(withDuration: 0.3, animations: animation) {
_ in
self.dismiss(animated: false)
NotificationCenter.default.post(name: .modalShowDismissed, object: nil)
}
}
}
| apache-2.0 | ebd902ce27a391a35e798c0fc1d64ea2 | 30.472527 | 163 | 0.656774 | 5.518304 | false | false | false | false |
zwaldowski/ale | Sources/Command/HelpCommand.swift | 1 | 2049 | //
// HelpCommand.swift
// Command
//
// Created by Justin Spahr-Summers on 10/10/2014.
// Copyright © 2014 Carthage. All rights reserved.
// Copyright © 2016 Zachary Waldowski. All rights reserved.
//
/// A basic implementation of a `help` command, using information available in a
/// `CommandRegistry`.
///
/// If you want to use this command, initialize it with the registry, then add
/// it to that same registry:
///
/// let commands = CommandRegistry()
/// let helpCommand = HelpCommand(registry: commands)
/// commands.register(helpCommand)
///
public struct HelpCommand: CommandProtocol {
public struct Options: OptionsProtocol {
fileprivate let verb: String?
public enum Key { case verb }
public static let all: DictionaryLiteral<Key, Argument> = [
.verb: .positional(defaultValue: "", usage: "the command to display help for")
]
public init(parsedFrom arguments: ArgumentParser<HelpCommand.Options.Key>) throws {
self.verb = try arguments.value(for: .verb) { !$0.isEmpty }
}
}
public let verb = "help"
public let function = "Display general or command-specific help"
private let registry: CommandRegistry
/// Initializes the command to provide help from the given registry of
/// commands.
public init(registry: CommandRegistry) {
self.registry = registry
}
public func run(_ options: Options) throws {
if let verb = options.verb {
if let command = self.registry[verb] {
return print(command, to: &CommandLine.standardError)
} else {
print("Unrecognized command: '\(verb)'", to: &CommandLine.standardError)
}
}
print("Available commands:\n")
let maxVerbLength = self.registry.commands.map { $0.verb.characters.count }.max() ?? 0
for command in self.registry.commands {
let padding = String(repeating: " ", count: maxVerbLength - command.verb.characters.count)
print(" \(command.verb)\(padding) \(command.function)", to: &CommandLine.standardError)
}
}
}
| mit | ba8ba1478e9518bed159652968775a9a | 30.984375 | 102 | 0.672692 | 4.053465 | false | false | false | false |
Holight/QuiltLayout | QuiltLayout/QuiltLayout.swift | 1 | 16566 | //
// QuiltLayout.swift
// QuiltLayout
//
import Foundation
import UIKit
@objc protocol QuiltLayoutDelegate: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
}
class QuiltLayout: UICollectionViewLayout {
var delegate: QuiltLayoutDelegate?
var blockPixels: CGSize = CGSize(width: 100, height: 100) {
didSet {
invalidateLayout()
}
}
var direction: UICollectionView.ScrollDirection = .vertical {
didSet {
invalidateLayout()
}
}
// only use this if you don't have more than 1000ish items.
// this will give you the correct size from the start and
// improve scrolling speed, at the cost of time at the beginning
var prelayoutEverything = false
private var firstOpenSpace = CGPoint()
private var furthestBlockPoint = CGPoint()
func setFurthestBlockPoint(_ point: CGPoint) {
self.furthestBlockPoint = CGPoint(x: max(self.furthestBlockPoint.x, point.x), y: max(self.furthestBlockPoint.y, point.y))
}
// this will be a 2x2 dictionary storing nsindexpaths
// which indicate the available/filled spaces in our quilt
var indexPathByPosition = [CGFloat : [CGFloat : IndexPath]]()
// indexed by "section, row" this will serve as the rapid
// lookup of block position by indexpath.
var positionByIndexPath = [Int : [Int : CGPoint]]()
// previous layout cache. this is to prevent choppiness
// when we scroll to the bottom of the screen - uicollectionview
// will repeatedly call layoutattributesforelementinrect on
// each scroll event. pow!
var previousLayoutAttributes: [UICollectionViewLayoutAttributes]?
var previousLayoutRect: CGRect?
// remember the last indexpath placed, as to not
// relayout the same indexpaths while scrolling
var lastIndexPathPlaced: IndexPath?
var isVertical: Bool {
return self.direction == .vertical
}
override var collectionViewContentSize: CGSize {
let contentRect = collectionView!.frame.inset(by: collectionView!.contentInset);
if isVertical {
return CGSize(width: contentRect.width, height: (furthestBlockPoint.y+1) * blockPixels.height)
}
else {
return CGSize(width: (furthestBlockPoint.x+1) * blockPixels.width, height: contentRect.height)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard delegate != nil else {
return nil
}
guard rect != previousLayoutRect else {
return previousLayoutAttributes
}
previousLayoutRect = rect
let unrestrictedDimensionStart = Int(isVertical ? rect.origin.y / blockPixels.height : rect.origin.x / blockPixels.width)
let unrestrictedDimensionLength = Int((isVertical ? rect.size.height / blockPixels.height : rect.size.width / blockPixels.width) + 1)
let unrestrictedDimensionEnd = unrestrictedDimensionStart + unrestrictedDimensionLength
self.fillInBlocks(toUnrestricted: prelayoutEverything ? Int.max : unrestrictedDimensionEnd)
// find the indexPaths between those rows
var attributes = Set<UICollectionViewLayoutAttributes>()
self.traverseTilesBetweenUnrestrictedDimension(begin: unrestrictedDimensionStart, and: unrestrictedDimensionEnd) { point in
if let indexPath = self.indexPath(for: point),
let attribute = self.layoutAttributesForItem(at: indexPath) {
attributes.insert(attribute)
}
return true
}
previousLayoutAttributes = Array(attributes)
return previousLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let insets = delegate?.collectionView(collectionView!, layout: self, insetForSectionAt: indexPath.item) ?? UIEdgeInsets()
let itemFrame = frame(for: indexPath)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = itemFrame.inset(by: insets)
return attributes
}
func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return newBounds.size == collectionView!.frame.size
}
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)
for item in updateItems {
if item.updateAction == .insert || item.updateAction == .move {
fillInBlocks(to: item.indexPathAfterUpdate!)
}
}
}
override func invalidateLayout() {
super.invalidateLayout()
furthestBlockPoint = CGPoint.zero
firstOpenSpace = CGPoint.zero
previousLayoutRect = CGRect.zero
previousLayoutAttributes = nil
lastIndexPathPlaced = nil
indexPathByPosition.removeAll()
positionByIndexPath.removeAll()
}
override func prepare() {
super.prepare()
guard delegate != nil else { return }
let scrollOrigin = collectionView!.contentOffset
let scrollSize = collectionView!.frame.size
let scrollFrame = CGRect(origin: scrollOrigin, size: scrollSize)
let unrestrictedRow = isVertical ? Int(scrollFrame.maxY / blockPixels.height) + 1 : Int(scrollFrame.maxX / blockPixels.width) + 1
fillInBlocks(toUnrestricted: prelayoutEverything ? Int.max : unrestrictedRow)
}
func fillInBlocks(toUnrestricted endRow: Int) {
let startIndexPath: IndexPath
if let lastIndexPathPlaced = lastIndexPathPlaced {
startIndexPath = IndexPath(item: lastIndexPathPlaced.row + 1, section: lastIndexPathPlaced.section)
} else {
startIndexPath = IndexPath(row: 0, section: 0)
}
// we'll have our data structure as if we're planning
// a vertical layout, then when we assign positions to
// the items we'll invert the axis
let numSections = collectionView!.numberOfSections
for section in startIndexPath.section..<numSections {
let numRows = collectionView!.numberOfItems(inSection: section)
for row in startIndexPath.row..<numRows {
let indexPath = IndexPath(row: row, section: section)
if placeBlock(at: indexPath) {
lastIndexPathPlaced = indexPath
}
// only jump out if we've already filled up every space up till the resticted row
if (isVertical ? firstOpenSpace.y : firstOpenSpace.x) >= CGFloat(endRow) {
return
}
}
}
}
func fillInBlocks(to path: IndexPath) {
let startIndexPath: IndexPath
if let lastIndexPathPlaced = lastIndexPathPlaced {
startIndexPath = IndexPath(item: lastIndexPathPlaced.row + 1, section: lastIndexPathPlaced.section)
} else {
startIndexPath = IndexPath(row: 0, section: 0)
}
// we'll have our data structure as if we're planning
// a vertical layout, then when we assign positions to
// the items we'll invert the axis
let numSections = collectionView!.numberOfSections
for section in startIndexPath.section..<numSections {
let numRows = collectionView!.numberOfItems(inSection: section)
for row in startIndexPath.row..<numRows {
// exit when we are past the desired row
if section >= path.section && row > path.row {
return
}
let indexPath = IndexPath(row: row, section: section)
if placeBlock(at: indexPath) {
lastIndexPathPlaced = indexPath
}
}
}
}
func placeBlock(at indexPath: IndexPath) -> Bool {
let blockSize = getBlockSizeForItem(at: indexPath)
return !traverseOpenTiles() { blockOrigin in
// we need to make sure each square in the desired
// area is available before we can place the square
let didTraverseAllBlocks = self.traverseTiles(point: blockOrigin, with: blockSize) { point in
let spaceAvailable = self.indexPath(for: point) == nil
let inBounds = (self.isVertical ? point.x : point.y) < CGFloat(self.restrictedDimensionBlockSize)
let maximumRestrictedBoundSize = (isVertical ? blockOrigin.x : blockOrigin.y) == 0
if spaceAvailable && maximumRestrictedBoundSize && !inBounds {
print("\(type(of: self)): layout is not \(self.isVertical ? "wide" : "tall") enough for this piece size: \(blockSize)! Adding anyway...")
return true
}
return spaceAvailable && inBounds
}
if !didTraverseAllBlocks {
return true
}
// because we have determined that the space is all
// available, lets fill it in as taken.
self.setIndexPath(indexPath, for: blockOrigin)
self.traverseTiles(point: blockOrigin, with: blockSize) { point in
self.setPosition(point, for: indexPath)
self.setFurthestBlockPoint(point)
return true
}
return false
}
}
@discardableResult
func traverseTilesBetweenUnrestrictedDimension(begin: Int, and end: Int, iterator block: (CGPoint) -> Bool) -> Bool {
// the double ;; is deliberate, the unrestricted dimension should iterate indefinitely
for unrestrictedDimension in begin..<end {
for restrictedDimension in 0..<restrictedDimensionBlockSize {
let point = isVertical ? CGPoint(x: restrictedDimension, y: unrestrictedDimension) : CGPoint(x: unrestrictedDimension, y: restrictedDimension)
if !block(point) {
return false
}
}
}
return true
}
@discardableResult
func traverseTiles(point: CGPoint, with size: CGSize, iterator block: (CGPoint) -> Bool) -> Bool {
for col in Int(point.x)..<Int(point.x + size.width) {
for row in Int(point.y)..<Int(point.y + size.height) {
if !block(CGPoint(x: col, y: row)) {
return false
}
}
}
return true;
}
func traverseOpenTiles(block: (CGPoint) -> Bool) -> Bool {
var allTakenBefore = true
// the while true is deliberate, the unrestricted dimension should iterate indefinitely
var unrestrictedDimension = isVertical ? firstOpenSpace.y : firstOpenSpace.x
while true {
for restrictedDimension in 0..<restrictedDimensionBlockSize {
let point = CGPoint(x: isVertical ? CGFloat(restrictedDimension) : unrestrictedDimension,
y: isVertical ? unrestrictedDimension : CGFloat(restrictedDimension))
if indexPath(for: point) != nil {
continue
}
if allTakenBefore {
firstOpenSpace = point
allTakenBefore = false
}
if !block(point) {
return false
}
}
unrestrictedDimension += 1
}
assert(false, "Could find no good place for a block!")
return true
}
func indexPath(for point: CGPoint) -> IndexPath? {
// to avoid creating unbounded nsmutabledictionaries we should
// have the innerdict be the unrestricted dimension
let unrestrictedPoint = (isVertical ? point.y : point.x)
let restrictedPoint = (isVertical ? point.x : point.y)
return indexPathByPosition[restrictedPoint]?[unrestrictedPoint]
}
func setPosition(_ point: CGPoint, for indexPath: IndexPath) {
// to avoid creating unbounded nsmutabledictionaries we should
// have the innerdict be the unrestricted dimension
let unrestrictedPoint = isVertical ? point.y : point.x
let restrictedPoint = isVertical ? point.x : point.y
if indexPathByPosition[restrictedPoint] == nil {
indexPathByPosition[restrictedPoint] = [CGFloat : IndexPath]()
}
indexPathByPosition[restrictedPoint]![unrestrictedPoint] = indexPath
}
func position(for path: IndexPath) -> CGPoint {
// if item does not have a position, we will make one!
if positionByIndexPath[path.section]![path.row] == nil {
fillInBlocks(to: path)
}
return positionByIndexPath[path.section]![path.row]!
}
func setIndexPath(_ path: IndexPath, for point: CGPoint) {
if positionByIndexPath[path.section] == nil {
positionByIndexPath[path.section] = [Int : CGPoint]()
}
positionByIndexPath[path.section]![path.row] = point
}
func frame(for path: IndexPath) -> CGRect {
let itemPosition = position(for: path)
let itemSize = getBlockSizeForItem(at: path)
let contentRect = collectionView!.frame.inset(by: collectionView!.contentInset)
if isVertical {
let initialPaddingForContraintedDimension = (contentRect.width - CGFloat(restrictedDimensionBlockSize) * blockPixels.width) / 2
return CGRect(x: itemPosition.x * blockPixels.width + initialPaddingForContraintedDimension,
y: itemPosition.y * blockPixels.height,
width: itemSize.width * blockPixels.width,
height: itemSize.height * blockPixels.height)
}
else {
let initialPaddingForContraintedDimension = (contentRect.height - CGFloat(restrictedDimensionBlockSize) * blockPixels.height) / 2
return CGRect(x: itemPosition.x * blockPixels.width,
y: itemPosition.y * blockPixels.height + initialPaddingForContraintedDimension,
width: itemSize.width * blockPixels.width,
height: itemSize.height * blockPixels.height)
}
}
//This method is prefixed with get because it may return its value indirectly
func getBlockSizeForItem(at indexPath: IndexPath) -> CGSize {
let blockSize = delegate?.collectionView(collectionView!, layout: self, sizeForItemAt: indexPath)
return blockSize ?? CGSize(width: 1, height: 1)
}
override func targetIndexPath(forInteractivelyMovingItem previousIndexPath: IndexPath, withPosition position: CGPoint) -> IndexPath {
let point = CGPoint(x: Int(position.x / blockPixels.width), y: Int(position.y / blockPixels.height))
return indexPath(for: point) ?? super.targetIndexPath(forInteractivelyMovingItem: previousIndexPath, withPosition: position)
}
private var didShowMessage = false
// this will return the maximum width or height the quilt
// layout can take, depending on we're growing horizontally
// or vertically
var restrictedDimensionBlockSize: Int {
let contentRect = collectionView!.frame.inset(by: collectionView!.contentInset)
let size = Int(isVertical ? contentRect.width / blockPixels.width : contentRect.height / blockPixels.height)
if (size == 0) {
print("\(type(of: self)): cannot fit block of size: \(blockPixels) in content rect \(contentRect)! Defaulting to 1")
return 1
}
return size
}
}
| unlicense | df3e46a280ef5bbd41d14e2cf34b74e1 | 40.623116 | 160 | 0.616806 | 5.594732 | false | false | false | false |
Legoless/iOS-Course | 2015-1/Lesson12/Photos/Photos/ViewController.swift | 1 | 2112 | //
// ViewController.swift
// Photos
//
// Created by Dal Rupnik on 18/11/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
var images : [String] {
var allImages = [String]()
for var i = 1; i <= 23; i++ {
allImages.append(String(i))
}
return allImages
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSBundle.mainBundle().
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImageCell
cell.backgroundColor = UIColor.blackColor()
cell.imageView.image = UIImage(named: images[indexPath.item])
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath = collectionView?.indexPathForCell(sender as! UICollectionViewCell)
if let destinationVC = segue.destinationViewController as? DetailViewController, indexPath = indexPath {
destinationVC.image = UIImage(named: images[indexPath.item])
}
}
}
extension ViewController : UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if let image = UIImage(named: images[indexPath.item]) {
var size = image.size
size.width /= 8.0
size.height /= 8.0
return size
}
return CGSize(width: 100, height: 100)
}
}
| mit | f765128f29964bc0839ff4be19c6244c | 30.507463 | 169 | 0.639981 | 5.644385 | false | false | false | false |
practicalswift/swift | test/IDE/print_ast_tc_decls_errors.swift | 2 | 13355 | // Verify errors in this file to ensure that parse and type checker errors
// occur where we expect them.
// RUN: %target-typecheck-verify-swift -show-diagnostics-after-fatal %s
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=false > %t.printed.txt
// RUN: %FileCheck %s -strict-whitespace < %t.printed.txt
// RUN: %FileCheck -check-prefix=NO-TYPEREPR %s -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -strict-whitespace < %t.printed.txt
// RUN: %FileCheck -check-prefix=TYPEREPR %s -strict-whitespace < %t.printed.txt
//===---
//===--- Helper types.
//===---
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Import printing.
//===---
import not_existent_module_a // expected-error{{no such module 'not_existent_module_a'}}
// CHECK: {{^}}import not_existent_module_a{{$}}
import not_existent_module_a.submodule // expected-error{{no such module}}
// CHECK-NEXT: {{^}}import not_existent_module_a.submodule{{$}}
@_exported import not_existent_module_b // expected-error{{no such module 'not_existent_module_b'}}
// CHECK-NEXT: {{^}}@_exported import not_existent_module_b{{$}}
@_exported import not_existent_module_b.submodule // expected-error{{no such module}}
// CHECK-NEXT: {{^}}@_exported import not_existent_module_b.submodule{{$}}
import struct not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import struct not_existent_module_c.foo{{$}}
import class not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import class not_existent_module_c.foo{{$}}
import enum not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import enum not_existent_module_c.foo{{$}}
import protocol not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import protocol not_existent_module_c.foo{{$}}
import var not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import var not_existent_module_c.foo{{$}}
import func not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import func not_existent_module_c.foo{{$}}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithInheritance1 : FooNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYPEREPR: {{^}}struct StructWithInheritance1 : <<error type>> {{{$}}
// TYPEREPR: {{^}}struct StructWithInheritance1 : FooNonExistentProtocol {{{$}}
struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}} expected-error {{use of undeclared type 'BarNonExistentProtocol'}}
// NO-TYPEREPR: {{^}}struct StructWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYPEREPR: {{^}}struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithInheritance1 : FooNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}class ClassWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance1 : FooNonExistentProtocol {{{$}}
class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}} expected-error {{use of undeclared type 'BarNonExistentProtocol'}}
// NO-TYREPR: {{^}}class ClassWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}class ClassWithInheritance3 : FooClass, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {{{$}}
class ClassWithInheritance4 : FooProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{42-52=}}
// CHECK: {{^}}class ClassWithInheritance4 : FooProtocol, FooClass {{{$}}
class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{55-65=}}
// CHECK: {{^}}class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {{{$}}
class ClassWithInheritance6 : FooClass, BarClass {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance6 : FooClass, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance6 : FooClass, BarClass {{{$}}
class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance7 : FooClass, <<error type>>, FooProtocol {{{$}}
// TYREPR: {{^}}class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {{{$}}
class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance8 : FooClass, <<error type>>, FooProtocol, BarProtocol {{{$}}
// TYREPR: {{^}}class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}class ClassWithInheritance9 : FooClass, <<error type>>, FooProtocol, BarProtocol, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithInheritance1 : FooNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}enum EnumWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance1 : FooNonExistentProtocol {{{$}}
enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}} expected-error {{use of undeclared type 'BarNonExistentProtocol'}}
// NO-TYREPR: {{^}}enum EnumWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
enum EnumWithInheritance3 : FooClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-1{{'EnumWithInheritance3' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance3 : <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance3 : FooClass {{{$}}
enum EnumWithInheritance4 : FooClass, FooProtocol { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-1{{'EnumWithInheritance4' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance4 : <<error type>>, FooProtocol {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance4 : FooClass, FooProtocol {{{$}}
enum EnumWithInheritance5 : FooClass, BarClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}} expected-error {{multiple enum raw types 'FooClass' and 'BarClass'}}
// expected-error@-1{{'EnumWithInheritance5' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance5 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance5 : FooClass, BarClass {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithInheritance1 : FooNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance1 : FooNonExistentProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{use of undeclared type 'FooNonExistentProtocol'}} expected-error {{use of undeclared type 'BarNonExistentProtocol'}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
protocol ProtocolWithInheritance3 : FooClass {}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}}
protocol ProtocolWithInheritance4 : FooClass, FooProtocol {}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}}
protocol ProtocolWithInheritance5 : FooClass, BarClass {} // expected-error{{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error{{protocol 'ProtocolWithInheritance5' cannot be a subclass of both 'BarClass' and 'FooClass'}} // expected-note{{superclass constraint 'Self' : 'FooClass' written here}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance5 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance5 : FooClass, BarClass {{{$}}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias Typealias1 = FooNonExistentProtocol // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}}typealias Typealias1 = <<error type>>{{$}}
// TYREPR: {{^}}typealias Typealias1 = FooNonExistentProtocol{{$}}
// sr-197
func foo(bar: Typealias1<Int>) {} // Should not generate error "cannot specialize non-generic type '<<error type>>'"
// Associated types.
protocol AssociatedType1 {
// CHECK-LABEL: AssociatedType1 {
associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass{{$}}
associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass{{$}}
associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol // expected-error {{use of undeclared type 'FooNonExistentProtocol'}}
// NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : <<error type>>{{$}}
// TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol{{$}}
associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol // expected-error {{use of undeclared type 'FooNonExistentProtocol'}} expected-error {{use of undeclared type 'BarNonExistentProtocol'}}
// NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : <<error type>>, <<error type>>{{$}}
// TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol{{$}}
associatedtype AssociatedTypeDecl5 : FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl5 : FooClass{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var topLevelVar1 = 42
// CHECK: {{^}}var topLevelVar1: Int{{$}}
// CHECK-NOT: topLevelVar1
// CHECK: class C1
class C1 {
// CHECK: init(data: <<error type>>)
init(data:) // expected-error {{expected parameter type following ':'}}
}
protocol IllegalExtension {}
class OuterContext {
// CHECK: class OuterContext {
extension IllegalExtension { // expected-error {{declaration is only valid at file scope}}
// CHECK: extension IllegalExtension {
func protocolFunc() {}
// CHECK: func protocolFunc()
}
}
static func topLevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}}
// NO-TYPEPR: {{^}}func topLevelStaticFunc() -> <<error type>>{{$}}
// TYPEPR: {{^}}func topLevelStaticFunc() {{$}}
static var topLevelStaticVar = 42 // expected-error {{static properties may only be declared on a type}}
// CHECK: {{^}}var topLevelStaticVar: Int{{$}}
| apache-2.0 | 5740499b668ceac37afa667376f2429e | 57.574561 | 322 | 0.721003 | 4.854598 | false | false | false | false |
adamnemecek/AudioKit | Tests/AudioKitTests/Node Tests/RecordingTests.swift | 1 | 2628 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
@testable import AudioKit
import AVFoundation
import XCTest
#if !os(tvOS)
/// Tests for engine.inputNode - note can't be tested without an Info.plist
class RecordingTests: AudioFileTestCase {
func testMultiChannelRecording() throws {
guard Bundle.main.object(forInfoDictionaryKey: "NSMicrophoneUsageDescription") != nil else {
Log("Unsupported test: To record audio, you must include the NSMicrophoneUsageDescription in your Info.plist.",
type: .error)
return
}
let url = FileManager.default.temporaryDirectory.appendingPathComponent("_testMultiChannelRecording")
if !FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.createDirectory(at: url,
withIntermediateDirectories: true,
attributes: nil)
}
let expectation = XCTestExpectation(description: "recordWithPermission")
AVCaptureDevice.requestAccess(for: .audio) { allowed in
Log("requestAccess", allowed)
do {
// Record channels 3+4 in a multichannel device
// let channelMap: [Int32] = [2, 3]
// for test assume mono first channel
let channelMap: [Int32] = [0]
try self.recordWithLatency(url: url, channelMap: channelMap, ioLatency: 12345)
expectation.fulfill()
} catch {
XCTFail(error.localizedDescription)
}
}
try FileManager.default.removeItem(at: url)
wait(for: [expectation], timeout: 10)
}
/// unable to test this in AudioKit due to the lack of the Info.plist, but this should be addressed
func recordWithLatency(url: URL, channelMap: [Int32], ioLatency: AVAudioFrameCount = 0) throws {
// pull from channels 3+4 - needs to work with the device being tested
// var channelMap: [Int32] = [2, 3] // , 4, 5
let engine = AudioEngine()
let channelMap: [Int32] = [0] // mono first channel
let recorder = MultiChannelInputNodeTap(inputNode: engine.avEngine.inputNode)
recorder.ioLatency = ioLatency
try engine.start()
recorder.directory = url
recorder.prepare(channelMap: channelMap)
recorder.record()
wait(for: 3)
recorder.stop()
recorder.recordEnabled = false
wait(for: 1)
engine.stop()
}
}
#endif
| mit | 924645b5ef1b6cd3818b9bba99a0a3a5 | 36.014085 | 123 | 0.613394 | 4.91215 | false | true | false | false |
fthomasmorel/insapp-iOS | Insapp/SearchPostCell.swift | 1 | 3206 | //
// SearchPostCell.swift
// Insapp
//
// Created by Guillaume Courtet on 08/11/2016.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import UIKit
class SearchPostCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var postCollectionView: UICollectionView!
var delegate: PostCellDelegate?
var posts: [Post] = []
var parent: UIViewController!
var more = 0
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.postCollectionView.delegate = self
self.postCollectionView.dataSource = self
}
override func layoutSubviews() {
let layout: UICollectionViewFlowLayout = self.postCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
self.postCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kSearchPostCell)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(more == 1){
return posts.count
}
else {
return min(6,(posts.count))
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.postCollectionView.frame.width - 5)/3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kSearchPostCell, for: indexPath)
let imageView = UIImageView(frame: cell.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
cell.addSubview(imageView)
let post = self.posts[indexPath.row]
imageView.downloadedFrom(link: kCDNHostname + post.photourl!)
return cell
}
func loadPosts(_ posts: [Post]){
self.posts = posts
self.postCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let post = self.posts[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NewsViewController") as! NewsViewController
vc.activePost = post
vc.canReturn = true
vc.canRefresh = false
vc.canSearch = false
self.parent?.navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 68a10aa39e7592fb0e989046d77947cd | 36.267442 | 160 | 0.685179 | 5.386555 | false | false | false | false |
coach-plus/ios | Pods/YPImagePicker/Source/Helpers/Extensions/PHCachingImageManager+Extensions.swift | 1 | 4347 | //
// PHCachingImageManager+Helpers.swift
// YPImagePicker
//
// Created by Sacha DSO on 26/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Photos
extension PHCachingImageManager {
private func photoImageRequestOptions() -> PHImageRequestOptions {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.resizeMode = .exact
options.isSynchronous = true // Ok since we're already in a background thread
return options
}
func fetchImage(for asset: PHAsset, cropRect: CGRect, targetSize: CGSize, callback: @escaping (UIImage, [String: Any]) -> Void) {
let options = photoImageRequestOptions()
// Fetch Highiest quality image possible.
requestImageData(for: asset, options: options) { data, dataUTI, CTFontOrientation, info in
if let data = data, let image = UIImage(data: data)?.resetOrientation() {
// Crop the high quality image manually.
let xCrop: CGFloat = cropRect.origin.x * CGFloat(asset.pixelWidth)
let yCrop: CGFloat = cropRect.origin.y * CGFloat(asset.pixelHeight)
let scaledCropRect = CGRect(x: xCrop,
y: yCrop,
width: targetSize.width,
height: targetSize.height)
if let imageRef = image.cgImage?.cropping(to: scaledCropRect) {
let croppedImage = UIImage(cgImage: imageRef)
let exifs = self.metadataForImageData(data: data)
callback(croppedImage, exifs)
}
}
}
}
private func metadataForImageData(data: Data) -> [String: Any] {
if let imageSource = CGImageSourceCreateWithData(data as CFData, nil),
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil),
let metaData = imageProperties as? [String : Any] {
return metaData
}
return [:]
}
func fetchPreviewFor(video asset: PHAsset, callback: @escaping (UIImage) -> Void) {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.isSynchronous = true
let screenWidth = UIScreen.main.bounds.width
let ts = CGSize(width: screenWidth, height: screenWidth)
requestImage(for: asset, targetSize: ts, contentMode: .aspectFill, options: options) { image, _ in
if let image = image {
DispatchQueue.main.async {
callback(image)
}
}
}
}
func fetchPlayerItem(for video: PHAsset, callback: @escaping (AVPlayerItem) -> Void) {
let videosOptions = PHVideoRequestOptions()
videosOptions.deliveryMode = PHVideoRequestOptionsDeliveryMode.automatic
videosOptions.isNetworkAccessAllowed = true
requestPlayerItem(forVideo: video, options: videosOptions, resultHandler: { playerItem, _ in
DispatchQueue.main.async {
if let playerItem = playerItem {
callback(playerItem)
}
}
})
}
/// This method return two images in the callback. First is with low resolution, second with high.
/// So the callback fires twice.
func fetch(photo asset: PHAsset, callback: @escaping (UIImage, Bool) -> Void) {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true // Enables gettings iCloud photos over the network, this means PHImageResultIsInCloudKey will never be true.
options.deliveryMode = .opportunistic // Get 2 results, one low res quickly and the high res one later.
requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: options) { result, info in
guard let image = result else {
print("No Result 🛑")
return
}
DispatchQueue.main.async {
let isLowRes = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false
callback(image, isLowRes)
}
}
}
}
| mit | f32b9f9e9e3c34b0e5ee3619fb04d63f | 42.43 | 154 | 0.605802 | 5.328834 | false | false | false | false |
ricardorauber/iOS-Swift | iOS-Swift.playground/Pages/Arrays.xcplaygroundpage/Contents.swift | 1 | 2197 | //: ## Arrays
//: ----
//: [Previous](@previous)
import Foundation
var result = ""
//: Empty Array
var someInts = [Int]()
var anyObject = [AnyObject]()
var nsArray = [] // WATCHOUT - NSArray
someInts = [] // This is ok because it was defined previously to [Int]
//: Array with a Default Value
var threeDoubles = [Double](count: 3, repeatedValue: 1.0)
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
//: Adding Two Arrays Together
var sixDoubles = threeDoubles + anotherThreeDoubles
//: Array with an Array Literal
var shoppingList = ["Eggs", "Milk"]
var shoppingList2: [String] = ["Eggs", "Milk"]
var shoppingList3 = ["Eggs", 2] // WATCHOUT - Array with NSObject
var shoppingList4: [AnyObject] = ["Eggs", 2]
//: Array Count
print(shoppingList.count)
//: Check if it is Empty
if shoppingList.isEmpty {
result = "The shopping list is empty."
} else {
result = "The shopping list is not empty."
}
print(result)
if someInts.isEmpty {
result = "The integer list is empty."
} else {
result = "The integer list is not empty."
}
print(result)
//: Modifying an Array
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
shoppingList[0] = "Six eggs"
shoppingList.insert("Maple Syrup", atIndex: 0)
let mapleSyrup = shoppingList.removeAtIndex(0)
let apples = shoppingList.removeLast()
print(shoppingList)
//: Iterating Over an Array
for i in 0..<shoppingList.count {
print(shoppingList[i])
}
for item in shoppingList {
print(item)
}
for (index, value) in shoppingList.enumerate() {
print("\(index): \(value)")
}
//: Sorting Arrays
var sortShoppingList = shoppingList.sort()
sortShoppingList = shoppingList.sort({ (a: String, b: String) -> Bool in
return a > b
})
print(sortShoppingList)
//: Sorting Tuples/Objects
typealias MyTuple = (objectId: Int, name: String)
var customList: [MyTuple] = []
customList.append((objectId: 1, name: "First"))
customList.append((objectId: 2, name: "Second"))
customList.append((objectId: 3, name: "Third"))
customList.append((objectId: 4, name: "Fourth"))
customList = customList.sort({ (a: MyTuple, b: MyTuple) -> Bool in
return a.name < b.name
})
print(customList)
//: [Next](@next)
| mit | 82ae9ed3b8746b4ed0177585a7a0250d | 21.191919 | 72 | 0.686846 | 3.526485 | false | false | false | false |
itsmeichigo/DateTimePicker | Source/Bundle+Resource.swift | 1 | 1350 | //
// Bundle+Resource.swift
// DateTimePicker
//
// Created by Duy Tran on 10/9/20.
//
import Foundation
private class MyBundleFinder {}
extension Foundation.Bundle {
/**
The resource bundle associated with the current module..
- important: When `DateTimePicker` is distributed via Swift Package Manager, it will be synthesized automatically in the name of `Bundle.module`.
*/
static var resource: Bundle = {
let moduleName = "DateTimePicker"
#if COCOAPODS
let bundleName = moduleName
#else
let bundleName = "\(moduleName)_\(moduleName)"
#endif
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: MyBundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
fatalError("Unable to find bundle named \(bundleName)")
}()
}
| mit | 0b55c906af45728e0faa1cf186b56ba2 | 28.347826 | 150 | 0.607407 | 5.09434 | false | false | false | false |
rcbello/RLBCardsLayout | RLBCardsLayoutDemo/Pods/RLBCardsLayout/RLBCardsLayout/RLBCardsLayout.swift | 2 | 4814 | import UIKit
class RLBCardsLayout: UICollectionViewLayout {
static var visibleCellCount = 5
static var heightToWidth: CGFloat = 1.22
static var horizontalMargin: CGFloat = 30
static var cardYPositionDelta: CGFloat = 40
static var cardZPositionDelta: CGFloat = 140
fileprivate var normalItemSize = CGSize.zero {
didSet {
guard oldValue != normalItemSize else { return }
attributesByIndexPath.removeAll()
}
}
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
let bounds = collectionView.bounds
let size: CGSize
if (bounds.height / (bounds.width - RLBCardsLayout.horizontalMargin * 2)) > RLBCardsLayout.heightToWidth {
let width = (bounds.width - RLBCardsLayout.horizontalMargin * 2)
size = CGSize(width: width, height: ceil(width * RLBCardsLayout.heightToWidth))
} else {
size = CGSize(width: ceil(bounds.height/RLBCardsLayout.heightToWidth), height: bounds.height)
}
normalItemSize = size
}
override var collectionViewContentSize : CGSize {
guard let collectionView = collectionView else { return CGSize.zero }
let bounds = collectionView.bounds
let itemCount = (0..<collectionView.numberOfSections).reduce(0) { $0 + collectionView.numberOfItems(inSection: $1) }
return CGSize(width: bounds.width, height: CGFloat(itemCount) * bounds.height)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView, collectionView.contentSize == collectionViewContentSize else { return nil }
let bounds = collectionView.bounds
let frontRow = max(Int((bounds.maxY-1)/bounds.height), 0 )
let threeBack = max(frontRow - RLBCardsLayout.visibleCellCount, 0)
let attributes = (threeBack...frontRow).compactMap { row -> UICollectionViewLayoutAttributes? in
guard let indexPath = indexPathForIndex(row) else { return nil }
return layoutAttributesForItem(at: indexPath)
}
return attributes
}
fileprivate func indexPathForIndex(_ index: Int) -> IndexPath? {
guard let collectionView = collectionView else { return nil }
var cursor = index
for section in 0..<collectionView.numberOfSections {
let itemCount = collectionView.numberOfItems(inSection: section)
if cursor < itemCount {
return IndexPath(item: cursor, section: section)
} else {
cursor -= itemCount
}
}
return nil
}
fileprivate func indexForIndexPath(_ indexPath: IndexPath) -> Int {
guard let collectionView = collectionView else { return 0 }
var index = 0
for section in 0..<indexPath.section {
index += collectionView.numberOfItems(inSection: section)
}
index += indexPath.row
return index
}
fileprivate var attributesByIndexPath: [IndexPath: UICollectionViewLayoutAttributes] = [:]
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let collectionView = collectionView else { return nil }
let attributes: UICollectionViewLayoutAttributes
if let cachedAttr = attributesByIndexPath[indexPath] {
attributes = cachedAttr
} else {
attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
}
let bounds = collectionView.bounds
let index = indexForIndexPath(indexPath)
let frontIndex = Int((bounds.maxY)/bounds.height)
let backIndex = max(frontIndex - RLBCardsLayout.visibleCellCount, 0)
guard index >= backIndex && index <= frontIndex else {
attributes.isHidden = true
return attributes
}
let size = normalItemSize
let origin = CGPoint(x: bounds.midX - size.width/2, y: bounds.midY - size.height/2)
attributes.frame = CGRect(origin: origin, size: size)
attributes.zIndex = index
var transform = CATransform3DIdentity
let ratio = (bounds.minY - (bounds.height * CGFloat(index)))/bounds.height
transform.m34 = 1.0 / -1000
if index == frontIndex {
let angle = CGFloat.pi/2 * ratio
let radius = size.height/2
transform = CATransform3DTranslate(transform, 0, (1-cos(angle))*radius, 0)
transform = CATransform3DTranslate(transform, 0, 0, -sin(angle)*radius)
transform = CATransform3DRotate(transform, angle, 1, 0, 0)
attributes.transform3D = transform
attributes.alpha = 1+ratio
} else {
let delta = ratio * floor(size.height/RLBCardsLayout.cardYPositionDelta) * CGFloat(RLBCardsLayout.visibleCellCount)
transform = CATransform3DTranslate(transform, 0, 0, -(ratio * RLBCardsLayout.cardZPositionDelta))
transform = CATransform3DTranslate(transform, 0, -delta, 0)
attributes.transform3D = transform
attributes.alpha = 1 - (ratio/CGFloat(RLBCardsLayout.visibleCellCount))
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| mit | a25b8952e2abd9a23eaba2dde8eaa930 | 36.609375 | 120 | 0.73951 | 4.211724 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/FieldTag.swift | 1 | 2568 | // Sources/SwiftProtobuf/FieldTag.swift - Describes a binary field tag
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Types related to binary encoded tags (field numbers and wire formats).
///
// -----------------------------------------------------------------------------
/// Encapsulates the number and wire format of a field, which together form the
/// "tag".
///
/// This type also validates tags in that it will never allow a tag with an
/// improper field number (such as zero) or wire format (such as 6 or 7) to
/// exist. In other words, a `FieldTag`'s properties never need to be tested
/// for validity because they are guaranteed correct at initialization time.
internal struct FieldTag: RawRepresentable {
typealias RawValue = UInt32
/// The raw numeric value of the tag, which contains both the field number and
/// wire format.
let rawValue: UInt32
/// The field number component of the tag.
var fieldNumber: Int {
return Int(rawValue >> 3)
}
/// The wire format component of the tag.
var wireFormat: WireFormat {
// This force-unwrap is safe because there are only two initialization
// paths: one that takes a WireFormat directly (and is guaranteed valid at
// compile-time), or one that takes a raw value but which only lets valid
// wire formats through.
return WireFormat(rawValue: UInt8(rawValue & 7))!
}
/// A helper property that returns the number of bytes required to
/// varint-encode this tag.
var encodedSize: Int {
return Varint.encodedSize(of: rawValue)
}
/// Creates a new tag from its raw numeric representation.
///
/// Note that if the raw value given here is not a valid tag (for example, it
/// has an invalid wire format), this initializer will fail.
init?(rawValue: UInt32) {
// Verify that the field number and wire format are valid and fail if they
// are not.
guard rawValue & ~0x07 != 0,
let _ = WireFormat(rawValue: UInt8(rawValue % 8)) else {
return nil
}
self.rawValue = rawValue
}
/// Creates a new tag by composing the given field number and wire format.
init(fieldNumber: Int, wireFormat: WireFormat) {
self.rawValue = UInt32(truncatingBitPattern: fieldNumber) << 3 |
UInt32(wireFormat.rawValue)
}
}
| mit | 6fa2f4d1aa375923d108c21940e652a6 | 36.217391 | 80 | 0.658879 | 4.513181 | false | false | false | false |
AlexQuinlivan/Contrivd | Contrivd/StoryViewController.swift | 1 | 5252 | //
// StoryViewController.swift
// Contrivd
//
// Created by Alex Quinlivan on 20/07/15.
// Copyright (c) 2015 Alex Quinlivan. All rights reserved.
//
import UIKit
class StoryViewController: HLMViewController {
var story: CTRStuffStory!
var origRect: CGRect!
weak var storyContent: UILabel?
weak var storySource: UILabel?
weak var container: UIView?
weak var scrollViewChrome: CTRListStoryCell?
var snapshotView: UIView?
var textSize: CGFloat?
var viewHasPreviouslyAppeared: Bool = false
override var layoutResource: String {
return "@view/vc_story"
}
init(story: CTRStuffStory!, cellRect: CGRect, snapshot: UIView!) {
super.init(nibName: nil, bundle: nil)
self.story = story
self.origRect = cellRect
self.snapshotView = snapshot
navigationItem.rightBarButtonItem = createRightBarButtonItem()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
bindViews()
if let textSize = self.textSize {
storyContent?.hlm_textSize = textSize
} else {
textSize = storyContent?.hlm_textSize
}
storyContent?.attributedText = story.attributedBody()
storySource?.text = story.sourceName
scrollViewChrome?.story = story
toggleFontSize()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !viewHasPreviouslyAppeared {
viewHasPreviouslyAppeared = true
animateIn()
}
}
func bindViews() {
storyContent = view.hlm_viewWithId(UInt(bitPattern: "content".hash)) as? UILabel
storySource = view.hlm_viewWithId(UInt(bitPattern: "source".hash)) as? UILabel
container = view.hlm_viewWithId(UInt(bitPattern: "container".hash))
scrollViewChrome = view.hlm_viewWithId(UInt(bitPattern: "story_cell".hash)) as? CTRListStoryCell
}
func toggleFontSize() {
if var textSize = self.textSize {
textSize += 2
if textSize > 32 {
textSize = 12
}
self.textSize = textSize
storyContent?.hlm_textSize = textSize
}
}
func animateIn() {
let animDuration = 0.6
let origRect = self.origRect
if let chrome = snapshotView {
scrollViewChrome?.alpha = 0
navigationController?.view.insertSubview(
chrome,
belowSubview: navigationController!.navigationBar)
chrome.frame = origRect
chrome.clipsToBounds = false
chrome.layer.shadowColor = UIColor.blackColor().CGColor
chrome.layer.shadowRadius = 0
chrome.layer.shadowOpacity = 0.5
chrome.layer.addAnimation(
createShadowOffsetAnimation(animDuration),
forKey: "shadowOffset")
chrome.layer.addAnimation(
createShadowRadiusAnimation(animDuration),
forKey: "shadowRadius")
let navBarFrame = navigationController!.navigationBar.frame
UIView.animateWithDuration(animDuration, animations: {
var newRect = origRect
newRect.origin.y = navBarFrame.size.height + navBarFrame.origin.y
chrome.frame = newRect
}, completion: { _ in
chrome.removeFromSuperview()
self.snapshotView = nil
self.scrollViewChrome?.alpha = 1
})
Dispatch.delay(0.05) {
UIView.animateWithDuration((animDuration / 2) - 0.05, animations: {
chrome.transform = CGAffineTransformScale(chrome.transform, 1.05, 1.05)
}, completion: { _ in
UIView.animateWithDuration(animDuration / 2, animations: {
chrome.transform = CGAffineTransformIdentity
})
})
}
}
}
func createRightBarButtonItem() -> UIBarButtonItem {
return UIBarButtonItem(
image: UIImage(named: "font-size"),
style: .Plain,
target: self,
action: "toggleFontSize")
}
func createShadowOffsetAnimation(duration: CFTimeInterval) -> CABasicAnimation {
let anim = CABasicAnimation(keyPath: "shadowOffset")
anim.fromValue = NSValue(CGSize: .zeroSize)
anim.toValue = NSValue(CGSize: CGSize(width: 0, height: 6))
anim.duration = duration / 2.0
anim.autoreverses = true
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return anim
}
func createShadowRadiusAnimation(duration: CFTimeInterval) -> CABasicAnimation {
let anim = CABasicAnimation(keyPath: "shadowRadius")
anim.fromValue = NSNumber(integer: 0)
anim.toValue = NSNumber(integer: 10)
anim.duration = duration / 2.0
anim.autoreverses = true
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return anim
}
}
| apache-2.0 | bcf4aeb900ddb314256f11383435c53b | 34.013333 | 104 | 0.604341 | 5.231076 | false | false | false | false |
Ramotion/navigation-stack | Source/CollectionView/FlowLayout/CollectionViewStackFlowLayout.swift | 1 | 5867 | //
// CollectionViewStackFlowLayout.swift
// NavigationStackDemo
//
// Copyright (c) 26/02/16 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: CollectionViewStackFlowLayout
class CollectionViewStackFlowLayout: UICollectionViewFlowLayout {
let itemsCount: Int
let overlay: Float // from 0 to 1
let maxScale: Float
let scaleRatio: Float
var additionScale = 1.0
var openAnimating = false
var dxOffset: Float = 0
init(itemsCount: Int, overlay: Float, scaleRatio: Float, scale: Float) {
self.itemsCount = itemsCount
self.overlay = overlay
self.scaleRatio = scaleRatio
maxScale = scale
super.init()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CollectionViewStackFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let items = NSArray(array: super.layoutAttributesForElements(in: rect)!, copyItems: true)
var headerAttributes: UICollectionViewLayoutAttributes?
items.enumerateObjects({ (object, _, _) -> Void in
let attributes = object as! UICollectionViewLayoutAttributes
if attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
headerAttributes = attributes
} else {
self.updateCellAttributes(attributes, headerAttributes: headerAttributes)
}
})
return items as? [UICollectionViewLayoutAttributes]
}
func updateCellAttributes(_ attributes: UICollectionViewLayoutAttributes, headerAttributes _: UICollectionViewLayoutAttributes?) {
guard let collectionView = self.collectionView else {
return
}
let itemWidth = collectionView.bounds.size.width - collectionView.bounds.size.width * CGFloat(overlay)
let allWidth = itemWidth * CGFloat(itemsCount - 1)
// set contentOffset range
let contentOffsetX = min(max(0, collectionView.contentOffset.x), allWidth)
let scale = transformScale(attributes, allWidth: allWidth, offset: contentOffsetX)
let move = transformMove(attributes, itemWidth: itemWidth, offset: contentOffsetX)
attributes.transform = scale.concatenating(move)
attributes.alpha = calculateAlpha(attributes, itemWidth: itemWidth, offset: contentOffsetX)
if additionScale > 0 && openAnimating {
additionScale -= 0.02
additionScale = additionScale < 0 ? 0 : additionScale
}
attributes.zIndex = (attributes.indexPath as NSIndexPath).row
}
override func shouldInvalidateLayout(forBoundsChange _: CGRect) -> Bool {
return true
}
}
// MARK: helpers
extension CollectionViewStackFlowLayout {
fileprivate func transformScale(_ attributes: UICollectionViewLayoutAttributes,
allWidth: CGFloat,
offset: CGFloat) -> CGAffineTransform {
var maximum = CGFloat(maxScale) - CGFloat(itemsCount - (attributes.indexPath as NSIndexPath).row) / CGFloat(scaleRatio)
maximum += CGFloat(1.0 - maximum) * CGFloat(additionScale)
var minimum = CGFloat(maxScale - 0.1) - CGFloat(itemsCount - (attributes.indexPath as NSIndexPath).row) / CGFloat(scaleRatio)
minimum += CGFloat(1.0 - minimum) * CGFloat(additionScale)
var currentScale = (maximum + minimum) - (minimum + offset / (allWidth / (maximum - minimum)))
currentScale = max(min(maximum, currentScale), minimum)
return CGAffineTransform(scaleX: currentScale, y: currentScale)
}
fileprivate func transformMove(_ attributes: UICollectionViewLayoutAttributes,
itemWidth: CGFloat,
offset: CGFloat) -> CGAffineTransform {
var currentContentOffsetX = offset - itemWidth * CGFloat((attributes.indexPath as NSIndexPath).row)
currentContentOffsetX = min(max(currentContentOffsetX, 0), itemWidth)
var dx = (currentContentOffsetX / itemWidth)
if let collectionView = self.collectionView {
dx *= collectionView.bounds.size.width / 8.0
}
dx = currentContentOffsetX - dx
return CGAffineTransform(translationX: dx, y: 0)
}
fileprivate func calculateAlpha(_ attributes: UICollectionViewLayoutAttributes, itemWidth: CGFloat, offset: CGFloat) -> CGFloat {
var currentContentOffsetX = offset - itemWidth * CGFloat((attributes.indexPath as NSIndexPath).row)
currentContentOffsetX = min(max(currentContentOffsetX, 0), itemWidth)
let dx = (currentContentOffsetX / itemWidth)
return 1.0 - dx
}
}
| mit | f2cdf293ee7641b7389f4c8d2fd660d2 | 40.316901 | 134 | 0.690131 | 5.478058 | false | false | false | false |
ipagong/PGTabBar-Swift | PGTabBar/Classes/TabUtils.swift | 1 | 2232 | //
// TabUtils.swift
// Pods
//
// Created by ipagong on 2017. 4. 19..
//
//
import Foundation
public class TabText {
private var text:String = ""
private var attributes:[String:Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15), NSForegroundColorAttributeName: UIColor.black]
public class func title(_ title:String) -> TabText {
let text = TabText()
text.text = title
return text
}
public func title(_ title:String) -> TabText {
self.text = title
return self
}
public func font(_ font:UIFont) -> TabText {
self.attributes.updateValue(font, forKey: NSFontAttributeName)
return self
}
public func font(size:CGFloat) -> TabText {
self.attributes.updateValue(UIFont.systemFont(ofSize: size), forKey: NSFontAttributeName)
return self
}
public func boldFont(size:CGFloat) -> TabText {
self.attributes.updateValue(UIFont.boldSystemFont(ofSize: size), forKey: NSFontAttributeName)
return self
}
public func color(_ color:UIColor) -> TabText {
self.attributes.updateValue(color, forKey: NSForegroundColorAttributeName)
return self
}
public func add(_ value:Any, attrKey:String) -> TabText {
self.attributes.updateValue(value, forKey: attrKey)
return self
}
public var attrText:NSAttributedString {
return NSAttributedString(string: text, attributes: attributes)
}
}
public struct TabStateElement<Element:Any> {
var normal:Element
var selected:Element?
var highlighted:Element?
var disabled:Element?
public init(common:Element) {
self.normal = common
self.selected = common
self.highlighted = common
self.disabled = common
}
public init(normal:Element, selected:Element, highlighted:Element, disabled:Element) {
self.normal = normal
self.selected = selected
self.highlighted = highlighted
self.disabled = disabled
}
}
extension NSInteger {
func indexPath(_ section:NSInteger? = 0) -> IndexPath { return IndexPath(row: self, section: section!) }
}
| mit | e89a9d504980a6211a40d8d3f8aafebb | 26.555556 | 142 | 0.638441 | 4.630705 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/MIDI/AKMIDI+SendingMIDI.swift | 1 | 3617 | //
// AKMIDI+SendingMIDI.swift
// AudioKit For OSX
//
// Created by Aurelius Prochazka on 4/30/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
extension AKMIDI {
/// Array of destination names
public var destinationNames: [String] {
var nameArray = [String]()
let outputCount = MIDIGetNumberOfDestinations()
for i in 0 ..< outputCount {
let destination = MIDIGetDestination(i)
var endpointName: Unmanaged<CFString>?
endpointName = nil
MIDIObjectGetStringProperty(destination, kMIDIPropertyName, &endpointName)
let endpointNameStr = (endpointName?.takeRetainedValue())! as String
nameArray.append(endpointNameStr)
}
return nameArray
}
/// Open a MIDI Output Port
///
/// - parameter namedOutput: String containing the name of the MIDI Input
///
public func openOutput(namedOutput: String = "") {
var result = noErr
let outputCount = MIDIGetNumberOfDestinations()
var foundDest = false
result = MIDIOutputPortCreate(client, outputPortName, &outputPort)
if result != noErr {
print("Error creating MIDI output port : \(result)")
}
for i in 0 ..< outputCount {
let src = MIDIGetDestination(i)
var endpointName: Unmanaged<CFString>? = nil
MIDIObjectGetStringProperty(src, kMIDIPropertyName, &endpointName)
let endpointNameStr = (endpointName?.takeRetainedValue())! as String
if namedOutput.isEmpty || namedOutput == endpointNameStr {
print("Found destination at \(endpointNameStr)")
endpoints.append(MIDIGetDestination(i))
foundDest = true
}
}
if !foundDest {
print("no midi destination found named \"\(namedOutput)\"")
}
}
/// Send Message with data
public func sendMessage(data: [UInt8]) {
var result = noErr
let packetListPointer: UnsafeMutablePointer<MIDIPacketList> = UnsafeMutablePointer.alloc(1)
var packet: UnsafeMutablePointer<MIDIPacket> = nil
packet = MIDIPacketListInit(packetListPointer)
packet = MIDIPacketListAdd(packetListPointer, 1024, packet, 0, data.count, data)
for _ in 0 ..< endpoints.count {
result = MIDISend(outputPort, endpoints[0], packetListPointer)
if result != noErr {
print("error sending midi : \(result)")
}
}
if virtualOutput != 0 {
MIDIReceived(virtualOutput, packetListPointer)
}
packetListPointer.destroy()
packetListPointer.dealloc(1)//necessary? wish i could do this without the alloc above
}
/// Send Messsage from midi event data
public func sendEvent(event: AKMIDIEvent) {
sendMessage(event.internalData)
}
/// Send a Note On Message
public func sendNoteMessage(note: Int, velocity: Int, channel: Int = 0) {
let noteCommand: UInt8 = UInt8(0x90) + UInt8(channel)
let message: [UInt8] = [noteCommand, UInt8(note), UInt8(velocity)]
self.sendMessage(message)
}
/// Send a Continuous Controller message
public func sendControllerMessage(control: Int, value: Int, channel: Int = 0) {
let controlCommand: UInt8 = UInt8(0xB0) + UInt8(channel)
let message: [UInt8] = [controlCommand, UInt8(control), UInt8(value)]
self.sendMessage(message)
}
}
| apache-2.0 | 6c863cab33ae4ade7ed9243e1959a4e4 | 35.16 | 99 | 0.609513 | 4.879892 | false | false | false | false |
maple1994/RxZhiHuDaily | RxZhiHuDaily/Controller/MPThemeViewController.swift | 1 | 4965 | //
// MPOtherTypeViewController.swift
// RxZhiHuDaily
//
// Created by Maple on 2017/9/21.
// Copyright © 2017年 Maple. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import SnapKit
/// 主题列表控制器
class MPThemeViewController: UIViewController {
fileprivate let disposeBag = DisposeBag()
fileprivate var stroies = Variable([MPStoryModel]())
/// 菜单栏Item
var themeModel: MPMenuItemModel? {
didSet{
navigationItem.title = themeModel?.name
if let urlString = themeModel?.thumbnail {
headerImg.kf.setImage(with: URL.init(string: urlString), placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, _, _, _) in
self.navImgV.image = image
})
}
if let id = themeModel?.id {
MPApiService.shareAPI.loadThemeList(ID: id)
.asDriver(onErrorJustReturn: [])
.drive(stroies)
.addDisposableTo(disposeBag)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
tableView.register(NewsTableViewCell.self, forCellReuseIdentifier: "ThemeCellID")
tableView.rowHeight = 100
backBtn.rx.tap
.subscribe(onNext: {
self.slideMenuController()?.openLeft()
})
.addDisposableTo(disposeBag)
stroies.asDriver()
.drive(tableView.rx.items(cellIdentifier: "ThemeCellID", cellType: NewsTableViewCell.self)) { (row, element, cell) in
cell.model = element
}
.addDisposableTo(disposeBag)
tableView.rx.contentOffset
.filter { $0.y < 0 }
.map { $0.y }
.subscribe(onNext: { offsetY in
self.headerImg.frame.origin.y = offsetY
self.headerImg.frame.size.height = 64 - offsetY
})
.addDisposableTo(disposeBag)
tableView.rx
.itemSelected
.subscribe(onNext: { indexPath in
self.showDetailVC(indexPath: indexPath)
})
.addDisposableTo(disposeBag)
tableView.rx
.contentOffset
.map { $0.y }
.subscribe(onNext: { y in
self.navView.alpha = (y > 0) ? 1 : 0
})
.addDisposableTo(disposeBag)
}
fileprivate func showDetailVC(indexPath: IndexPath) {
var idArr = [Int]()
let sectionModel = self.stroies.value
for item in sectionModel {
if let id = item.id {
idArr.append(id)
}
}
let detailVC = MPNewsDetailViewController(idArr: idArr, index: indexPath.row)
self.navigationController?.pushViewController(detailVC, animated: true)
}
fileprivate func setupUI() {
automaticallyAdjustsScrollViewInsets = false
view.addSubview(tableView)
view.addSubview(navView)
navView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(-64)
make.leading.trailing.equalToSuperview()
make.height.equalTo(64)
}
navView.alpha = 0
navView.addSubview(navImgV)
navImgV.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
tableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(-64)
make.leading.trailing.bottom.equalToSuperview()
}
tbHeaderView.frame = CGRect(x: 0, y: 0 , width: screenW, height: 64)
headerImg.frame = tbHeaderView.frame
tbHeaderView.addSubview(headerImg)
tableView.tableHeaderView = tbHeaderView
// 设置导航栏
navigationController?.navigationBar.subviews.first?.alpha = 0
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.tintColor = UIColor.white
backBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 60))
backBtn.setImage(UIImage.init(named: "Back_White"), for: .normal)
backBtn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -20, bottom: 0, right: 60)
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: backBtn)
}
// MARK: - View
fileprivate lazy var navView = UIView()
fileprivate lazy var navImgV = UIImageView()
fileprivate lazy var tableView = UITableView()
fileprivate var backBtn: UIButton!
fileprivate lazy var headerImg = UIImageView()
fileprivate lazy var tbHeaderView = UIView()
}
| mit | f9db1f5b7dd382f2d1e16666a3e3b656 | 32.100671 | 165 | 0.599757 | 4.936937 | false | false | false | false |
Mai-Tai-D/maitaid001 | maitaid002/ExamplesDefaults.swift | 2 | 3207 | //
// ExamplesDefaults.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
struct ExamplesDefaults {
static var chartSettings: ChartSettings {
if Env.iPad {
return iPadChartSettings
} else {
return iPhoneChartSettings
}
}
static var chartSettingsWithPanZoom: ChartSettings {
if Env.iPad {
return iPadChartSettingsWithPanZoom
} else {
return iPhoneChartSettingsWithPanZoom
}
}
fileprivate static var iPadChartSettings: ChartSettings {
var chartSettings = ChartSettings()
chartSettings.leading = 20
chartSettings.top = 20
chartSettings.trailing = 20
chartSettings.bottom = 20
chartSettings.labelsToAxisSpacingX = 10
chartSettings.labelsToAxisSpacingY = 10
chartSettings.axisTitleLabelsToLabelsSpacing = 5
chartSettings.axisStrokeWidth = 1
chartSettings.spacingBetweenAxesX = 15
chartSettings.spacingBetweenAxesY = 15
chartSettings.labelsSpacing = 0
return chartSettings
}
fileprivate static var iPhoneChartSettings: ChartSettings {
var chartSettings = ChartSettings()
chartSettings.leading = 10
chartSettings.top = 10
chartSettings.trailing = 10
chartSettings.bottom = 10
chartSettings.labelsToAxisSpacingX = 5
chartSettings.labelsToAxisSpacingY = 5
chartSettings.axisTitleLabelsToLabelsSpacing = 4
chartSettings.axisStrokeWidth = 0.2
chartSettings.spacingBetweenAxesX = 8
chartSettings.spacingBetweenAxesY = 8
chartSettings.labelsSpacing = 0
return chartSettings
}
fileprivate static var iPadChartSettingsWithPanZoom: ChartSettings {
var chartSettings = iPadChartSettings
chartSettings.zoomPan.panEnabled = true
chartSettings.zoomPan.zoomEnabled = true
return chartSettings
}
fileprivate static var iPhoneChartSettingsWithPanZoom: ChartSettings {
var chartSettings = iPhoneChartSettings
chartSettings.zoomPan.panEnabled = true
chartSettings.zoomPan.zoomEnabled = true
return chartSettings
}
static func chartFrame(_ containerBounds: CGRect) -> CGRect {
return CGRect(x: 0, y: 70, width: containerBounds.size.width, height: containerBounds.size.height - 70)
}
static var labelSettings: ChartLabelSettings {
return ChartLabelSettings(font: ExamplesDefaults.labelFont)
}
static var labelFont: UIFont {
return ExamplesDefaults.fontWithSize(Env.iPad ? 14 : 11)
}
static var labelFontSmall: UIFont {
return ExamplesDefaults.fontWithSize(Env.iPad ? 12 : 10)
}
static func fontWithSize(_ size: CGFloat) -> UIFont {
return UIFont(name: "Helvetica", size: size) ?? UIFont.systemFont(ofSize: size)
}
static var guidelinesWidth: CGFloat {
return Env.iPad ? 0.5 : 0.1
}
static var minBarSpacing: CGFloat {
return Env.iPad ? 10 : 5
}
}
| mit | 63f6d7939b5ae9b0e77c33e9a2d49285 | 30.135922 | 111 | 0.665419 | 5.799277 | false | false | false | false |
wenluma/swift | test/IRGen/generic_types.swift | 1 | 5944 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: CPU=x86_64
// CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }>
// CHECK: [[INT]] = type <{ i64 }>
// CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }>
// CHECK: [[C:%T13generic_types1CC]] = type
// CHECK: [[D:%T13generic_types1DC]] = type
// CHECK-LABEL: @_T013generic_types1ACMP = internal global
// CHECK: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_A,
// CHECK-native-SAME: i32 160,
// CHECK-objc-SAME: i32 344,
// CHECK-SAME: i16 1,
// CHECK-SAME: i16 16,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[A]]*)* @_T013generic_types1ACfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 152,
// CHECK-SAME: i32 16,
// CHECK-SAME: %swift.type* null,
// CHECK-SAME: void (%swift.opaque*, [[A]]*)* @_T013generic_types1AC3run{{[_0-9a-zA-Z]*}}F
// CHECK-SAME: %T13generic_types1AC* (i64, %T13generic_types1AC*)* @_T013generic_types1ACACyxGSi1y_tcfc
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1BCMP = internal global
// CHECK-SAME: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_B,
// CHECK-native-SAME: i32 152,
// CHECK-objc-SAME: i32 336,
// CHECK-SAME: i16 1,
// CHECK-SAME: i16 16,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[B]]*)* @_T013generic_types1BCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 144,
// CHECK-SAME: i32 16,
// CHECK-SAME: %swift.type* null
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1CCMP = internal global
// CHECK-SAME: void ([[C]]*)* @_T013generic_types1CCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: }
// CHECK-LABEL: @_T013generic_types1DCMP = internal global
// CHECK-SAME: void ([[D]]*)* @_T013generic_types1DCfD,
// CHECK-SAME: i8** @_T0BoWV,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_A(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]])
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_B(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]])
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
class A<T> {
var x = 0
func run(_ t: T) {}
init(y : Int) {}
}
class B<T> {
var ptr : UnsafeMutablePointer<T>
init(ptr: UnsafeMutablePointer<T>) {
self.ptr = ptr
}
deinit {
ptr.deinitialize()
}
}
class C<T> : A<Int> {}
class D<T> : A<Int> {
override func run(_ t: Int) {}
}
struct E<T> {
var x : Int
func foo() { bar() }
func bar() {}
}
class ClassA {}
class ClassB {}
// This type is fixed-size across specializations, but it needs to use
// a different implementation in IR-gen so that types match up.
// It just asserts if we get it wrong.
struct F<T: AnyObject> {
var value: T
}
func testFixed() {
var a = F(value: ClassA()).value
var b = F(value: ClassB()).value
}
| mit | 5292a5673d9d6e5b84998afdcf070c4d | 38.364238 | 147 | 0.6107 | 2.780168 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/Starscream/WebSocket.swift | 3 | 30599 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import Security
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : Array<String>?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((NSData) -> Void)?
public var onPong: ((Void) -> Void)?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var isConnected :Bool {
return connected
}
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var isCreated = false
private var writeQueue = NSOperationQueue()
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
//init the websocket with a url
public init(url: NSURL) {
self.url = url
writeQueue.maxConcurrentOperationCount = 1
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
///Connect to the websocket server on a background thread
public func connect() {
if isCreated {
return
}
dispatch_async(queue,{ [weak self] in
self?.didDisconnect = false
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { [weak self] in
self?.isCreated = true
self?.createHTTPRequest()
self?.isCreated = false
})
}
///disconnect from the websocket server
public func disconnect(forceTimeout: Int = 0) {
writeError(CloseCode.Normal.rawValue)
if forceTimeout > 0 { //not needed most of the time, for an edge case
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(forceTimeout) * Int64(NSEC_PER_SEC)), queue, { [unowned self] in
self.disconnectStream(nil)
})
}
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest, Int(port!))
}
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest,
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if (resIn != errSecSuccess) {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if (resOut != errSecSuccess) {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
isRunLoop = true
inStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inStream.open()
outStream.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outStream.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if let sec = security where !certValidated && (eventCode == .HasBytesAvailable || eventCode == .HasSpaceAvailable) {
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
if let trust: AnyObject = possibleTrust {
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
}
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
writeQueue.waitUntilAllOperationsAreFinished()
if let stream = inputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
if let stream = outputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
outputStream = nil
isRunLoop = false
certValidated = false
doDisconnect(error)
connected = false
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
connected = processHTTP(buffer, bufferLen: length)
if !connected {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, length)
let code = CFHTTPMessageGetResponseStatusCode(response)
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
} else {
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if fragBuffer != nil {
let combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{ [weak self] in
guard let s = self else { return }
if let connectBlock = s.onConnect {
connectBlock()
}
s.delegate?.websocketDidConnect(s)
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
return false
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
let offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
let codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].bigEndian
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = UnsafePointer<UInt8>((buffer+offset))
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
doDisconnect(errorWithDetail("connection closed by server", code: code))
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].bigEndian
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].bigEndian)
offset += sizeof(UInt16)
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
dispatch_async(queue,{ [weak self] in
guard let s = self else { return }
if let pongBlock = s.onPong {
pongBlock()
}
s.pongDelegate?.websocketDidReceivePong(s)
})
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{ [weak self] in
guard let s = self else { return }
if let textBlock = s.onText {
textBlock(str! as String)
}
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{ [weak self] in
guard let s = self else { return }
if let dataBlock = s.onData {
dataBlock(data)
}
s.delegate?.websocketDidReceiveData(s, data: data)
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
let buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.bigEndian
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode) {
if !isConnected {
return
}
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
var offset = 2
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
let sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).bigEndian
offset += sizeof(UInt16)
} else {
buffer[1] = 127
let sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).bigEndian
offset += sizeof(UInt64)
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if !s.isConnected {
break
}
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: NSError?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error)
break
} else {
total += len
}
if total >= offset {
break
}
}
}
}
///used to preform the disconnect delegate
private func doDisconnect(error: NSError?) {
if !didDisconnect {
dispatch_async(queue,{ [weak self] in
guard let s = self else { return }
s.didDisconnect = true
if let disconnect = s.onDisconnect {
disconnect(error)
}
s.delegate?.websocketDidDisconnect(s, error: error)
})
}
}
}
| mit | 8cc24d05ce5f0195ffe235c149e89b44 | 40.973937 | 151 | 0.558711 | 5.516315 | false | false | false | false |
tbkka/swift-protobuf | Sources/SwiftProtobuf/Google_Protobuf_FieldMask+Extensions.swift | 4 | 4872 | // Sources/SwiftProtobuf/Google_Protobuf_FieldMask+Extensions.swift - Fieldmask extensions
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extend the generated FieldMask message with customized JSON coding and
/// convenience methods.
///
// -----------------------------------------------------------------------------
// TODO: We should have utilities to apply a fieldmask to an arbitrary
// message, intersect two fieldmasks, etc.
private func ProtoToJSON(name: String) -> String? {
var jsonPath = String()
var chars = name.makeIterator()
while let c = chars.next() {
switch c {
case "_":
if let toupper = chars.next() {
switch toupper {
case "a"..."z":
jsonPath.append(String(toupper).uppercased())
default:
return nil
}
} else {
return nil
}
case "A"..."Z":
return nil
default:
jsonPath.append(c)
}
}
return jsonPath
}
private func JSONToProto(name: String) -> String? {
var path = String()
for c in name {
switch c {
case "_":
return nil
case "A"..."Z":
path.append(Character("_"))
path.append(String(c).lowercased())
default:
path.append(c)
}
}
return path
}
private func parseJSONFieldNames(names: String) -> [String]? {
// An empty field mask is the empty string (no paths).
guard !names.isEmpty else { return [] }
var fieldNameCount = 0
var fieldName = String()
var split = [String]()
for c in names {
switch c {
case ",":
if fieldNameCount == 0 {
return nil
}
if let pbName = JSONToProto(name: fieldName) {
split.append(pbName)
} else {
return nil
}
fieldName = String()
fieldNameCount = 0
default:
fieldName.append(c)
fieldNameCount += 1
}
}
if fieldNameCount == 0 { // Last field name can't be empty
return nil
}
if let pbName = JSONToProto(name: fieldName) {
split.append(pbName)
} else {
return nil
}
return split
}
extension Google_Protobuf_FieldMask {
/// Creates a new `Google_Protobuf_FieldMask` from the given array of paths.
///
/// The paths should match the names used in the .proto file, which may be
/// different than the corresponding Swift property names.
///
/// - Parameter protoPaths: The paths from which to create the field mask,
/// defined using the .proto names for the fields.
public init(protoPaths: [String]) {
self.init()
paths = protoPaths
}
/// Creates a new `Google_Protobuf_FieldMask` from the given paths.
///
/// The paths should match the names used in the .proto file, which may be
/// different than the corresponding Swift property names.
///
/// - Parameter protoPaths: The paths from which to create the field mask,
/// defined using the .proto names for the fields.
public init(protoPaths: String...) {
self.init(protoPaths: protoPaths)
}
/// Creates a new `Google_Protobuf_FieldMask` from the given paths.
///
/// The paths should match the JSON names of the fields, which may be
/// different than the corresponding Swift property names.
///
/// - Parameter jsonPaths: The paths from which to create the field mask,
/// defined using the JSON names for the fields.
public init?(jsonPaths: String...) {
// TODO: This should fail if any of the conversions from JSON fails
#if swift(>=4.1)
self.init(protoPaths: jsonPaths.compactMap(JSONToProto))
#else
self.init(protoPaths: jsonPaths.flatMap(JSONToProto))
#endif
}
// It would be nice if to have an initializer that accepted Swift property
// names, but translating between swift and protobuf/json property
// names is not entirely deterministic.
}
extension Google_Protobuf_FieldMask: _CustomJSONCodable {
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
let s = try decoder.scanner.nextQuotedString()
if let names = parseJSONFieldNames(names: s) {
paths = names
} else {
throw JSONDecodingError.malformedFieldMask
}
}
func encodedJSONString(options: JSONEncodingOptions) throws -> String {
// Note: Proto requires alphanumeric field names, so there
// cannot be a ',' or '"' character to mess up this formatting.
var jsonPaths = [String]()
for p in paths {
if let jsonPath = ProtoToJSON(name: p) {
jsonPaths.append(jsonPath)
} else {
throw JSONEncodingError.fieldMaskConversion
}
}
return "\"" + jsonPaths.joined(separator: ",") + "\""
}
}
| apache-2.0 | 84336529b6aa3c2b183536e62764d1f8 | 28.889571 | 90 | 0.629516 | 4.417044 | false | false | false | false |
NikolaevSergey/KRDeviceInfo | ExampleApp/ExampleApp/ViewController.swift | 1 | 1097 | //
// ViewController.swift
// ExampleApp
//
// Created by Kruperfone on 16.11.15.
// Copyright © 2015 Sergey Nikolaev. All rights reserved.
//
import UIKit
import KRDeviceInfo
class ViewController: UIViewController {
@IBOutlet weak var machineLabel : UILabel!
@IBOutlet weak var humanLabel : UILabel!
@IBOutlet weak var sizeLabel : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let model = KRDeviceModel()
let screen = KRDeviceSize()
var machineText: String = ""
for str in model.machineNames {
if machineText.characters.count > 0 {
machineText += ", "
}
machineText += str
}
self.machineLabel.text = machineText
self.humanLabel.text = model.humanName
self.sizeLabel.text = screen?.description ?? "Unknow size type"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 596a00e576c114cfc0ba4c7dd813d55c | 23.355556 | 75 | 0.596715 | 4.744589 | false | false | false | false |
mattiasjahnke/SerialTyper | SerialTyper/AppDelegate.swift | 1 | 1260 | //
// AppDelegate.swift
// SerialTyper
//
// Created by Mattias Jähnke on 2017-05-21.
// Copyright © 2017 Mattias Jähnke. All rights reserved.
//
import Cocoa
var terminateAppOnSerialClose = false
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
if !accessEnabled {
let alert = NSAlert()
alert.messageText = "SerialTyper"
alert.informativeText = "You need to enable accessibility for SerialTyper (see dialog behind this one) in System Preferences and launch this app again."
alert.addButton(withTitle: "OK")
alert.runModal()
NSApp.terminate(self)
}
// Listen for serial port close
// This workaround aims to fix a problem with kernel panics when terminating the app
NotificationCenter.default.addObservers(forNames: .serialPortClosed) { _ in
guard terminateAppOnSerialClose else { return }
NSApp.terminate(self)
}
}
}
| mit | 322ab3005fe5b98657c4bf8e9f73633b | 34.914286 | 164 | 0.674622 | 4.834615 | false | false | false | false |
tkremenek/swift | test/Interop/Cxx/namespace/classes-module-interface.swift | 1 | 2201 | // RUN: %target-swift-ide-test -print-module -module-to-print=Classes -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s
// CHECK-NOT: extension
// CHECK: extension ClassesNS1.ClassesNS2 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK: }
// CHECK: struct ForwardDeclaredStruct {
// CHECK: init()
// CHECK: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK: }
// CHECK: }
// CHECK-NOT: extension
// CHECK: extension ClassesNS1 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK: }
// CHECK: struct ForwardDeclaredStruct {
// CHECK: init()
// CHECK: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK: }
// CHECK: }
// CHECK-NOT: extension
// CHECK: extension ClassesNS3 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK: }
// CHECK: }
// CHECK-NOT: extension
// CHECK: typealias GlobalAliasToNS1 = ClassesNS1
// CHECK: extension ClassesNS4 {
// CHECK: typealias AliasToGlobalNS1 = ClassesNS1
// CHECK: typealias AliasToGlobalNS2 = ClassesNS1.ClassesNS2
// CHECK: typealias AliasToInnerNS5 = ClassesNS4.ClassesNS5
// CHECK: typealias AliasToNS2 = ClassesNS1.ClassesNS2
// CHECK: typealias AliasChainToNS1 = ClassesNS1
// CHECK: typealias AliasChainToNS2 = ClassesNS1.ClassesNS2
// CHECK: }
// CHECK: extension ClassesNS4.ClassesNS5 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: }
// CHECK: }
// CHECK: extension ClassesNS5 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: }
// CHECK: typealias AliasToAnotherNS5 = ClassesNS4.ClassesNS5
// CHECK: typealias AliasToGlobalNS5 = ClassesNS5
// CHECK: typealias AliasToLocalNS5 = ClassesNS5.ClassesNS5
// CHECK: typealias AliasToNS5 = ClassesNS5.ClassesNS5
// CHECK: }
// CHECK: extension ClassesNS5.ClassesNS5 {
// CHECK: struct BasicStruct {
// CHECK: init()
// CHECK: }
// CHECK: typealias AliasToNS5NS5 = ClassesNS5.ClassesNS5
// CHECK: }
// CHECK-NOT: extension
| apache-2.0 | 911d375d9e9dc90b0c69c68484c4ce34 | 32.861538 | 137 | 0.681054 | 3.69916 | false | false | false | false |
ja-mes/experiments | Old/Random/Maps Demo/Maps Demo/ViewController.swift | 1 | 3084 | //
// ViewController.swift
// Maps Demo
//
// Created by James Brown on 11/30/15.
// Copyright © 2015 James Brown. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
let latitude:CLLocationDegrees = 40.7
let longitude:CLLocationDegrees = -73.9
let latDelta:CLLocationDegrees = 0.01
let lonDelta:CLLocationDegrees = 0.01
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Foo Bar"
annotation.subtitle = "This is some test text"
map.addAnnotation(annotation)
let uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")
uilpgr.minimumPressDuration = 2
map.addGestureRecognizer(uilpgr)
}
func action(gestureReconizer:UIGestureRecognizer) {
let touchPoint = gestureReconizer.locationInView(self.map)
let newCoordinate:CLLocationCoordinate2D = map.convertPoint(touchPoint, toCoordinateFromView: self.map)
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinate
annotation.title = "New Place"
annotation.subtitle = "This is some test text"
map.addAnnotation(annotation)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation:CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude;
let longitude = userLocation.coordinate.longitude
let latDelta:CLLocationDegrees = 0.01
let lonDelta:CLLocationDegrees = 0.01
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 081d0c24c9fef0d55c6861bc309d7fcd | 28.932039 | 111 | 0.653909 | 5.917466 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/Differentiator/Sources/Differentiator/Diff.swift | 3 | 32630 | //
// Differentiator.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
fileprivate extension AnimatableSectionModelType {
init(safeOriginal: Self, safeItems: [Item]) throws {
self.init(original: safeOriginal, items: safeItems)
if self.items != safeItems || self.identity != safeOriginal.identity {
throw Diff.Error.invalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity)
}
}
}
public enum Diff {
public enum Error : Swift.Error, CustomDebugStringConvertible {
case duplicateItem(item: Any)
case duplicateSection(section: Any)
case invalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any)
public var debugDescription: String {
switch self {
case let .duplicateItem(item):
return "Duplicate item \(item)"
case let .duplicateSection(section):
return "Duplicate section \(section)"
case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier):
return "Wrong initializer implementation for: \(section)\n" +
"Expected it should return items: \(expectedItems)\n" +
"Expected it should have id: \(expectedIdentifier)"
}
}
}
private enum EditEvent : CustomDebugStringConvertible {
case inserted // can't be found in old sections
case insertedAutomatically // Item inside section being inserted
case deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated
case deletedAutomatically // Item inside section that is being deleted
case moved // same item, but was on different index, and needs explicit move
case movedAutomatically // don't need to specify any changes for those rows
case untouched
var debugDescription: String {
get {
switch self {
case .inserted:
return "Inserted"
case .insertedAutomatically:
return "InsertedAutomatically"
case .deleted:
return "Deleted"
case .deletedAutomatically:
return "DeletedAutomatically"
case .moved:
return "Moved"
case .movedAutomatically:
return "MovedAutomatically"
case .untouched:
return "Untouched"
}
}
}
}
private struct SectionAssociatedData : CustomDebugStringConvertible {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: Int?
var itemCount: Int
var debugDescription: String {
get {
return "\(event), \(String(describing: indexAfterDelete))"
}
}
static var initial: SectionAssociatedData {
return SectionAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil, itemCount: 0)
}
}
private struct ItemAssociatedData: CustomDebugStringConvertible {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: ItemPath?
var debugDescription: String {
get {
return "\(event) \(String(describing: indexAfterDelete))"
}
}
static var initial : ItemAssociatedData {
return ItemAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
private static func indexSections<Section: AnimatableSectionModelType>(_ sections: [Section]) throws -> [Section.Identity : Int] {
var indexedSections: [Section.Identity : Int] = [:]
for (i, section) in sections.enumerated() {
guard indexedSections[section.identity] == nil else {
#if DEBUG
if indexedSections[section.identity] != nil {
print("Section \(section) has already been indexed at \(indexedSections[section.identity]!)")
}
#endif
throw Error.duplicateSection(section: section)
}
indexedSections[section.identity] = i
}
return indexedSections
}
//================================================================================
// Optimizations because Swift dictionaries are extremely slow (ARC, bridging ...)
//================================================================================
// swift dictionary optimizations {
private struct OptimizedIdentity<Identity: Hashable> : Hashable {
let identity: UnsafePointer<Identity>
private let cachedHashValue: Int
init(_ identity: UnsafePointer<Identity>) {
self.identity = identity
self.cachedHashValue = identity.pointee.hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.cachedHashValue)
}
static func == (lhs: OptimizedIdentity<Identity>, rhs: OptimizedIdentity<Identity>) -> Bool {
if lhs.hashValue != rhs.hashValue {
return false
}
if lhs.identity.distance(to: rhs.identity) == 0 {
return true
}
return lhs.identity.pointee == rhs.identity.pointee
}
}
private static func calculateAssociatedData<Item: IdentifiableType>(
initialItemCache: ContiguousArray<ContiguousArray<Item>>,
finalItemCache: ContiguousArray<ContiguousArray<Item>>
) throws
-> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) {
typealias Identity = Item.Identity
let totalInitialItems = initialItemCache.map { $0.count }.reduce(0, +)
var initialIdentities: ContiguousArray<Identity> = ContiguousArray()
var initialItemPaths: ContiguousArray<ItemPath> = ContiguousArray()
initialIdentities.reserveCapacity(totalInitialItems)
initialItemPaths.reserveCapacity(totalInitialItems)
for (i, items) in initialItemCache.enumerated() {
for j in 0 ..< items.count {
let item = items[j]
initialIdentities.append(item.identity)
initialItemPaths.append(ItemPath(sectionIndex: i, itemIndex: j))
}
}
var initialItemData = ContiguousArray(initialItemCache.map { items in
return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count)
})
var finalItemData = ContiguousArray(finalItemCache.map { items in
return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count)
})
try initialIdentities.withUnsafeBufferPointer { (identitiesBuffer: UnsafeBufferPointer<Identity>) -> () in
var dictionary: [OptimizedIdentity<Identity>: Int] = Dictionary(minimumCapacity: totalInitialItems * 2)
for i in 0 ..< initialIdentities.count {
let identityPointer = identitiesBuffer.baseAddress!.advanced(by: i)
let key = OptimizedIdentity(identityPointer)
if let existingValueItemPathIndex = dictionary[key] {
let itemPath = initialItemPaths[existingValueItemPathIndex]
let item = initialItemCache[itemPath.sectionIndex][itemPath.itemIndex]
#if DEBUG
print("Item \(item) has already been indexed at \(itemPath)" )
#endif
throw Error.duplicateItem(item: item)
}
dictionary[key] = i
}
for (i, items) in finalItemCache.enumerated() {
for j in 0 ..< items.count {
let item = items[j]
var identity = item.identity
let key = OptimizedIdentity(&identity)
guard let initialItemPathIndex = dictionary[key] else {
continue
}
let itemPath = initialItemPaths[initialItemPathIndex]
if initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex != nil {
throw Error.duplicateItem(item: item)
}
initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex = ItemPath(sectionIndex: i, itemIndex: j)
finalItemData[i][j].moveIndex = itemPath
}
}
return ()
}
return (initialItemData, finalItemData)
}
// } swift dictionary optimizations
/*
I've uncovered this case during random stress testing of logic.
This is the hardest generic update case that causes two passes, first delete, and then move/insert
[
NumberSection(model: "1", items: [1111]),
NumberSection(model: "2", items: [2222]),
]
[
NumberSection(model: "2", items: [0]),
NumberSection(model: "1", items: []),
]
If update is in the form
* Move section from 2 to 1
* Delete Items at paths 0 - 0, 1 - 0
* Insert Items at paths 0 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 1 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 0 - 0
it crashes table view.
No matter what change is performed, it fails for me.
If anyone knows how to make this work for one Changeset, PR is welcome.
*/
// If you are considering working out your own algorithm, these are tricky
// transition cases that you can use.
// case 1
/*
from = [
NumberSection(model: "section 4", items: [10, 11, 12]),
NumberSection(model: "section 9", items: [25, 26, 27]),
]
to = [
HashableSectionModel(model: "section 9", items: [11, 26, 27]),
HashableSectionModel(model: "section 4", items: [10, 12])
]
*/
// case 2
/*
from = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 7", items: [5, 29]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 5", items: [16]),
HashableSectionModel(model: "section 4", items: []),
HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20])
]
to = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 9", items: [3]),
HashableSectionModel(model: "section 5", items: [16, 8]),
HashableSectionModel(model: "section 8", items: [15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20]),
HashableSectionModel(model: "Section 2", items: [7])
]
*/
// case 3
/*
from = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: []),
HashableSectionModel(model: "section 2", items: [2, 26]),
HashableSectionModel(model: "section 8", items: [23]),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
to = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: [16]),
HashableSectionModel(model: "section 7", items: [17, 15, 4]),
HashableSectionModel(model: "section 2", items: [2, 26, 23]),
HashableSectionModel(model: "section 8", items: []),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
*/
// Generates differential changes suitable for sectioned view consumption.
// It will not only detect changes between two states, but it will also try to compress those changes into
// almost minimal set of changes.
//
// I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and
// avoids UITableView quirks.
//
// Please take into consideration that I was also convinced about 20 times that I've found a simple general
// solution, but then UITableView falls apart under stress testing :(
//
// Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think
// that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :)
//
// Maybe it can be made somewhat simpler, but don't think it can be made much simpler.
//
// The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates.
//
// * stage 1 - remove deleted sections and items
// * stage 2 - move sections into place
// * stage 3 - fix moved and new items
//
// There maybe exists a better division, but time will tell.
//
public static func differencesForSectionedView<Section: AnimatableSectionModelType>(
initialSections: [Section],
finalSections: [Section])
throws -> [Changeset<Section>] {
typealias I = Section.Item
var result: [Changeset<Section>] = []
var sectionCommands = try CommandGenerator<Section>.generatorForInitialSections(initialSections, finalSections: finalSections)
result.append(contentsOf: try sectionCommands.generateDeleteSectionsDeletedItemsAndUpdatedItems())
result.append(contentsOf: try sectionCommands.generateInsertAndMoveSections())
result.append(contentsOf: try sectionCommands.generateInsertAndMovedItems())
return result
}
private struct CommandGenerator<Section: AnimatableSectionModelType> {
typealias Item = Section.Item
let initialSections: [Section]
let finalSections: [Section]
let initialSectionData: ContiguousArray<SectionAssociatedData>
let finalSectionData: ContiguousArray<SectionAssociatedData>
let initialItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>>
let finalItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>>
let initialItemCache: ContiguousArray<ContiguousArray<Item>>
let finalItemCache: ContiguousArray<ContiguousArray<Item>>
static func generatorForInitialSections(
_ initialSections: [Section],
finalSections: [Section]
) throws -> CommandGenerator<Section> {
let (initialSectionData, finalSectionData) = try calculateSectionMovements(initialSections: initialSections, finalSections: finalSections)
let initialItemCache = ContiguousArray(initialSections.map {
ContiguousArray($0.items)
})
let finalItemCache = ContiguousArray(finalSections.map {
ContiguousArray($0.items)
})
let (initialItemData, finalItemData) = try calculateItemMovements(
initialItemCache: initialItemCache,
finalItemCache: finalItemCache,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData
)
return CommandGenerator<Section>(
initialSections: initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData,
initialItemData: initialItemData,
finalItemData: finalItemData,
initialItemCache: initialItemCache,
finalItemCache: finalItemCache
)
}
static func calculateItemMovements(
initialItemCache: ContiguousArray<ContiguousArray<Item>>,
finalItemCache: ContiguousArray<ContiguousArray<Item>>,
initialSectionData: ContiguousArray<SectionAssociatedData>,
finalSectionData: ContiguousArray<SectionAssociatedData>) throws
-> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) {
var (initialItemData, finalItemData) = try Diff.calculateAssociatedData(
initialItemCache: initialItemCache,
finalItemCache: finalItemCache
)
let findNextUntouchedOldIndex = { (initialSectionIndex: Int, initialSearchIndex: Int?) -> Int? in
guard var i2 = initialSearchIndex else {
return nil
}
while i2 < initialSectionData[initialSectionIndex].itemCount {
if initialItemData[initialSectionIndex][i2].event == .untouched {
return i2
}
i2 = i2 + 1
}
return nil
}
// first mark deleted items
for i in 0 ..< initialItemCache.count {
guard let _ = initialSectionData[i].moveIndex else {
continue
}
var indexAfterDelete = 0
for j in 0 ..< initialItemCache[i].count {
guard let finalIndexPath = initialItemData[i][j].moveIndex else {
initialItemData[i][j].event = .deleted
continue
}
// from this point below, section has to be move type because it's initial and not deleted
// because there is no move to inserted section
if finalSectionData[finalIndexPath.sectionIndex].event == .inserted {
initialItemData[i][j].event = .deleted
continue
}
initialItemData[i][j].indexAfterDelete = indexAfterDelete
indexAfterDelete += 1
}
}
// mark moved or moved automatically
for i in 0 ..< finalItemCache.count {
guard let originalSectionIndex = finalSectionData[i].moveIndex else {
continue
}
var untouchedIndex: Int? = 0
for j in 0 ..< finalItemCache[i].count {
untouchedIndex = findNextUntouchedOldIndex(originalSectionIndex, untouchedIndex)
guard let originalIndex = finalItemData[i][j].moveIndex else {
finalItemData[i][j].event = .inserted
continue
}
// In case trying to move from deleted section, abort, otherwise it will crash table view
if initialSectionData[originalIndex.sectionIndex].event == .deleted {
finalItemData[i][j].event = .inserted
continue
}
// original section can't be inserted
else if initialSectionData[originalIndex.sectionIndex].event == .inserted {
try precondition(false, "New section in initial sections, that is wrong")
}
let initialSectionEvent = initialSectionData[originalIndex.sectionIndex].event
try precondition(initialSectionEvent == .moved || initialSectionEvent == .movedAutomatically, "Section not moved")
let eventType = originalIndex == ItemPath(sectionIndex: originalSectionIndex, itemIndex: untouchedIndex ?? -1)
? EditEvent.movedAutomatically : EditEvent.moved
initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].event = eventType
finalItemData[i][j].event = eventType
}
}
return (initialItemData, finalItemData)
}
static func calculateSectionMovements(initialSections: [Section], finalSections: [Section]) throws
-> (ContiguousArray<SectionAssociatedData>, ContiguousArray<SectionAssociatedData>) {
let initialSectionIndexes = try Diff.indexSections(initialSections)
var initialSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: initialSections.count)
var finalSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: finalSections.count)
for (i, section) in finalSections.enumerated() {
finalSectionData[i].itemCount = finalSections[i].items.count
guard let initialSectionIndex = initialSectionIndexes[section.identity] else {
continue
}
if initialSectionData[initialSectionIndex].moveIndex != nil {
throw Error.duplicateSection(section: section)
}
initialSectionData[initialSectionIndex].moveIndex = i
finalSectionData[i].moveIndex = initialSectionIndex
}
var sectionIndexAfterDelete = 0
// deleted sections
for i in 0 ..< initialSectionData.count {
initialSectionData[i].itemCount = initialSections[i].items.count
if initialSectionData[i].moveIndex == nil {
initialSectionData[i].event = .deleted
continue
}
initialSectionData[i].indexAfterDelete = sectionIndexAfterDelete
sectionIndexAfterDelete += 1
}
// moved sections
var untouchedOldIndex: Int? = 0
let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in
guard var i = initialSearchIndex else {
return nil
}
while i < initialSections.count {
if initialSectionData[i].event == .untouched {
return i
}
i = i + 1
}
return nil
}
// inserted and moved sections {
// this should fix all sections and move them into correct places
// 2nd stage
for i in 0 ..< finalSections.count {
untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex)
// oh, it did exist
if let oldSectionIndex = finalSectionData[i].moveIndex {
let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.moved : EditEvent.movedAutomatically
finalSectionData[i].event = moveType
initialSectionData[oldSectionIndex].event = moveType
}
else {
finalSectionData[i].event = .inserted
}
}
// inserted sections
for (i, section) in finalSectionData.enumerated() {
if section.moveIndex == nil {
_ = finalSectionData[i].event == .inserted
}
}
return (initialSectionData, finalSectionData)
}
mutating func generateDeleteSectionsDeletedItemsAndUpdatedItems() throws -> [Changeset<Section>] {
var deletedSections = [Int]()
var deletedItems = [ItemPath]()
var updatedItems = [ItemPath]()
var afterDeleteState = [Section]()
// mark deleted items {
// 1rst stage again (I know, I know ...)
for (i, initialItems) in initialItemCache.enumerated() {
let event = initialSectionData[i].event
// Deleted section will take care of deleting child items.
// In case of moving an item from deleted section, tableview will
// crash anyway, so this is not limiting anything.
if event == .deleted {
deletedSections.append(i)
continue
}
var afterDeleteItems: [Section.Item] = []
for j in 0 ..< initialItems.count {
let event = initialItemData[i][j].event
switch event {
case .deleted:
deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved, .movedAutomatically:
let finalItemIndex = try initialItemData[i][j].moveIndex.unwrap()
let finalItem = finalItemCache[finalItemIndex.sectionIndex][finalItemIndex.itemIndex]
if finalItem != initialSections[i].items[j] {
updatedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
}
afterDeleteItems.append(finalItem)
default:
try precondition(false, "Unhandled case")
}
}
afterDeleteState.append(try Section.init(safeOriginal: initialSections[i], safeItems: afterDeleteItems))
}
// }
if deletedItems.isEmpty && deletedSections.isEmpty && updatedItems.isEmpty {
return []
}
return [Changeset(
finalSections: afterDeleteState,
deletedSections: deletedSections,
deletedItems: deletedItems,
updatedItems: updatedItems
)]
}
func generateInsertAndMoveSections() throws -> [Changeset<Section>] {
var movedSections = [(from: Int, to: Int)]()
var insertedSections = [Int]()
for i in 0 ..< initialSections.count {
switch initialSectionData[i].event {
case .deleted:
break
case .moved:
movedSections.append((from: try initialSectionData[i].indexAfterDelete.unwrap(), to: try initialSectionData[i].moveIndex.unwrap()))
case .movedAutomatically:
break
default:
try precondition(false, "Unhandled case in initial sections")
}
}
for i in 0 ..< finalSections.count {
switch finalSectionData[i].event {
case .inserted:
insertedSections.append(i)
default:
break
}
}
if insertedSections.isEmpty && movedSections.isEmpty {
return []
}
// sections should be in place, but items should be original without deleted ones
let sectionsAfterChange: [Section] = try self.finalSections.enumerated().map { i, s -> Section in
let event = self.finalSectionData[i].event
if event == .inserted {
// it's already set up
return s
}
else if event == .moved || event == .movedAutomatically {
let originalSectionIndex = try finalSectionData[i].moveIndex.unwrap()
let originalSection = initialSections[originalSectionIndex]
var items: [Section.Item] = []
items.reserveCapacity(originalSection.items.count)
let itemAssociatedData = self.initialItemData[originalSectionIndex]
for j in 0 ..< originalSection.items.count {
let initialData = itemAssociatedData[j]
guard initialData.event != .deleted else {
continue
}
guard let finalIndex = initialData.moveIndex else {
try precondition(false, "Item was moved, but no final location.")
continue
}
items.append(finalItemCache[finalIndex.sectionIndex][finalIndex.itemIndex])
}
let modifiedSection = try Section.init(safeOriginal: s, safeItems: items)
return modifiedSection
}
else {
try precondition(false, "This is weird, this shouldn't happen")
return s
}
}
return [Changeset(
finalSections: sectionsAfterChange,
insertedSections: insertedSections,
movedSections: movedSections
)]
}
mutating func generateInsertAndMovedItems() throws -> [Changeset<Section>] {
var insertedItems = [ItemPath]()
var movedItems = [(from: ItemPath, to: ItemPath)]()
// mark new and moved items {
// 3rd stage
for i in 0 ..< finalSections.count {
let finalSection = finalSections[i]
let sectionEvent = finalSectionData[i].event
// new and deleted sections cause reload automatically
if sectionEvent != .moved && sectionEvent != .movedAutomatically {
continue
}
for j in 0 ..< finalSection.items.count {
let currentItemEvent = finalItemData[i][j].event
try precondition(currentItemEvent != .untouched, "Current event is not untouched")
let event = finalItemData[i][j].event
switch event {
case .inserted:
insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved:
let originalIndex = try finalItemData[i][j].moveIndex.unwrap()
let finalSectionIndex = try initialSectionData[originalIndex.sectionIndex].moveIndex.unwrap()
let moveFromItemWithIndex = try initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].indexAfterDelete.unwrap()
let moveCommand = (
from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex),
to: ItemPath(sectionIndex: i, itemIndex: j)
)
movedItems.append(moveCommand)
default:
break
}
}
}
// }
if insertedItems.isEmpty && movedItems.isEmpty {
return []
}
return [Changeset(
finalSections: finalSections,
insertedItems: insertedItems,
movedItems: movedItems
)]
}
}
}
| mit | e19793a220db3e8f60f3e3c49620ce13 | 40.40736 | 151 | 0.552116 | 6.097739 | false | false | false | false |
zoeyzhong520/InformationTechnology | InformationTechnology/InformationTechnology/Classes/Public公共类/KTCSegCtrl.swift | 1 | 4047 | //
// KTCSegCtrl.swift
// TestKitchen
//
// Created by qianfeng on 16/11/1.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
protocol KTCSegCtrlDelegate:NSObjectProtocol {
//点击事件
func segCtrl(segCtrl:KTCSegCtrl, didClickBtnAtIndex index:Int)
}
class KTCSegCtrl: UIView {
//代理属性
weak var delegate:KTCSegCtrlDelegate?
//下划线
private var lineView: UIImageView?
//设置当前的序号
var selectIndex:Int = 0 {
didSet {
if selectIndex != oldValue {
//取消之前的选中状态
let lastBtn = viewWithTag(300+oldValue)
if lastBtn?.isKindOfClass(KTCSegBtn) == true {
let tmpBtn = lastBtn as! KTCSegBtn
tmpBtn.clicked = false
}
//选中当前点击的按钮
let curBtn = viewWithTag(300+selectIndex)
if curBtn?.isKindOfClass(KTCSegBtn) == true {
let tmpBtn = curBtn as! KTCSegBtn
tmpBtn.clicked = true
}
//修改下划线的位置
UIView.animateWithDuration(0.25, animations: {
self.lineView?.frame.origin.x = (self.lineView?.frame.size.width)!*CGFloat(self.selectIndex)
})
}
}
}
//重新给一个初始化方法
init(frame: CGRect, titleArray:Array<String>) {
super.init(frame: frame)
//创建按钮
if titleArray.count > 0 {
createBtns(titleArray)
}
}
//创建按钮
func createBtns(titleArray:Array<String>) {
//按钮宽度
let w = bounds.size.width/CGFloat(titleArray.count)
for i in 0..<titleArray.count {
//循环创建按钮
let frame = CGRectMake(w*CGFloat(i), 0, w, bounds.size.height)
let btn = KTCSegBtn(frame: frame)
//默认选中第一个
if i == 0 {
btn.clicked = true
}else{
btn.clicked = false
}
btn.config(titleArray[i])
//添加点击事件
btn.tag = 300+i
btn.addTarget(self, action: #selector(clickBtn(_:)), forControlEvents: .TouchUpInside)
addSubview(btn)
}
//下划线
lineView = UIImageView(frame: CGRectMake(0, bounds.size.height-2, w, 2))
lineView?.backgroundColor = UIColor(red: 209/255.0, green: 49/255.0, blue: 92/255.0, alpha: 1.0)
addSubview(lineView!)
}
func clickBtn(btn:KTCSegBtn) {
let index = btn.tag-300
//修改选中的UI
selectIndex = index
delegate?.segCtrl(self, didClickBtnAtIndex: index)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//自定制按钮
class KTCSegBtn:UIControl {
private var titleLabel:UILabel?
//设置选中状态
var clicked:Bool = false {
didSet {
if clicked == true {
//选中
titleLabel?.textColor = UIColor(red: 209/255.0, green: 49/255.0, blue: 92/255.0, alpha: 1.0)
}else{
//取消
titleLabel?.textColor = UIColor.blackColor()
}
}
}
//显示数据
func config(title:String?) {
titleLabel?.text = title
}
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel = UILabel()
titleLabel?.textAlignment = .Center
titleLabel?.font = UIFont.systemFontOfSize(17)
titleLabel?.frame = bounds
addSubview(titleLabel!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 5cb3a6421f0c111bb6dccbd5f4a26730 | 23.96732 | 112 | 0.512042 | 4.630303 | false | false | false | false |
pseudomuto/CircuitBreaker | Pod/Classes/ClosedState.swift | 1 | 1042 | //
// ClosedState.swift
// Pods
//
// Created by David Muto on 2016-02-05.
//
//
class ClosedState: BaseState {
let errorThreshold: Int
let invocationTimeout: NSTimeInterval
private(set) var failures: Int
init(_ breakerSwitch: Switch, invoker: Invoker, errorThreshold: Int, invocationTimeout: NSTimeInterval) {
self.errorThreshold = errorThreshold
self.invocationTimeout = invocationTimeout
self.failures = 0
super.init(breakerSwitch, invoker: invoker)
}
override func type() -> StateType {
return .Closed
}
override func activate() {
synchronized {
self.failures = 0
}
}
override func onSuccess() {
activate()
}
override func onError() {
synchronized {
self.failures++
if self.failures == self.errorThreshold {
self.breakerSwitch.trip(self)
}
}
}
override func invoke<T>(block: () throws -> T) throws -> T {
return try invoker.invoke(self, timeout: invocationTimeout, block: block)
}
}
| mit | 79808ba6364c781cdbde861befc65cfd | 19.84 | 107 | 0.637236 | 4.253061 | false | false | false | false |
alblue/swift | stdlib/public/core/ManagedBuffer.swift | 1 | 22809 | //===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
@usableFromInline
internal typealias _HeapObject = SwiftShims.HeapObject
@usableFromInline
@_silgen_name("swift_bufferAllocate")
internal func _swift_bufferAllocate(
bufferType type: AnyClass,
size: Int,
alignmentMask: Int
) -> AnyObject
/// A class whose instances contain a property of type `Header` and raw
/// storage for an array of `Element`, whose size is determined at
/// instance creation.
///
/// Note that the `Element` array is suitably-aligned **raw memory**.
/// You are expected to construct and---if necessary---destroy objects
/// there yourself, using the APIs on `UnsafeMutablePointer<Element>`.
/// Typical usage stores a count and capacity in `Header` and destroys
/// any live elements in the `deinit` of a subclass.
/// - Note: Subclasses must not have any stored properties; any storage
/// needed should be included in `Header`.
@_fixed_layout // FIXME(sil-serialize-all)
open class ManagedBuffer<Header, Element> {
/// Create a new instance of the most-derived class, calling
/// `factory` on the partially-constructed object to generate
/// an initial `Header`.
@inlinable // FIXME(sil-serialize-all)
public final class func create(
minimumCapacity: Int,
makingHeaderWith factory: (
ManagedBuffer<Header, Element>) throws -> Header
) rethrows -> ManagedBuffer<Header, Element> {
let p = Builtin.allocWithTailElems_1(
self,
minimumCapacity._builtinWordValue, Element.self)
let initHeaderVal = try factory(p)
p.headerAddress.initialize(to: initHeaderVal)
// The _fixLifetime is not really needed, because p is used afterwards.
// But let's be conservative and fix the lifetime after we use the
// headerAddress.
_fixLifetime(p)
return p
}
/// The actual number of elements that can be stored in this object.
///
/// This header may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@inlinable // FIXME(sil-serialize-all)
public final var capacity: Int {
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self))
let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr)
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) -
firstElementAddress
return realCapacity
}
@inlinable // FIXME(sil-serialize-all)
internal final var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self,
Element.self))
}
@inlinable // FIXME(sil-serialize-all)
internal final var headerAddress: UnsafeMutablePointer<Header> {
return UnsafeMutablePointer<Header>(Builtin.addressof(&header))
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@inlinable // FIXME(sil-serialize-all)
public final func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(headerAddress, firstElementAddress)
}
/// The stored `Header` instance.
///
/// During instance creation, in particular during
/// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s
/// `header` property is as-yet uninitialized, and therefore
/// reading the `header` property during `ManagedBuffer.create` is undefined.
public final var header: Header
//===--- internal/private API -------------------------------------------===//
/// Make ordinary initialization unavailable
@inlinable // FIXME(sil-serialize-all)
internal init(_doNotCallMe: ()) {
_sanityCheckFailure("Only initialize these by calling create")
}
}
/// Contains a buffer object, and provides access to an instance of
/// `Header` and contiguous storage for an arbitrary number of
/// `Element` instances stored in that buffer.
///
/// For most purposes, the `ManagedBuffer` class works fine for this
/// purpose, and can simply be used on its own. However, in cases
/// where objects of various different classes must serve as storage,
/// `ManagedBufferPointer` is needed.
///
/// A valid buffer class is non-`@objc`, with no declared stored
/// properties. Its `deinit` must destroy its
/// stored `Header` and any constructed `Element`s.
///
/// Example Buffer Class
/// --------------------
///
/// class MyBuffer<Element> { // non-@objc
/// typealias Manager = ManagedBufferPointer<(Int, String), Element>
/// deinit {
/// Manager(unsafeBufferObject: self).withUnsafeMutablePointers {
/// (pointerToHeader, pointerToElements) -> Void in
/// pointerToElements.deinitialize(count: self.count)
/// pointerToHeader.deinitialize(count: 1)
/// }
/// }
///
/// // All properties are *computed* based on members of the Header
/// var count: Int {
/// return Manager(unsafeBufferObject: self).header.0
/// }
/// var name: String {
/// return Manager(unsafeBufferObject: self).header.1
/// }
/// }
///
@_fixed_layout
public struct ManagedBufferPointer<Header, Element> : Equatable {
/// Create with new storage containing an initial `Header` and space
/// for at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
/// - parameter factory: A function that produces the initial
/// `Header` instance stored in the buffer, given the `buffer`
/// object and a function that can be called on it to get the actual
/// number of allocated elements.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@inlinable // FIXME(sil-serialize-all)
public init(
bufferClass: AnyClass,
minimumCapacity: Int,
makingHeaderWith factory:
(_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header
) rethrows {
self = ManagedBufferPointer(
bufferClass: bufferClass, minimumCapacity: minimumCapacity)
// initialize the header field
try withUnsafeMutablePointerToHeader {
$0.initialize(to:
try factory(
self.buffer,
{
ManagedBufferPointer(unsafeBufferObject: $0).capacity
}))
}
// FIXME: workaround for <rdar://problem/18619176>. If we don't
// access header somewhere, its addressor gets linked away
_ = header
}
/// Manage the given `buffer`.
///
/// - Precondition: `buffer` is an instance of a non-`@objc` class whose
/// `deinit` destroys its stored `Header` and any constructed `Element`s.
@inlinable // FIXME(sil-serialize-all)
public init(unsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._checkValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
/// Internal version for use by _ContiguousArrayBuffer where we know that we
/// have a valid buffer class.
/// This version of the init function gets called from
/// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get
/// specialized with current versions of the compiler, we can't get rid of the
/// _debugPreconditions in _checkValidBufferClass for any array. Since we know
/// for the _ContiguousArrayBuffer that this check must always succeed we omit
/// it in this specialized constructor.
@inlinable // FIXME(sil-serialize-all)
internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
/// The stored `Header` instance.
@inlinable // FIXME(sil-serialize-all)
public var header: Header {
addressWithNativeOwner {
return (UnsafePointer(_headerPointer), _nativeBuffer)
}
_modify {
yield &_headerPointer.pointee
}
}
/// Returns the object instance being used for storage.
@inlinable // FIXME(sil-serialize-all)
public var buffer: AnyObject {
return Builtin.castFromNativeObject(_nativeBuffer)
}
/// The actual number of elements that can be stored in this object.
///
/// This value may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@inlinable // FIXME(sil-serialize-all)
public var capacity: Int {
return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only
/// for the duration of the call to `body`.
@inlinable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@inlinable // FIXME(sil-serialize-all)
public func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(_nativeBuffer) }
return try body(_headerPointer, _elementPointer)
}
/// Returns `true` iff `self` holds the only strong reference to its buffer.
///
/// See `isUniquelyReferenced` for details.
@inlinable // FIXME(sil-serialize-all)
public mutating func isUniqueReference() -> Bool {
return _isUnique(&_nativeBuffer)
}
//===--- internal/private API -------------------------------------------===//
/// Create with new storage containing space for an initial `Header`
/// and at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@inlinable // FIXME(sil-serialize-all)
internal init(
bufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true)
_precondition(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
self.init(
_uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity)
}
/// Internal version for use by _ContiguousArrayBuffer.init where we know that
/// we have a valid buffer class and that the capacity is >= 0.
@inlinable // FIXME(sil-serialize-all)
internal init(
_uncheckedBufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true)
_sanityCheck(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
let totalSize = _My._elementOffset
+ minimumCapacity * MemoryLayout<Element>.stride
let newBuffer: AnyObject = _swift_bufferAllocate(
bufferType: _uncheckedBufferClass,
size: totalSize,
alignmentMask: _My._alignmentMask)
self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer)
}
/// Manage the given `buffer`.
///
/// - Note: It is an error to use the `header` property of the resulting
/// instance unless it has been initialized.
@inlinable // FIXME(sil-serialize-all)
internal init(_ buffer: ManagedBuffer<Header, Element>) {
_nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
@usableFromInline // FIXME(sil-serialize-all)
internal typealias _My = ManagedBufferPointer
@inlinable // FIXME(sil-serialize-all)
internal static func _checkValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_debugPrecondition(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_debugPrecondition(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
@inlinable // FIXME(sil-serialize-all)
internal static func _sanityCheckValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_sanityCheck(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_sanityCheck(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
/// The required alignment for allocations of this type, minus 1
@inlinable // FIXME(sil-serialize-all)
internal static var _alignmentMask: Int {
return max(
MemoryLayout<_HeapObject>.alignment,
max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1
}
/// The actual number of bytes allocated for this object.
@inlinable // FIXME(sil-serialize-all)
internal var _capacityInBytes: Int {
return _swift_stdlib_malloc_size(_address)
}
/// The address of this instance in a convenient pointer-to-bytes form
@inlinable // FIXME(sil-serialize-all)
internal var _address: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer))
}
/// Offset from the allocated storage for `self` to the stored `Header`
@inlinable // FIXME(sil-serialize-all)
internal static var _headerOffset: Int {
_onFastPath()
return _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Header>.alignment)
}
/// An **unmanaged** pointer to the storage for the `Header`
/// instance. Not safe to use without _fixLifetime calls to
/// guarantee it doesn't dangle
@inlinable // FIXME(sil-serialize-all)
internal var _headerPointer: UnsafeMutablePointer<Header> {
_onFastPath()
return (_address + _My._headerOffset).assumingMemoryBound(
to: Header.self)
}
/// An **unmanaged** pointer to the storage for `Element`s. Not
/// safe to use without _fixLifetime calls to guarantee it doesn't
/// dangle.
@inlinable // FIXME(sil-serialize-all)
internal var _elementPointer: UnsafeMutablePointer<Element> {
_onFastPath()
return (_address + _My._elementOffset).assumingMemoryBound(
to: Element.self)
}
/// Offset from the allocated storage for `self` to the `Element` storage
@inlinable // FIXME(sil-serialize-all)
internal static var _elementOffset: Int {
_onFastPath()
return _roundUp(
_headerOffset + MemoryLayout<Header>.size,
toAlignment: MemoryLayout<Element>.alignment)
}
@inlinable // FIXME(sil-serialize-all)
public static func == (
lhs: ManagedBufferPointer, rhs: ManagedBufferPointer
) -> Bool {
return lhs._address == rhs._address
}
@usableFromInline
internal var _nativeBuffer: Builtin.NativeObject
}
// FIXME: when our calling convention changes to pass self at +0,
// inout should be dropped from the arguments to these functions.
// FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too,
// but currently does not. rdar://problem/29341361
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean
/// expression. In debug builds, an instance in the left-hand side of a `&&`
/// or `||` expression may still be referenced when evaluating the right-hand
/// side, inflating the instance's reference count. For example, this version
/// of the `update(withValue)` method will re-copy `myStorage` on every call:
///
/// // Copies too frequently:
/// mutating func badUpdate(withValue value: T) {
/// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to
/// the left-hand side or store the result of the first expression in a local
/// constant:
///
/// mutating func goodUpdate(withValue value: T) {
/// let shouldCopy = myStorage.shouldCopy
/// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`.
@inlinable
public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool
{
return _isUnique(&object)
}
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`. If `object` is `nil`, the return value is `false`.
@inlinable
public func isKnownUniquelyReferenced<T : AnyObject>(
_ object: inout T?
) -> Bool {
return _isUnique(&object)
}
| apache-2.0 | e39ec34a0c4899c16c264647f0022e33 | 37.989744 | 92 | 0.687536 | 4.634092 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/TDCourseCatalogDetailViewController/Views/TDCourseButtonsCell.swift | 1 | 1647 | //
// TDCourseButtonsCell.swift
// edX
//
// Created by Ben on 2017/5/5.
// Copyright © 2017年 edX. All rights reserved.
//
import UIKit
class TDCourseButtonsCell: UITableViewCell {
let bgView = UIView()
let submitButton = UIButton()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.whiteColor()
configView()
setViewConstraint()
}
func configView() {
bgView.backgroundColor = UIColor.whiteColor()
self.contentView.addSubview(bgView)
submitButton.backgroundColor = OEXStyles.sharedStyles().baseColor1()
submitButton.layer.cornerRadius = 4.0
submitButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
submitButton.titleLabel?.font = UIFont.init(name: "OpenSans", size: 16)
bgView.addSubview(submitButton)
// submitButton.setTitle("立即加入", forState: .Normal)
}
func setViewConstraint() {
bgView.snp_makeConstraints { (make) in
make.left.right.top.equalTo(self.contentView)
make.bottom.equalTo(self.contentView).offset(1)
}
submitButton.snp_makeConstraints { (make) in
make.left.equalTo(bgView.snp_left).offset(18)
make.right.equalTo(bgView.snp_right).offset(-18)
make.centerY.equalTo(bgView)
make.height.equalTo(44)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | ac5af52899f1e8604bee3b22bde61822 | 29.296296 | 79 | 0.635697 | 4.519337 | false | false | false | false |
mozilla-mobile/firefox-ios | Extensions/ShareTo/SendToDevice.swift | 2 | 2324 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import Shared
import Storage
import SwiftUI
class SendToDevice: DevicePickerViewControllerDelegate, InstructionsViewDelegate {
var sharedItem: ShareItem?
weak var delegate: ShareControllerDelegate?
func initialViewController() -> UIViewController {
if !hasAccount() {
let instructionsView = InstructionsView(backgroundColor: ShareTheme.defaultBackground.color,
textColor: ShareTheme.textColor.color,
imageColor: ShareTheme.iconColor.color,
dismissAction: { [weak self] in
self?.dismissInstructionsView()
})
let hostingViewController = UIHostingController(rootView: instructionsView)
return hostingViewController
}
let devicePickerViewController = DevicePickerViewController()
devicePickerViewController.pickerDelegate = self
devicePickerViewController.profile = nil // This means the picker will open and close the default profile
return devicePickerViewController
}
func finish() {
delegate?.finish(afterDelay: 0)
}
func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) {
guard let item = sharedItem else {
return finish()
}
let profile = BrowserProfile(localName: "profile")
profile.sendItem(item, toDevices: devices).uponQueue(.main) { _ in
profile.shutdown()
self.finish()
addAppExtensionTelemetryEvent(forMethod: "send-to-device")
}
}
func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) {
finish()
}
func dismissInstructionsView() {
finish()
}
private func hasAccount() -> Bool {
let profile = BrowserProfile(localName: "profile")
defer {
profile.shutdown()
}
return profile.hasAccount()
}
}
| mpl-2.0 | 30f868651124fb3ee03ff0e71f266e3c | 34.753846 | 135 | 0.638554 | 5.989691 | false | false | false | false |
evering7/iSpeak8 | iSpeak8/Data_ItemFeedObj.swift | 1 | 3733 | //
// Data_ItemFeedObj.swift
// iSpeak8
//
// Created by JianFei Li on 19/09/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import FeedKit
import SWXMLHash
class ItemFeed_Mem_TS: NSObject {
private var accessQueue: DispatchQueue?
// main elements list
// var sourceTitle = String_TS(queueLabel: "Item feed memory source title", initialValue: "")
var itemTitle = String_TS(queueLabel: "item feed memory item title", initialValue: "")
var pubDate = Date_TS(queueLabel: "ItemFeed_Mem_TS.pubDate",
initialValue: Date(timeIntervalSince1970: 0))
var author = String_TS(queueLabel: "ItemFeed_Mem_TS.author", initialValue: "")
var itemLink = String_TS(queueLabel: "ItemFeed_Mem_TS.itemLink", initialValue: "")
var fileNameForDigest = String_TS(queueLabel: "ItemFeed_Mem_TS.fileNameForDigest", initialValue: "")
var fileNameForFullText = String_TS(queueLabel: "ItemFeed_Mem_TS.fileNameForFullText",
initialValue: "")
init(queueLabel: String ){
let labelStr = UUID().uuidString + "com.blogspot.cnshoe.iSpeak8.itemfeed.mem.ts" +
queueLabel
self.accessQueue = DispatchQueue(label: labelStr,
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
super.init()
}
deinit {
printLog("Deconstruction of ItemFeed memory thread safe")
printLog("class object name = \(type(of: self))")
printLog("label of accessqueue = \(self.accessQueue?.label ?? "nil")")
}
func loadUpdateSave_Data_FromParsedEntry(
itemEntry: AtomFeedEntry,
entryIndex: Int,
resultSWXMLHash: XMLIndexer?) -> Bool {
// Here: Need to do some work.
self.itemTitle.setStrValue(value: (itemEntry.title ?? "no title"))
// TODO: 2017.9.21 add date_TS type
// self.pubDate
self.author.setStrValue(value: (itemEntry.authors?[0].name ?? "unkown author"))
self.itemLink.setStrValue(value: (itemEntry.links?[0].attributes?.href ?? "no link"))
self.fileNameForDigest.setStrValue(value: "") // get an unexist file name
self.fileNameForFullText.setStrValue(value: "") // get an unexist file name
// add a spooling of file names to avoid the possible crash
return false
} // func loadData_FromParsedEntry 2017.9.20
} // class ItemFeed_Mem_TS: NSObject 2017.9.19
class ListOfItemFeeds_Memory_TS: NSObject {
private var listOfItemFeeds_Unsafe : [ItemFeed_Mem_TS] = []
private let accessQueue: DispatchQueue?
init(queueLabel: String){
let labelStr = UUID().uuidString +
"com.blogspot.cnshoe.iSpeak8.listOfItemFeeds_mem_ts" +
queueLabel
self.accessQueue = DispatchQueue(label: labelStr,
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
super.init()
} // init(queueLabel: String ) 2017.9.19
deinit{
printLog("deconstruction of class object ListOfItemFeeds_Memory_TS")
printLog("class name = \(type(of: self))")
printLog("class queue label = [\(self.accessQueue?.label ?? "")]")
} // deinit 2017.9.20
} // class ListOfItemFeeds_Memory_TS: NSObject 2017.9.19
| mit | 2e00004109fb2377f26b2b65f40a1610 | 37.474227 | 104 | 0.582529 | 4.567931 | false | false | false | false |
JohnPJenkins/swift-t | stc/docs/gallery/merge-sort/merge.swift | 2 | 473 | import string;
app (file o) sort(file i, file j)
{
// This uses the standard sort -m feature (merge)
"sort" "-mn" i j @stdout=o;
}
(file o) merge(int i, int j)
{
if (j-i == 1)
{
file fi = input(sprintf("data-%i.txt",i));
file fj = input(sprintf("data-%i.txt",j));
o = sort(fi, fj);
}
else
{
d = j - i + 1;
m = d %/ 2; // integer divide operator
o = sort(merge(i,i+m-1), merge(i+m,j));
}
}
file result <"sorted.txt"> = merge(0,7);
| apache-2.0 | 6563cd0d85ece5feda09ce54c1955ff2 | 17.92 | 51 | 0.530655 | 2.47644 | false | false | false | false |
mlibai/OMApp | iOS Example/Browser/HTTPViewController.swift | 1 | 6006 | //
// HTTPViewController.swift
// Browser
//
// Created by mlibai on 2017/6/14.
// Copyright © 2017年 mlibai. All rights reserved.
//
import UIKit
import XZKit
let kUserTokenDefaultsKey = "kHTTPHeadersDefaultsKey"
let kAccessTokenDefaultsKey = "kHTTPParametersDefaultsKey"
let kAutoRequestDefaultsKey = "kAutoRequestDefaultsKey"
protocol HTTPViewControllerDelegate: class {
func httpViewController(success: Bool, with result: Any?)
}
class HTTPViewController: UITableViewController, NavigationBarCustomizable, NavigationGestureDrivable {
static func viewController(requestObject: [String: Any]) -> HTTPViewController {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "http") as! HTTPViewController
viewController.requestObject = requestObject
return viewController
}
lazy var requestObject: [String: Any] = [:]
weak var delegate: HTTPViewControllerDelegate?
@IBOutlet weak var requestLabel: UILabel!
@IBOutlet weak var accessTokenTextField: UITextField!
@IBOutlet weak var userTokenTextField: UITextField!
@IBOutlet weak var autoRequestSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
if navigationController!.isNavigationBarCustomizable {
customNavigationBar.barTintColor = .red
customNavigationBar.title = "HTTP 测试"
}
let string = requestObject.map { (item) -> String in
return "\(item.key): \(item.value)"
}.joined(separator: " \n")
requestLabel.text = string
if let text = UserDefaults.standard.object(forKey: kUserTokenDefaultsKey) as? String {
userTokenTextField.text = text
}
if let text = UserDefaults.standard.object(forKey: kAccessTokenDefaultsKey) as? String {
accessTokenTextField.text = text
} else {
let uuid = UUID().uuidString
accessTokenTextField.text = uuid
UserDefaults.standard.setValue(uuid, forKey: kAccessTokenDefaultsKey)
}
self.autoRequestSwitch.isOn = UserDefaults.standard.bool(forKey: kAutoRequestDefaultsKey)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func autoRequestSwitchAction(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: kAutoRequestDefaultsKey)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row == tableView.numberOfRows(inSection: 0) - 1 else {
return
}
sendHTTP(with: requestObject, accessToken: accessTokenTextField.text, userToken: userTokenTextField.text) { (success, result) in
self.delegate?.httpViewController(success: success, with: result)
self.navigationController?.popViewController(animated: true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
func sendHTTP(with requestObject: [String: Any], accessToken: String?, userToken: String?, completion: @escaping ((Bool, Any?)->Void)) {
guard let url: String = requestObject["url"] as? String else {
return
}
guard let method: String = requestObject["method"] as? String else {
return
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = method
// headers
if let headers = requestObject["headers"] as? [String: Any] {
for item in headers {
request.addValue(String.init(forceCast: item.value), forHTTPHeaderField: item.key)
}
}
if let accessToken = accessToken {
request.setValue(accessToken, forHTTPHeaderField: "access-token")
}
if let userToken = userToken {
request.setValue(userToken, forHTTPHeaderField: "user-token")
}
// parameters
var parameters: [String: Any] = (requestObject["params"] as? [String: Any]) ?? [:]
if let userToken = userToken {
parameters["user_token"] = userToken
}
let httpBody = parameters.map({ (item) -> String in
return "\(item.key)=\(item.value)"
}).joined(separator: "&")
request.httpBody = httpBody.data(using: .utf8)
let activity = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activity.frame = UIScreen.main.bounds
activity.backgroundColor = UIColor.black.withAlphaComponent(0.7)
UIApplication.shared.keyWindow?.addSubview(activity)
activity.startAnimating()
activity.hidesWhenStopped = true
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
var result: Any? = nil
if let data = data {
if let response = response {
if let mimeType = response.mimeType {
if mimeType == "application/json" {
result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}
}
}
if result == nil {
result = String(data: data, encoding: .utf8)
}
}
DispatchQueue.main.async {
activity.stopAnimating()
activity.removeFromSuperview()
completion(error == nil, result)
}
}).resume()
UserDefaults.standard.setValue(userToken, forKey: kUserTokenDefaultsKey)
UserDefaults.standard.setValue(accessToken, forKey: kAccessTokenDefaultsKey)
}
| mit | 3992bc6a35cdb58db3ab3f1e71e93d96 | 34.922156 | 141 | 0.653442 | 5.003336 | false | false | false | false |
ahayman/RxStream | RxStream/Operators.swift | 1 | 1142 | //
// Operators.swift
// RxStream iOS
//
// Created by Aaron Hayman on 5/5/20.
// Copyright © 2020 Aaron Hayman. All rights reserved.
//
import Foundation
import Foundation
/**
Convenience operators for Rx
*/
infix operator <- : AssignmentPrecedence
@discardableResult public func <- <T>(left: ObservableInput<T>, right: T) -> T {
left.set(right)
return right
}
@discardableResult public func <- <T>(left: HotInput<T>, right: T) -> T {
left.push(right)
return right
}
public func == <T: Equatable>(left: Observable<T>, right: T) -> Bool {
return left.value == right
}
public func == <T: Equatable>(left: T, right: Observable<T>) -> Bool {
return left == right.value
}
public func != <T: Equatable>(left: Observable<T>, right: T) -> Bool {
return left.value != right
}
public func != <T: Equatable>(left: T, right: Observable<T>) -> Bool {
return left != right.value
}
@discardableResult public func <- <T>(left: HotWrap<T>, right: T) -> T {
left.push(value: right)
return right
}
@discardableResult public func <- <T>(left: ObservableWrap<T>, right: T) -> T {
left.push(value: right)
return right
}
| mit | 71cea8c8864aa17f9ac5a517284825b5 | 20.528302 | 80 | 0.658195 | 3.297688 | false | false | false | false |
ja-mes/experiments | iOS/MiraclePill/MiraclePill/AppDelegate.swift | 1 | 4582 | //
// AppDelegate.swift
// MiraclePill
//
// Created by James Brown on 8/10/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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 invalidate graphics rendering callbacks. 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 active 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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "MiraclePill")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 05a5561e5976fcb8a9c493256a6dff02 | 48.258065 | 285 | 0.685003 | 5.820839 | false | false | false | false |
nghiaphunguyen/NKit | NKit/Source/CustomViews/NKCircleImageView.swift | 1 | 2197 | //
// ProfilePictureImageView.swift
// FastSell
//
// Created by Nghia Nguyen on 2/20/16.
// Copyright © 2016 vn.fastsell. All rights reserved.
//
import UIKit
class NKCircleImageView: UIView {
lazy var circleView = NKCircleView(frame: CGRect.zero)
lazy var enableCircle = true
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.clipsToBounds = true
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
func setupView() {
self.backgroundColor = UIColor.clear
self.clipsToBounds = true
self.imageView.backgroundColor = UIColor.clear
self.addSubview(self.imageView)
self.circleView.backgroundColor = UIColor.clear
self.addSubview(self.circleView)
self.imageView.snp.makeConstraints { (make) -> Void in
make.top.equalToSuperview().offset(1)
make.leading.equalToSuperview().offset(1)
make.trailing.equalToSuperview().offset(-1)
make.bottom.equalToSuperview().offset(-1)
}
self.circleView.snp.makeConstraints { (make) -> Void in
make.edges.equalToSuperview()
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.enableCircle {
let width = rect.size.width / 2 - 1
self.imageView.layer.cornerRadius = width
}
}
}
class NKCircleView : UIView {
lazy var circleLineWidth: CGFloat = 0
lazy var circleColor = UIColor.white
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.setLineWidth(self.circleLineWidth)
context.setStrokeColor(self.circleColor.cgColor)
context.addEllipse(in: rect.insetBy(dx: self.circleLineWidth / 2, dy: self.circleLineWidth / 2))
context.strokePath()
}
}
| mit | 152f79e3efb2aa59d549630fed62adad | 26.45 | 104 | 0.602914 | 4.692308 | false | false | false | false |
HarrisLee/Utils | MySampleCode-master/GraphicsPerformance-Starter/GraphicsPerformance-Starter/CustomTableCell.swift | 1 | 1103 | //
// CustomTableCell.swift
// GraphicsPerformance-Starter
//
// Created by 张星宇 on 16/1/21.
// Copyright © 2016年 zxy. All rights reserved.
//
import UIKit
class CustomTableCell: UITableViewCell {
let imgView = UIImageView(frame: CGRectMake(10, 10, 180, 180))
let label = UILabel(frame: CGRectMake(220, 90, 150, 20))
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
imgView.layer.shadowColor = UIColor.blackColor().CGColor
imgView.layer.shadowOpacity = 1
imgView.layer.shadowRadius = 2
imgView.layer.shadowOffset = CGSizeMake(1, 1)
label.layer.shouldRasterize = true
self.contentView.addSubview(imgView)
self.contentView.addSubview(label)
}
func setupContent(imgName: String, text: String) {
imgView.image = UIImage(named: imgName)
label.text = text
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 603fc006fb1ac5c5699698ea9e7509e4 | 28.567568 | 74 | 0.656307 | 4.393574 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Helpers/PaymentSheetLinkAccount.swift | 1 | 18108 | //
// PaymentSheetLinkAccount.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 7/8/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
@_spi(STP) import StripePayments
protocol PaymentSheetLinkAccountInfoProtocol {
var email: String { get }
var redactedPhoneNumber: String? { get }
var isRegistered: Bool { get }
var isLoggedIn: Bool { get }
}
class PaymentSheetLinkAccount: PaymentSheetLinkAccountInfoProtocol {
enum SessionState {
case requiresSignUp
case requiresVerification
case verified
}
enum ConsentAction: String {
case checkbox = "clicked_checkbox_mobile"
case button = "clicked_button_mobile"
}
// Dependencies
let apiClient: STPAPIClient
let cookieStore: LinkCookieStore
/// Publishable key of the Consumer Account.
private(set) var publishableKey: String?
let email: String
var redactedPhoneNumber: String? {
return currentSession?.redactedPhoneNumber
}
var isRegistered: Bool {
return currentSession != nil
}
var isLoggedIn: Bool {
return sessionState == .verified
}
var sessionState: SessionState {
if let currentSession = currentSession {
// sms verification is not required if we are in the signup flow
return currentSession.hasVerifiedSMSSession || currentSession.isVerifiedForSignup ? .verified : .requiresVerification
} else {
return .requiresSignUp
}
}
var hasStartedSMSVerification: Bool {
return currentSession?.hasStartedSMSVerification ?? false
}
private var currentSession: ConsumerSession? = nil
init(
email: String,
session: ConsumerSession?,
publishableKey: String?,
apiClient: STPAPIClient = .shared,
cookieStore: LinkCookieStore = LinkSecureCookieStore.shared
) {
self.email = email
self.currentSession = session
self.publishableKey = publishableKey
self.apiClient = apiClient
self.cookieStore = cookieStore
}
func signUp(
with phoneNumber: PhoneNumber,
legalName: String?,
consentAction: ConsentAction,
completion: @escaping (Result<Void, Error>) -> Void
) {
signUp(
with: phoneNumber.string(as: .e164),
legalName: legalName,
countryCode: phoneNumber.countryCode,
consentAction: consentAction,
completion: completion
)
}
func signUp(
with phoneNumber: String,
legalName: String?,
countryCode: String?,
consentAction: ConsentAction,
completion: @escaping (Result<Void, Error>) -> Void
) {
guard case .requiresSignUp = sessionState else {
assertionFailure()
DispatchQueue.main.async {
completion(.failure(
PaymentSheetError.unknown(debugDescription: "Don't call sign up if not needed")
))
}
return
}
ConsumerSession.signUp(
email: email,
phoneNumber: phoneNumber,
legalName: legalName,
countryCode: countryCode,
consentAction: consentAction.rawValue,
with: apiClient,
cookieStore: cookieStore
) { [weak self, email] result in
switch result {
case .success(let signupResponse):
self?.currentSession = signupResponse.consumerSession
self?.publishableKey = signupResponse.preferences.publishableKey
self?.cookieStore.write(key: .lastSignupEmail, value: email)
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
func startVerification(completion: @escaping (Result<Bool, Error>) -> Void) {
guard case .requiresVerification = sessionState else {
DispatchQueue.main.async {
completion(.success(false))
}
return
}
guard let session = currentSession else {
assertionFailure()
DispatchQueue.main.async {
completion(.failure(
PaymentSheetError.unknown(debugDescription: "Don't call verify if not needed")
))
}
return
}
session.startVerification(
with: apiClient,
cookieStore: cookieStore,
consumerAccountPublishableKey: publishableKey
) { [weak self] result in
switch result {
case .success(let newSession):
self?.currentSession = newSession
completion(.success(newSession.hasStartedSMSVerification))
case .failure(let error):
completion(.failure(error))
}
}
}
func verify(with oneTimePasscode: String, completion: @escaping (Result<Void, Error>) -> Void) {
guard case .requiresVerification = sessionState,
hasStartedSMSVerification,
let session = currentSession else {
assertionFailure()
DispatchQueue.main.async {
completion(.failure(
PaymentSheetError.unknown(debugDescription: "Don't call verify if not needed")
))
}
return
}
session.confirmSMSVerification(
with: oneTimePasscode,
with: apiClient,
cookieStore: cookieStore,
consumerAccountPublishableKey: publishableKey
) { [weak self] result in
switch result {
case .success(let verifiedSession):
self?.currentSession = verifiedSession
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
func createLinkAccountSession(
completion: @escaping (Result<LinkAccountSession, Error>) -> Void
) {
guard let session = currentSession else {
assertionFailure()
completion(.failure(
PaymentSheetError.unknown(debugDescription: "Linking account session without valid consumer session")
))
return
}
retryingOnAuthError(completion: completion) { [publishableKey] completionWrapper in
session.createLinkAccountSession(
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func createPaymentDetails(
with paymentMethodParams: STPPaymentMethodParams,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
guard let session = currentSession else {
assertionFailure()
completion(
.failure(PaymentSheetError.unknown(debugDescription: "Saving to Link without valid session"))
)
return
}
retryingOnAuthError(completion: completion) { [apiClient, publishableKey] completionWrapper in
session.createPaymentDetails(
paymentMethodParams: paymentMethodParams,
with: apiClient,
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func createPaymentDetails(
linkedAccountId: String,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
guard let session = currentSession else {
assertionFailure()
completion(.failure(PaymentSheetError.unknown(debugDescription: "Saving to Link without valid session")))
return
}
retryingOnAuthError(completion: completion) { [publishableKey] completionWrapper in
session.createPaymentDetails(
linkedAccountId: linkedAccountId,
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func listPaymentDetails(
completion: @escaping (Result<[ConsumerPaymentDetails], Error>) -> Void
) {
guard let session = currentSession else {
assertionFailure()
completion(.failure(PaymentSheetError.unknown(debugDescription: "Paying with Link without valid session")))
return
}
retryingOnAuthError(completion: completion) { [apiClient, publishableKey] completionWrapper in
session.listPaymentDetails(
with: apiClient,
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func deletePaymentDetails(id: String, completion: @escaping (Result<Void, Error>) -> Void) {
guard let session = currentSession else {
assertionFailure()
return completion(.failure(PaymentSheetError.unknown(
debugDescription: "Deleting Link payment details without valid session")
))
}
retryingOnAuthError(completion: completion) { [apiClient, publishableKey] completionWrapper in
session.deletePaymentDetails(
with: apiClient,
id: id,
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func updatePaymentDetails(
id: String,
updateParams: UpdatePaymentDetailsParams,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
guard let session = currentSession else {
assertionFailure()
return completion(.failure(PaymentSheetError.unknown(
debugDescription: "Updating Link payment details without valid session")
))
}
retryingOnAuthError(completion: completion) { [apiClient, publishableKey] completionWrapper in
session.updatePaymentDetails(
with: apiClient,
id: id,
updateParams: updateParams,
consumerAccountPublishableKey: publishableKey,
completion: completionWrapper
)
}
}
func logout(completion: (() -> Void)? = nil) {
guard let session = currentSession else {
assertionFailure("Cannot logout without an active session")
completion?()
return
}
session.logout(
with: apiClient,
cookieStore: cookieStore,
consumerAccountPublishableKey: publishableKey
) { _ in
completion?()
}
// Delete cookie.
cookieStore.delete(key: .session)
markEmailAsLoggedOut()
// Forget current session.
self.currentSession = nil
}
func markEmailAsLoggedOut() {
guard let hashedEmail = email.lowercased().sha256 else {
return
}
cookieStore.write(key: .lastLogoutEmail, value: hashedEmail)
}
}
// MARK: - Equatable
extension PaymentSheetLinkAccount: Equatable {
static func == (lhs: PaymentSheetLinkAccount, rhs: PaymentSheetLinkAccount) -> Bool {
return (
lhs.email == rhs.email &&
lhs.currentSession == rhs.currentSession &&
lhs.publishableKey == rhs.publishableKey
)
}
}
// MARK: - Session refresh
private extension PaymentSheetLinkAccount {
typealias CompletionBlock<T> = (Result<T, Error>) -> Void
func retryingOnAuthError<T>(
completion: @escaping CompletionBlock<T>,
apiCall: @escaping (@escaping CompletionBlock<T>) -> Void
) {
apiCall() { [weak self] result in
switch result {
case .success(_):
completion(result)
case .failure(let error as NSError):
let isAuthError = (
error.domain == STPError.stripeDomain &&
error.code == STPErrorCode.authenticationError.rawValue
)
if isAuthError {
self?.refreshSession { refreshSessionResult in
switch refreshSessionResult {
case .success():
apiCall(completion)
case .failure(_):
completion(result)
}
}
} else {
completion(result)
}
}
}
}
func refreshSession(
completion: @escaping (Result<Void, Error>) -> Void
) {
// The consumer session lookup endpoint currently serves as our endpoint for
// refreshing the session. To refresh the session, we need to call this endpoint
// without providing an email address.
ConsumerSession.lookupSession(
for: nil, // No email address
with: apiClient,
cookieStore: cookieStore
) { [weak self] result in
switch result {
case .success(let response):
switch response.responseType {
case .found(let consumerSession, let preferences):
self?.currentSession = consumerSession
self?.publishableKey = preferences.publishableKey
completion(.success(()))
case .notFound(let errorMessage):
completion(
.failure(PaymentSheetError.unknown(debugDescription: errorMessage))
)
case .noAvailableLookupParams:
completion(
.failure(PaymentSheetError.unknown(debugDescription: "The client secret is missing"))
)
}
case .failure(let error):
completion(.failure(error))
}
}
}
}
// MARK: - Payment method params
extension PaymentSheetLinkAccount {
/// Converts a `ConsumerPaymentDetails` into a `STPPaymentMethodParams` object, injecting
/// the required Link credentials.
///
/// Returns `nil` if not authenticated/logged in.
///
/// - Parameter paymentDetails: Payment details
/// - Returns: Payment method params for paying with Link.
func makePaymentMethodParams(from paymentDetails: ConsumerPaymentDetails) -> STPPaymentMethodParams? {
guard let currentSession = currentSession else {
assertionFailure("Cannot make payment method params without an active session.")
return nil
}
let params = STPPaymentMethodParams(type: .link)
params.link?.paymentDetailsID = paymentDetails.stripeID
params.link?.credentials = ["consumer_session_client_secret": currentSession.clientSecret]
if let cvc = paymentDetails.cvc {
params.link?.additionalAPIParameters["card"] = [
"cvc": cvc
]
}
return params
}
}
// MARK: - Payment method availability
extension PaymentSheetLinkAccount {
/// Returns a set containing the Payment Details types that the user is able to use for confirming the given `intent`.
/// - Parameter intent: The Intent that the user is trying to confirm.
/// - Returns: A set containing the supported Payment Details types.
func supportedPaymentDetailsTypes(for intent: Intent) -> Set<ConsumerPaymentDetails.DetailsType> {
guard let currentSession = currentSession, let fundingSources = intent.linkFundingSources else {
return []
}
var supportedPaymentDetailsTypes: Set<ConsumerPaymentDetails.DetailsType> = .init(
currentSession.supportedPaymentDetailsTypes ?? []
)
// Take the intersection of the consumer session types and the merchant-provided Link funding sources
let fundingSourceDetailsTypes = Set(fundingSources.compactMap { $0.detailsType })
supportedPaymentDetailsTypes.formIntersection(fundingSourceDetailsTypes)
// Special testmode handling
if !intent.livemode && Self.emailSupportsMultipleFundingSourcesOnTestMode(email) {
supportedPaymentDetailsTypes.insert(.bankAccount)
}
return supportedPaymentDetailsTypes
}
func supportedPaymentMethodTypes(for intent: Intent) -> [STPPaymentMethodType] {
var supportedPaymentMethodTypes = [STPPaymentMethodType]()
for paymentDetailsType in supportedPaymentDetailsTypes(for: intent) {
switch paymentDetailsType {
case .card:
supportedPaymentMethodTypes.append(.card)
case .bankAccount:
supportedPaymentMethodTypes.append(.linkInstantDebit)
}
}
if supportedPaymentMethodTypes.isEmpty {
// Card is the default payment method type when no other type is available.
supportedPaymentMethodTypes.append(.card)
}
return supportedPaymentMethodTypes
}
}
// MARK: - Helpers
private extension PaymentSheetLinkAccount {
/// On *testmode* we use special email addresses for testing multiple funding sources. This method returns `true`
/// if the given `email` is one of such email addresses.
///
/// - Parameter email: Email.
/// - Returns: Whether or not should enable multiple funding sources on test mode.
static func emailSupportsMultipleFundingSourcesOnTestMode(_ email: String) -> Bool {
return email.contains("+multiple_funding_sources@")
}
}
private extension LinkSettings.FundingSource {
var detailsType: ConsumerPaymentDetails.DetailsType? {
switch self {
case .card:
return .card
case .bankAccount:
return .bankAccount
}
}
}
| mit | a0454fc846ee45cdaf6d9bfba7d1e4da | 32.469501 | 129 | 0.599437 | 5.98183 | false | false | false | false |
DasilvaKareem/yum | ios/yum/yum/LoginViewController.swift | 1 | 2977 | //
// LoginViewController.swift
// yum
//
// Created by Kareem Dasilva on 9/9/17.
// Copyright © 2017 poeen. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class LoginViewController: UIViewController {
private var ref: DatabaseReference!
private var userHelper: BaseUserHelper? = nil
@IBOutlet var emailTextField: UITextField!
@IBOutlet var passwordTextfield: UITextField!
@IBOutlet var loginButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
userHelper = (UIApplication.shared.delegate as! AppDelegate).userHelper
self.ref = Database.database().reference()
loginButton?.layer.borderColor = UIColor.white.cgColor
loginButton?.layer.cornerRadius = 8
loginButton?.layer.borderWidth = 1
emailTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logic(_ sender: Any) {
if let email = emailTextField.text, let password = passwordTextfield.text {
self.signIn(email: email, password: password)
}
}
func signIn(email: String, password: String) {
userHelper?.loginWith(email: email, password: password, ref: self.ref) { (loggedIn) in
if loggedIn {
print("logged in successfully")
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error == nil {
print("Can't sign in user")
} else {
self.dismiss(animated: true, completion: {
})
}
}
} else {
print("there is an error with logging in")
let alertController = UIAlertController(title: "Sorry", message: "Either your password or email is incorrect, try again.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{
(result: UIAlertAction) -> Void in
print("You pressed OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
| mit | 10be185954acbf37723d97a55ac18ae8 | 31.703297 | 184 | 0.615591 | 5.352518 | false | false | false | false |
BryanHoke/swift-corelibs-foundation | Foundation/NSCFDictionary.swift | 2 | 6096 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal final class _NSCFDictionary : NSMutableDictionary {
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
required init() {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) {
fatalError()
}
required convenience init(dictionaryLiteral elements: (NSObject, AnyObject)...) {
fatalError()
}
override var count: Int {
return CFDictionaryGetCount(unsafeBitCast(self, CFDictionaryRef.self))
}
override func objectForKey(aKey: AnyObject) -> AnyObject? {
let value = CFDictionaryGetValue(_cfObject, unsafeBitCast(aKey, UnsafePointer<Void>.self))
if value != nil {
return unsafeBitCast(value, AnyObject.self)
} else {
return nil
}
}
// This doesn't feel like a particularly efficient generator of CFDictionary keys, but it works for now. We should probably put a function into CF that allows us to simply iterate the keys directly from the underlying CF storage.
private struct _NSCFKeyGenerator : GeneratorType {
var keyArray : [NSObject] = []
var index : Int = 0
let count : Int
mutating func next() -> AnyObject? {
if index == count {
return nil
} else {
return keyArray[index++]
}
}
init(_ dict : _NSCFDictionary) {
let cf = dict._cfObject
count = CFDictionaryGetCount(cf)
let keys = UnsafeMutablePointer<UnsafePointer<Void>>.alloc(count)
CFDictionaryGetKeysAndValues(cf, keys, nil)
for idx in 0..<count {
let key = unsafeBitCast(keys.advancedBy(idx).memory, NSObject.self)
keyArray.append(key)
}
keys.destroy()
keys.dealloc(count)
}
}
override func keyEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(_NSCFKeyGenerator(self))
}
override func removeObjectForKey(aKey: AnyObject) {
CFDictionaryRemoveValue(_cfMutableObject, unsafeBitCast(aKey, UnsafePointer<Void>.self))
}
override func setObject(anObject: AnyObject, forKey aKey: NSObject) {
CFDictionarySetValue(_cfMutableObject, unsafeBitCast(aKey, UnsafePointer<Void>.self), unsafeBitCast(anObject, UnsafePointer<Void>.self))
}
}
internal func _CFSwiftDictionaryGetCount(dictionary: AnyObject) -> CFIndex {
return (dictionary as! NSDictionary).count
}
internal func _CFSwiftDictionaryGetCountOfKey(dictionary: AnyObject, key: AnyObject) -> CFIndex {
if _CFSwiftDictionaryContainsKey(dictionary, key: key) {
return 1
} else {
return 0
}
}
internal func _CFSwiftDictionaryContainsKey(dictionary: AnyObject, key: AnyObject) -> Bool {
return (dictionary as! NSDictionary).objectForKey(key) != nil
}
//(AnyObject, AnyObject) -> Unmanaged<AnyObject>
internal func _CFSwiftDictionaryGetValue(dictionary: AnyObject, key: AnyObject) -> Unmanaged<AnyObject>? {
if let obj = (dictionary as! NSDictionary).objectForKey(key) {
return Unmanaged<AnyObject>.passUnretained(obj)
} else {
return nil
}
}
internal func _CFSwiftDictionaryGetValueIfPresent(dictionary: AnyObject, key: AnyObject, value: UnsafeMutablePointer<Unmanaged<AnyObject>?>) -> Bool {
if let val = _CFSwiftDictionaryGetValue(dictionary, key: key) {
value.memory = val
return true
} else {
value.memory = nil
return false
}
}
internal func _CFSwiftDictionaryGetCountOfValue(dictionary: AnyObject, value: AnyObject) -> CFIndex {
if _CFSwiftDictionaryContainsValue(dictionary, value: value) {
return 1
} else {
return 0
}
}
internal func _CFSwiftDictionaryContainsValue(dictionary: AnyObject, value: AnyObject) -> Bool {
NSUnimplemented()
}
internal func _CFSwiftDictionaryGetKeysAndValues(dictionary: AnyObject, keybuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>, valuebuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>) {
var idx = 0
(dictionary as! NSDictionary).enumerateKeysAndObjectsUsingBlock { key, value, _ in
keybuf[idx] = Unmanaged<AnyObject>.passUnretained(key)
valuebuf[idx] = Unmanaged<AnyObject>.passUnretained(value)
idx++
}
}
internal func _CFSwiftDictionaryApplyFunction(dictionary: AnyObject, applier: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer<Void>) -> Void, context: UnsafeMutablePointer<Void>) {
(dictionary as! NSDictionary).enumerateKeysAndObjectsUsingBlock { key, value, _ in
applier(key, value, context)
}
}
internal func _CFSwiftDictionaryAddValue(dictionary: AnyObject, key: AnyObject, value: AnyObject) {
(dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject)
}
internal func _CFSwiftDictionaryReplaceValue(dictionary: AnyObject, key: AnyObject, value: AnyObject) {
(dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject)
}
internal func _CFSwiftDictionarySetValue(dictionary: AnyObject, key: AnyObject, value: AnyObject) {
(dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject)
}
internal func _CFSwiftDictionaryRemoveValue(dictionary: AnyObject, key: AnyObject) {
(dictionary as! NSMutableDictionary).removeObjectForKey(key)
}
internal func _CFSwiftDictionaryRemoveAllValues(dictionary: AnyObject) {
(dictionary as! NSMutableDictionary).removeAllObjects()
}
| apache-2.0 | be43f8a0ca49fc947ff52474290fc99c | 34.858824 | 233 | 0.681923 | 4.96013 | false | false | false | false |
noodlewerk/XLForm | Examples/Swift/Examples/Inputs/InputsFormViewController.swift | 17 | 5895 | //
// InputsFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 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.
class InputsFormViewController : XLFormViewController {
private enum Tags : String {
case Name = "name"
case Email = "email"
case Twitter = "twitter"
case Number = "number"
case Integer = "integer"
case Decimal = "decimal"
case Password = "password"
case Phone = "phone"
case Url = "url"
case ZipCode = "zipCode"
case TextView = "textView"
case Notes = "notes"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Text Fields")
form.assignFirstResponderOnShow = true
section = XLFormSectionDescriptor.formSectionWithTitle("TextField Types")
section.footerTitle = "This is a long text that will appear on section footer"
form.addFormSection(section)
// Name
row = XLFormRowDescriptor(tag: Tags.Name.rawValue, rowType: XLFormRowDescriptorTypeText, title: "Name")
row.required = true
section.addFormRow(row)
// Email
row = XLFormRowDescriptor(tag: Tags.Email.rawValue, rowType: XLFormRowDescriptorTypeEmail, title: "Email")
// validate the email
row.addValidator(XLFormValidator.emailValidator())
section.addFormRow(row)
// Twitter
row = XLFormRowDescriptor(tag: Tags.Name.rawValue, rowType: XLFormRowDescriptorTypeTwitter, title: "Twitter")
row.disabled = NSNumber(bool: true)
row.value = "@no_editable"
section.addFormRow(row)
// Zip Code
row = XLFormRowDescriptor(tag: Tags.ZipCode.rawValue, rowType: XLFormRowDescriptorTypeZipCode, title: "Zip Code")
section.addFormRow(row)
// Number
row = XLFormRowDescriptor(tag: Tags.Number.rawValue, rowType: XLFormRowDescriptorTypeNumber, title: "Number")
section.addFormRow(row)
// Integer
row = XLFormRowDescriptor(tag: Tags.Integer.rawValue, rowType: XLFormRowDescriptorTypeInteger, title: "Integer")
section.addFormRow(row)
// Decimal
row = XLFormRowDescriptor(tag: Tags.Decimal.rawValue, rowType: XLFormRowDescriptorTypeDecimal, title: "Decimal")
section.addFormRow(row)
// Password
row = XLFormRowDescriptor(tag: Tags.Password.rawValue, rowType: XLFormRowDescriptorTypePassword, title: "Password")
section.addFormRow(row)
// Phone
row = XLFormRowDescriptor(tag: Tags.Phone.rawValue, rowType: XLFormRowDescriptorTypePhone, title: "Phone")
section.addFormRow(row)
// Url
row = XLFormRowDescriptor(tag: Tags.Url.rawValue, rowType: XLFormRowDescriptorTypeURL, title: "Url")
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// TextView
row = XLFormRowDescriptor(tag: Tags.TextView.rawValue, rowType: XLFormRowDescriptorTypeTextView)
row.cellConfigAtConfigure["textView.placeholder"] = "TEXT VIEW EXAMPLE"
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("TextView With Label Example")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Number.rawValue, rowType: XLFormRowDescriptorTypeTextView, title: "Notes")
section.addFormRow(row)
self.form = form
}
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: "savePressed:")
}
func savePressed(button: UIBarButtonItem)
{
let validationErrors : Array<NSError> = self.formValidationErrors() as! Array<NSError>
if (validationErrors.count > 0){
self.showFormValidationError(validationErrors.first)
return
}
self.tableView.endEditing(true)
let alertView = UIAlertView(title: "Valid Form", message: "No errors found", delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
}
| mit | 8f6355720c274971bd567f4725a894b1 | 37.529412 | 151 | 0.664801 | 5.130548 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/Messages/ReadTimeCarelinkMessageBody.swift | 1 | 1018 | //
// ReadTimeCarelinkMessageBody.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/17/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public class ReadTimeCarelinkMessageBody: CarelinkLongMessageBody {
public let dateComponents: DateComponents
public required init?(rxData: Data) {
guard rxData.count == type(of: self).length else {
return nil
}
var dateComponents = DateComponents()
dateComponents.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
dateComponents.hour = Int(rxData[1] as UInt8)
dateComponents.minute = Int(rxData[2] as UInt8)
dateComponents.second = Int(rxData[3] as UInt8)
dateComponents.year = Int(bigEndianBytes: rxData.subdata(in: 4..<6))
dateComponents.month = Int(rxData[6] as UInt8)
dateComponents.day = Int(rxData[7] as UInt8)
self.dateComponents = dateComponents
super.init(rxData: rxData)
}
}
| mit | 8ea4d978d553f29eb3c017701ddbfbdb | 28.911765 | 85 | 0.67355 | 4.202479 | false | false | false | false |
elysiumd/ios-wallet | BreadWallet/BRBSPatch.swift | 2 | 9447 | //
// BRBSPatch.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
//
// 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
enum BRBSPatchError: Error {
case unknown
case corruptPatch
case patchFileDoesntExist
case oldFileDoesntExist
}
class BRBSPatch {
static let patchLogEnabled = true
static func patch(_ oldFilePath: String, newFilePath: String, patchFilePath: String)
throws -> UnsafeMutablePointer<CUnsignedChar> {
func offtin(_ b: UnsafePointer<CUnsignedChar>) -> off_t {
var y = off_t(b[0])
y |= off_t(b[1]) << 8
y |= off_t(b[2]) << 16
y |= off_t(b[3]) << 24
y |= off_t(b[4]) << 32
y |= off_t(b[5]) << 40
y |= off_t(b[6]) << 48
y |= off_t(b[7] & 0x7f) << 56
if Int(b[7]) & 0x80 != 0 {
y = -y
}
return y
}
let patchFilePathBytes = UnsafePointer<Int8>((patchFilePath as NSString).utf8String)
let r = UnsafePointer<Int8>(("r" as NSString).utf8String)
// open patch file
guard let f = FileHandle(forReadingAtPath: patchFilePath) else {
log("unable to open file for reading at path \(patchFilePath)")
throw BRBSPatchError.patchFileDoesntExist
}
// read header
let headerData = f.readData(ofLength: 32)
let header = (headerData as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: headerData.count)
if headerData.count != 32 {
log("incorrect header read length \(headerData.count)")
throw BRBSPatchError.corruptPatch
}
// check for appropriate magic
let magicData = headerData.subdata(in: 0..<8)
if let magic = String(bytes: magicData, encoding: String.Encoding.ascii), magic != "BSDIFF40" {
log("incorrect magic: \(magic)")
throw BRBSPatchError.corruptPatch
}
// read lengths from header
let bzCrtlLen = offtin(header + 8)
let bzDataLen = offtin(header + 16)
let newSize = offtin(header + 24)
if bzCrtlLen < 0 || bzDataLen < 0 || newSize < 0 {
log("incorrect header data: crtlLen: \(bzCrtlLen) dataLen: \(bzDataLen) newSize: \(newSize)")
throw BRBSPatchError.corruptPatch
}
// close patch file and re-open it with bzip2 at the right positions
f.closeFile()
let cpf = fopen(patchFilePathBytes, r)
if cpf == nil {
let s = String(cString: strerror(errno))
let ff = String(cString: patchFilePathBytes!)
log("unable to open patch file c: \(s) \(ff)")
throw BRBSPatchError.unknown
}
let cpfseek = fseeko(cpf, 32, SEEK_SET)
if cpfseek != 0 {
log("unable to seek patch file c: \(cpfseek)")
throw BRBSPatchError.unknown
}
let cbz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let cpfbz2 = BZ2_bzReadOpen(cbz2err, cpf, 0, 0, nil, 0)
if cpfbz2 == nil {
log("unable to bzopen patch file c: \(cbz2err)")
throw BRBSPatchError.unknown
}
let dpf = fopen(patchFilePathBytes, r)
if dpf == nil {
log("unable to open patch file d")
throw BRBSPatchError.unknown
}
let dpfseek = fseeko(dpf, 32 + bzCrtlLen, SEEK_SET)
if dpfseek != 0 {
log("unable to seek patch file d: \(dpfseek)")
throw BRBSPatchError.unknown
}
let dbz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let dpfbz2 = BZ2_bzReadOpen(dbz2err, dpf, 0, 0, nil, 0)
if dpfbz2 == nil {
log("unable to bzopen patch file d: \(dbz2err)")
throw BRBSPatchError.unknown
}
let epf = fopen(patchFilePathBytes, r)
if epf == nil {
log("unable to open patch file e")
throw BRBSPatchError.unknown
}
let epfseek = fseeko(epf, 32 + bzCrtlLen + bzDataLen, SEEK_SET)
if epfseek != 0 {
log("unable to seek patch file e: \(epfseek)")
throw BRBSPatchError.unknown
}
let ebz2err = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
let epfbz2 = BZ2_bzReadOpen(ebz2err, epf, 0, 0, nil, 0)
if epfbz2 == nil {
log("unable to bzopen patch file e: \(ebz2err)")
throw BRBSPatchError.unknown
}
guard let oldData = try? Data(contentsOf: URL(fileURLWithPath: oldFilePath)) else {
log("unable to read old file path")
throw BRBSPatchError.unknown
}
let old = (oldData as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: oldData.count)
let oldSize = off_t(oldData.count)
var oldPos: off_t = 0, newPos: off_t = 0
let new = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: Int(newSize) + 1)
let buf = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 8)
var crtl = Array<off_t>(repeating: 0, count: 3)
while newPos < newSize {
// read control data
for i in 0...2 {
let lenread = BZ2_bzRead(cbz2err, cpfbz2, buf, 8)
if (lenread < 8) || ((cbz2err.pointee != BZ_OK) && (cbz2err.pointee != BZ_STREAM_END)) {
log("unable to read control data \(lenread) \(cbz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
crtl[i] = offtin(UnsafePointer<CUnsignedChar>(buf))
}
// sanity check
if (newPos + crtl[0]) > newSize {
log("incorrect size of crtl[0]")
throw BRBSPatchError.corruptPatch
}
// read diff string
let dlenread = BZ2_bzRead(dbz2err, dpfbz2, new + Int(newPos), Int32(crtl[0]))
if (dlenread < Int32(crtl[0])) || ((dbz2err.pointee != BZ_OK) && (dbz2err.pointee != BZ_STREAM_END)) {
log("unable to read diff string \(dlenread) \(dbz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
// add old data to diff string
if crtl[0] > 0 {
for i in 0...(Int(crtl[0]) - 1) {
if (oldPos + i >= 0) && (oldPos + i < oldSize) {
let np = Int(newPos) + i, op = Int(oldPos) + i
new[np] = new[np] &+ old[op]
}
}
}
// adjust pointers
newPos += crtl[0]
oldPos += crtl[0]
// sanity check
if (newPos + crtl[1]) > newSize {
log("incorrect size of crtl[1]")
throw BRBSPatchError.corruptPatch
}
// read extra string
let elenread = BZ2_bzRead(ebz2err, epfbz2, new + Int(newPos), Int32(crtl[1]))
if (elenread < Int32(crtl[1])) || ((ebz2err.pointee != BZ_OK) && (ebz2err.pointee != BZ_STREAM_END)) {
log("unable to read extra string \(elenread) \(ebz2err.pointee)")
throw BRBSPatchError.corruptPatch
}
// adjust pointers
newPos += crtl[1]
oldPos += crtl[2]
}
// clean up bz2 reads
BZ2_bzReadClose(cbz2err, cpfbz2)
BZ2_bzReadClose(dbz2err, dpfbz2)
BZ2_bzReadClose(ebz2err, epfbz2)
if (fclose(cpf) != 0) || (fclose(dpf) != 0) || (fclose(epf) != 0) {
log("unable to close bzip file handles")
throw BRBSPatchError.unknown
}
// write out new file
let fm = FileManager.default
if fm.fileExists(atPath: newFilePath) {
try fm.removeItem(atPath: newFilePath)
}
let newData = Data(bytes: UnsafePointer<UInt8>(new), count: Int(newSize))
try newData.write(to: URL(fileURLWithPath: newFilePath), options: .atomic)
return new
}
static fileprivate func log(_ string: String) {
if patchLogEnabled {
print("[BRBSPatch] \(string)")
}
}
}
| mit | 9f19148f44dd1bc0cef1b030f3d788a6 | 39.371795 | 114 | 0.560284 | 4.259243 | false | false | false | false |
edjiang/forward-swift-workshop | SwiftNotesIOS/Pods/Stormpath/Stormpath/Account.swift | 1 | 4545 | //
// Account.swift
// Stormpath
//
// Created by Edward Jiang on 2/11/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
/**
Account represents an account object from the Stormpath database.
*/
public class Account: NSObject {
/// Stormpath resource URL for the account
internal(set) public var href: NSURL!
/// Username of the user. Separate from the email, but is often set to the email
/// address.
internal(set) public var username: String!
/// Email address of the account.
internal(set) public var email: String!
/**
Given (first) name of the user. Will appear as "UNKNOWN" on platforms
that do not require `givenName`
*/
internal(set) public var givenName: String!
/// Middle name of the user. Optional.
internal(set) public var middleName: String?
/**
Sur (last) name of the user. Will appear as "UNKNOWN" on platforms that do not require `surname`
*/
internal(set) public var surname: String!
/// Full name of the user.
public var fullName: String {
return (middleName == nil || middleName == "") ? "\(givenName) \(surname)" : "\(givenName) \(middleName!) \(surname)"
}
/// Date the account was created in the Stormpath database.
internal(set) public var createdAt: NSDate!
/// Date the account was last modified in the Stormpath database.
internal(set) public var modifiedAt: NSDate!
/// Status of the account. Useful if email verification is needed.
internal(set) public var status: AccountStatus
/// A string of JSON representing the custom data for the account. Cannot be updated in the current version of the SDK.
internal(set) public var customData: String?
/// Initializer for the JSON object for the account. Expected to be wrapped in `{account: accountObject}`
init?(fromJSON jsonData: NSData) {
self.status = .Enabled //will be overridden below; hack to allow obj-c to access property since primitive types can't be optional
super.init()
guard let rootJSON = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []),
json = rootJSON["account"] as? [String: AnyObject],
hrefString = json["href"] as? String,
href = NSURL(string: hrefString),
username = json["username"] as? String,
email = json["email"] as? String,
givenName = json["givenName"] as? String,
surname = json["surname"] as? String,
createdAt = (json["createdAt"] as? String)?.dateFromISO8601Format,
modifiedAt = (json["modifiedAt"] as? String)?.dateFromISO8601Format,
status = json["status"] as? String else {
return nil
}
self.href = href
self.username = username
self.email = email
self.givenName = givenName
self.middleName = json["middleName"] as? String
self.surname = surname
self.createdAt = createdAt
self.modifiedAt = modifiedAt
switch status {
case "ENABLED":
self.status = AccountStatus.Enabled
case "UNVERIFIED":
self.status = AccountStatus.Unverified
case "DISABLED":
self.status = AccountStatus.Disabled
default:
return nil
}
if let customDataObject = json["customData"] as? [String: AnyObject],
customDataData = try? NSJSONSerialization.dataWithJSONObject(customDataObject, options: []),
customDataString = String(data: customDataData, encoding: NSUTF8StringEncoding) {
self.customData = customDataString
}
}
}
/// Stormpath Account Status
@objc public enum AccountStatus: Int {
//It's an int for Obj-C compatibility
/// Enabled means that we can login to this account
case Enabled
/// Unverified is the same as disabled, but a user can enable it by
/// clicking on the activation email.
case Unverified
/// Disabled means that users cannot log in to the account.
case Disabled
}
/// Helper extension to make optional chaining easier.
private extension String {
var dateFromISO8601Format: NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.dateFromString(self)
}
} | apache-2.0 | c22c91733b8c3cb0ce25c8d9b3341a1e | 35.071429 | 137 | 0.637324 | 4.778128 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/Lab/QDThemeViewController.swift | 1 | 4953 | //
// QDThemeViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/16.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDThemeViewController: QDCommonViewController {
private lazy var themes: [NSObject & QDThemeProtocol] = {
var themes: [NSObject & QDThemeProtocol] = []
let allThemeClassName = [
String(describing: QMUIConfigurationTemplate.self),
String(describing: QMUIConfigurationTemplateGrapefruit.self),
String(describing: QMUIConfigurationTemplateGrass.self),
String(describing: QMUIConfigurationTemplatePinkRose.self),
]
allThemeClassName.forEach({
if let currentTheme = QDThemeManager.shared.currentTheme {
if $0 == String(describing: type(of: currentTheme)) {
themes.append(currentTheme)
} else {
if let cls: NSObject.Type = NSClassFromString($0) as? NSObject.Type {
if let theme = cls.init() as? (NSObject & QDThemeProtocol) {
themes.append(theme)
}
}
}
}
})
return themes
}()
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: view.bounds)
return scrollView
}()
private var themeButtons: [QDThemeButton] = []
override func didInitialized() {
super.didInitialized()
}
override func initSubviews() {
super.initSubviews()
view.addSubview(scrollView)
themes.forEach {
var isCurrentTheme = false
let currentTheme = QDThemeManager.shared.currentTheme
if type(of: currentTheme) == type(of: $0) {
isCurrentTheme = true
}
let themeButton = QDThemeButton()
themeButton.themeColor = $0.themeTintColor
themeButton.themeName = $0.themeName
themeButton.isSelected = isCurrentTheme
themeButton.addTarget(self, action: #selector(handleThemeButtonEvent(_:)), for: .touchUpInside)
scrollView.addSubview(themeButton)
themeButtons.append(themeButton)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
let padding = UIEdgeInsets(top: 24, left: 24, bottom: 24, right: 24)
let buttonSpacing: CGFloat = 24
let buttonSize = CGSize(width: scrollView.bounds.width - padding.horizontalValue, height: 110).flatted
var buttonMinY = padding.top
for (i, themeButton) in themeButtons.enumerated() {
themeButton.frame = CGRect(x: padding.left, y: buttonMinY, width: buttonSize.width, height: buttonSize.height)
buttonMinY = themeButton.frame.maxY + CGFloat(i == themeButtons.count - 1 ? 0 : buttonSpacing)
}
scrollView.contentSize = CGSize(width: scrollView.bounds.width - padding.horizontalValue, height: buttonMinY + padding.bottom)
}
@objc func handleThemeButtonEvent(_ themeButton: QDThemeButton) {
themeButtons.forEach {
$0.isSelected = themeButton == $0
}
let themeIndex = themeButtons.firstIndex(of: themeButton) ?? 0
let theme = themes[themeIndex]
QDThemeManager.shared.currentTheme = theme
let value = String(describing: type(of: theme))
UserDefaults.standard.set(value, forKey: QDSelectedThemeClassName)
}
}
class QDThemeButton: QMUIButton {
fileprivate var themeColor: UIColor? {
didSet {
backgroundColor = themeColor
setTitleColor(themeColor, for: .normal)
}
}
fileprivate var themeName: String? {
didSet {
setTitle(themeName, for: .normal)
}
}
override var isSelected: Bool {
didSet {
titleLabel?.font = isSelected ? UIFontBoldMake(14) : UIFontMake(14)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.font = UIFontMake(14)
titleLabel?.textAlignment = .center
titleLabel?.backgroundColor = UIColorWhite
setTitleColor(UIColorGray3, for: .normal)
layer.borderWidth = PixelOne
layer.borderColor = UIColor(r: 0, g: 0, b: 0, a: 0.1).cgColor
layer.cornerRadius = 4
layer.masksToBounds = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let labelHeight: CGFloat = 36
titleLabel?.frame = CGRect(x: 0, y: bounds.height - labelHeight, width: bounds.width, height: labelHeight)
}
}
| mit | 6d6cfb806dc6d63453a29f12ada66f6f | 33.333333 | 134 | 0.599312 | 5.034623 | false | false | false | false |
eliasbloemendaal/KITEGURU | KITEGURU/KITEGURU/MapViewController.swift | 1 | 2029 | //
// MapViewController.swift
// KITEGURU
//
// Created by Elias Houttuijn Bloemendaal on 09-01-16.
// Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController ,MKMapViewDelegate ,CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
// self.mapView.showsUserLocation = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("ERROR: " + error.localizedDescription)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 34d29f53d1f89e7f03e84cc7d990b63e | 31.709677 | 127 | 0.70858 | 5.51087 | false | false | false | false |
GTMYang/GTMRouter | GTMRouter/UIViewController+GTMRouter.swift | 1 | 3016 | //
// UIViewController+GTMRouter.swift
// GTMRouter
//
// Created by luoyang on 2016/12/20.
// Copyright © 2016年 luoyang. All rights reserved.
//
import UIKit
extension UIViewController {
// 注入url参数
func initQueryParameters(parameters: [String: String]) {
let children = Mirror(reflecting: self).children.filter { $0.label != nil }
for child in children {
if let key = child.label, let val = parameters[key] {
let propertyType = type(of: child.value)
switch propertyType {
case _ as String.Type, _ as Optional<String>.Type:
self.setValue(val, forKey: key)
case _ as Int.Type:
self.setValue(val.intValue, forKey: key)
case _ as Optional<Int>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Int>类型,改成Int类型")
case _ as Float.Type:
self.setValue(val.floatValue, forKey: key)
case _ as Optional<Float>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Float>类型,改成Float类型")
case _ as Double.Type:
self.setValue(val.doubleValue, forKey: key)
case _ as Optional<Double>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Double>类型,改成Double类型")
case _ as Bool.Type:
self.setValue(val.boolValue, forKey: key)
case _ as Optional<Bool>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Bool>类型,改成Bool类型")
default:
break
}
}
}
}
// 注入dic参数
func initliazeDicParameters(parameters: [String: Any]) {
let children = Mirror(reflecting: self).children.filter { $0.label != nil }
for child in children {
if let key = child.label, let val = parameters[key] {
let propertyType = type(of: child.value)
switch propertyType {
case _ as Optional<Int>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Int>类型,改成Int类型")
case _ as Optional<Float>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Float>类型,改成Float类型")
case _ as Optional<Double>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Double>类型,改成Double类型")
case _ as Optional<Bool>.Type:
assert(false, "GTMRouter --> 参数不支持Optional<Bool>类型,改成Bool类型")
default:
break
}
self.setValue(val, forKey: key)
}
}
}
}
| mit | 3bd533f1ac347ba5ceb063b51620bd93 | 38.507042 | 85 | 0.507308 | 4.762309 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Extensions/UITableView-Extensions.swift | 1 | 563 | //
// UITableView-Extensions.swift
// Habitica
//
// Created by Phillip Thelen on 20.08.20.
// Copyright © 2020 HabitRPG Inc. All rights reserved.
//
import Foundation
extension UITableView {
func isVisible(indexPath: IndexPath) -> Bool {
return indexPathsForVisibleRows?.contains(where: { visiblePath -> Bool in
return visiblePath.section == indexPath.section && visiblePath.item == indexPath.item
}) == true
}
func isVisible(cell: UITableViewCell) -> Bool {
return visibleCells.contains(cell)
}
}
| gpl-3.0 | 126a37f9b3222d2bffd93429f126d65b | 25.761905 | 97 | 0.66548 | 4.390625 | false | false | false | false |
InsectQY/HelloSVU_Swift | HelloSVU_Swift/Classes/Expand/Tools/Calculate/CalculateTool.swift | 1 | 1123 | //
// CalculateTool.swift
// HelloSVU_Swift
//
// Created by Insect on 2017/11/3.
// Copyright © 2017年 Insect. All rights reserved.
//
import UIKit
class CalculateTool: NSObject {
// MARK: - 获得步行距离(传入单位 "米")
class func getWalkDistance(_ walkingDistance: CGFloat) -> String {
if walkingDistance == 0 {
return "同站换乘"
}
/// 距离
let distance = walkingDistance / 1000.0
if distance < 1 { //步行距离在一千米以内
return String(format: "步行%.f米", walkingDistance)
} else {
return String(format: "步行%.1f公里", distance)
}
}
// MARK: - 获得所花费时间(传入单位 "秒")
class func getDuration(_ duration: Int) -> String {
let duration = duration / 60
if duration < 60 { //时间在一小时以内
return "\(duration)分钟"
} else {
let hour = duration / 60
let minute = duration % 60
return "\(hour)小时\(minute)分钟"
}
}
}
| apache-2.0 | adf9d20f195c4d4b049c90c05bbf3207 | 23.390244 | 70 | 0.521 | 3.861004 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/InputPasswordController.swift | 1 | 5242 | //
// InputPasswordController.swift
// Telegram
//
// Created by Mikhail Filimonov on 06/06/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import TelegramCore
import TGUIKit
enum InputPasswordValueError {
case generic
case wrong
}
private struct InputPasswordState : Equatable {
let error: InputDataValueError?
let value: InputDataValue
let isLoading: Bool
init(value: InputDataValue, error: InputDataValueError?, isLoading: Bool) {
self.value = value
self.error = error
self.isLoading = isLoading
}
func withUpdatedError(_ error: InputDataValueError?) -> InputPasswordState {
return InputPasswordState(value: self.value, error: error, isLoading: self.isLoading)
}
func withUpdatedValue(_ value: InputDataValue) -> InputPasswordState {
return InputPasswordState(value: value, error: self.error, isLoading: self.isLoading)
}
func withUpdatedLoading(_ isLoading: Bool) -> InputPasswordState {
return InputPasswordState(value: self.value, error: self.error, isLoading: isLoading)
}
}
private let _id_input_pwd:InputDataIdentifier = InputDataIdentifier("_id_input_pwd")
private func inputPasswordEntries(state: InputPasswordState, desc:String) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.input(sectionId: sectionId, index: index, value: state.value, error: state.error, identifier: _id_input_pwd, mode: .secure, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().inputPasswordControllerPlaceholder, filter: { $0 }, limit: 255))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(desc), data: InputDataGeneralTextData(detectBold: false, viewType: .textBottomItem)))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func InputPasswordController(context: AccountContext, title: String, desc: String, checker:@escaping(String)->Signal<Never, InputPasswordValueError>) -> InputDataModalController {
let initialState: InputPasswordState = InputPasswordState(value: .string(nil), error: nil, isLoading: false)
let stateValue: Atomic<InputPasswordState> = Atomic(value: initialState)
let statePromise:ValuePromise<InputPasswordState> = ValuePromise(initialState, ignoreRepeated: true)
let updateState:(_ f:(InputPasswordState)->InputPasswordState) -> Void = { f in
statePromise.set(stateValue.modify(f))
}
let dataSignal = statePromise.get() |> map { state in
return inputPasswordEntries(state: state, desc: desc)
} |> map { entries in
return InputDataSignalValue(entries: entries)
}
let checkPassword = MetaDisposable()
var dismiss:(()->Void)?
let controller = InputDataController(dataSignal: dataSignal, title: title, validateData: { data in
return .fail(.doSomething { f in
if let pwd = data[_id_input_pwd]?.stringValue, !stateValue.with({$0.isLoading}) {
updateState {
return $0.withUpdatedLoading(true)
}
checkPassword.set(showModalProgress(signal: checker(pwd), for: context.window).start(error: { error in
let text: String
switch error {
case .wrong:
text = strings().inputPasswordControllerErrorWrongPassword
case .generic:
text = strings().unknownError
}
updateState {
return $0.withUpdatedLoading(false).withUpdatedError(InputDataValueError(description: text, target: .data))
}
f(.fail(.fields([_id_input_pwd : .shake])))
}, completed: {
updateState {
return $0.withUpdatedLoading(false)
}
dismiss?()
}))
}
})
}, updateDatas: { data in
updateState {
return $0.withUpdatedValue(data[_id_input_pwd]!).withUpdatedError(nil)
}
return .fail(.none)
}, afterDisappear: {
checkPassword.dispose()
}, hasDone: true)
let interactions = ModalInteractions(acceptTitle: strings().navigationDone, accept: { [weak controller] in
controller?.validateInputValues()
}, drawBorder: true, height: 50, singleButton: true)
controller.getBackgroundColor = {
theme.colors.listBackground
}
let modalController = InputDataModalController(controller, modalInteractions: interactions, size: NSMakeSize(300, 300))
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
dismiss = { [weak modalController] in
modalController?.close()
}
return modalController
}
| gpl-2.0 | 2ee8466becec898d18ca55bca5883cff | 36.170213 | 301 | 0.642053 | 5.068665 | false | false | false | false |
acediac/BananasSwift | Common/UI/AAPLMainMenu.swift | 1 | 1406 | //
// AAPLMainMenu.swift
// BananasSwift
//
// Created by Andrew on 20/04/2015.
// Copyright (c) 2015 Machina Venefici. All rights reserved.
//
/*
Abstract:
A Sprite Kit node that provides the title screen for the game, displayed by the AAPLInGameScene class.
*/
import Foundation
import SpriteKit
class AAPLMainMenu: SKNode {
var gameLogo: SKSpriteNode
// var myLabelBackground: SKLabelNode
init(frameSize:CGSize) {
self.gameLogo = SKSpriteNode(imageNamed:"art.scnassets/level/interface/logo_bananas.png")
super.init()
self.position = CGPointMake(frameSize.width * 0.5, frameSize.height * 0.15)
self.userInteractionEnabled = true
// resize logo to fit the screen
var size: CGSize = self.gameLogo.size
let factor: CGFloat = frameSize.width / size.width
size.width *= factor
size.height *= factor
self.gameLogo.size = size
self.gameLogo.anchorPoint = CGPointMake(1, 0)
self.gameLogo.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(self.gameLogo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func touchUpAtPoint(location: CGPoint) {
self.hidden = true
AAPLGameSimulation.sim.gameState = .InGame
}
} | gpl-2.0 | 0dbb704041eab3ded3dc1d7b87864abf | 27.14 | 102 | 0.655761 | 4.23494 | false | false | false | false |
mayongl/CS193P | Cassini/Cassini/DemoURL.swift | 1 | 802 | //
// DemoURL.swift
// Cassini
//
// Created by Yonglin Ma on 3/27/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import Foundation
struct DemoURL
{
static let Standford = URL(string: "http://comm.stanford.edu/mm/2016/08/mcclatchy-hall-600x300.jpg")
static var NASA : Dictionary<String,URL> = {
let NASAURLStrings = [
"Cassini" : "http://mimg.xmeise.com/thumb/m/mmimg/39/39990/39990_44.jpg",
"Earth" : "http://img.daimg.com/uploads/allimg/161019/3-161019225355.jpg",
"Saturn" : "http://mimg.xmeise.com/thumb/m/mmimg/39/39973/39973_13.jpg"]
var urls = Dictionary<String, URL>()
for (key, value) in NASAURLStrings {
urls[key] = URL(string: value)
}
return urls
}()
}
| apache-2.0 | 57e747a6d55bb9e5d4373952109f5318 | 27.607143 | 104 | 0.602996 | 3.034091 | false | false | false | false |
choefele/AlexaSkillsKit | Sources/AlexaSkillsKit/ResponseGeneratorV1.swift | 1 | 2702 | import Foundation
public class ResponseGeneratorV1: ResponseGenerator {
public var standardResponse: StandardResponse?
public var sessionAttributes: [String: Any]
public init(standardResponse: StandardResponse = StandardResponse(), sessionAttributes: [String: Any] = [:]) {
self.standardResponse = standardResponse
self.sessionAttributes = sessionAttributes
}
public func generateJSONObject() -> [String: Any] {
var json: [String: Any] = ["version": "1.0"]
json["sessionAttributes"] = sessionAttributes.isEmpty ? nil : sessionAttributes
json["response"] = standardResponse.map{ ResponseGeneratorV1.generateStandardResponse($0) }
return json
}
}
extension ResponseGeneratorV1 {
class func generateStandardResponse(_ standardResponse: StandardResponse) -> [String: Any] {
var jsonResponse = [String: Any]()
if let outputSpeech = standardResponse.outputSpeech {
jsonResponse["outputSpeech"] = ResponseGeneratorV1.generateOutputSpeech(outputSpeech)
}
if let reprompt = standardResponse.reprompt {
let jsonOutputSpeech = ["outputSpeech": ResponseGeneratorV1.generateOutputSpeech(reprompt)]
jsonResponse["reprompt"] = jsonOutputSpeech
}
if let card = standardResponse.card {
jsonResponse["card"] = ResponseGeneratorV1.generateCard(card)
}
if !standardResponse.shouldEndSession {
#if os(Linux)
jsonResponse["shouldEndSession"] = NSNumber(booleanLiteral: standardResponse.shouldEndSession)
#else
jsonResponse["shouldEndSession"] = standardResponse.shouldEndSession
#endif
}
return jsonResponse
}
class func generateOutputSpeech(_ outputSpeech: OutputSpeech) -> [String: Any] {
switch outputSpeech {
case .plain(let text): return ["type": "PlainText", "text": text]
}
}
class func generateCard(_ card: Card) -> [String: Any] {
switch card {
case .simple(let title, let content):
var jsonCard: [String: Any] = ["type": "Simple"]
jsonCard["title"] = title
jsonCard["content"] = content
return jsonCard
case .standard(let title, let text, let image):
var jsonCard: [String: Any] = ["type": "Standard"]
jsonCard["title"] = title
jsonCard["text"] = text
jsonCard["image"] = ["smallImageUrl": image?.smallImageUrl, "largeImageUrl": image?.largeImageUrl]
return jsonCard
}
}
}
| mit | 87220bd3ef736c0761286bcd4216311d | 37.056338 | 114 | 0.618431 | 5.267057 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/CreationModal/RoomCreationEventsModal/RoomCreationEventsModalCoordinator.swift | 1 | 2673 | // File created from ScreenTemplate
// $ createScreen.sh Modal2/RoomCreation RoomCreationEventsModal
/*
Copyright 2020 New Vector Ltd
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 UIKit
final class RoomCreationEventsModalCoordinator: RoomCreationEventsModalCoordinatorType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private var roomCreationEventsModalViewModel: RoomCreationEventsModalViewModelType
private let roomCreationEventsModalViewController: RoomCreationEventsModalViewController
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: RoomCreationEventsModalCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, bubbleData: MXKRoomBubbleCellDataStoring, roomState: MXRoomState) {
self.session = session
let roomCreationEventsModalViewModel = RoomCreationEventsModalViewModel(session: self.session, bubbleData: bubbleData, roomState: roomState)
let roomCreationEventsModalViewController = RoomCreationEventsModalViewController.instantiate(with: roomCreationEventsModalViewModel)
self.roomCreationEventsModalViewModel = roomCreationEventsModalViewModel
self.roomCreationEventsModalViewController = roomCreationEventsModalViewController
}
// MARK: - Public methods
func start() {
self.roomCreationEventsModalViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.roomCreationEventsModalViewController
}
func toSlidingModalPresentable() -> UIViewController & SlidingModalPresentable {
return self.roomCreationEventsModalViewController
}
}
// MARK: - RoomCreationEventsModalViewModelCoordinatorDelegate
extension RoomCreationEventsModalCoordinator: RoomCreationEventsModalViewModelCoordinatorDelegate {
func roomCreationEventsModalViewModelDidTapClose(_ viewModel: RoomCreationEventsModalViewModelType) {
self.delegate?.roomCreationEventsModalCoordinatorDidTapClose(self)
}
}
| apache-2.0 | c89f8b9423ab4821a1440652eacf6eac | 36.125 | 148 | 0.766554 | 6.472155 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/Startup/ProprietaryURLActionHandler.swift | 1 | 3657 | import Foundation
import UIKit
struct ProprietaryURLActionHandler {
var window: UIWindow
init(window: UIWindow) {
self.window = window
}
func handle(_ action: ProprietaryURLAction) -> Bool {
switch action {
case .viewBook(let id):
UserEngagement.logEvent(.openBookFromUrl)
if let book = getBookFromIdentifier(id) {
showBook(book)
return true
} else {
return false
}
case .editBookReadLog(let id):
UserEngagement.logEvent(.openEditReadLogFromUrl)
if let book = getBookFromIdentifier(id) {
showReadLog(for: book)
return true
} else {
return false
}
case .addBookSearchOnline:
UserEngagement.logEvent(.openSearchOnlineFromUrl)
searchOnline()
return true
case .addBookScanBarcode:
UserEngagement.logEvent(.openScanBarcodeFromUrl)
scanBarcode()
return true
case .addBookManually:
UserEngagement.logEvent(.openAddManuallyFromUrl)
addManually()
return true
}
}
func getBookFromIdentifier(_ identifier: BookIdentifier) -> Book? {
switch identifier {
case .googleBooksId(let googleBooksId):
return Book.get(fromContext: PersistentStoreManager.container.viewContext, googleBooksId: googleBooksId)
case .isbn(let isbn):
return Book.get(fromContext: PersistentStoreManager.container.viewContext, isbn: isbn)
case .manualId(let manualId):
return Book.get(fromContext: PersistentStoreManager.container.viewContext, manualBookId: manualId)
}
}
func showBook(_ book: Book) {
guard let tabBarController = window.rootViewController as? TabBarController else {
assertionFailure()
return
}
tabBarController.simulateBookSelection(book, allowTableObscuring: true)
}
func showReadLog(for book: Book) {
guard let tabBarController = window.rootViewController as? TabBarController,
let selectedViewController = tabBarController.selectedSplitViewController else {
assertionFailure()
return
}
selectedViewController.present(
EditBookReadState(existingBookID: book.objectID).inNavigationController(),
animated: false
)
}
func searchOnline() {
guard let tabBarController = window.rootViewController as? TabBarController else {
assertionFailure()
return
}
QuickAction.searchOnline.perform(from: tabBarController)
}
func scanBarcode() {
guard let tabBarController = window.rootViewController as? TabBarController else {
assertionFailure()
return
}
QuickAction.scanBarcode.perform(from: tabBarController)
}
func addManually() {
guard let tabBarController = window.rootViewController as? TabBarController else {
assertionFailure()
return
}
tabBarController.selectedTab = .toRead
// Dismiss any modal views before presenting
let navController = tabBarController.selectedSplitViewController!.masterNavigationController
navController.dismissAndPopToRoot()
let viewController = EditBookMetadata(bookToCreateReadState: .toRead).inNavigationController()
navController.viewControllers.first!.present(viewController, animated: true, completion: nil)
}
}
| gpl-3.0 | 9de0b38d3c1ef49dfa7d64a70d58e59c | 33.828571 | 116 | 0.634126 | 5.652241 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 02--Fourth-Dimensionally/TipCalculator.playground/Contents.swift | 1 | 1587 | //let tipAndTotal = (4.00, 25.19)
//tipAndTotal.0
//tipAndTotal.1
//let (theTipAmt, theTotal) = tipAndTotal
//theTipAmt
//theTotal
let tipAndTotalNamed = (tipAmt: 5.00, total: 30.25)
tipAndTotalNamed.0
tipAndTotalNamed.tipAmt
let total = 21.09
let taxPercent = 0.06
let subTotal = total / (taxPercent + 1)
func calcTipWithTipPercent(tipPercent: Double) -> (tipAmount: Double, total: Double)
{
let tipAmount = subTotal * tipPercent
let finalTotal = total + tipAmount
return (tipAmount, finalTotal)
}
let tipAndTotal = calcTipWithTipPercent(0.20)
tipAndTotal.tipAmount
class TipCalculator
{
let total: Double
let taxPct: Double
let subTotal: Double
init(total: Double, taxPct: Double)
{
self.total = total
self.taxPct = taxPct;
self.subTotal = total / (taxPct + 1)
}
func calcTipWithTipPct(tipPct: Double) -> Double
{
return subTotal * tipPct
}
func printPossibleTips()
{
print("15%: $\(calcTipWithTipPct(0.15))")
print("18%: $\(calcTipWithTipPct(0.18))")
print("20%: $\(calcTipWithTipPct(0.20))")
}
func returnPossibleTips() -> [Int: Double]
{
let possibleTips = [0.15, 0.18, 0.20]
var rValue = [Int: Double]()
for possibleTip in possibleTips
{
let intPct = Int(possibleTip*100)
rValue[intPct] = calcTipWithTipPct(possibleTip)
}
return rValue
}
}
let tipCalc = TipCalculator(total: 33.25, taxPct: 0.06)
//tipCalc.printPossibleTips()
tipCalc.returnPossibleTips()
| cc0-1.0 | 94fe3e032d951ffa50620e63193030b1 | 23.045455 | 84 | 0.6339 | 3.673611 | false | false | false | false |
badoo/Chatto | ChattoApp/ChattoApp/Source/Chat Items/Compound Messages/DemoText2MessageContentFactory.swift | 1 | 3701 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// 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 Chatto
import ChattoAdditions
struct DemoText2MessageContentFactory: MessageContentFactoryProtocol {
private let font = UIFont.systemFont(ofSize: 17)
private let textInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
func canCreateMessageContent(forModel model: DemoCompoundMessageModel) -> Bool {
return model.text2 != nil
}
func createContentView() -> UIView {
let textView = TextView()
textView.label.numberOfLines = 0
textView.label.font = self.font
return textView
}
func createContentPresenter(forModel model: DemoCompoundMessageModel) -> MessageContentPresenterProtocol {
let layoutProvider = self.createTextLayoutProvider(forModel: model)
return DefaultMessageContentPresenter<DemoCompoundMessageModel, TextView>(
message: model,
showBorder: false,
onBinding: { message, textView in
guard let textView = textView else { return }
textView.label.text = message.text2
textView.label.textColor = message.isIncoming ? .black : .white
textView.layoutProvider = layoutProvider
}
)
}
func createLayoutProvider(forModel model: DemoCompoundMessageModel) -> MessageManualLayoutProviderProtocol {
self.createTextLayoutProvider(forModel: model)
}
func createMenuPresenter(forModel model: DemoCompoundMessageModel) -> ChatItemMenuPresenterProtocol? {
return nil
}
private func createTextLayoutProvider(forModel model: DemoCompoundMessageModel) -> TextMessageLayoutProviderProtocol {
TextMessageLayoutProvider(text: model.text2!,
font: self.font,
textInsets: self.textInsets)
}
}
private final class TextView: UIView {
let label = UILabel()
var layoutProvider: TextMessageLayoutProviderProtocol? {
didSet {
guard self.layoutProvider != nil else { return }
self.setNeedsLayout()
}
}
init() {
super.init(frame: .zero)
self.addSubview(label)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let layoutProvider = self.layoutProvider else { return }
self.label.frame = layoutProvider.layout(for: self.bounds.size, safeAreaInsets: self.safeAreaInsets).frame
}
}
| mit | fd6b1f10989b9f2a7f1db4fc2a88db66 | 37.154639 | 122 | 0.692245 | 5.076818 | false | false | false | false |
BiAtoms/Request.swift | Tests/RequestSwiftTests/RequestSwiftTests.swift | 1 | 5650 | //
// RequestSwiftTests.swift
// RequestSwiftTests
//
// Created by Orkhan Alikhanov on 7/11/17.
// Copyright © 2017 BiAtoms. All rights reserved.
//
import XCTest
@testable import RequestSwift
class RequestSwiftTests: XCTestCase {
struct a {
static let client = Client()
}
var client: Client {
return a.client
}
func testHttp() {
let ex = expectation(description: "http")
client.request("http://example.com/", headers: ["Accept": "text/html"]).response { response, error in
XCTAssertNil(error, "error should be nil")
XCTAssertNotNil(response, "response should no be nil")
let response = response!
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.reasonPhrase, "OK")
XCTAssert(String(cString: response.body).contains("<h1>Example Domain</h1>"))
ex.fulfill()
}
waitForExpectations()
}
func testHttps() {
let ex = expectation(description: "https")
client.request("https://example.com", headers: ["Accept": "text/html"]).response { response, error in
XCTAssertNil(error, "error should be nil")
XCTAssertNotNil(response, "response should no be nil")
let response = response!
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.reasonPhrase, "OK")
XCTAssert(String(cString: response.body).contains("<h1>Example Domain</h1>"))
ex.fulfill()
}
waitForExpectations()
}
func testErrorTimeout() {
let ex = expectation(description: "timeout")
client.firesImmediately = false
let requester = client.request("http://httpstat.us/200?sleep=1000")
requester.timeout = 500 //ms
client.firesImmediately = true
requester.startAsync()
requester.response { response, error in
XCTAssertNil(response, "response must be nil")
XCTAssertNotNil(error, "error must not be nil")
let err = (error as? Request.Error)
XCTAssertNotNil(err)
XCTAssertEqual(err, Request.Error.timeout)
ex.fulfill()
}
waitForExpectations()
}
func testErrorDNS() {
let ex = expectation(description: "dns error")
client.request("http://aBadDomain.com").response { response, error in
XCTAssertNil(response, "response must be nil")
XCTAssertNotNil(error, "error must not be nil")
let err = (error as? Request.Error)
XCTAssertNotNil(err)
XCTAssertEqual(err, Request.Error.couldntResolveHost)
ex.fulfill()
}
waitForExpectations()
}
func testUrlEncoding() {
let request = Request(method: .get, url: "http://example.com/?q=123&b=32", headers: [:], body: [])
URLEncoding.queryString.encode(request, with: ["apple": "ban ana", "ms": "msdn"])
XCTAssertEqual(request.url, "http://example.com/?q=123&b=32&apple=ban%20ana&ms=msdn")
let request1 = Request(method: .get, url: "http://example.com/", headers: [:], body: [])
URLEncoding.httpBody.encode(request1, with: ["apple": "ban ana", "ms": "msdn"])
XCTAssertEqual(request1.body, "apple=ban%20ana&ms=msdn".bytes)
}
func testRequestPath() {
var request = Request(method: .get, url: "http://example.com/dir/1/2/search.html?arg=0-a&arg1=1-b")
XCTAssertEqual(request.path, "/dir/1/2/search.html?arg=0-a&arg1=1-b")
request = Request(method: .get, url: "http://example.com/")
XCTAssertEqual(request.path, "/")
request = Request(method: .get, url: "http://example.com")
XCTAssertEqual(request.path, "/")
}
func testRequestWriter() {
let body = "This is request's body"
let request = Request(method: .patch, url: "http://www.example.com:443/dir/1/2/search.html?arg=0-a&arg1=1-b", headers: ["User-Agent": "Test"], body: body.bytes)
let writer = RequestWriter(request: request)
XCTAssertEqual(writer.buildRequestLine(), "PATCH /dir/1/2/search.html?arg=0-a&arg1=1-b HTTP/1.0\r\n")
//checking sorted array of written string (sperated by "\n\r") instead of the string itself
//since the headers dictionary had elements with different order on every run
let writtenStringArray = writer.write().string.components(separatedBy: "\r\n").sorted()
let requestStringArray = ("PATCH /dir/1/2/search.html?arg=0-a&arg1=1-b HTTP/1.0\r\n"
+ "User-Agent: Test\r\n"
+ "Content-Length: \(body.bytes.count)\r\n"
+ "Host: www.example.com:443\r\n"
+ "\r\n"
+ body).components(separatedBy: "\r\n").sorted()
XCTAssertEqual(writtenStringArray, requestStringArray)
}
static var allTests = [
("testHttp", testHttp),
("testHttps", testHttps),
("testErrorTimeout", testErrorTimeout),
("testErrorDNS", testErrorDNS),
("testUrlEncoding", testUrlEncoding),
("testRequestPath", testErrorDNS),
("testRequestWriter", testRequestWriter),
]
}
extension XCTestCase {
func waitForExpectations() {
waitForExpectations(timeout: 1.5)
}
}
extension Array where Element == UInt8 {
var string: String {
return String(data: Data(bytes: self, count: self.count), encoding: .utf8)!
}
}
| mit | a2c247041be78239fa39b426e761462a | 35.211538 | 168 | 0.59391 | 4.203125 | false | true | false | false |
sai-prasanna/SWMessages | SWMessages/Source/SWMessageView.swift | 1 | 18188 | //
// SWMessageView.swift
//
// Copyright (c) 2016-present Sai Prasanna R
//
// 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
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
private let messageViewMinimumPadding :CGFloat = 15.0
open class SWMessageView :UIView , UIGestureRecognizerDelegate {
public struct Style {
let image: UIImage?
let backgroundColor: UIColor
let textColor: UIColor
let textShadowColor: UIColor?
let titleFont: UIFont?
let contentFont: UIFont?
let shadowOffset: CGSize?
public init (image: UIImage? = nil, backgroundColor: UIColor, textColor: UIColor, textShadowColor: UIColor? = nil, titleFont: UIFont? = nil, contentFont: UIFont? = nil, shadowOffset: CGSize? = nil){
self.image = image
self.backgroundColor = backgroundColor
self.textColor = textColor
self.textShadowColor = textShadowColor
self.titleFont = titleFont
self.contentFont = contentFont
self.shadowOffset = shadowOffset
}
}
/** The displayed title of this message */
open let title :String
/** The displayed subtitle of this message */
open let subtitle :String?
/** The view controller this message is displayed in */
open let viewController :UIViewController
open let buttonTitle :String?
/** The duration of the displayed message. */
open var duration :SWMessageDuration = .automatic
/** The position of the message (top or bottom or as overlay) */
open var messagePosition :SWMessageNotificationPosition
open var notificationType :SWMessageNotificationType
/** Is the message currenlty fully displayed? Is set as soon as the message is really fully visible */
open var messageIsFullyDisplayed = false
/** Function to customize style globally, initialized to default style. Priority will be This customOptions in init > styleForMessageType */
open static var styleForMessageType :(SWMessageNotificationType) -> SWMessageView.Style = defaultStyleForMessageType
var fadeOut :(() -> Void)?
fileprivate let titleLabel = UILabel()
fileprivate lazy var contentLabel = UILabel()
fileprivate var iconImageView :UIImageView?
fileprivate var button :UIButton?
fileprivate let backgroundView = UIView()
fileprivate var textSpaceLeft :CGFloat = 0
fileprivate var textSpaceRight :CGFloat = 0
fileprivate var callback :(()-> Void)?
fileprivate var buttonCallback :(()-> Void)?
fileprivate let padding :CGFloat
/**
Inits the notification view. Do not call this from outside this library.
- Parameter title: The title of the notification view
- Parameter subtitle: The subtitle of the notification view (optional)
- Parameter image: A custom icon image (optional), it will override any image specfied in SWMessageView.styleForMessageType, and style
- Parameter notificationType: The type (color) of the notification view
- Parameter duration: The duration this notification should be displayed (optional)
- Parameter viewController: The view controller this message should be displayed in
- Parameter callback: The block that should be executed, when the user tapped on the message
- Parameter buttonTitle: The title for button (optional)
- Parameter buttonCallback: The block that should be executed, when the user tapped on the button
- Parameter position: The position of the message on the screen
- Parameter dismissingEnabled: Should this message be dismissed when the user taps/swipes it?
- Parameter style: Override default/global style
*/
init(title :String,
subtitle :String?,
image :UIImage?,
type :SWMessageNotificationType,
duration :SWMessageDuration?,
viewController :UIViewController,
callback :(()-> Void)?,
buttonTitle :String?,
buttonCallback :(()-> Void)?,
position :SWMessageNotificationPosition,
dismissingEnabled :Bool,
style: SWMessageView.Style? = nil
)
{
self.title = title
self.subtitle = subtitle
self.buttonTitle = buttonTitle
self.duration = duration ?? .automatic
self.viewController = viewController
self.messagePosition = position
self.callback = callback
self.buttonCallback = buttonCallback
let screenWidth: CGFloat = viewController.view.bounds.size.width
self.padding = messagePosition == .navBarOverlay ? messageViewMinimumPadding + 10 : messageViewMinimumPadding
self.notificationType = type
super.init(frame :CGRect.zero)
let options = style ?? SWMessageView.styleForMessageType(type)
let currentImage = image ?? options.image
backgroundColor = UIColor.clear
backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundView.backgroundColor = options.backgroundColor
addSubview(backgroundView)
let fontColor: UIColor = options.textColor
textSpaceLeft = padding
if let currentImage = currentImage {
textSpaceLeft += padding + 20
let imageView = UIImageView(image: currentImage)
iconImageView = imageView
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: padding + 5, y: padding, width: 20, height: 20)
addSubview(imageView)
}
// Set up title label
titleLabel.text = title
titleLabel.textColor = fontColor
titleLabel.backgroundColor = UIColor.clear
titleLabel.font = options.titleFont ?? UIFont.boldSystemFont(ofSize: 14)
if let shadowColor = options.textShadowColor,let shadowOffset = options.shadowOffset {
titleLabel.shadowColor = shadowColor
titleLabel.shadowOffset = shadowOffset
}
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
addSubview(titleLabel)
// Set up content label (if set)
if subtitle?.characters.count > 0 {
contentLabel.text = subtitle
contentLabel.textColor = options.textColor
contentLabel.backgroundColor = UIColor.clear
contentLabel.font = options.contentFont ?? UIFont.systemFont(ofSize: 12)
contentLabel.shadowColor = titleLabel.shadowColor
contentLabel.shadowOffset = titleLabel.shadowOffset
contentLabel.lineBreakMode = titleLabel.lineBreakMode
contentLabel.numberOfLines = 0
addSubview(contentLabel)
}
// Set up button (if set)
if let buttonTitle = buttonTitle , buttonTitle.characters.count > 0 {
button = UIButton(type: .custom)
button?.setTitle(buttonTitle, for: UIControlState())
let buttonTitleTextColor = options.textColor
button?.setTitleColor(buttonTitleTextColor, for: UIControlState())
button?.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14.0)
if let shadowColor = options.textShadowColor,let shadowOffset = options.shadowOffset {
button?.titleLabel?.shadowColor = shadowColor
button?.titleLabel?.shadowOffset = shadowOffset
}
button?.addTarget(self, action: #selector(SWMessageView.buttonTapped(_:)), for: .touchUpInside)
button?.contentEdgeInsets = UIEdgeInsetsMake(0.0, 5.0, 0.0, 5.0)
button?.sizeToFit()
button?.frame = CGRect(x: screenWidth - padding - button!.frame.size.width, y: 0.0, width: button!.frame.size.width, height: 31.0)
addSubview(button!)
textSpaceRight = button!.frame.size.width + padding
}
let actualHeight: CGFloat = updateHeightOfMessageView()
// this call also takes care of positioning the labels
var topPosition: CGFloat = -actualHeight
if messagePosition == .bottom {
topPosition = viewController.view.bounds.size.height
}
frame = CGRect(x: 0.0, y: topPosition, width: screenWidth, height: actualHeight)
if messagePosition == .top {
autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin]
}
else {
autoresizingMask = ([.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin])
}
if dismissingEnabled {
let gestureRec: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SWMessageView.fadeMeOut))
gestureRec.direction = (messagePosition == .top ? .up : .down)
addGestureRecognizer(gestureRec)
let tapRec: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SWMessageView.fadeMeOut))
addGestureRecognizer(tapRec)
}
if let _ = callback {
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SWMessageView.handleTap(_:)))
tapGesture.delegate = self
addGestureRecognizer(tapGesture)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateHeightOfMessageView() -> CGFloat {
var currentHeight: CGFloat
let screenWidth: CGFloat = viewController.view.bounds.size.width
titleLabel.frame = CGRect(x: textSpaceLeft, y: padding, width: screenWidth - padding - textSpaceLeft - textSpaceRight, height: 0.0)
titleLabel.sizeToFit()
if subtitle?.characters.count > 0 {
contentLabel.frame = CGRect(x: textSpaceLeft, y: titleLabel.frame.origin.y + titleLabel.frame.size.height + 5.0, width: screenWidth - padding - textSpaceLeft - textSpaceRight, height: 0.0)
contentLabel.sizeToFit()
currentHeight = contentLabel.frame.origin.y + contentLabel.frame.size.height
}
else {
// only the title was set
currentHeight = titleLabel.frame.origin.y + titleLabel.frame.size.height
}
currentHeight += padding
if let iconImageView = iconImageView {
// Check if that makes the popup larger (height)
if iconImageView.frame.origin.y + iconImageView.frame.size.height + padding > currentHeight {
currentHeight = iconImageView.frame.origin.y + iconImageView.frame.size.height + padding
}
else {
// z-align
iconImageView.center = CGPoint(x: iconImageView.center.x, y: round(currentHeight / 2.0))
}
}
frame = CGRect(x: 0.0, y: frame.origin.y, width: frame.size.width, height: currentHeight)
if let button = button {
// z-align button
button.center = CGPoint(x: button.center.x, y: round(currentHeight / 2.0))
button.frame = CGRect(x: frame.size.width - textSpaceRight, y: round((frame.size.height / 2.0) - button.frame.size.height / 2.0), width: button.frame.size.width, height: button.frame.size.height)
}
var backgroundFrame: CGRect = CGRect(x: 0, y: 0, width: screenWidth, height: currentHeight)
// increase frame of background view because of the spring animation
if messagePosition == .top {
var topOffset: CGFloat = 0.0
let navigationController: UINavigationController? = viewController as? UINavigationController ?? viewController.navigationController
if let nav = navigationController {
let isNavBarIsHidden: Bool = SWMessageView.isNavigationBarInNavigationControllerHidden(nav)
let isNavBarIsOpaque: Bool = !nav.navigationBar.isTranslucent && nav.navigationBar.alpha == 1
if isNavBarIsHidden || isNavBarIsOpaque {
topOffset = -30.0
}
}
backgroundFrame = UIEdgeInsetsInsetRect(backgroundFrame, UIEdgeInsetsMake(topOffset, 0.0, 0.0, 0.0))
}
else if messagePosition == .bottom {
backgroundFrame = UIEdgeInsetsInsetRect(backgroundFrame, UIEdgeInsetsMake(0.0, 0.0, -30.0, 0.0))
}
backgroundView.frame = backgroundFrame
return currentHeight
}
override open func layoutSubviews() {
super.layoutSubviews()
let _ = updateHeightOfMessageView()
}
override open func didMoveToWindow() {
super.didMoveToWindow()
if duration == .endless && superview != nil && window == nil {
// view controller was dismissed, let's fade out
fadeMeOut()
}
}
func fadeMeOut() {
fadeOut?()
}
func buttonTapped(_ sender: AnyObject) {
buttonCallback?()
fadeMeOut()
}
func handleTap(_ tapGesture: UITapGestureRecognizer) {
if tapGesture.state == .recognized {
callback?()
}
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return touch.view is UIControl
}
class func isNavigationBarInNavigationControllerHidden(_ navController: UINavigationController) -> Bool {
if navController.isNavigationBarHidden {
return true
}
else if navController.navigationBar.isHidden {
return true
}
else {
return false
}
}
}
private class SWBlurView :UIView {
var blurTintColor :UIColor? {
get {
return toolbar.barTintColor
}
set(newValue) {
toolbar.barTintColor = newValue
}
}
fileprivate lazy var toolbar :UIToolbar = {
let toolbar = UIToolbar(frame: self.bounds)
toolbar.isUserInteractionEnabled = false
toolbar.isTranslucent = false
toolbar.autoresizingMask = [.flexibleWidth, .flexibleHeight]
toolbar.setBackgroundImage(nil, forToolbarPosition: .any, barMetrics: .default)
self.addSubview(toolbar)
return toolbar
}()
}
private func defaultStyleForMessageType(_ type: SWMessageNotificationType) -> SWMessageView.Style {
let contentFontSize = CGFloat(12)
let titleFontSize = CGFloat(14)
let shadowOffsetX = 0
func bundledImageNamed(_ name: String) -> UIImage? {
let bundle: Bundle = Bundle(for: SWMessage.self)
let imagePath: String = bundle.path(forResource: name, ofType: nil) ?? ""
return UIImage(contentsOfFile: imagePath) ?? UIImage(named: name)
}
switch type {
case .success:
return SWMessageView.Style(
image: bundledImageNamed("NotificationBackgroundSuccessIcon.png"),
backgroundColor: UIColor(hexString: "#76CF67"),
textColor: UIColor.white,
textShadowColor: UIColor(hexString: "#67B759"),
titleFont: UIFont.systemFont(ofSize: titleFontSize),
contentFont: UIFont.systemFont(ofSize: contentFontSize),
shadowOffset: CGSize(width: 0, height: -1)
)
case .message:
return SWMessageView.Style(
image: nil,
backgroundColor: UIColor(hexString: "#D4DDDF"),
textColor: UIColor(hexString: "#727C83"),
textShadowColor: UIColor(hexString: "#EBEEF1"),
titleFont: UIFont.systemFont(ofSize: titleFontSize),
contentFont: UIFont.systemFont(ofSize: contentFontSize),
shadowOffset: CGSize(width: 0, height: -1)
)
case .warning:
return SWMessageView.Style(
image: bundledImageNamed("NotificationBackgroundWarningIcon.png"),
backgroundColor: UIColor(hexString: "#DAC43C"),
textColor: UIColor(hexString: "#484638"),
textShadowColor: UIColor(hexString: "#E5D87C"),
titleFont: UIFont.systemFont(ofSize: titleFontSize),
contentFont: UIFont.systemFont(ofSize: contentFontSize),
shadowOffset: CGSize(width: 0, height: 1)
)
case .error:
return SWMessageView.Style(
image: bundledImageNamed("NotificationBackgroundErrorIcon.png"),
backgroundColor: UIColor(hexString: "#DD3B41"),
textColor: UIColor.white,
textShadowColor: UIColor(hexString: "#812929"),
titleFont: UIFont.systemFont(ofSize: titleFontSize),
contentFont: UIFont.systemFont(ofSize: contentFontSize),
shadowOffset: CGSize(width: 0, height: -1)
)
}
}
| mit | 686b9e80779bb10806d8a4728985d3c7 | 41.694836 | 207 | 0.64691 | 5.236971 | false | false | false | false |
wdxgtsh/SwiftPasscodeLock | SwiftPasscodeLock/Keychain/Keychain.swift | 5 | 3643 | //
// Keychain.swift
// SwiftKeychain
//
// Created by Yanko Dimitrov on 11/11/14.
// Copyright (c) 2014 Yanko Dimitrov. All rights reserved.
//
import Foundation
public class Keychain: KeychainService {
public let accessMode: String
public let serviceName: String
public var accessGroup: String?
private let errorDomain = "swift.keychain.error.domain"
public class var sharedKeychain: Keychain {
struct Singleton {
static let instance = Keychain()
}
return Singleton.instance
}
///////////////////////////////////////////////////////
// MARK: - Initializers
///////////////////////////////////////////////////////
init(serviceName name: String, accessMode: String = kSecAttrAccessibleWhenUnlocked as String, group: String? = nil) {
self.accessMode = accessMode
serviceName = name
accessGroup = group
}
convenience init() {
self.init(serviceName: "swift.keychain")
}
///////////////////////////////////////////////////////
// MARK: - Methods
///////////////////////////////////////////////////////
private func errorForStatusCode(statusCode: OSStatus) -> NSError {
return NSError(domain: errorDomain, code: Int(statusCode), userInfo: nil)
}
///////////////////////////////////////////////////////
// MARK: - KeychainService
///////////////////////////////////////////////////////
public func add(key: KeychainItem) -> NSError? {
let secretFields = key.fieldsToLock()
if secretFields.count == 0 {
return errorForStatusCode(errSecParam)
}
let query = key.makeQueryForKeychain(self)
query.addFields(secretFields)
let status = SecItemAdd(query.fields, nil)
if status != errSecSuccess {
return errorForStatusCode(status)
}
return nil
}
public func update(key: KeychainItem) -> NSError? {
let changes = key.fieldsToLock()
if changes.count == 0 {
return errorForStatusCode(errSecParam)
}
let query = key.makeQueryForKeychain(self)
let status = SecItemUpdate(query.fields, changes)
if status != errSecSuccess {
return errorForStatusCode(status)
}
return nil
}
public func remove(key: KeychainItem) -> NSError? {
let query = key.makeQueryForKeychain(self)
let status = SecItemDelete(query.fields)
if status != errSecSuccess {
return errorForStatusCode(status)
}
return nil
}
public func get<T: BaseKey>(key: T) -> (item: T?, error: NSError?) {
var query = key.makeQueryForKeychain(self)
query.shouldReturnData()
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) {
cfPointer -> OSStatus in
SecItemCopyMatching(query.fields, UnsafeMutablePointer(cfPointer))
}
if status != errSecSuccess {
return (nil, errorForStatusCode(status))
}
if let resultData = result as? NSData {
key.unlockData(resultData)
return (key, nil)
}
return (nil, nil)
}
}
| mit | b8bc392db4737b9018def38012cf183c | 25.208633 | 121 | 0.487236 | 6.051495 | false | false | false | false |
neoneye/SwiftyFORM | Example/TextField/TextFieldKeyboardTypesViewController.swift | 1 | 1610 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class TextFieldKeyboardTypesViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "Keyboard Types"
builder.toolbarMode = .none
builder.demo_showInfo("Shows all the UIKeyboardType variants")
builder += TextFieldFormItem().styleClass("align").title("ASCIICapable").placeholder("Lorem Ipsum").keyboardType(.asciiCapable)
builder += TextFieldFormItem().title("NumbersAndPunctuation").placeholder("123.45").keyboardType(.numbersAndPunctuation)
builder += TextFieldFormItem().styleClass("align").title("URL").placeholder("example.com/blog").keyboardType(.URL)
builder += TextFieldFormItem().styleClass("align").title("NumberPad").placeholder("0123456789").keyboardType(.numberPad)
builder += TextFieldFormItem().styleClass("align").title("PhonePad").placeholder("+999#22;123456,27").keyboardType(.phonePad)
builder += TextFieldFormItem().styleClass("align").title("EmailAddress").placeholder("[email protected]").keyboardType(.emailAddress)
builder += TextFieldFormItem().styleClass("align").title("DecimalPad").placeholder("1234.5678").keyboardType(.decimalPad)
builder += TextFieldFormItem().styleClass("align").title("Twitter").placeholder("@user or #hashtag").keyboardType(.twitter)
builder += TextFieldFormItem().styleClass("align").title("WebSearch").placeholder("how to do this.").keyboardType(.webSearch)
builder.alignLeftElementsWithClass("align")
builder += SectionFooterTitleFormItem().title("Footer text")
}
}
| mit | a7baf335d5dee361def6aa0366001558 | 72.181818 | 141 | 0.773292 | 4.893617 | false | false | false | false |
ryan-blunden/ga-mobile | Kittens/Kittens/KTDesignableView.swift | 2 | 953 | //
// KTDesignableView.swift
// Kittens
//
// Created by Ryan Blunden on 28/05/2015.
// Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
public class KTDesignableView: UIView {
@IBInspectable public var bgColor: UIColor = UIColor.clearColor() {
didSet {
backgroundColor = bgColor
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupButton()
}
func setupButton() {
layer.masksToBounds = true
}
}
| gpl-3.0 | 0fe80e46acedb40230cafd7090004631 | 18.06 | 69 | 0.658972 | 4.412037 | false | false | false | false |
pascaljette/PokeBattleDemo | PokeBattleDemo/Pods/GearKit/Pod/GearKit/DataStructures/GKQueue.swift | 2 | 9220 | // The MIT License (MIT)
//
// Copyright (c) 2015 pascaljette
//
// 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
/// Node for the queue (private)
private final class GKQueueNode<Element> {
/// Shortcut for the node type
typealias NodeType = GKQueueNode<Element>
/// Element
var element: Element
/// Next node in the queue. Nil if tail.
var next: NodeType? = nil
/// Initialize with a value.
///
/// - parameter value: The value of the element to add.
init(element: Element) {
self.element = element
}
}
/// Implementation for the queue. This offers more flexibility since we can keep
/// a reference on each implementations and we can also access deinit functions from the
/// queue struct.
private class GKQueueImplementation<Element> {
///
/// MARK: Nested types
///
/// Shortcut for the node type (same as the queue).
typealias NodeType = GKQueueNode<Element>
/// Shortcut for our own type.
typealias ImplementationType = GKQueueImplementation<Element>
///
/// MARK: Stored properties
///
/// Reference on the head helement.
var head: NodeType? = nil
/// Reference on the tail element.
var tail: NodeType? = nil
///
/// MARK: Initializers
///
/// Empty parameterless constructor.
init() {
}
/// Essentially a copy constructor. Use the head of another implementation
/// and generate a new implementation with copies of all the nodes.
init(head: NodeType?) {
guard let headInstance = head else {
return
}
self.tail = GKQueueNode(element: headInstance.element)
self.head = self.tail
var sequencer = headInstance.next
while let sequencerInstance = sequencer {
let oldTail = tail
self.tail = NodeType(element: sequencerInstance.element)
oldTail?.next = self.tail
sequencer = sequencer?.next
}
}
}
extension GKQueueImplementation {
///
/// MARK: Computed properties
///
/// Count of the elements in the queue.
var count: Int {
var sequencer = head
if sequencer == nil {
return 0
}
var returnCount: Int = 0
while sequencer != nil {
returnCount += 1
sequencer = sequencer!.next
}
return returnCount
}
}
extension GKQueueImplementation {
///
/// MARK: Methods
///
/// Append a node to the queue.
func append(newElement: Element) {
let oldTail = tail
tail = GKQueueNode(element: newElement)
if head == nil {
head = tail
}
else {
oldTail?.next = self.tail
}
}
/// Remove an element from the queue and return its value.
func dequeue() -> Element? {
guard let headInstance = self.head else {
return nil
}
self.head = headInstance.next
if headInstance.next == nil {
tail = nil
}
return headInstance.element
}
/// Return the value of the last element in the queue without removing it.
func peek() -> Element? {
return head?.element
}
/// Return a new copy of the implementation with copies of the nodes for a struct-like behavior.
func copy() -> ImplementationType {
return ImplementationType(head: self.head)
}
/// Clear the queue.
func clear() {
// ARC ensures that setting the head and tail to nil will free
// all nodes.
head = nil
tail = nil
}
}
extension GKQueueImplementation {
///
/// MARK: SequenceType implementation
///
/// Generate the sequence from the queue.
///
/// - returns: The generator that builds the sequence.
func generate() -> AnyGenerator<Element> {
var current : NodeType? = self.head
return AnyGenerator {
while (current != nil) {
if let currentInstance = current {
current = current?.next
return currentInstance.element
}
}
return nil
}
}
}
/// Implementation of a generic FIFO queue. It has copy-on-write semantics.
/// Note: We do not implement the MutableCollectionType or CollectionType for this class.
/// The reason is that subscript should intuitively be a O(1) operation, and in the case
/// of a queue, it would require traversal and therefore be O(n). Therefore, we prefer using
/// the SequenceType protocol.
public struct GKQueue<Element> {
///
/// MARK: Nested types
///
/// Shortcut for the type of the associated implementation.
private typealias ImplementationType = GKQueueImplementation<Element>
///
/// MARK: Initializers
///
/// Empty parameterless constructor.
public init() {
}
/// Initialize from another sequence.
///
/// - parameter s: Other sequence from which to initialize (typically an Array).
public init<S : SequenceType>(_ s: S) {
var generator = s.generate()
while let nextElement = generator.next() {
append(nextElement as! Element)
}
}
///
/// MARK: Stored properties
///
/// Reference on the implementation. This allows us to combine the safeness and elegance
/// of a struct with the functionalities of a class (reference, deinit functionalities, etc.).
private var implementation: ImplementationType = ImplementationType()
}
extension GKQueue {
///
/// MARK: Private methods
///
/// Ensure that we have a unique reference on our struct.
/// Otherwise, we create a copy.
private mutating func ensureUnique() {
if !isUniquelyReferencedNonObjC(&implementation) {
implementation = implementation.copy()
}
}
}
extension GKQueue {
/// Append at the end of the queue.
///
/// - parameter newElement: Value of the new element to append at the end of the queue.
public mutating func append(newElement: Element) {
ensureUnique()
implementation.append(newElement)
}
/// Remove the first element from the queue and returns its value.
///
/// - returns: Value of the first element in the queue, nil if the queue is empty.
public mutating func dequeue() -> Element? {
ensureUnique()
return implementation.dequeue()
}
/// Returns the value of the first element in the queue without removing it.
///
/// - returns: Value of the first element in the queue, nil if the queue is empty.
public func peek() -> Element? {
return implementation.peek()
}
/// Delete all the nodes in the queue. Note if you have references on the elements
/// inside the queue itself, they will not be deleted.
public mutating func clear() {
ensureUnique()
return implementation.clear()
}
}
extension GKQueue {
///
/// MARK: Computed properties
///
/// Returns the number of elements in the queue.
public var count: Int {
return implementation.count
}
/// Returns true for an empty queue (count == 0) and false otherwise.
public var isEmpty: Bool {
return count == 0
}
}
extension GKQueue : SequenceType {
///
/// MARK: SequenceType implementation
///
/// Generate the sequence from the queue.
///
/// - returns: The generator that builds the sequence.
public func generate() -> AnyGenerator<Element> {
return implementation.generate()
}
}
| mit | 5bfd8bf3d0b74d1b09b6401a361b5563 | 25.418338 | 100 | 0.590347 | 5.168161 | false | false | false | false |
wikimedia/wikipedia-ios | Command Line Tools/Update Languages/WikipediaLanguageCommandLineUtilityAPI.swift | 1 | 5714 | import Foundation
import Combine
/// Utility for making API calls that update prebuilt lists of information about different language Wikipedias
class WikipediaLanguageCommandLineUtilityAPI {
// We can't use codable because this API's response has a dictionary with arbitrary keys mapped to values of mixed type.
// For example, the mixing of ints and dictionaries in "sitematrix":
// "sitematrix": {
// "count": 951,
// "0": {
// "code": "aa",
// "name": "Qaf\u00e1r af",
// ...
// },
// "1": {
// "code": "ab",
// "name":"аԥсшәа",
// ...
// },
// ...
// }
func getSites() -> AnyPublisher<[Wikipedia], Error> {
let sitematrixURL = URL(string: "https://meta.wikimedia.org/w/api.php?action=sitematrix&smsiteprop=url%7Cdbname%7Ccode%7Csitename%7Clang&format=json&formatversion=2&origin=*")!
return URLSession.shared
.dataTaskPublisher(for: sitematrixURL)
.tryMap { result -> [String: Any] in
/// See above as to why all of this is necessary instead of using codable
guard let jsonObject = try JSONSerialization.jsonObject(with: result.data, options: .allowFragments) as? [String: Any] else {
throw WikipediaLanguageUtilityAPIError.generic
}
return jsonObject
}
.map { jsonObject -> [Wikipedia] in
/// See above as to why all of this is necessary instead of using codable
guard let sitematrix = jsonObject["sitematrix"] as? [String: Any] else {
return []
}
var wikipedias = sitematrix.compactMap { (kv) -> Wikipedia? in
guard
let result = kv.value as? [String: Any],
let code = result["code"] as? String,
let name = result["name"] as? String,
let localname = result["localname"] as? String
else {
return nil
}
guard code != "no" else {
// Norwegian (Bokmål) has a different ISO code than it's subdomain, which is useful to reference in some instances (prepopulating preferredLanguages from iOS device languages, and choosing the correct alternative article language from the langlinks endpoint).
//https://phabricator.wikimedia.org/T276645
//https://phabricator.wikimedia.org/T272193
return Wikipedia(languageCode: code, languageName: name, localName: localname, altISOCode: "nb")
}
return Wikipedia(languageCode: code, languageName: name, localName: localname, altISOCode: nil)
}
// Add testwiki, it's not returned by the site matrix
wikipedias.append(Wikipedia(languageCode: "test", languageName: "Test", localName: "Test", altISOCode: nil))
return wikipedias
}.eraseToAnyPublisher()
}
func getSiteInfo(with languageCode: String) -> AnyPublisher<SiteInfo, Error> {
let siteInfoURL = URL(string: "https://\(languageCode).wikipedia.org/w/api.php?action=query&format=json&prop=&list=&meta=siteinfo&siprop=namespaces%7Cgeneral%7Cnamespacealiases&formatversion=2&origin=*")!
return URLSession.shared
.dataTaskPublisher(for: siteInfoURL)
.tryMap { (result) -> SiteInfo in
try JSONDecoder().decode(SiteInfo.self, from: result.data)
}.eraseToAnyPublisher()
}
func getCodeMirrorConfigJSON(for wikiLanguage: String) -> AnyPublisher<String, Error> {
let codeMirrorConfigURL = URL(string: "http://\(wikiLanguage).wikipedia.org/w/load.php?debug=false&lang=en&modules=ext.CodeMirror.data")!
return URLSession.shared.dataTaskPublisher(for: codeMirrorConfigURL)
.tryMap { (result) -> String in
guard
let responseString = String(data: result.data, encoding: .utf8),
let soughtSubstring = self.extractJSONString(from: responseString)
else {
throw WikipediaLanguageUtilityAPIError.generic
}
return soughtSubstring.replacingOccurrences(of: "!0", with: "true")
}.eraseToAnyPublisher()
}
private let jsonExtractionRegex = try! NSRegularExpression(pattern: #"(?:mw\.config\.set\()(.*?)(?:\);\n*\}\);)"#, options: [.dotMatchesLineSeparators])
private func extractJSONString(from responseString: String) -> String? {
let results = jsonExtractionRegex.matches(in: responseString, range: NSRange(responseString.startIndex..., in: responseString))
guard
results.count == 1,
let firstResult = results.first,
firstResult.numberOfRanges == 2,
let soughtCaptureGroupRange = Range(firstResult.range(at: 1), in: responseString)
else {
return nil
}
return String(responseString[soughtCaptureGroupRange])
}
}
enum WikipediaLanguageUtilityAPIError: Error {
case generic
}
struct SiteInfo: Codable {
struct Namespace: Codable {
let id: Int
let name: String
let canonical: String?
}
struct NamespaceAlias: Codable {
let id: Int
let alias: String
}
struct General: Codable {
let mainpage: String
}
struct Query: Codable {
let general: General
let namespaces: [String: Namespace]
let namespacealiases: [NamespaceAlias]
}
let query: Query
}
| mit | 5bf49267294dc296c10d8b695171d1ab | 44.293651 | 279 | 0.597687 | 4.681706 | false | false | false | false |
fgengine/quickly | Quickly/StringValidator/QNumberStringValidator.swift | 1 | 2045 | //
// Quickly
//
open class QNumberStringValidator : IQStringValidator {
public var minimumValue: Decimal?
public let minimumError: String?
public var maximumValue: Decimal?
public let maximumError: String?
public let notNumberError: String
public init(
minimumValue: Decimal,
minimumError: String,
notNumberError: String
) {
self.minimumValue = minimumValue
self.minimumError = minimumError
self.maximumValue = nil
self.maximumError = nil
self.notNumberError = notNumberError
}
public init(
maximumValue: Decimal,
maximumError: String,
notNumberError: String
) {
self.minimumValue = nil
self.minimumError = nil
self.maximumValue = maximumValue
self.maximumError = maximumError
self.notNumberError = notNumberError
}
public init(
minimumValue: Decimal,
minimumError: String,
maximumValue: Decimal,
maximumError: String,
notNumberError: String
) {
self.minimumValue = minimumValue
self.minimumError = minimumError
self.maximumValue = maximumValue
self.maximumError = maximumError
self.notNumberError = notNumberError
}
open func validate(_ string: String) -> QStringValidatorResult {
var errors = Set< String >()
if let number = NSDecimalNumber.decimalNumber(from: string) {
let value = number as Decimal
if let limit = self.minimumValue, let error = self.minimumError {
if value < limit {
errors.insert(error)
}
}
if let limit = self.maximumValue, let error = self.maximumError {
if value > limit {
errors.insert(error)
}
}
} else {
errors.insert(self.notNumberError)
}
return QStringValidatorResult(
errors: Array(errors)
)
}
}
| mit | 49be00c1ac3a3d2dc1fa6ffb87b23668 | 27.013699 | 77 | 0.589242 | 5.424403 | false | false | false | false |
RamonGilabert/Wall | Source/Library/ImageList.swift | 2 | 374 | import UIKit
public struct ImageList {
public struct Basis {
public static var playButton = ""
public static var reportButton = ""
public static var disclosure = ""
public static var placeholder = ""
}
public struct Action {
public static var likeButton = ""
public static var likedButton = ""
public static var commentButton = ""
}
}
| mit | a6b22060a37c1a9f75a41e265bf75186 | 21 | 40 | 0.665775 | 4.921053 | false | false | false | false |
claudetech/cordova-plugin-media-lister | src/ios/MediaLister.swift | 1 | 6372 | import Foundation
import AssetsLibrary
import MobileCoreServices
// TODO: Rewrite in ObjC or Photo
@objc(HWPMediaLister) public class MediaLister: CDVPlugin{
let library = ALAssetsLibrary()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
var command: CDVInvokedUrlCommand!
var option: [String: AnyObject] = [:]
var result:[[String: AnyObject]] = []
var success: Bool!
public func readLibrary(command: CDVInvokedUrlCommand){
dispatch_async(dispatch_get_global_queue(priority, 0)){
self.result = []
self.command = command
let temp = command.arguments[0] as! [String: AnyObject]
self.option = self.initailizeOption(temp)
self.loadMedia(self.option)
}
}
public func startLoad(thumbnail: Bool = true, limit: Int = 20, mediaTypes: [String] = ["image"], offset:Int = 0) -> [[String: AnyObject]]{
option = ["thumbnail": thumbnail, "limit":limit , "mediaTypes": mediaTypes, "offset": offset]
loadMedia(option)
return result
}
private func initailizeOption(option:[String: AnyObject]) -> [String: AnyObject]{
var tempOption = option
if tempOption["offset"] == nil{
tempOption["offset"] = 0
}
if tempOption["limit"] == nil{
tempOption["limit"] = 20
}
if tempOption["thumbnail"] == nil{
tempOption["thumbnail"] = true
}
if tempOption["mediaTypes"] == nil{
tempOption["mdeiaTypes"] = ["image"]
}
return tempOption
}
private func sendResult(){
dispatch_async(dispatch_get_main_queue()){
var pluginResult: CDVPluginResult! = nil
if self.success == true {
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArray: self.result)
} else {
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
}
self.commandDelegate?.sendPluginResult(pluginResult, callbackId: self.command.callbackId)
}
}
private func loadMedia(option: [String: AnyObject]){
success = false
library.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos,usingBlock: {
(group: ALAssetsGroup!, stop: UnsafeMutablePointer) in
if group == nil{
return
}
self.success = true
if let filter = self.getFilter(option["mediaTypes"] as! [String]){
group.setAssetsFilter(filter)
} else {
return
}
let num = group.numberOfAssets()
let indexSet = self.getIndexSet(num, limit: option["limit"] as! Int, offset: option["offset"] as! Int)
if indexSet == nil{
return
}
group.enumerateAssetsAtIndexes(indexSet!, options: NSEnumerationOptions.Reverse){
(asset:ALAsset!, id:Int , stop: UnsafeMutablePointer) in
if asset != nil{
self.result.append(self.setDictionary(asset, id: id, option:option))
}
}
self.sendResult()
}, failureBlock:{
(myerror: NSError!) -> Void in
print("error occurred: \(myerror.localizedDescription)")
}
)
}
// TODO: Add data of Location etc.
private func setDictionary(asset: ALAsset, id: Int, option: [String: AnyObject]) -> [String: AnyObject]{
var data: [String: AnyObject] = [:]
data["id"] = id
data["mediaType"] = setType(asset)
let date: NSDate = asset.valueForProperty(ALAssetPropertyDate) as! NSDate
data["dateAdded"] = date.timeIntervalSince1970
data["path"] = asset.valueForProperty(ALAssetPropertyAssetURL).absoluteString
let rep = asset.defaultRepresentation()
data["size"] = Int(rep.size())
data["orientation"] = rep.metadata()["Orientation"]
data["title"] = rep.filename()
data["height"] = rep.dimensions().height
data["wigth"] = rep.dimensions().width
data["mimeType"] = UTTypeCopyPreferredTagWithClass(rep.UTI(), kUTTagClassMIMEType)!.takeUnretainedValue()
if (option["thumbnail"] as! Bool) {
data["thumbnailPath"] = saveThumbnail(asset, id: id)
}
return data
}
private func saveThumbnail(asset: ALAsset, id: Int) -> NSString{
let thumbnail = asset.thumbnail().takeUnretainedValue()
let image = UIImage(CGImage: thumbnail)
let imageData = UIImageJPEGRepresentation(image, 0.8)
let cacheDirPath: NSString = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as NSString
let filePath = cacheDirPath.stringByAppendingPathComponent("\(id).jpeg")
if imageData!.writeToFile(filePath, atomically: true){
return filePath
} else {
print("error occured: Cannot save thumbnail image")
return ""
}
}
private func setType(asset:ALAsset) -> String{
let type = asset.valueForProperty(ALAssetPropertyType) as! String
if type == ALAssetTypePhoto{
return "image"
} else if type == ALAssetTypeVideo {
return "video"
}
return ""
}
// TODO: Add music and playlist and audio
private func getFilter(mediaTypes: [String]) -> ALAssetsFilter?{
if mediaTypes.contains("image"){
if mediaTypes.contains("video"){
return ALAssetsFilter.allAssets()
} else {
return ALAssetsFilter.allPhotos()
}
} else if mediaTypes.contains("video"){
return ALAssetsFilter.allVideos()
}
return nil
}
private func getIndexSet(max: Int, limit:Int, offset: Int) -> NSIndexSet?{
if offset >= max{
return nil
} else if offset + limit > max{
return NSIndexSet(indexesInRange: NSMakeRange(0, max - offset))
} else {
return NSIndexSet(indexesInRange: NSMakeRange(max - offset - limit, limit))
}
}
} | mit | 6ea9ac8842d7ff444e6117b9f7b2a270 | 36.710059 | 142 | 0.574074 | 5.053132 | false | false | false | false |
ctinnell/ct-playgrounds | HackerRank/GSTest.playground/Contents.swift | 1 | 1213 | import Foundation
func rangeFromNSRange(nsRange: NSRange, str: String) -> Range<String.Index>? {
let from16 = str.utf16.startIndex.advancedBy(nsRange.location, limit: str.utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: str.utf16.endIndex)
if let from = String.Index(from16, within: str),
let to = String.Index(to16, within: str) {
return from ..< to
}
return nil
}
func locate(stringToLocate: String, baseString: String) -> [Range<String.Index>] {
var ranges = [Range<String.Index>]()
do {
// Create the regular expression.
let regex = try NSRegularExpression(pattern: stringToLocate, options: [])
// Use the regular expression to get an array of NSTextCheckingResult.
// Use map to extract the range from each result.
ranges = regex.matchesInString(baseString, options: [], range: NSMakeRange(0, baseString.characters.count)).map({rangeFromNSRange($0.range, str: baseString)!})
}
catch {
// There was a problem creating the regular expression
ranges = []
}
return ranges
}
let results = locate("11111", baseString: "111111111111111")
print(results)
| mit | 5158fb7ef46b30a0b2f7edddac8971c4 | 34.676471 | 167 | 0.663644 | 4.25614 | false | false | false | false |
NikitaAsabin/pdpDecember | DayPhoto/SwipeInteractionController.swift | 1 | 1942 | //
// SwipeInteractionController.swift
// DayPhoto
//
// Created by Nikita Asabin on 14.01.16.
// Copyright © 2016 Flatstack. All rights reserved.
//
import UIKit
class SwipeInteractionController: UIPercentDrivenInteractiveTransition {
var interactionInProgress = false
private var shouldCompleteTransition = false
private weak var viewController: UIViewController!
func wireToViewController(viewController: UIViewController!) {
self.viewController = viewController
prepareGestureRecognizerInView(viewController.view)
}
private func prepareGestureRecognizerInView(view: UIView) {
let gesture = UIScreenEdgePanGestureRecognizer(target: self, action: "handleGesture:")
gesture.edges = UIRectEdge.Left
view.addGestureRecognizer(gesture)
}
func handleGesture(gestureRecognizer: UIScreenEdgePanGestureRecognizer) {
let translation = gestureRecognizer.translationInView(gestureRecognizer.view!.superview!)
var progress = (translation.x / 200)
progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))
switch gestureRecognizer.state {
case .Began:
interactionInProgress = true
viewController.dismissViewControllerAnimated(true, completion: nil)
case .Changed:
shouldCompleteTransition = progress > 0.5
updateInteractiveTransition(progress)
case .Cancelled:
interactionInProgress = false
cancelInteractiveTransition()
case .Ended:
interactionInProgress = false
if !shouldCompleteTransition {
cancelInteractiveTransition()
} else {
finishInteractiveTransition()
}
default:
print("Unsupported")
}
}
}
| mit | 1c37e775b6b0defc56ba468bf35d5875 | 29.809524 | 97 | 0.634724 | 6.491639 | false | false | false | false |
dvSection8/dvSection8 | dvSection8/Classes/Utils/DVTypealias.swift | 1 | 688 | //
// Typealias.swift
// Rush
//
// Created by MJ Roldan on 05/07/2017.
// Copyright © 2017 Mark Joel Roldan. All rights reserved.
//
import Foundation
public typealias StringDictionary = Dictionary<String, String>
public typealias JSONDictionary = Dictionary<String, Any>
public typealias JSONDictionaryArray = [JSONDictionary]
public typealias StringArray = [(String, String)]
public typealias Paremeters = [String: Any]
public typealias HTTPHeaders = [String: String]
public typealias ResponseSuccessBlock = (JSONDictionary) -> ()
public typealias ResponseFailedBlock = (APIErrorCode) -> ()
public typealias APIResponseBlock = (jsonResult: JSONDictionary, error: APIErrorCode)
| mit | 24662d146db4de381607da847963a850 | 33.35 | 85 | 0.772926 | 4.348101 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/UI/PlacePage/PlacePageLayout/Content/TaxiCell/PlacePageTaxiCell.swift | 2 | 1658 | @objc(MWMPlacePageTaxiCell)
final class PlacePageTaxiCell: MWMTableViewCell {
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var title: UILabel! {
didSet {
title.font = UIFont.bold14()
title.textColor = UIColor.blackPrimaryText()
}
}
@IBOutlet private weak var orderButton: UIButton! {
didSet {
let l = orderButton.layer
l.cornerRadius = 8
l.borderColor = UIColor.linkBlue().cgColor
l.borderWidth = 1
orderButton.setTitle(L("taxi_order"), for: .normal)
orderButton.setTitleColor(UIColor.white, for: .normal)
orderButton.titleLabel?.font = UIFont.bold14()
orderButton.backgroundColor = UIColor.linkBlue()
}
}
private weak var delegate: MWMPlacePageButtonsProtocol!
private var type: MWMPlacePageTaxiProvider!
@objc func config(type: MWMPlacePageTaxiProvider, delegate: MWMPlacePageButtonsProtocol) {
self.delegate = delegate
self.type = type
switch type {
case .taxi:
icon.image = #imageLiteral(resourceName: "icTaxiTaxi")
title.text = L("taxi")
case .uber:
icon.image = #imageLiteral(resourceName: "icTaxiUber")
title.text = L("uber")
case .yandex:
icon.image = #imageLiteral(resourceName: "ic_taxi_logo_yandex")
title.text = L("yandex_taxi_title")
case .maxim:
icon.image = #imageLiteral(resourceName: "ic_taxi_logo_maksim")
title.text = L("maxim_taxi_title")
case .rutaxi:
icon.image = #imageLiteral(resourceName: "ic_taxi_logo_rutaxi")
title.text = L("rutaxi_title")
}
}
@IBAction func orderAction() {
delegate.orderTaxi(type)
}
}
| apache-2.0 | 111fdfa9c5783e5a051ba873bf54f797 | 30.884615 | 92 | 0.673703 | 3.995181 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift | 19 | 1259 | // RUN: %swift -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s4main5ValueVyAA7IntegerVGMf"
struct Value<First : Equatable> {
let first: First
}
struct Integer : Equatable {
let value: Int
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
func doit() {
consume( Value(first: Integer(value: 13)) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_CONFORMANCE:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_CONFORMANCE]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 56d496b7ee34a037a8242fec4937946a | 34.971429 | 274 | 0.644162 | 3.055825 | false | false | false | false |
aronse/Hero | Sources/Extensions/UIView+Hero.swift | 1 | 6131 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class SnapshotWrapperView: UIView {
let contentView: UIView
init(contentView: UIView) {
self.contentView = contentView
super.init(frame: contentView.frame)
addSubview(contentView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.bounds.size = bounds.size
contentView.center = bounds.center
}
}
public extension UIView {
private struct AssociatedKeys {
static var heroID = "heroID"
static var heroModifiers = "heroModifers"
static var heroStoredAlpha = "heroStoredAlpha"
static var heroEnabled = "heroEnabled"
static var heroEnabledForSubviews = "heroEnabledForSubviews"
}
/**
**heroID** is the identifier for the view. When doing a transition between two view controllers,
Hero will search through all the subviews for both view controllers and matches views with the same **heroID**.
Whenever a pair is discovered,
Hero will automatically transit the views from source state to the destination state.
*/
@IBInspectable public var heroID: String? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.heroID) as? String }
set { objc_setAssociatedObject(self, &AssociatedKeys.heroID, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
/**
**isHeroEnabled** allows to specify whether a view and its subviews should be consider for animations.
If true, Hero will search through all the subviews for heroIds and modifiers. Defaults to true
*/
@IBInspectable public var isHeroEnabled: Bool {
get { return objc_getAssociatedObject(self, &AssociatedKeys.heroEnabled) as? Bool ?? true }
set { objc_setAssociatedObject(self, &AssociatedKeys.heroEnabled, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
/**
**isHeroEnabledForSubviews** allows to specify whether a view's subviews should be consider for animations.
If true, Hero will search through all the subviews for heroIds and modifiers. Defaults to true
*/
@IBInspectable public var isHeroEnabledForSubviews: Bool {
get { return objc_getAssociatedObject(self, &AssociatedKeys.heroEnabledForSubviews) as? Bool ?? true }
set { objc_setAssociatedObject(self, &AssociatedKeys.heroEnabledForSubviews, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
/**
Use **heroModifiers** to specify animations alongside the main transition. Checkout `HeroModifier.swift` for available modifiers.
*/
public var heroModifiers: [HeroModifier]? {
get { return objc_getAssociatedObject(self, &AssociatedKeys.heroModifiers) as? [HeroModifier] }
set { objc_setAssociatedObject(self, &AssociatedKeys.heroModifiers, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
/**
**heroModifierString** provides another way to set **heroModifiers**. It can be assigned through storyboard.
*/
@IBInspectable public var heroModifierString: String? {
get { fatalError("Reverse lookup is not supported") }
set { heroModifiers = newValue?.parse() }
}
internal func slowSnapshotView() -> UIView {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView(image: image)
imageView.frame = bounds
return SnapshotWrapperView(contentView: imageView)
}
internal func snapshotView() -> UIView? {
let snapshot = snapshotView(afterScreenUpdates: true)
if #available(iOS 11.0, *), let oldSnapshot = snapshot {
// in iOS 11, the snapshot taken by snapshotView(afterScreenUpdates) won't contain a container view
return SnapshotWrapperView(contentView: oldSnapshot)
} else {
return snapshot
}
}
internal var flattenedViewHierarchy: [UIView] {
guard isHeroEnabled else { return [] }
if #available(iOS 9.0, *), isHidden && (superview is UICollectionView || superview is UIStackView || self is UITableViewCell) {
return []
} else if isHidden && (superview is UICollectionView || self is UITableViewCell) {
return []
} else if isHeroEnabledForSubviews {
return [self] + subviews.flatMap { $0.flattenedViewHierarchy }
} else {
return [self]
}
}
/// Used for .overFullScreen presentation
internal var heroStoredAlpha: CGFloat? {
get {
if let doubleValue = (objc_getAssociatedObject(self, &AssociatedKeys.heroStoredAlpha) as? NSNumber)?.doubleValue {
return CGFloat(doubleValue)
}
return nil
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, NSNumber(value: newValue.native), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
| mit | 8f65e8c43a02e7f89a199203713e5ccc | 40.425676 | 141 | 0.730387 | 4.854315 | false | false | false | false |
raphaelhanneken/apple-juice | AppleJuice/NotificationKey.swift | 1 | 751 | //
// NotificationKey.swift
// Apple Juice
// https://github.com/raphaelhanneken/apple-juice
//
/// Defines a notification at a given percentage.
///
/// - invalid: Not a valid notification percentage.
/// - fivePercent: Notify the user at five percent remaining charge.
/// - tenPercent: Notify the user at ten percent remaining charge.
/// - fifeteenPercent: Notify the user at fifetenn percent remaining charge.
/// - twentyPercent: Notify the user at twenty percent remaining charge.
/// - hundredPercent: Notify the user when the battery is fully charged.
enum NotificationKey: Int {
case invalid = 0
case fivePercent = 5
case tenPercent = 10
case fifeteenPercent = 15
case twentyPercent = 20
case hundredPercent = 100
}
| mit | dd13c9724104fca7d35975d5b2232692 | 33.136364 | 76 | 0.725699 | 4.195531 | false | false | false | false |
stetro/domradio-ios | domradio-ios/Controller/NewsViewController.swift | 1 | 4364 | //
// NewsViewController.swift
// domradio-ios
//
// Created by Steffen Tröster on 23/06/15.
// Copyright (c) 2015 Steffen Tröster. All rights reserved.
//
import UIKit
import QuartzCore
import MWFeedParser
import RKDropdownAlert
import KLCPopup
class NewsViewController: UITableViewController, DomradioFeedParserDelegate {
var parser:DomradioFeedParser?
var items:[MWFeedItem] = [MWFeedItem]()
override func viewDidLoad() {
super.viewDidLoad()
self.parser = DomradioFeedParser(target:self)
self.title = parser?.title
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "loadNews:", forControlEvents: UIControlEvents.ValueChanged)
refreshControl.attributedTitle = NSAttributedString(string: "Zum Aktualisieren herunterziehen ...")
self.refreshControl = refreshControl;
self.tableView.addSubview(refreshControl)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 200.0
self.parser!.parseNews()
}
func loadNews(sender:UIRefreshControl){
self.parser!.parseNews()
}
func startParsinggNews() {
self.refreshControl?.beginRefreshing()
}
func succeedNewsParsing(items: [MWFeedItem]) {
self.refreshControl!.endRefreshing()
self.title = parser?.title
self.items = items
self.tableView.reloadSections(
NSIndexSet(indexesInRange: NSMakeRange(0, self.tableView.numberOfSections)),
withRowAnimation: .None)
self.tableView.setContentOffset(CGPointZero, animated: true)
}
func failedNewsParsing(error:NSError) {
self.refreshControl?.endRefreshing()
RKDropdownAlert.title("Fehler", message: "Nachrichten konnten nicht geladen werden!" );
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let _ = segue.identifier{
if(segue.identifier! == "showNews"){
let detailController = segue.destinationViewController as! NewsDetailViewController
detailController.item = items[self.tableView.indexPathForSelectedRow!.item]
self.tableView.deselectRowAtIndexPath(self.tableView.indexPathForSelectedRow!, animated: true)
}
if(segue.identifier! == "selectCategory"){
let detailController = segue.destinationViewController as! NavigationController
let categoryViewController = detailController.viewControllers.first as! CategoryViewController
categoryViewController.updatingCategoryCallback = self.parser!.update
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! NewsTableViewCell
cell.fillNews(items[indexPath.item])
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layoutMargins = UIEdgeInsetsZero
}
func openDomradioDe(){
let url = NSURL(string:"http://domradio.de")!
UIApplication.sharedApplication().openURL(url)
}
@IBAction func showInfo(){
let cv = UIViewController(nibName: "InfoView", bundle: nil)
let view = cv.view
let popup = KLCPopup(contentView: view, showType: KLCPopupShowType.BounceIn, dismissType: KLCPopupDismissType.BounceOutToBottom, maskType: KLCPopupMaskType.Dimmed, dismissOnBackgroundTouch: true, dismissOnContentTouch: false)
let domradio = view.viewWithTag(3) as! UIButton // domradio.de Button
let close = view.viewWithTag(4) as! UIButton // Close Button
close.addTarget(popup, action: "dismiss", forControlEvents: UIControlEvents.TouchUpInside)
domradio.addTarget(self, action: "openDomradioDe", forControlEvents: UIControlEvents.TouchUpInside)
popup.show()
}
}
| mit | 907e6122484dad923195a3b019722385 | 39.766355 | 233 | 0.695782 | 5.186683 | false | false | false | false |
hejunbinlan/Operations | examples/Permissions/Pods/TaylorSource/framework/TaylorSource/YapDatabase/YapDBFactory.swift | 1 | 4119 | //
// Created by Daniel Thorpe on 16/04/2015.
//
import YapDatabase
public struct YapDBCellIndex: IndexPathIndexType {
public let indexPath: NSIndexPath
public let transaction: YapDatabaseReadTransaction
public init(indexPath: NSIndexPath, transaction: YapDatabaseReadTransaction) {
self.indexPath = indexPath
self.transaction = transaction
}
}
public struct YapDBSupplementaryIndex: IndexPathIndexType {
public let group: String
public let indexPath: NSIndexPath
public let transaction: YapDatabaseReadTransaction
public init(group: String, indexPath: NSIndexPath, transaction: YapDatabaseReadTransaction) {
self.group = group
self.indexPath = indexPath
self.transaction = transaction
}
}
public class YapDBFactory<
Item, Cell, SupplementaryView, View
where
View: CellBasedView>: Factory<Item, Cell, SupplementaryView, View, YapDBCellIndex, YapDBSupplementaryIndex> {
public override init(cell: GetCellKey? = .None, supplementary: GetSupplementaryKey? = .None) {
super.init(cell: cell, supplementary: supplementary)
}
}
// MARK: - UpdatableView
extension UITableView {
public func processChanges(changeset: YapDatabaseViewMappings.Changeset) {
func processSectionChanges(sectionChanges: [YapDatabaseViewSectionChange]) {
for change in sectionChanges {
let indexes = NSIndexSet(index: Int(change.index))
switch change.type {
case .Delete:
deleteSections(indexes, withRowAnimation: .Automatic)
case .Insert:
insertSections(indexes, withRowAnimation: .Automatic)
default:
break
}
}
}
func processRowChanges(rowChanges: [YapDatabaseViewRowChange]) {
for change in rowChanges {
switch change.type {
case .Delete:
deleteRowsAtIndexPaths([change.indexPath], withRowAnimation: .Automatic)
case .Insert:
insertRowsAtIndexPaths([change.newIndexPath], withRowAnimation: .Automatic)
case .Move:
deleteRowsAtIndexPaths([change.indexPath], withRowAnimation: .Automatic)
insertRowsAtIndexPaths([change.newIndexPath], withRowAnimation: .Automatic)
case .Update:
reloadRowsAtIndexPaths([change.indexPath], withRowAnimation: .Automatic)
}
}
}
beginUpdates()
processSectionChanges(changeset.sections)
processRowChanges(changeset.items)
endUpdates()
}
}
extension UICollectionView {
public func processChanges(changeset: YapDatabaseViewMappings.Changeset) {
func processSectionChanges(sectionChanges: [YapDatabaseViewSectionChange]) {
for change in sectionChanges {
let indexes = NSIndexSet(index: Int(change.index))
switch change.type {
case .Delete:
deleteSections(indexes)
case .Insert:
insertSections(indexes)
default:
break
}
}
}
func processItemChanges(itemChanges: [YapDatabaseViewRowChange]) {
for change in itemChanges {
switch change.type {
case .Delete:
deleteItemsAtIndexPaths([change.indexPath])
case .Insert:
insertItemsAtIndexPaths([change.newIndexPath])
case .Move:
deleteItemsAtIndexPaths([change.indexPath])
insertItemsAtIndexPaths([change.newIndexPath])
case .Update:
reloadItemsAtIndexPaths([change.indexPath])
}
}
}
performBatchUpdates({
processSectionChanges(changeset.sections)
processItemChanges(changeset.items)
}, completion: nil)
}
}
| mit | 61d57d34b649066fd68288ccf87bf12e | 32.487805 | 113 | 0.603059 | 6.057353 | false | false | false | false |
greycats/Greycats.swift | Greycats/Core/Filter.swift | 1 | 2802 | //
// Filter.swift
// Greycats
//
// Created by Rex Sheng on 1/28/15.
// Copyright (c) 2016 Interactive Labs. All rights reserved.
//
// available in pod 'Greycats', '~> 0.1.4'
import Foundation
public protocol Filtering {
var valueToFilter: String? { get }
func highlightMatches(_ matches: [NSTextCheckingResult])
func clearMatches()
}
public enum Filter {
case characterSequences
case wordSequences
case wordInitialSequences
case startWith
case contains
func pattern(_ string: String) throws -> NSRegularExpression {
var pattern = "(?:.*?)"
let range = Range<String.Index>(uncheckedBounds: (string.startIndex, string.endIndex))
switch self {
case .characterSequences:
string.enumerateSubstrings(in: range, options: NSString.EnumerationOptions.byComposedCharacterSequences) { substring, _, _, _ -> Void in
let escaped = NSRegularExpression.escapedPattern(for: substring!)
pattern.append("(\(escaped))(?:.*?)")
}
case .wordSequences:
string.enumerateSubstrings(in: range, options: .byWords) { substring, _, _, _ -> Void in
let escaped = NSRegularExpression.escapedPattern(for: substring!)
pattern.append("(\(escaped))(?:.*?)")
}
case .wordInitialSequences:
string.enumerateSubstrings(in: range, options: .byWords) { substring, _, _, _ -> Void in
let escaped = NSRegularExpression.escapedPattern(for: substring!)
pattern.append("\\b(\(escaped))(?:.*?)")
}
case .startWith:
let escaped = NSRegularExpression.escapedPattern(for: string)
pattern = "(\(escaped)).*?"
case .contains:
let escaped = NSRegularExpression.escapedPattern(for: string)
pattern = ".*?(\(escaped)).*?"
}
return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
}
public func apply<T: Filtering>(_ string: String?, objects: [T]) -> [T] {
if let keyword = string,
let r = try? pattern(keyword) {
var filtered: [T] = []
objects.forEach { object in
if let value = object.valueToFilter {
let matches = r.matches(in: value, options: .anchored, range: NSRange(location: 0, length: value.count))
if matches.count > 0 {
object.highlightMatches(matches)
filtered.append(object)
}
}
}
return filtered
} else {
for t in objects {
t.clearMatches()
}
return objects
}
}
}
| mit | 6e81e04de1647e698b371bd1da2556e1 | 35.868421 | 148 | 0.568879 | 4.959292 | false | false | false | false |
nolol/Swift-Notes | Resources/GuidedTour.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift | 2 | 4075 | //: ## Control Flow
//:
//: Use `if` and `switch` to make conditionals, and use `for`-`in`, `for`, `while`, and `repeat`-`while` to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.
//:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//: In an `if` statement, the conditional must be a Boolean expression—this means that code such as `if score { ... }` is an error, not an implicit comparison to zero.
//:
//: You can use `if` and `let` together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains `nil` to indicate that a value is missing. Write a question mark (`?`) after the type of a value to mark the value as optional.
//:
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
//: - Experiment:
//: Change `optionalName` to `nil`. What greeting do you get? Add an `else` clause that sets a different greeting if `optionalName` is `nil`.
//:
//: If the optional value is `nil`, the conditional is `false` and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after `let`, which makes the unwrapped value available inside the block of code.
//:
//: Another way to handle optional values is to provide a default value using the `??` operator. If the optional value is missing, the default value is used instead.
//:
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
//: Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
//:
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
//: - Experiment:
//: Try removing the default case. What error do you get?
//:
//: Notice how `let` can be used in a pattern to assign the value that matched the pattern to a constant.
//:
//: After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end of each case’s code.
//:
//: You use `for`-`in` to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.
//:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
//: - Experiment:
//: Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.
//:
//: Use `while` to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.
//:
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
//: You can keep an index in a loop by using `..<` to make a range of indexes.
//:
var total = 0
for i in 0..<4 {
total += i
}
print(total)
//: Use `..<` to make a range that omits its upper value, and use `...` to make a range that includes both values.
//:
//: [Previous](@previous) | [Next](@next) | mit | 443c9a03eeba1250a1173b0a8a0cf435 | 37 | 307 | 0.680197 | 3.908654 | false | false | false | false |
AndreMuis/Algorithms | CountingSort.playground/Contents.swift | 1 | 483 | //: Playground - noun: a place where people can play
import UIKit
let count : Int = 10
var numbers : [Int] = Array(count: count, repeatedValue: 0)
for i : Int in 0...count - 1
{
numbers[i] = Int(arc4random() % 5)
}
numbers
var buckets = Array(count: 5, repeatedValue: [Int]())
for number : Int in numbers
{
buckets[number].append(number)
}
var sortedNumbers : [Int] = []
for bucket : Array in buckets
{
sortedNumbers += bucket
}
sortedNumbers
| mit | e14eac53701cf2a5bcd9012d7a6d6681 | 9.0625 | 59 | 0.63354 | 3.308219 | false | false | false | false |
hfutrell/BezierKit | BezierKit/Library/Utils.swift | 1 | 17240 | //
// Utils.swift
// BezierKit
//
// Created by Holmes Futrell on 11/3/16.
// Copyright © 2016 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
internal extension Array where Element: Comparable {
func sortedAndUniqued() -> [Element] {
guard self.count > 1 else { return self }
return self.sorted().duplicatesRemovedFromSorted()
}
func duplicatesRemovedFromSorted() -> [Element] {
return self.indices.compactMap {
let element = self[$0]
guard $0 > self.startIndex else { return element }
guard element != self[$0 - 1] else { return nil }
return element
}
}
}
internal class Utils {
private static let binomialTable: [[CGFloat]] = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 2, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 3, 3, 1, 0, 0, 0, 0, 0, 0],
[1, 4, 6, 4, 1, 0, 0, 0, 0, 0],
[1, 5, 10, 10, 5, 1, 0, 0, 0, 0],
[1, 6, 15, 20, 15, 6, 1, 0, 0, 0],
[1, 7, 21, 35, 35, 21, 7, 1, 0, 0],
[1, 8, 28, 56, 70, 56, 28, 8, 1, 0],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]
static func binomialCoefficient(_ n: Int, choose k: Int) -> CGFloat {
precondition(n >= 0 && k >= 0 && n <= 9 && k <= 9)
return binomialTable[n][k]
}
// float precision significant decimal
static let epsilon: Double = 1.0e-5
static let tau: Double = 2.0 * Double.pi
// Legendre-Gauss abscissae with n=24 (x_i values, defined at i=n as the roots of the nth order Legendre polynomial Pn(x))
private static let Tvalues: ContiguousArray<CGFloat> = [
-0.0640568928626056260850430826247450385909,
0.0640568928626056260850430826247450385909,
-0.1911188674736163091586398207570696318404,
0.1911188674736163091586398207570696318404,
-0.3150426796961633743867932913198102407864,
0.3150426796961633743867932913198102407864,
-0.4337935076260451384870842319133497124524,
0.4337935076260451384870842319133497124524,
-0.5454214713888395356583756172183723700107,
0.5454214713888395356583756172183723700107,
-0.6480936519369755692524957869107476266696,
0.6480936519369755692524957869107476266696,
-0.7401241915785543642438281030999784255232,
0.7401241915785543642438281030999784255232,
-0.8200019859739029219539498726697452080761,
0.8200019859739029219539498726697452080761,
-0.8864155270044010342131543419821967550873,
0.8864155270044010342131543419821967550873,
-0.9382745520027327585236490017087214496548,
0.9382745520027327585236490017087214496548,
-0.9747285559713094981983919930081690617411,
0.9747285559713094981983919930081690617411,
-0.9951872199970213601799974097007368118745,
0.9951872199970213601799974097007368118745
]
// Legendre-Gauss weights with n=24 (w_i values, defined by a function linked to in the Bezier primer article)
static let Cvalues: ContiguousArray<CGFloat> = [
0.1279381953467521569740561652246953718517,
0.1279381953467521569740561652246953718517,
0.1258374563468282961213753825111836887264,
0.1258374563468282961213753825111836887264,
0.1216704729278033912044631534762624256070,
0.1216704729278033912044631534762624256070,
0.1155056680537256013533444839067835598622,
0.1155056680537256013533444839067835598622,
0.1074442701159656347825773424466062227946,
0.1074442701159656347825773424466062227946,
0.0976186521041138882698806644642471544279,
0.0976186521041138882698806644642471544279,
0.0861901615319532759171852029837426671850,
0.0861901615319532759171852029837426671850,
0.0733464814110803057340336152531165181193,
0.0733464814110803057340336152531165181193,
0.0592985849154367807463677585001085845412,
0.0592985849154367807463677585001085845412,
0.0442774388174198061686027482113382288593,
0.0442774388174198061686027482113382288593,
0.0285313886289336631813078159518782864491,
0.0285313886289336631813078159518782864491,
0.0123412297999871995468056670700372915759,
0.0123412297999871995468056670700372915759
]
static func getABC(n: Int, S: CGPoint, B: CGPoint, E: CGPoint, t: CGFloat = 0.5) -> (A: CGPoint, B: CGPoint, C: CGPoint) {
let u = Utils.projectionRatio(n: n, t: t)
let um = 1-u
let C = CGPoint(
x: u*S.x + um*E.x,
y: u*S.y + um*E.y
)
let s = Utils.abcRatio(n: n, t: t)
let A = CGPoint(
x: B.x + (B.x-C.x)/s,
y: B.y + (B.y-C.y)/s
)
return ( A:A, B:B, C:C )
}
static func abcRatio(n: Int, t: CGFloat = 0.5) -> CGFloat {
// see ratio(t) note on http://pomax.github.io/bezierinfo/#abc
assert(n == 2 || n == 3)
if t == 0 || t == 1 {
return t
}
let bottom = pow(t, CGFloat(n)) + pow(1 - t, CGFloat(n))
let top = bottom - 1
return abs(top/bottom)
}
static func projectionRatio(n: Int, t: CGFloat = 0.5) -> CGFloat {
// see u(t) note on http://pomax.github.io/bezierinfo/#abc
assert(n == 2 || n == 3)
if t == 0 || t == 1 {
return t
}
let top = pow(1.0 - t, CGFloat(n))
let bottom = pow(t, CGFloat(n)) + top
return top/bottom
}
static func map(_ v: CGFloat, _ ds: CGFloat, _ de: CGFloat, _ ts: CGFloat, _ te: CGFloat) -> CGFloat {
let t = (v - ds) / (de - ds)
return t * te + (1 - t) * ts
}
static func approximately(_ a: Double, _ b: Double, precision: Double) -> Bool {
return abs(a-b) <= precision
}
static func linesIntersection(_ line1p1: CGPoint, _ line1p2: CGPoint, _ line2p1: CGPoint, _ line2p2: CGPoint) -> CGPoint? {
let x1 = line1p1.x; let y1 = line1p1.y
let x2 = line1p2.x; let y2 = line1p2.y
let x3 = line2p1.x; let y3 = line2p1.y
let x4 = line2p2.x; let y4 = line2p2.y
let d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
guard d != 0, d.isFinite else { return nil }
let a = x1 * y2 - y1 * x2
let b = x3 * y4 - y3 * x4
let n = a * (line2p1 - line2p2) - b * (line1p1 - line1p2)
return (1.0 / d) * n
}
// cube root function yielding real roots
static private func crt(_ v: Double) -> Double {
return (v < 0) ? -pow(-v, 1.0/3.0) : pow(v, 1.0/3.0)
}
static func clamp(_ x: CGFloat, _ a: CGFloat, _ b: CGFloat) -> CGFloat {
precondition(b >= a)
if x < a {
return a
} else if x > b {
return b
} else {
return x
}
}
static func droots(_ p0: CGFloat, _ p1: CGFloat, _ p2: CGFloat, _ p3: CGFloat, callback: (CGFloat) -> Void) {
// convert the points p0, p1, p2, p3 to a cubic polynomial at^3 + bt^2 + ct + 1 and solve
// see http://www.trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm
let p0 = Double(p0)
let p1 = Double(p1)
let p2 = Double(p2)
let p3 = Double(p3)
let d = -p0 + 3 * p1 - 3 * p2 + p3
let smallValue: Double = 1.0e-8
guard abs(d) >= smallValue else {
// solve the quadratic polynomial at^2 + bt + c instead
let a = (3 * p0 - 6 * p1 + 3 * p2)
let b = (-3 * p0 + 3 * p1)
let c = p0
droots(CGFloat(c), CGFloat(b / 2.0 + c), CGFloat(a + b + c), callback: callback)
return
}
let a = (3 * p0 - 6 * p1 + 3 * p2) / d
let b = (-3 * p0 + 3 * p1) / d
let c = p0 / d
let p = (3 * b - a * a) / 3
let q = (2 * a * a * a - 9 * a * b + 27 * c) / 27
let q2 = q/2
let discriminant = q2 * q2 + p * p * p / 27
let tinyValue = 1.0e-14
if discriminant < -tinyValue {
let r = sqrt(-p * p * p / 27)
let t = -q / (2 * r)
let cosphi = t < -1 ? -1 : t > 1 ? 1 : t
let phi = acos(cosphi)
let crtr = crt(r)
let t1 = 2 * crtr
let root1 = CGFloat(t1 * cos((phi + tau) / 3) - a / 3)
let root2 = CGFloat(t1 * cos((phi + 2 * tau) / 3) - a / 3)
let root3 = CGFloat(t1 * cos(phi / 3) - a / 3)
callback(root1)
if root2 > root1 {
callback(root2)
}
if root3 > root2 {
callback(root3)
}
} else if discriminant > tinyValue {
let sd = sqrt(discriminant)
let u1 = crt(-q2 + sd)
let v1 = crt(q2 + sd)
callback(CGFloat(u1 - v1 - a / 3))
} else if discriminant.isNaN == false {
let u1 = q2 < 0 ? crt(-q2) : -crt(q2)
let root1 = CGFloat(2 * u1 - a / 3)
let root2 = CGFloat(-u1 - a / 3)
if root1 < root2 {
callback(root1)
callback(root2)
} else if root1 > root2 {
callback(root2)
callback(root1)
} else {
callback(root1)
}
}
}
static func droots(_ p0: CGFloat, _ p1: CGFloat, _ p2: CGFloat, callback: (CGFloat) -> Void) {
// quadratic roots are easy
// do something with each root
let p0 = Double(p0)
let p1 = Double(p1)
let p2 = Double(p2)
let d = p0 - 2.0 * p1 + p2
guard d.isFinite else { return }
guard abs(d) > epsilon else {
if p0 != p1 {
callback(CGFloat(0.5 * p0 / (p0 - p1)))
}
return
}
let radical = p1 * p1 - p0 * p2
guard radical >= 0 else { return }
let m1 = sqrt(radical)
let m2 = p0 - p1
let v1 = CGFloat((m2 + m1) / d)
let v2 = CGFloat((m2 - m1) / d)
if v1 < v2 {
callback(v1)
callback(v2)
} else if v1 > v2 {
callback(v2)
callback(v1)
} else {
callback(v1)
}
}
static func droots(_ p0: CGFloat, _ p1: CGFloat, callback: (CGFloat) -> Void) {
guard p0 != p1 else { return }
callback(p0 / (p0 - p1))
}
static func linearInterpolate(_ v1: CGPoint, _ v2: CGPoint, _ t: CGFloat) -> CGPoint {
return v1 + t * (v2 - v1)
}
static func linearInterpolate(_ first: CGFloat, _ second: CGFloat, _ t: CGFloat) -> CGFloat {
return (1 - t) * first + t * second
}
static func arcfn(_ t: CGFloat, _ derivativeFn: (_ t: CGFloat) -> CGPoint) -> CGFloat {
let d = derivativeFn(t)
return d.length
}
static func length(_ derivativeFn: (_ t: CGFloat) -> CGPoint) -> CGFloat {
let z: CGFloat = 0.5
let len = Utils.Tvalues.count
var sum: CGFloat = 0.0
for i in 0..<len {
let t = z * Utils.Tvalues[i] + z
sum += Utils.Cvalues[i] * Utils.arcfn(t, derivativeFn)
}
return z * sum
}
static func angle(o: CGPoint, v1: CGPoint, v2: CGPoint) -> CGFloat {
let d1 = v1 - o
let d2 = v2 - o
return atan2(d1.cross(d2), d1.dot(d2))
}
@inline(__always) private static func shouldRecurse<C>(for subcurve: Subcurve<C>, boundingBoxSize: CGPoint, accuracy: CGFloat) -> Bool {
guard subcurve.canSplit else { return false }
guard boundingBoxSize.x + boundingBoxSize.y >= accuracy else { return false }
if MemoryLayout<CGFloat>.size == 4 {
let curve = subcurve.curve
// limit recursion when we exceed Float32 precision
let midPoint = curve.point(at: 0.5)
if midPoint == curve.startingPoint ||
midPoint == curve.endingPoint {
guard curve.selfIntersects else { return false }
}
}
return true
}
// disable this SwiftLint warning about function having more than 5 parameters
// swiftlint:disable function_parameter_count
static func pairiteration<C1, C2>(_ c1: Subcurve<C1>, _ c2: Subcurve<C2>,
_ c1b: BoundingBox, _ c2b: BoundingBox,
_ results: inout [Intersection],
_ accuracy: CGFloat,
_ totalIterations: inout Int) -> Bool {
let maximumIterations = 900
let maximumIntersections = c1.curve.order * c2.curve.order
totalIterations += 1
guard totalIterations <= maximumIterations else { return false }
guard results.count <= maximumIntersections else { return false }
guard c1b.overlaps(c2b) else { return true }
let shouldRecurse1 = shouldRecurse(for: c1, boundingBoxSize: c1b.size, accuracy: accuracy)
let shouldRecurse2 = shouldRecurse(for: c2, boundingBoxSize: c2b.size, accuracy: accuracy)
if shouldRecurse1 == false, shouldRecurse2 == false {
// subcurves are small enough or we simply cannot recurse any more
let l1 = LineSegment(p0: c1.curve.startingPoint, p1: c1.curve.endingPoint)
let l2 = LineSegment(p0: c2.curve.startingPoint, p1: c2.curve.endingPoint)
guard let intersection = l1.intersections(with: l2, checkCoincidence: false).first else { return true }
let t1 = intersection.t1
let t2 = intersection.t2
results.append(Intersection(t1: t1 * c1.t2 + (1.0 - t1) * c1.t1,
t2: t2 * c2.t2 + (1.0 - t2) * c2.t1))
} else if shouldRecurse1, shouldRecurse2 {
let cc1 = c1.split(at: 0.5)
let cc2 = c2.split(at: 0.5)
let cc1lb = cc1.left.curve.boundingBox
let cc1rb = cc1.right.curve.boundingBox
let cc2lb = cc2.left.curve.boundingBox
let cc2rb = cc2.right.curve.boundingBox
guard Utils.pairiteration(cc1.left, cc2.left, cc1lb, cc2lb, &results, accuracy, &totalIterations) else { return false }
guard Utils.pairiteration(cc1.left, cc2.right, cc1lb, cc2rb, &results, accuracy, &totalIterations) else { return false }
guard Utils.pairiteration(cc1.right, cc2.left, cc1rb, cc2lb, &results, accuracy, &totalIterations) else { return false }
guard Utils.pairiteration(cc1.right, cc2.right, cc1rb, cc2rb, &results, accuracy, &totalIterations) else { return false }
} else if shouldRecurse1 {
let cc1 = c1.split(at: 0.5)
let cc1lb = cc1.left.curve.boundingBox
let cc1rb = cc1.right.curve.boundingBox
guard Utils.pairiteration(cc1.left, c2, cc1lb, c2b, &results, accuracy, &totalIterations) else { return false }
guard Utils.pairiteration(cc1.right, c2, cc1rb, c2b, &results, accuracy, &totalIterations) else { return false }
} else if shouldRecurse2 {
let cc2 = c2.split(at: 0.5)
let cc2lb = cc2.left.curve.boundingBox
let cc2rb = cc2.right.curve.boundingBox
guard Utils.pairiteration(c1, cc2.left, c1b, cc2lb, &results, accuracy, &totalIterations) else { return false }
guard Utils.pairiteration(c1, cc2.right, c1b, cc2rb, &results, accuracy, &totalIterations) else { return false }
}
return true
}
// swiftlint:enable function_parameter_count
static func hull(_ p: [CGPoint], _ t: CGFloat) -> [CGPoint] {
let c: Int = p.count
var q: [CGPoint] = p
q.reserveCapacity(c * (c+1) / 2) // reserve capacity ahead of time to avoid re-alloc
// we linearInterpolate between all points (in-place), until we have 1 point left.
var start: Int = 0
for count in (1 ..< c).reversed() {
let end: Int = start + count
for i in start ..< end {
let pt = Utils.linearInterpolate(q[i], q[i+1], t)
q.append(pt)
}
start = end + 1
}
return q
}
}
#if !canImport(CoreGraphics)
public typealias NSInteger = Int
public typealias CGAffineTransform = AffineTransform
extension CGPoint {
func applying(_ t: CGAffineTransform) -> CGPoint {
t.transform(self)
}
}
extension CGAffineTransform {
init(scaleX sx: CGFloat, y sy: CGFloat) {
self.init(scaleByX: sx, byY: sy)
}
init(translationX tx: CGFloat, y ty: CGFloat) {
self.init(translationByX: tx, byY: ty)
}
init(a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat, tx: CGFloat, ty: CGFloat) {
self.init(m11: a, m12: b, m21: c, m22: d, tX: tx, tY: ty)
}
}
#endif
| mit | b57d5e0e47a5896d619722d0faaca6cc | 39.562353 | 140 | 0.556761 | 3.366335 | false | false | false | false |
grandiere/box | box/View/GridVisor/VGridVisorMetal.swift | 1 | 4858 | import UIKit
import MetalKit
class VGridVisorMetal:MTKView
{
private weak var controller:CGridVisor?
private let samplerState:MTLSamplerState
private let commandQueue:MTLCommandQueue
private let simplePipelineState:MTLRenderPipelineState
private let colourPipelineState:MTLRenderPipelineState
init?(controller:CGridVisor)
{
guard
let device:MTLDevice = MTLCreateSystemDefaultDevice(),
let library:MTLLibrary = device.newDefaultLibrary(),
let vertexFunction:MTLFunction = library.makeFunction(
name:MetalConstants.kVertexFunction),
let simpleFragmentFunction:MTLFunction = library.makeFunction(
name:MetalConstants.kFragmentFunctionSimple),
let colourFragmentFunction:MTLFunction = library.makeFunction(
name:MetalConstants.kFragmentFunctionColour)
else
{
return nil
}
commandQueue = device.makeCommandQueue()
let sampleDescriptor = MTLSamplerDescriptor()
sampleDescriptor.minFilter = MetalConstants.kSamplerMinFilter
sampleDescriptor.magFilter = MetalConstants.kSamplerMagFilter
sampleDescriptor.mipFilter = MetalConstants.kSamplerMipFilter
sampleDescriptor.sAddressMode = MetalConstants.kSamplerSAddressMode
sampleDescriptor.tAddressMode = MetalConstants.kSamplerTAddressMode
sampleDescriptor.rAddressMode = MetalConstants.kSamplerRAddressMode
sampleDescriptor.lodMinClamp = MetalConstants.kSamplerLodMinClamp
sampleDescriptor.lodMaxClamp = MetalConstants.kSamplerLodMaxClamp
sampleDescriptor.maxAnisotropy = MetalConstants.kSamplerMaxAnisotropy
sampleDescriptor.normalizedCoordinates = MetalConstants.kSamplerNormalizedCoordinates
samplerState = device.makeSamplerState(descriptor:sampleDescriptor)
let simplePipelineDescriptor:MTLRenderPipelineDescriptor = MTLRenderPipelineDescriptor()
simplePipelineDescriptor.vertexFunction = vertexFunction
simplePipelineDescriptor.fragmentFunction = simpleFragmentFunction
MetalConstants.colorAttachmentConfig(pipelineDescriptor:simplePipelineDescriptor)
let colourPipelineDescriptor:MTLRenderPipelineDescriptor = MTLRenderPipelineDescriptor()
colourPipelineDescriptor.vertexFunction = vertexFunction
colourPipelineDescriptor.fragmentFunction = colourFragmentFunction
MetalConstants.colorAttachmentConfig(pipelineDescriptor:colourPipelineDescriptor)
do
{
try simplePipelineState = device.makeRenderPipelineState(
descriptor:simplePipelineDescriptor)
}
catch
{
return nil
}
do
{
try colourPipelineState = device.makeRenderPipelineState(
descriptor:colourPipelineDescriptor)
}
catch
{
return nil
}
super.init(frame:CGRect.zero, device:device)
backgroundColor = UIColor.clear
framebufferOnly = true
clipsToBounds = true
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
contentMode = UIViewContentMode.center
autoResizeDrawable = true
isPaused = false
self.controller = controller
}
required init(coder:NSCoder)
{
fatalError()
}
override func draw()
{
super.draw()
guard
let controller:CGridVisor = self.controller
else
{
return
}
controller.viewGridVisor.viewMenu.updateMenu()
guard
let drawable:CAMetalDrawable = currentDrawable,
let passDescriptor:MTLRenderPassDescriptor = currentRenderPassDescriptor
else
{
return
}
let commandBuffer:MTLCommandBuffer = commandQueue.makeCommandBuffer()
let renderEncoder:MTLRenderCommandEncoder = commandBuffer.makeRenderCommandEncoder(
descriptor:passDescriptor)
renderEncoder.setCullMode(MTLCullMode.none)
renderEncoder.setFragmentSamplerState(
samplerState,
at:MetalConstants.kFragmentSamplerIndex)
let renderManager:MetalRenderManager = MetalRenderManager(
renderEncoder:renderEncoder,
simplePipelineState:simplePipelineState,
colourPipelineState:colourPipelineState)
controller.modelRender?.render(manager:renderManager)
renderEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
| mit | 46e2357b9997800ad1f8c8a2afad6191 | 34.720588 | 96 | 0.671264 | 6.920228 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift | 22 | 14806 | //
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension Reactive where Base: UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items) { (tableView, row, element) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(row)"
return cell
}
.disposed(by: disposeBag)
*/
public func items<S: Sequence, O: ObservableType>
(_ source: O)
-> (_ cellFactory: @escaping (UITableView, Int, S.Iterator.Element) -> UITableViewCell)
-> Disposable
where O.E == S {
return { cellFactory in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.items(dataSource: dataSource)(source)
}
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = "\(element) @ row \(row)"
}
.disposed(by: disposeBag)
*/
public func items<S: Sequence, Cell: UITableViewCell, O : ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: O)
-> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
-> Disposable
where O.E == S {
return { source in
return { configureCell in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = IndexPath(item: i, section: 0)
let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
This method will retain the data source for as long as the subscription isn't disposed (result `Disposable`
being disposed).
In case `source` observable sequence terminates successfully, the data source will present latest element
until the subscription isn't disposed.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
Example
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
let items = Observable.just([
SectionModel(model: "First section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Second section", items: [
1.0,
2.0,
3.0
]),
SectionModel(model: "Third section", items: [
1.0,
2.0,
3.0
])
])
dataSource.configureCell = { (dataSource, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
items
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
*/
public func items<
DataSource: RxTableViewDataSourceType & UITableViewDataSource,
O: ObservableType>
(dataSource: DataSource)
-> (_ source: O)
-> Disposable
where DataSource.Element == O.E {
return { source in
// This is called for sideeffects only, and to make sure delegate proxy is in place when
// data source is being bound.
// This is needed because theoretically the data source subscription itself might
// call `self.rx.delegate`. If that happens, it might cause weird side effects since
// setting data source will set delegate, and UITableView might get into a weird state.
// Therefore it's better to set delegate proxy first, just to be sure.
_ = self.delegate
// Strong reference is needed because data source is in use until result subscription is disposed
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = tableView else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
}
extension UITableView {
/**
Factory method that enables subclasses to implement their own `delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
/**
Factory method that enables subclasses to implement their own `rx.dataSource`.
- returns: Instance of delegate proxy that wraps `dataSource`.
*/
public func createRxDataSourceProxy() -> RxTableViewDataSourceProxy {
return RxTableViewDataSourceProxy(parentObject: self)
}
}
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var dataSource: DelegateProxy {
return RxTableViewDataSourceProxy.proxyForObject(base)
}
/**
Installs data source as forwarding delegate on `rx.dataSource`.
Data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setDataSource(_ dataSource: UITableViewDataSource)
-> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var itemSelected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
*/
public var itemDeselected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`.
*/
public var itemAccessoryButtonTapped: ControlEvent<IndexPath> {
let source: Observable<IndexPath> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemInserted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert
}
.map { a in
return (try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemDeleted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete
}
.map { a in
return try castOrThrow(IndexPath.self, a[2])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:)))
.map { a in
return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`.
*/
public var willDisplayCell: ControlEvent<WillDisplayCellEvent> {
let source: Observable<WillDisplayCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`.
*/
public var didEndDisplayingCell: ControlEvent<DidEndDisplayingCellEvent> {
let source: Observable<DidEndDisplayingCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelSelected(MyModel.self)
.map { ...
```
*/
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeselected(MyModel.self)
.map { ...
```
*/
public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
*/
public func model<T>(at indexPath: IndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.")
let element = try dataSource.model(at: indexPath)
return castOrFatalError(element)
}
}
#endif
#if os(tvOS)
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)))
.map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = a[1] as! UIFocusUpdateContext
let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2])
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif
| mit | 2e3d1321a14f3c8f22e61534a865d3ff | 36.292191 | 200 | 0.626748 | 5.329374 | false | false | false | false |
vincent-cheny/DailyRecord | DailyRecord/AboutViewController.swift | 1 | 2032 | //
// AboutViewController.swift
// DailyRecord
//
// Created by ChenYong on 16/2/13.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
import UIKit
import TTTAttributedLabel
class AboutViewController: UIViewController, TTTAttributedLabelDelegate {
@IBOutlet weak var link1: TTTAttributedLabel!
@IBOutlet weak var link2: TTTAttributedLabel!
@IBOutlet weak var link3: TTTAttributedLabel!
@IBOutlet weak var link4: TTTAttributedLabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
link1.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
link1.addLinkToURL(NSURL(string: link1.text!), withRange: NSRange(location: 0, length: (link1.text! as NSString).length))
link1.delegate = self
link2.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
link2.addLinkToURL(NSURL(string: link2.text!), withRange: NSRange(location: 0, length: (link2.text! as NSString).length))
link2.delegate = self
link3.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
link3.addLinkToURL(NSURL(string: link3.text!), withRange: NSRange(location: 0, length: (link3.text! as NSString).length))
link3.delegate = self
link4.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
link4.addLinkToURL(NSURL(string: link4.text!), withRange: NSRange(location: 0, length: (link4.text! as NSString).length))
link4.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
let webView = UIWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
webView.loadRequest(NSURLRequest(URL: url))
self.view.addSubview(webView)
}
} | gpl-2.0 | c1d18efb80a66d7b90039913c87d0afb | 43.130435 | 130 | 0.712666 | 4.439825 | false | false | false | false |
tolkiana/faces | faces/FacesTableViewController.swift | 1 | 1025 | //
// FacesTableViewController.swift
// faces
//
// Created by Nelida Velázquez on 10/12/15.
// Copyright © 2015 Nelida Velázquez. All rights reserved.
//
import UIKit
class FacesTableViewController: UIViewController, UITableViewDataSource {
var faces: [Face] = [
Face(title: "Matías", emoticon: "😀", imageName: "name"),
Face(title: "Mamá", emoticon: "😁", imageName: "name"),
]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return faces.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FaceCellIdentifier") as! FaceTableViewCell
cell.faceTitleLabel.text = faces[indexPath.row].title
cell.emoticonLabel.text = faces[indexPath.row].emoticon
cell.imageView?.image = UIImage(named: faces[indexPath.row].imageName)
return cell
}
}
| gpl-2.0 | e4620bf95dc1c98656a6ac6b5e53f062 | 29.727273 | 109 | 0.674556 | 4.447368 | false | false | false | false |
uptech/Constraid | Sources/Constraid/LimitByMargin.swift | 1 | 9788 | // We don't conditional import AppKit like normal here because AppKit Autolayout doesn't support
// the margin attributes that UIKit does. And of course this file isn't included in the MacOS
// build target.
#if os(iOS)
import UIKit
/**
Constrains the object's leading edge to be limited by the
leading margin of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
leading margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byLeadingMarginOf itemB: Any?,
times multiplier: CGFloat = 1.0,
insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
itemA.translatesAutoresizingMaskIntoConstraints = false
let collection = Constraid.ConstraintCollection([
NSLayoutConstraint(item: itemA, attribute: .leading,
relatedBy: .greaterThanOrEqual, toItem: itemB,
attribute: .leadingMargin, multiplier: multiplier,
constant: inset, priority: priority)
])
return collection
}
/**
Constrains the object's trailing edge to be limited by the
trailing margin of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
trailing margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byTrailingMarginOf itemB: Any?,
times multiplier: CGFloat = 1.0,
insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
itemA.translatesAutoresizingMaskIntoConstraints = false
let collection = Constraid.ConstraintCollection([
NSLayoutConstraint(item: itemA, attribute: .trailing,
relatedBy: .lessThanOrEqual, toItem: itemB,
attribute: .trailingMargin, multiplier: multiplier,
constant: (inset * -1), priority: priority)
])
return collection
}
/**
Constrains the object's top edge to be limited by the
top margin of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
top margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byTopMarginOf itemB: Any?,
times multiplier: CGFloat = 1.0,
insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
itemA.translatesAutoresizingMaskIntoConstraints = false
let collection = Constraid.ConstraintCollection([
NSLayoutConstraint(item: itemA, attribute: .top,
relatedBy: .greaterThanOrEqual, toItem: itemB,
attribute: .topMargin, multiplier: multiplier,
constant: inset, priority: priority)
])
return collection
}
/**
Constrains the object's bottom edge to be limited by the
bottom margin of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
bottom margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byBottomMarginOf itemB: Any?,
times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
itemA.translatesAutoresizingMaskIntoConstraints = false
let collection = Constraid.ConstraintCollection([
NSLayoutConstraint(item: itemA, attribute: .bottom,
relatedBy: .lessThanOrEqual, toItem: itemB,
attribute: .bottomMargin, multiplier: multiplier,
constant: (inset * -1), priority: priority)
])
return collection
}
/**
Constrains the object's top & bottom edges to be limited
by the top & bottom margins of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
top & bottom margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byHorizontalMarginsOf itemB: Any?,
times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
let collection = Constraid.limit(itemA, byTopMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority) +
Constraid.limit(itemA, byBottomMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority)
return collection
}
/**
Constrains the object's leading & trailing edges to be limited
by the leading & trailing margins of `item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
leading & trailing margin of the item prior to the `constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byVerticalMarginsOf itemB: Any?,
times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
let collection = Constraid.limit(itemA, byLeadingMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority) +
Constraid.limit(itemA, byTrailingMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority)
return collection
}
/**
Constrains the object's top, bottom, leading & trailing edges to be
limited by the top, bottom, leading & trailing margins of
`item`
- parameter itemA: The `item` you want to constrain in relation to another object
- parameter itemB: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
top, bottom, leading & trailing margin of the item prior to the
`constant` being applied.
- parameter constant: The amount to add to the constraint equation
after the multiplier.
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraint collection containing the generated constraint
*/
public func limit(_ itemA: Constraid.View, byMarginsOf itemB: Any?,
times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired
) -> Constraid.ConstraintCollection {
let collection = Constraid.limit(itemA, byTopMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority) +
Constraid.limit(itemA, byBottomMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority) +
Constraid.limit(itemA, byLeadingMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority) +
Constraid.limit(itemA, byTrailingMarginOf: itemB, times: multiplier, insetBy: inset,
priority: priority)
return collection
}
#endif
| mit | 66e149b1e35ee8ada88c381fbeeb49cc | 44.314815 | 104 | 0.711177 | 5.279396 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/UnneededBreakInSwitchRule.swift | 1 | 4325 | import Foundation
import SourceKittenFramework
private func embedInSwitch(_ text: String, case: String = "case .bar") -> String {
return "switch foo {\n" +
"\(`case`):\n" +
" \(text)\n" +
"}"
}
public struct UnneededBreakInSwitchRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "unneeded_break_in_switch",
name: "Unneeded Break in Switch",
description: "Avoid using unneeded break statements.",
kind: .idiomatic,
nonTriggeringExamples: [
embedInSwitch("break"),
embedInSwitch("break", case: "default"),
embedInSwitch("for i in [0, 1, 2] { break }"),
embedInSwitch("if true { break }"),
embedInSwitch("something()")
],
triggeringExamples: [
embedInSwitch("something()\n ↓break"),
embedInSwitch("something()\n ↓break // comment"),
embedInSwitch("something()\n ↓break", case: "default"),
embedInSwitch("something()\n ↓break", case: "case .foo, .foo2 where condition")
]
)
public func validate(file: File) -> [StyleViolation] {
return file.match(pattern: "break", with: [.keyword]).compactMap { range in
let contents = file.contents.bridge()
guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length),
let innerStructure = file.structure.structures(forByteOffset: byteRange.location).last,
innerStructure.kind.flatMap(StatementKind.init) == .case,
let caseOffset = innerStructure.offset,
let caseLength = innerStructure.length,
let lastPatternEnd = patternEnd(dictionary: innerStructure) else {
return nil
}
let caseRange = NSRange(location: caseOffset, length: caseLength)
let tokens = file.syntaxMap.tokens(inByteRange: caseRange).filter { token in
guard let kind = SyntaxKind(rawValue: token.type),
token.offset > lastPatternEnd else {
return false
}
return !kind.isCommentLike
}
// is the `break` the only token inside `case`? If so, it's valid.
guard tokens.count > 1 else {
return nil
}
// is the `break` found the last (non-comment) token inside `case`?
guard let lastValidToken = tokens.last,
SyntaxKind(rawValue: lastValidToken.type) == .keyword,
lastValidToken.offset == byteRange.location,
lastValidToken.length == byteRange.length else {
return nil
}
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location))
}
}
private func patternEnd(dictionary: [String: SourceKitRepresentable]) -> Int? {
let patternEnds = dictionary.elements.compactMap { subDictionary -> Int? in
guard subDictionary.kind == "source.lang.swift.structure.elem.pattern",
let offset = subDictionary.offset,
let length = subDictionary.length else {
return nil
}
return offset + length
}
return patternEnds.max()
}
}
private extension Structure {
func structures(forByteOffset byteOffset: Int) -> [[String: SourceKitRepresentable]] {
var results = [[String: SourceKitRepresentable]]()
func parse(_ dictionary: [String: SourceKitRepresentable]) {
guard let offset = dictionary.offset,
let byteRange = dictionary.length.map({ NSRange(location: offset, length: $0) }),
NSLocationInRange(byteOffset, byteRange) else {
return
}
results.append(dictionary)
dictionary.substructure.forEach(parse)
}
parse(dictionary)
return results
}
}
| mit | 8f64887c1a5605ed9de4aa2a6f297807 | 38.972222 | 107 | 0.576789 | 5.258222 | false | false | false | false |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/BotParser/FetchBot.swift | 1 | 34391 | //
// FetchBot.swift
// S8Blocker
//
// Created by virus1993 on 2018/1/15.
// Copyright © 2018年 ascp. All rights reserved.
//
import Foundation
//import Gzip
typealias ParserMaker = (String) -> ContentInfo
typealias AsyncFinish = () -> Void
enum Host: String {
case dytt = "www.ygdy8.net"
case sex8 = "sex8.cc"
}
/// 演员导演信息
struct Creator {
var name : String
var english : String
}
/// 列表页面链接信息
struct FetchURL : Equatable {
var site : String
var page : Int
var maker : (FetchURL) -> String
var url : URL {
get {
return URL(string: maker(self))!;
}
}
static func ==(lhs: FetchURL, rhs: FetchURL) -> Bool {
return lhs.url == rhs.url
}
}
/// 抓取内容页面信息模型
struct ContentInfo : Equatable {
var title : String
var page : String
var msk : String
var time : String
var size : String
var format : String
var passwod : String
var titleMD5 : String {
return title.md5()
}
var downloafLink : [String]
var imageLink : [String]
// ◎译 名 电锯惊魂8:竖锯/电锯惊魂8/夺魂锯:游戏重启(台)/恐惧斗室之狂魔再现(港)/电锯惊魂:遗产
var translateName : String
// ◎片 名 Jigsaw
var movieRawName : String
// ◎年 代 2017
var releaseYear : String
// ◎产 地 美国
var produceLocation : String
// ◎类 别 悬疑/惊悚/恐怖
var styles : [String]
// ◎语 言 英语
var languages : [String]
// ◎字 幕 中英双字幕
var subtitle : String
// ◎上映日期 2017-10-27(美国)
var showTimeInfo : String
var fileFormart : String
// ◎文件格式 HD-RMVB
var videoSize : String
// ◎视频尺寸 1280 x 720
var movieTime : String
// ◎片 长 91分钟
var directes : [Creator]
// ◎导 演 迈克尔·斯派瑞 Michael Spierig / 彼得·斯派瑞 Peter Spierig
var actors : [Creator]
// ◎主 演 马特·帕斯摩尔 Matt Passmore
var _note : String
var note : String {
set {
_note = newValue.replacingOccurrences(of: "</p>", with: "").replacingOccurrences(of: "<p>", with: "").replacingOccurrences(of: "<br /><br />", with: "\n").replacingOccurrences(of: "<br />", with: "\n").replacingOccurrences(of: "<br", with: "") //.removingHTMLEntities
}
get {
return _note
}
}
init() {
page = ""
title = ""
msk = ""
time = ""
size = ""
format = ""
passwod = ""
downloafLink = [String]()
imageLink = [String]()
translateName = ""
movieRawName = ""
releaseYear = ""
produceLocation = ""
styles = [String]()
languages = [String]()
subtitle = ""
showTimeInfo = ""
fileFormart = ""
videoSize = ""
movieTime = ""
directes = [Creator]()
actors = [Creator]()
_note = ""
}
static func ==(lhs: ContentInfo, rhs: ContentInfo) -> Bool {
return lhs.title == rhs.title && lhs.page == rhs.page
}
func contain(keyword: String) -> Bool {
return title.contains(keyword) ||
translateName.contains(keyword) ||
movieRawName.contains(keyword) ||
actors.filter({ $0.name.contains(keyword) || $0.english.contains(keyword) }).count > 0 ||
directes.filter({ $0.name.contains(keyword) || $0.english.contains(keyword) }).count > 0
}
}
struct Site {
var host : Host
var parentUrl : URL
var categrory : ListCategrory?
var listRule : ParserTagRule
var contentRule : ParserTagRule
var listEncode : String.Encoding
var contentEncode : String.Encoding
init(parentUrl: URL,
listRule: ParserTagRule,
contentRule: ParserTagRule,
listEncode: String.Encoding,
contentEncode: String.Encoding,
hostName: Host) {
self.host = hostName
self.listRule = listRule
self.contentRule = contentRule
self.listEncode = listEncode
self.contentEncode = contentEncode
self.parentUrl = parentUrl
}
func page(bySuffix suffix: Int) -> URL {
switch self.host {
case .dytt:
return parentUrl.appendingPathComponent("list_23_\(suffix).html")
case .sex8:
return parentUrl.appendingPathComponent("forum-\(categrory?.site ?? "103")-\(suffix).html")
}
}
static let dytt = Site(parentUrl: URL(string: "http://www.ygdy8.net/html/gndy/dyzz")!,
listRule: PageRuleOption.mLink,
contentRule: PageRuleOption.mContent,
listEncode: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.HZ_GB_2312.rawValue))),
contentEncode: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))),
hostName: .dytt)
static let netdisk = Site(parentUrl: URL(string: "http://sex8.cc")!,
listRule: PageRuleOption.link,
contentRule: PageRuleOption.content,
listEncode: .utf8,
contentEncode: .utf8,
hostName: .sex8)
var parserMaker: ParserMaker? {
get {
switch self.host {
case .dytt:
return { mainContent in
var info = ContentInfo()
let titlesRule = InfoRuleOption.mainTitle
for result in parse(string:mainContent, rule: titlesRule) ?? [] {
info.title = result.innerHTML
print("**** title: \(result.innerHTML)")
}
let actorsRule = InfoRuleOption.mainActor
for result in parse(string:mainContent, rule: actorsRule) ?? [] {
for resultx in parse(string:result.innerHTML, rule: InfoRuleOption.singleActor) ?? [] {
info.actors.append(Creator(name: resultx.innerHTML, english: ""))
print("*********** actor link: \(resultx.innerHTML)")
}
}
let directorsRule = InfoRuleOption.mainDirector
for result in parse(string:mainContent, rule: directorsRule) ?? [] {
for resultx in parse(string:result.innerHTML, rule: InfoRuleOption.singleDirector) ?? [] {
info.directes.append(Creator(name: resultx.innerHTML, english: ""))
print("*********** director link: \(resultx.innerHTML)")
}
}
let translateNameRule = InfoRuleOption.translateName
for result in parse(string:mainContent, rule: translateNameRule) ?? [] {
info.translateName = result.innerHTML
print("***** translateName: \(result.innerHTML)")
}
let movieRawNameRule = InfoRuleOption.movieRawName
for result in parse(string:mainContent, rule: movieRawNameRule) ?? [] {
info.movieRawName = result.innerHTML
print("***** movieRawName: \(result.innerHTML)")
}
let releaseYearRule = InfoRuleOption.releaseYear
for result in parse(string:mainContent, rule: releaseYearRule) ?? [] {
info.releaseYear = result.innerHTML
print("***** releaseYear: \(result.innerHTML)")
}
let produceLocationRule = InfoRuleOption.produceLocation
for result in parse(string:mainContent, rule: produceLocationRule) ?? [] {
info.produceLocation = result.innerHTML
print("***** produceLocation: \(result.innerHTML)")
}
let subtitleRule = InfoRuleOption.subtitle
for result in parse(string:mainContent, rule: subtitleRule) ?? [] {
info.subtitle = result.innerHTML
print("***** subtitle: \(result.innerHTML)")
}
let showTimeInfoRule = InfoRuleOption.showTimeInfo
for result in parse(string:mainContent, rule: showTimeInfoRule) ?? [] {
info.showTimeInfo = result.innerHTML
print("***** showTimeInfo: \(result.innerHTML)")
}
let fileFormartRule = InfoRuleOption.fileFormart
for result in parse(string:mainContent, rule: fileFormartRule) ?? [] {
info.fileFormart = result.innerHTML
print("***** fileFormart: \(result.innerHTML)")
}
let movieTimeRule = InfoRuleOption.movieTime
for result in parse(string:mainContent, rule: movieTimeRule) ?? [] {
info.movieTime = result.innerHTML
print("***** movieTime: \(result.innerHTML)")
}
let noteRule = InfoRuleOption.note
for result in parse(string:mainContent, rule: noteRule) ?? [] {
info.note = result.innerHTML
print("***** note: \(result.innerHTML)")
}
let imageRule = InfoRuleOption.mainMovieImage
for result in parse(string:mainContent, rule: imageRule) ?? [] {
if let src = result.attributes["src"] {
info.imageLink.append(src)
print("*********** image: \(src)")
}
}
let dowloadLinkRule = InfoRuleOption.movieDowloadLink
for linkResult in parse(string:mainContent, rule: dowloadLinkRule) ?? [] {
info.downloafLink.append(linkResult.innerHTML)
print("*********** download link: \(linkResult.innerHTML)")
}
return info
}
case .sex8:
return { mainContent in
var info = ContentInfo()
for result in parse(string:mainContent, rule: InfoRuleOption.netdiskTitle) ?? [] {
info.title = result.innerHTML
print("*********** title: \(result.innerHTML)")
}
for rule in [InfoRuleOption.downloadLink, InfoRuleOption.downloadLinkLi, InfoRuleOption.v4DownloadLink] {
for linkResult in parse(string:mainContent, rule: rule) ?? [] {
if InfoRuleOption.v4DownloadLink.regex == rule.regex {
info.downloafLink.append(linkResult.innerHTML.replacingOccurrences(of: "\"", with: ""))
} else {
info.downloafLink.append(linkResult.innerHTML)
}
print("*********** download link: \(linkResult.innerHTML)")
}
}
let imageLinkRule = InfoRuleOption.imageLink
for imageResult in parse(string:mainContent, rule: imageLinkRule) ?? [] {
for attribute in imageLinkRule.attrubutes {
if let item = imageResult.attributes[attribute.key] {
info.imageLink.append(item)
print("*********** image: \(item)")
break
}
}
}
let mskRule = InfoRuleOption.msk
if let last = parse(string:mainContent, rule: mskRule)?.last {
info.msk = last.innerHTML
print("*********** msk: \(info.msk)")
}
let timeRule = InfoRuleOption.time
if let last = parse(string:mainContent, rule: timeRule)?.last {
info.time = last.innerHTML
print("*********** time: \(info.time)")
}
let sizeRule = InfoRuleOption.size
if let last = parse(string:mainContent, rule: sizeRule)?.last {
info.size = last.innerHTML
print("*********** size: \(info.size)")
}
let formatRule = InfoRuleOption.format
if let last = parse(string:mainContent, rule: formatRule)?.last {
info.format = last.innerHTML
print("*********** format: \(info.format)")
}
let passwodRule = InfoRuleOption.password
if let last = parse(string:mainContent, rule: passwodRule)?.last {
info.passwod = last.innerHTML
print("*********** passwod: \(info.passwod)")
}
return info
}
}
}
}
}
/// 内容信息正则规则选项
struct InfoRuleOption {
static let netdiskTitle = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "<span id=\"thread_subject\">", hasSuffix: nil, innerRegex: "[^<]*")
/// 是否有码
static let msk = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "((【是否有码】)|(【有碼無碼】)|(【影片说明】)|(【影片說明】)|(【是否有碼】)){1}[::]{0,1}(( )|(\\s))*", hasSuffix: nil, innerRegex: "([^<::( )])+")
/// 影片时间
static let time = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "((【影片时间】)|(【影片時間】)|(【视频时间】)){1}[::]{0,1}(( )|(\\s))*", hasSuffix: nil, innerRegex: "([^<( )])+")
/// 影片大小
static let size = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "((【影片大小】)|(【视频大小】)){1}[::]{0,1}(( )|(\\s))*", hasSuffix: nil, innerRegex: "([^<::( )])+")
/// 影片格式
static let format = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "((【影片格式】)|(【视频格式】)){1}[::]{0,1}", hasSuffix: nil, innerRegex: "([^<::])+")
/// 解压密码
static let password = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "((【解壓密碼】)|(【解压密码】)|(解壓密碼)|(解压密码)){1}[::]{0,1}(( )|(\\s))*", hasSuffix: nil, innerRegex: "([^<::])+")
/// 下载链接
/// 下载地址[\\s\\S]+<a( \\w+=\"[^\"]+\")+>[^<]+</a>
static let downloadLink = ParserTagRule(tag: "a", isTagPaser: true, attrubutes: [], inTagRegexString: " \\w+=\"\\w+:\\/\\/[\\w+\\.]+[\\/\\-\\w\\.]+\" \\w+=\"\\w+\"", hasSuffix: nil, innerRegex: "\\w+:\\/\\/[\\w+\\.]+[\\/\\-\\w\\.]+")
/// 下载地址2
static let downloadLinkLi = ParserTagRule(tag: "li", isTagPaser: true, attrubutes: [], inTagRegexString: "", hasSuffix: nil, innerRegex: "\\w+:\\/\\/[\\w+\\.]+[\\/\\-\\w\\.]+")
/// 下载地址3
static let v4DownloadLink = ParserTagRule(tag: "a", isTagPaser: false, attrubutes: [], inTagRegexString: "((下载链接)|(下載鏈接)|(下载地址)|(下載地址))[^\"]+", hasSuffix: nil, innerRegex: "\"[^\"]+\"")
/// 图片链接
static let imageLink = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [ParserAttrubuteRule(key: "file"), ParserAttrubuteRule(key: "href"), ParserAttrubuteRule(key: "src")], inTagRegexString: "<img([^>]+class=\"zoom\"[^>]+)|(((\\ssrc=\"\\w+:[^\"]+\")|(\\salt=\"\\w+\\.\\w+\")|(\\stitle=\"\\w+\\.\\w+\")){3})", hasSuffix: nil, innerRegex: nil)
/// 主内容标签
static let main = ParserTagRule(tag: "td", isTagPaser: true, attrubutes: [], inTagRegexString: " \\w+=\"t_f\" \\w+=\"postmessage_\\d+\"", hasSuffix: nil, innerRegex: nil)
/// ---- 电影天堂 ---
/// 主演列表
static let mainActor = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎主[\\s]+演", hasSuffix: "◎", innerRegex: "[^◎]+")
/// 主演名称
static let singleActor = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "\\s*", hasSuffix: "<", innerRegex: "[^>]+")
/// 导演列表
static let mainDirector = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎导[\\s]+演", hasSuffix: "◎", innerRegex: "[^◎]+")
/// 导演名称
static let singleDirector = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "\\s*", hasSuffix: "[<|\\/]+", innerRegex: "[^\\/]+")
/// 类别列表
static let mainStyle = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎类[\\s]+别", hasSuffix: "◎", innerRegex: "[^◎]+")
/// 类别名称
static let singleStyle = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "[\\s\\/]*", hasSuffix: nil, innerRegex: "[^\\/]+")
/// 语言列表
static let mainLanguage = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎语[\\s]+言", hasSuffix: "◎", innerRegex: "[^◎]+")
/// 语言名称
static let singleLanguage = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "[\\s\\/]*", hasSuffix: nil, innerRegex: "[^\\/]+")
static let translateName = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎译[\\s]+名[\\s]+", hasSuffix: "<", innerRegex: "[^◎<]+")
static let movieRawName = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎片[\\s]+名[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let releaseYear = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎年[\\s]+代[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let produceLocation = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎产[\\s]+地[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let subtitle = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎字[\\s]+幕[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let showTimeInfo = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎上映日期[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let fileFormart = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎文件格式[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let videoSize = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎视频尺寸[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
static let movieTime = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎片[\\s]+长[\\s]+", hasSuffix: "<", innerRegex: "[^<]+")
// static let note = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎简[\\s]+介\\s+[<br \\/>]+", hasSuffix: "<img ", innerRegex: "[\\s\\S]+")◎简\s+介[^◎]+(◎|(<img))
static let note = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "◎简\\s+介\\s*[(<br />)|(</{0,1}p>)]+", hasSuffix: "(◎|(<img)|(<p><strong>))", innerRegex: "[^◎]+")
/// 标题列表
static let mainTitle = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "<div \\w+=\"\\w+\"><h1><font \\w+=#\\w+>", hasSuffix: "</font></h1></div>", innerRegex: "[\\s\\S]*")
/// 标题名称
static let singleTitle = ParserTagRule(tag: "font", isTagPaser: true, attrubutes: [], inTagRegexString: " \\w+=\"#\\w+\"", hasSuffix: nil, innerRegex: "[^<]+")
/// 图片列表
static let mainMovieImage = ParserTagRule(tag: "img", isTagPaser: false, attrubutes: [ParserAttrubuteRule(key: "src")], inTagRegexString: "<img[^>]+\\w+=\"\\w+:[^>]+", hasSuffix: ">", innerRegex: "[^>]+")
/// 下载地址
static let movieDowloadLink = ParserTagRule(tag: "a", isTagPaser: true, attrubutes: [ParserAttrubuteRule(key: "thunderrestitle"), ParserAttrubuteRule(key: "src"), ParserAttrubuteRule(key: "aexuztdb"), ParserAttrubuteRule(key: "href")], inTagRegexString: " \\w+=\"\\w+:\\/\\/\\w+:\\w+@\\w+.\\w+.\\w+:\\w+\\/[^\"]+\"", hasSuffix: nil, innerRegex: "\\w+:\\/\\/\\w+:\\w+@\\w+.\\w+.\\w+:\\w+\\/[^<]+")
}
/// 列表页面正则规则选项
struct PageRuleOption {
/// 内容页面链接
static let link = ParserTagRule(tag: "a", isTagPaser: false, attrubutes: [ParserAttrubuteRule(key: "href")], inTagRegexString: "<a \\w+=\"[^\"]+\" \\w+=\"\\w+\\(\\w+\\)\" \\w+=\"s xst\">", hasSuffix: "</a>", innerRegex: "[^<]+")
static let content = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "<tbody id=\"separatorline\">", hasSuffix: "下一页", innerRegex: "[\\s\\S]*")
/// ---- 电影天堂 ---
static let mLink = ParserTagRule(tag: "a", isTagPaser: true, attrubutes: [ParserAttrubuteRule(key: "href")], inTagRegexString: " href=\"[\\/\\w]+\\.\\w+\" class=\"ulink\"", hasSuffix: nil, innerRegex: nil)
static let mContent = ParserTagRule(tag: "", isTagPaser: false, attrubutes: [], inTagRegexString: "<div class=\"co_area2\">", hasSuffix: nil, innerRegex: "[\\s\\S]*")
}
/// 自动抓取机器人
class FetchBot {
private lazy var session : URLSession = {
let config = URLSessionConfiguration.default
let queue = OperationQueue.current
let downloadSession = URLSession(configuration: config, delegate: nil, delegateQueue: queue)
return downloadSession
}()
private static let _bot = FetchBot()
static var shareBot : FetchBot {
get {
return _bot
}
}
var delegate : FetchBotDelegate?
var contentDatas = [ContentInfo]()
var runTasks = [FetchURL]()
var badTasks = [FetchURL]()
var startPage: UInt = 1
var pageOffset: UInt = 0
var count : Int = 0
var startTime : Date?
var sem : DispatchSemaphore?
private var isRunning = false
/// 初始化方法
///
/// - Parameters:
/// - start: 开始页面,大于1
/// - offset: 结束页面 = start + offset
init(start: UInt = 1, offset: UInt = 0) {
self.startPage = start > 0 ? start:1
self.pageOffset = offset
}
func start(withSite site: Site) {
startTime = Date()
runTasks.removeAll()
badTasks.removeAll()
count = 0
contentDatas.removeAll()
DispatchQueue.main.async { [unowned self] in
self.delegate?.bot(didStartBot: self)
}
fetchGroup(start: startPage, offset: pageOffset, site: site)
}
func stop(compliention: AsyncFinish) {
if isRunning {
sem = DispatchSemaphore(value: 0)
sem?.wait()
compliention()
sem = nil
} else {
compliention()
}
}
private func fetchGroup(start: UInt, offset: UInt, site : Site) {
isRunning = true
let maker : (FetchURL) -> String = { (s) -> String in
site.page(bySuffix: s.page).absoluteString
}
struct PageItem {
var request : URLRequest
var url : FetchURL
var links : [ParserResult]
}
struct LinkItem {
var link : String
var title : String
}
let startIndex = Int(start)
let radio = 5
let splitGroupCount = Int(offset) / radio + 1
var pages = [PageItem]()
for x in 0..<splitGroupCount {
if let _ = self.sem {
print("************ Recive Stop Signal ************")
break
}
let listGroup = DispatchGroup()
for y in 0..<radio {
if let _ = self.sem {
print("************ Recive Stop Signal ************")
break
}
let index = x * radio + y + startIndex
if index >= Int(offset) + startIndex {
break
}
let fetchURL = FetchURL(site: site.host.rawValue, page: Int(index), maker: maker)
let request = browserRequest(url: fetchURL.url, refer: site.host.rawValue)
listGroup.enter()
print(">>> enter \(index)")
let task = session.dataTask(with: request, completionHandler: { [unowned self] (data, response, err) in
defer {
listGroup.leave()
}
if let _ = self.sem {
print("************ Recive Stop Signal ************")
return
}
guard let html = data?.asiicCombineUTF8StringDecode() else {
if let e = err {
print(e)
}
print("---------- bad decoder, \(response?.description ?? "") ----------")
self.badTasks.append(fetchURL)
return
}
if let _ = html.range(of: "<html>\r\n<head>\r\n<META NAME=\"robots\" CONTENT=\"noindex,nofollow\">") {
print("---------- robot detected! ----------")
self.badTasks.append(fetchURL)
return
}
let rule = site.listRule
self.runTasks.append(fetchURL)
print("---------- 开始解析 \(index) 页面 ----------")
guard let links = parse(string:html, rule: rule) else {
return
}
print("++++++ 解析到 \(links.count) 个内容链接")
pages.append(PageItem(request: request, url: fetchURL, links: links))
})
task.resume()
}
listGroup.wait()
}
var currentCount = 0
for page in pages {
if let _ = self.sem {
print("************ Recive Stop Signal ************")
break
}
let pageSplitCount = page.links.count / radio + 1
for x in 0..<pageSplitCount {
if let _ = self.sem {
print("************ Recive Stop Signal ************")
break
}
var centenGroup = DispatchGroup()
for y in 0..<radio {
if let _ = self.sem {
print("************ Recive Stop Signal ************")
break
}
let index = x * radio + y
if index >= Int(page.links.count) {
break
}
guard let href = page.links[index].attributes["href"] else {
continue
}
self.count += 1
let linkMaker : (FetchURL) -> String = { (s) -> String in
URL(string: "https://\(s.site)")!.appendingPathComponent(href).absoluteString
}
let linkURL = FetchURL(site: site.host.rawValue, page: page.url.page, maker: linkMaker)
let request = browserRequest(url: linkURL.url, refer: site.host.rawValue)
centenGroup.enter()
print("<<< enter \(index)")
let subTask = session.dataTask(with: request) { [unowned self] (data, response, err) in
defer {
centenGroup.leave()
}
if let _ = self.sem {
print("************ Recive Stop Signal ************")
return
}
guard let html = data?.asiicCombineUTF8StringDecode() else {
if let e = err {
print(e)
}
self.badTasks.append(linkURL)
return
}
if let _ = html.range(of: "<html>\r\n<head>\r\n<META NAME=\"robots\" CONTENT=\"noindex,nofollow\">") {
print("---------- robot detected! ----------")
self.badTasks.append(linkURL)
return
}
print("++++ \(page.url.page)页\(index)项 parser: \(href)")
if let xinfo = site.parserMaker?(html), !xinfo.title.isEmpty {
var info = xinfo
info.page = linkURL.url.absoluteString
self.contentDatas.append(info)
self.delegate?.bot(self, didLoardContent: info, atIndexPath: index)
}
self.runTasks.append(linkURL)
}
subTask.resume()
}
centenGroup.wait()
}
}
self.delegate?.bot(self, didFinishedContents: self.contentDatas, failedLink: self.badTasks)
isRunning = false
if let s = sem {
s.signal()
}
}
}
protocol FetchBotDelegate {
func bot(_ bot: FetchBot, didLoardContent content: ContentInfo, atIndexPath index: Int)
func bot(didStartBot bot: FetchBot)
func bot(_ bot: FetchBot, didFinishedContents contents: [ContentInfo], failedLink : [FetchURL])
}
/// 模仿浏览器URL请求
///
/// - Parameter url: URL对象
/// - Returns: URLRequest请求对象
func browserRequest(url : URL, refer: String) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("zh-CN,zh;q=0.8,en;q=0.6", forHTTPHeaderField: "Accept-Language")
request.addValue("Refer", forHTTPHeaderField: refer)
request.addValue("1", forHTTPHeaderField: "Upgrade-Insecure-Requests")
request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control")
request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
request.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", forHTTPHeaderField: "Accept")
return request
}
extension Data {
func asiicCombineUTF8StringDecode() -> String {
var html = ""
var index = 0
if self.count <= 0 {
return html
}
self.withUnsafeBytes { pointer in
repeat {
let value = pointer.load(fromByteOffset: index, as: UInt8.self)
if value < 192 {
index += 1
html += String(format: "%c", value)
} else {
if value >= 252 {
let offset = 6
html += String.init(bytes: pointer[index..<(index + offset)], encoding: .utf8) ?? ""
index += offset
} else if value >= 248 && value < 252 {
let offset = 5
html += String.init(bytes: pointer[index..<(index + offset)], encoding: .utf8) ?? ""
index += offset
} else if value >= 240 && value < 248 {
let offset = 4
html += String.init(bytes: pointer[index..<(index + offset)], encoding: .utf8) ?? ""
index += offset
} else if value >= 224 && value < 240 {
let offset = 3
html += String.init(bytes: pointer[index..<(index + offset)], encoding: .utf8) ?? ""
index += offset
} else if value >= 192 && value < 224 {
let offset = 2
html += String.init(bytes: pointer[index..<(index + offset)], encoding: .utf8) ?? ""
index += offset
} else {
index += 1
}
}
} while (index < self.count)
}
return html
}
}
| apache-2.0 | af7e9395569d2d32722dc0bcdf3f4877 | 44.871901 | 400 | 0.486863 | 4.910498 | false | false | false | false |
velvetroom/columbus | Source/View/Home/VHomeStandbyCell+Factory.swift | 1 | 3163 | import UIKit
extension VHomeStandbyCell
{
//MARK: private
private func factoryTitle(model:MHomeInfoProtocol) -> NSAttributedString
{
let string:NSAttributedString = NSAttributedString(
string:model.title,
attributes:attributesTitle)
return string
}
private func factoryDescr(model:MHomeInfoProtocol) -> NSAttributedString
{
let string:NSAttributedString = NSAttributedString(
string:model.descr,
attributes:attributesDescr)
return string
}
//MARK: internal
class func factoryAttributesTitle(fontSize:CGFloat) -> [NSAttributedStringKey:Any]
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.medium(size:fontSize),
NSAttributedStringKey.foregroundColor : UIColor.colourBackgroundDark]
return attributes
}
class func factoryAttributesDescr(fontSize:CGFloat) -> [NSAttributedStringKey:Any]
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.regular(size:fontSize),
NSAttributedStringKey.foregroundColor : UIColor(white:0.5, alpha:1)]
return attributes
}
func factoryViews()
{
let icon:UIImageView = UIImageView()
icon.isUserInteractionEnabled = false
icon.translatesAutoresizingMaskIntoConstraints = false
icon.clipsToBounds = true
icon.contentMode = UIViewContentMode.center
self.icon = icon
let labelInfo:UILabel = UILabel()
labelInfo.isUserInteractionEnabled = false
labelInfo.translatesAutoresizingMaskIntoConstraints = false
labelInfo.backgroundColor = UIColor.clear
labelInfo.numberOfLines = 0
self.labelInfo = labelInfo
addSubview(icon)
addSubview(labelInfo)
NSLayoutConstraint.topToTop(
view:icon,
toView:self)
NSLayoutConstraint.leftToLeft(
view:icon,
toView:self)
NSLayoutConstraint.size(
view:icon,
constant:VHomeStandbyCell.Constants.iconSize)
NSLayoutConstraint.topToTop(
view:labelInfo,
toView:self,
constant:VHomeStandbyCell.Constants.infoTop)
layoutInfoHeight = NSLayoutConstraint.height(
view:labelInfo)
NSLayoutConstraint.leftToRight(
view:labelInfo,
toView:icon)
NSLayoutConstraint.rightToRight(
view:labelInfo,
toView:self,
constant:VHomeStandbyCell.Constants.infoRight)
}
func factoryInfo(model:MHomeInfoProtocol) -> NSAttributedString
{
let title:NSAttributedString = factoryTitle(model:model)
let descr:NSAttributedString = factoryDescr(model:model)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(title)
mutableString.append(descr)
return mutableString
}
}
| mit | d8d09a0b8fc193232dd2acbd07f0eba2 | 30.63 | 86 | 0.635789 | 6.03626 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Dialog/HBCIAnonymousDialog.swift | 1 | 3504 | //
// HBCIAnonymousDialog.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 31.01.15.
// Copyright (c) 2015 Frank Emminghaus. All rights reserved.
//
import Foundation
open class HBCIAnonymousDialog {
var connection:HBCIConnection?
var dialogId:String?;
let hbciVersion:String!
let product:String;
let version:String;
var syntax:HBCISyntax! // todo: replace with let once Xcode bug is fixed
var messageNum = 1;
public init(hbciVersion:String, product:String, version:String = "100") throws {
self.hbciVersion = hbciVersion;
self.product = product;
self.version = version;
let syntax = try HBCISyntax.syntaxWithVersion(hbciVersion)
self.syntax = syntax
}
@discardableResult func sendMessage(_ message:String, values:Dictionary<String,Any>) throws ->HBCIResultMessage? {
if let md = self.syntax.msgs[message] {
if let msg = md.compose() as? HBCIMessage {
for (path, value) in values {
if !msg.setElementValue(value, path: path) {
return nil;
}
}
if !msg.enumerateSegments() {
return nil;
}
if !msg.finalize() {
return nil;
}
if !msg.validate() {
return nil;
}
//println(msg.description);
let msgData = msg.messageData();
//println(msg.messageString());
// send message to bank
let result = try self.connection!.sendMessage(msgData);
logDebug("Message received:");
logDebug(String(data: result, encoding: String.Encoding.isoLatin1));
let resultMsg = HBCIResultMessage(syntax: self.syntax);
if !resultMsg.parse(result) {
return nil;
} else {
return resultMsg;
}
}
}
return nil;
}
open func dialogWithURL(_ url:URL, bankCode:String) throws ->HBCIResultMessage? {
self.connection = HBCIPinTanConnection(url: url);
let values:Dictionary<String,Any> = ["ProcPrep.BPD":"0", "ProcPrep.UPD":"0", "ProcPrep.lang":"1", "ProcPrep.prodName":product,
"ProcPrep.prodVersion":version, "Idn.KIK.country":"280", "Idn.KIK.blz":bankCode, "TAN.process":"4", "TAN.ordersegcode":"HKIDN" ];
if let resultMsg = try sendMessage("DialogInitAnon", values: values) {
// get dialog id
if let dialogId = resultMsg.valueForPath("MsgHead.dialogid") as? String {
self.dialogId = dialogId;
// only if we have the dialogid, we can close the dialog
let values = ["MsgHead.dialogid":dialogId, "DialogEnd.dialogid":dialogId,
"MsgHead.msgnum":"2", "MsgTail.msgnum":"2" ];
do {
// don't care if end dialog message fails or not
if resultMsg.isOk() {
_ = try sendMessage("DialogEndAnon", values: values as Dictionary<String, Any>);
}
} catch { };
}
return resultMsg;
}
return nil;
}
}
| gpl-2.0 | 673a033213631446185a07b0c6b9a06f | 35.884211 | 174 | 0.51484 | 4.741543 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01217-swift-typechecker-resolveidentifiertype.swift | 1 | 764 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
private class B<C> {
let enum S<T> : P {
func f<T>() -> T -> T {
return { x in x 1 {
b[c][c] = 1
}
}
class A {
class func a() -> String {
let d: String = {
return self.a()
}()
}
struct d<f : e, g: e where g.h == f.h> {
}
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
struct D : C {
func g<T where T.E == F>(f: B<T>) {
}
protocol A {
}
struct B<T : A> {
| apache-2.0 | 637254645dc8c592be4737d73bd7b46f | 20.828571 | 79 | 0.625654 | 2.748201 | false | false | false | false |
intonarumori/OnboardingController | OnboardingControllerExamples/OnboardingFlow/3-ModalExample/ModalExampleViewController.swift | 1 | 1708 | //
// ModalExampleViewController.swift
// OnboardingControllerExamples
//
// Created by Daniel Langh on 09/04/16.
// Copyright © 2016 rumori. All rights reserved.
//
import UIKit
class ModalExampleViewController: UIViewController, EmptyModalViewControllerDelegate {
@IBOutlet var bodyLabel: UILabel!
@IBOutlet var skipButton: UIButton!
@IBOutlet var modalButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// show the onboarding background by making our view transparent
view.backgroundColor = UIColor.clear
// style the buttons
skipButton.backgroundColor = .blue
skipButton.setTitleColor(.white, for: .normal)
skipButton.layer.cornerRadius = 30.0
modalButton.backgroundColor = .blue
modalButton.setTitleColor(.white, for: .normal)
modalButton.layer.cornerRadius = 30.0
}
// MARK: - user actions
@IBAction func next() {
onboardingController?.moveToNext(true)
}
// MARK: - modal viewcontroller presentation
@IBAction func showModal() {
let exampleModalViewController = EmptyModalViewController()
let navigationController = UINavigationController(rootViewController: exampleModalViewController)
exampleModalViewController.delegate = self
present(navigationController, animated: true, completion: nil)
}
// MARK: - EmptyModalViewController delegate
func emptyModalViewController(didFinish exampleModalViewController: EmptyModalViewController) {
self.dismiss(animated: true, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| mit | 5854aa9f89726f5109e31347f3732ce5 | 28.947368 | 105 | 0.710018 | 5.419048 | false | false | false | false |
zhubofei/IGListKit | Examples/Examples-iOS/IGListKitTodayExample/TodayViewController.swift | 4 | 2453 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import NotificationCenter
import UIKit
@available(iOSApplicationExtension 10.0, *)
final class TodayViewController: UIViewController, NCWidgetProviding, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
let data = "Maecenas faucibus mollis interdum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.".components(separatedBy: " ")
override func viewDidLoad() {
super.viewDidLoad()
adapter.collectionView = collectionView
adapter.dataSource = self
view.addSubview(collectionView)
// Enables the 'Show More' button in the widget interface
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
}
override func loadView() {
view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 110))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: NCWidgetProviding
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
preferredContentSize = maxSize
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return data as [ListDiffable]
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
return LabelSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
| mit | b711959fbb79feef123b17fb51f686df | 34.550725 | 177 | 0.731349 | 5.379386 | false | false | false | false |
qinting513/SwiftNote | HandyJSONDemo-JSON转模型工具!/HandyJSONDemo/ViewController.swift | 1 | 9026 | //
// ViewController.swift
// HandyJSONDemo
//
// Created by Qinting on 2016/11/14.
// Copyright © 2016年 QT. All rights reserved.
//
import UIKit
import HandyJSON
//原文:http://www.cocoachina.com/swift/20161010/17711.html
//课外阅读:[HandyJSON] 设计思路简析] http://www.cocoachina.com/swift/20161109/18010.html
class ViewController: UIViewController {
// 可先用swiftyJSON 转化为JSON数据
override func viewDidLoad() {
super.viewDidLoad()
// self.testAnimal() // 简单的json
// self.testCat() // 稍复杂点的,各类型都有的
// self.testQiantao() //测试嵌套
// self.testNote() // 指定某个节点的
// self.testInherit() // 有继承关系的
// self.testCustomParse() // 网络返回json跟自己定义的key 需进行匹配的
self.parseMainJson() //解析根节点是数组的,并且有嵌套的
// modelToJOSN() //model 转 json
}
}
extension ViewController {
func testAnimal() {
let jsonString = "{\"name\":\"cat\",\"id\":\"12345\", \"num\":180}"
/// 要指定类型: Animal,要不然报错 Generic parameter 'T'could not be inferred
if let animal : Animal = JSONDeserializer.deserializeFrom(json: jsonString) {
print(animal.name) //注意打印出来的是可选类型 Optional("cat")
print(animal.id)
print(animal.num)
}
}
}
extension ViewController {
func testCat() {
let jsonString = "{\"id\":1234567,\"name\":\"Kitty\",\"friend\":[\"Tom\",\"Jack\",\"Lily\",\"Black\"],\"weight\":15.34,\"alive\":false,\"color\":\"white\"}"
/// 要指定类型: Animal,要不然报错 Generic parameter 'T'could not be inferred
if let cat :Cat = JSONDeserializer.deserializeFrom(json: jsonString) {
print(cat.name)
print(cat.friend)
print(cat.weight)
print(cat.alive)
}
}
}
extension ViewController {
/// 测试嵌套
func testQiantao(){
let jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"
if let composition : Composition = JSONDeserializer.deserializeFrom(json: jsonString) {
print(composition.num)
print(composition.comp1)
}
}
}
extension ViewController {
/// 指定反序列化到某个节点
/* 有时候服务端返回给我们的JSON文本包含了大量的状态信息,和Model无关,比如statusCode,debugMessage等,或者有用的数据是在某个节点以下,那么我们可以指定反序列化哪个节点 */
func testNote(){
// 服务端返回了这个JSON,我们想解析的只有data里的cat
let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"
if let cat : Cat = JSONDeserializer.deserializeFrom(json: jsonString, designatedPath: "data.cat") {
print(cat.name)
print(cat.id)
}
}
}
extension ViewController {
//解析有继承关系的,这个用到的也很多
func testInherit() {
let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"Animal\",\"dogName\":\"dog\",\"xxxooo\":\"fuck\"}"
if let dog : Dog = JSONDeserializer.deserializeFrom(json: jsonString) {
print(dog.name)
print(dog.dogName)
print(dog.xxx) // 随便来个属性,没值也不会报错 nil
}
}
}
extension ViewController {
/* 自定义解析方式
HandyJSON还提供了一个扩展能力,就是允许自行定义Model类某个字段的解析Key、解析方式。我们经常会有这样的需求:
某个Model中,我们不想使用和服务端约定的key作为属性名,想自己定一个;
有些类型如enum、tuple是无法直接从JSON中解析出来的,但我们在Model类中有这样的属性;
HandyJSON协议提供了一个可选的mapping()函数,我们可以在其中指定某个字段用什么Key、或者用什么方法从JSON中解析出它的值。如我们有一个Model类和一个服务端返回的JSON串:
*/
func testCustomParse() {
let jsonString = "{\"mouse_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\"}"
if let mouse : Mouse = JSONDeserializer.deserializeFrom(json: jsonString) {
print(mouse.name)
print(mouse.parent)
}
}
}
/* ============================模型类================================ */
class Animal: HandyJSON {
var name: String?
var id: String?
var num: Int?
required init() {} // 如果定义是struct,连init()函数都不用声明;
}
struct Cat: HandyJSON {
var id: Int64!
var name: String!
var friend: [String]?
var weight: Double?
var alive: Bool = true
var color: NSString?
}
class Dog : Animal {
var dogName : String?
var xxx : String?
required init() { }
}
struct Component: HandyJSON {
var aInt: Int?
var aString: String?
}
struct Composition: HandyJSON {
var num: Int?
var comp1: Component?
var comp2: Component?
}
class Mouse: HandyJSON {
var id: Int64!
var name: String!
var parent: (String, String)?
required init() {}
//需要重写mapper方法去比配
func mapping(mapper: HelpingMapper) {
// 指定 id 字段用 "mouse_id" 去解析
mapper.specify(property: &id, name: "mouse_id")
// 指定 parent 字段用这个方法去解析
mapper.specify(property: &parent) { (rawString) -> (String, String) in
// split{$0 == "/"} 分割, map(String.init) 转化为字符串
let parentNames = rawString.characters.split{$0 == "/"}.map(String.init)
return (parentNames[0], parentNames[1])
}
}
}
/* ======================== 模拟解析网络请求回来的数据 根节点是数组 ========================= */
/*模型类*/
class MainModel : HandyJSON {
let clsName : String? = ""
let title : String? = ""
let imageName : String = ""
let visitorInfo : VisitorInfo? = nil
required init() { }
}
class VisitorInfo : HandyJSON {
let imageName : String? = ""
let message : String? = ""
required init() { }
}
extension ViewController {
/// 解析数据 方法
func parseMainJson() {
// 获取沙盒json
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
var data = NSData(contentsOfFile: jsonPath)
if data == nil {
// 如果沙盒里的为空 则从bundle里获取
let path = Bundle.main.path(forResource: "main.json", ofType: nil)
data = NSData(contentsOfFile: path!)
}
//方法1: 直接将data数据转化为String
let strData = String(data: data as! Data, encoding: String.Encoding.utf8)
//方法2: 先通过SwiftyJSON将data类型序列化成JSON格式,再转成String类型,
// 感觉方法2比方法1多绕了1步,不是很好
let json = JSON(data:data as! Data).rawString()
print(json)
// 需要用 deserializeModelArrayFrom 解析根节点是数组的
if let mainModelArray : [MainModel?] = JSONDeserializer.deserializeModelArrayFrom(json: strData) {
for model in mainModelArray {
if let clsName = model?.clsName,
let title = model?.title, // 这样子 中间有个模块没其他数据 就没显示出来,可分条写
let message = model?.visitorInfo?.message {
print(clsName)
print(title)
print(message)
print("======================")
}
}
}
}
}
/* ============================ Model to JSON ================================ */
enum Gender: String {
case Male = "male"
case Female = "Female"
}
struct Subject {
var id: Int64?
var name: String?
init(id: Int64, name: String) {
self.id = id
self.name = name
}
}
class Student {
var name: String?
var gender: Gender?
var subjects: [Subject]?
}
extension ViewController{
func modelToJOSN(){
let student = Student()
student.name = "Jack"
student.gender = .Female
student.subjects = [Subject(id: 1, name: "math"), Subject(id: 2, name: "English"), Subject(id: 3, name: "Philosophy")]
//将Model序列化成json
print(JSONSerializer.serializeToJSON(object: student)!)
print(JSONSerializer.serializeToJSON(object: student, prettify: true)!)
}
}
| apache-2.0 | 7806d17776d9b702e0fc658fdc81cc62 | 27.309091 | 164 | 0.566217 | 3.79386 | false | false | false | false |
psharanda/vmc2 | 1. MassiveVC/MassiveVC/MainViewController.swift | 1 | 2480 | //
// Created by Pavel Sharanda on 17.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
private lazy var button = UIButton(type: .system)
private lazy var label = UILabel()
private lazy var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
title = "Massive VC"
view.backgroundColor = .white
view.addSubview(activityIndicator)
button.setTitle("Load", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
view.addSubview(button)
label.numberOfLines = 0
view.addSubview(label)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Details", style: .plain, target: self, action: #selector(doneClicked))
navigationItem.rightBarButtonItem?.isEnabled = false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
activityIndicator.frame = view.bounds
label.frame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 80, left: 20, bottom: 80, right: 20))
button.frame = CGRect(x: 20, y: view.bounds.height - 60, width: view.bounds.width - 40, height: 40)
}
@objc private func doneClicked() {
navigationController?.pushViewController(DetailsViewController(text: label.text), animated: true)
}
@objc private func buttonClicked() {
activityIndicator.startAnimating()
label.text = nil
navigationItem.rightBarButtonItem?.isEnabled = false
loadText {
self.activityIndicator.stopAnimating()
self.label.text = $0
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
}
private func loadText(completion: @escaping (String)->Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
completion("Cras mattis consectetur purus sit amet fermentum. Donec ullamcorper nulla non metus auctor fringilla. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Aenean lacinia bibendum nulla sed consectetur. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.")
}
}
}
| mit | f6f07c110b63be7bde2dc01ed4ebe729 | 37.138462 | 401 | 0.668818 | 5.143154 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.