repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
MoZhouqi/KMPlaceholderTextView | Package.swift | 1 | 427 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "KMPlaceholderTextView",
products: [
.library(
name: "KMPlaceholderTextView",
targets: ["KMPlaceholderTextView"]),
],
targets: [
.target(
name: "KMPlaceholderTextView"),
]
)
| mit |
jyunderwood/Talkboy-iOS | Talkboy/RecordedAudio.swift | 1 | 237 | //
// RecordedAudio.swift
// Talkboy
//
// Created by Jonathan on 3/21/15.
// Copyright (c) 2015 Jonathan Underwood. All rights reserved.
//
import Foundation
struct RecordedAudio {
let filePathUrl: URL
let title: String
}
| mit |
pixelspark/catena | Sources/CatenaCore/Gossip.swift | 1 | 26070 | import Foundation
import Kitura
import LoggerAPI
import KituraWebSocket
import Dispatch
#if !os(Linux)
import Starscream
#endif
public enum GossipError: LocalizedError {
case missingActionKey
case unknownAction(String)
case deserializationFailed
case limitExceeded
public var localizedDescription: String {
switch self {
case .missingActionKey: return "action key is missing"
case .unknownAction(let a): return "unknown action '\(a)'"
case .deserializationFailed: return "deserialization of payload failed"
case .limitExceeded: return "a limit was exceeded"
}
}
}
public enum Gossip<LedgerType: Ledger> {
public typealias BlockchainType = LedgerType.BlockchainType
public typealias BlockType = BlockchainType.BlockType
/** Request the peer's index. The reply is either of type 'index' or 'passive'. */
case query // -> index or passive
/** Reply message that contains the peer's index. */
case index(Index<BlockType>)
/** Unsolicited new blocks. */
case block([String: Any]) // no reply
/** Response to a fetch request. `extra` contains a few predecessor blocks to improve fetch speeds (may be empty). */
case result(block: [String: Any], extra: [BlockType.HashType: [String: Any]])
/** Request a specific block from the peer. The reply is of type 'result'. The 'extra' parameter
specifies how many predecessor blocks may be included in the result (as 'extra' blocks). */
case fetch(hash: BlockType.HashType, extra: Int) // -> block
/** An error has occurred. Only sent in reply to a request by the peer. */
case error(String)
/** A transaction the peer wants us to store/relay. */
case transaction([String: Any])
/** The peer indicates that it is a passive peer without an index (in response to a query request) */
case passive
/** The peer requests to be forgotten, most probably because its UUID does not match the requested UUID. */
case forget
init(json: [String: Any]) throws {
if let q = json[LedgerType.ParametersType.actionKey] as? String {
if q == "query" {
self = .query
}
else if q == "block" {
if let blockData = json["block"] as? [String: Any] {
self = .block(blockData)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "result" {
if let blockData = json["block"] as? [String: Any] {
var extraBlocks: [BlockType.HashType: [String: Any]] = [:]
if let extra = json["extra"] as? [String: [String: Any]] {
if extra.count > LedgerType.ParametersType.maximumExtraBlocks {
throw GossipError.limitExceeded
}
for (hash, extraBlockData) in extra {
extraBlocks[try BlockType.HashType(hash: hash)] = extraBlockData
}
}
self = .result(block: blockData, extra: extraBlocks)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "fetch" {
if let hash = json["hash"] as? String {
let extra = (json["extra"] as? Int) ?? 0
self = .fetch(hash: try BlockType.HashType(hash: hash), extra: extra)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "index" {
if let idx = json["index"] as? [String: Any] {
self = .index(try Index<BlockType>(json: idx))
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "error" {
if let message = json["message"] as? String {
self = .error(message)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "tx" {
if let tx = json["tx"] as? [String: Any] {
self = .transaction(tx)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "passive" {
self = .passive
}
else if q == "forget" {
self = .forget
}
else {
throw GossipError.unknownAction(q)
}
}
else {
throw GossipError.missingActionKey
}
}
var json: [String: Any] {
switch self {
case .query:
return [LedgerType.ParametersType.actionKey: "query"]
case .result(block: let b, extra: let extra):
var extraData: [String: [String: Any]] = [:]
for (hash, extraBlock) in extra {
extraData[hash.stringValue] = extraBlock
}
return [LedgerType.ParametersType.actionKey: "result", "block": b, "extra": extraData]
case .block(let b):
return [LedgerType.ParametersType.actionKey: "block", "block": b]
case .index(let i):
return [LedgerType.ParametersType.actionKey: "index", "index": i.json]
case .fetch(hash: let h, extra: let e):
return [LedgerType.ParametersType.actionKey: "fetch", "hash": h.stringValue, "extra": e]
case .transaction(let tx):
return [LedgerType.ParametersType.actionKey: "tx", "tx": tx]
case .error(let m):
return [LedgerType.ParametersType.actionKey: "error", "message": m]
case .passive:
return [LedgerType.ParametersType.actionKey: "passive"]
case .forget:
return [LedgerType.ParametersType.actionKey: "forget"]
}
}
}
public class Server<LedgerType: Ledger>: WebSocketService {
public typealias BlockchainType = LedgerType.BlockchainType
public typealias BlockType = BlockchainType.BlockType
public let router = Router()
public let port: Int
private let mutex = Mutex()
private var gossipConnections = [String: PeerIncomingConnection<LedgerType>]()
weak var node: Node<LedgerType>?
init(node: Node<LedgerType>, port: Int) {
self.node = node
self.port = port
WebSocket.register(service: self, onPath: "/")
Kitura.addHTTPServer(onPort: port, with: router)
}
public func connected(connection: WebSocketConnection) {
Log.debug("[Server] gossip connected incoming \(connection.request.remoteAddress) \(connection.request.urlURL.absoluteString)")
self.mutex.locked {
do {
let pic = try PeerIncomingConnection<LedgerType>(connection: connection)
self.node?.add(peer: pic)
self.gossipConnections[connection.id] = pic
}
catch {
Log.error("[Server] \(error.localizedDescription)")
}
}
}
public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) {
Log.info("[Server] disconnected gossip \(connection.id); reason=\(reason)")
self.mutex.locked {
if let pic = self.gossipConnections[connection.id] {
pic.disconnected()
self.gossipConnections.removeValue(forKey: connection.id)
}
}
}
public func received(message: Data, from: WebSocketConnection) {
do {
if let d = try JSONSerialization.jsonObject(with: message, options: []) as? [Any] {
try self.handleGossip(data: d, from: from)
}
else {
Log.error("[Gossip] Invalid format")
}
}
catch {
Log.error("[Gossip] Invalid: \(error.localizedDescription)")
}
}
public func received(message: String, from: WebSocketConnection) {
do {
if let d = try JSONSerialization.jsonObject(with: message.data(using: .utf8)!, options: []) as? [Any] {
try self.handleGossip(data: d, from: from)
}
else {
Log.error("[Gossip] Invalid format")
}
}
catch {
Log.error("[Gossip] Invalid: \(error.localizedDescription)")
}
}
func handleGossip(data: [Any], from: WebSocketConnection) throws {
Log.debug("[Gossip] received \(data)")
self.mutex.locked {
if let pic = self.gossipConnections[from.id] {
DispatchQueue.global().async {
pic.receive(data: data)
}
}
else {
Log.error("[Server] received gossip data for non-connection: \(from.id)")
}
}
}
}
public struct Index<BlockType: Block>: Equatable {
let genesis: BlockType.HashType
let peers: [URL]
let highest: BlockType.HashType
let height: BlockType.IndexType
let timestamp: BlockType.TimestampType
init(genesis: BlockType.HashType, peers: [URL], highest: BlockType.HashType, height: BlockType.IndexType, timestamp: BlockType.TimestampType) {
self.genesis = genesis
self.peers = peers
self.highest = highest
self.height = height
self.timestamp = timestamp
}
init(json: [String: Any]) throws {
if let genesisHash = json["genesis"] as? String,
let highestHash = json["highest"] as? String,
let peers = json["peers"] as? [String] {
let genesis = try BlockType.HashType(hash: genesisHash)
let highest = try BlockType.HashType(hash: highestHash)
self.genesis = genesis
self.highest = highest
self.peers = peers.compactMap { return URL(string: $0) }
if let height = json["height"] as? NSNumber, let timestamp = json["time"] as? NSNumber {
// Darwin
self.height = BlockType.IndexType(height.uint64Value)
self.timestamp = BlockType.TimestampType(timestamp.uint64Value)
}
else if let height = json["height"] as? Int, let timestamp = json["time"] as? Int {
// Linux
self.height = BlockType.IndexType(height)
self.timestamp = BlockType.TimestampType(timestamp)
}
else {
throw GossipError.deserializationFailed
}
}
else {
throw GossipError.deserializationFailed
}
}
public static func ==(lhs: Index<BlockType>, rhs: Index<BlockType>) -> Bool {
return lhs.genesis == rhs.genesis &&
lhs.peers == rhs.peers &&
lhs.highest == rhs.highest &&
lhs.height == rhs.height &&
lhs.timestamp == rhs.timestamp
}
var json: [String: Any] {
return [
"highest": self.highest.stringValue,
"height": NSNumber(value: self.height),
"genesis": self.genesis.stringValue,
"time": NSNumber(value: self.timestamp),
"peers": self.peers.map { $0.absoluteString }
]
}
}
public protocol PeerConnectionDelegate {
associatedtype LedgerType: Ledger
func peer(connection: PeerConnection<LedgerType>, requests gossip: Gossip<LedgerType>, counter: Int)
func peer(connected _: PeerConnection<LedgerType>)
func peer(disconnected _: PeerConnection<LedgerType>)
}
public class PeerConnection<LedgerType: Ledger> {
public typealias GossipType = Gossip<LedgerType>
public typealias Callback = (Gossip<LedgerType>) -> ()
public let mutex = Mutex()
private var counter = 0
private var callbacks: [Int: Callback] = [:]
public weak var delegate: Peer<LedgerType>? = nil
fileprivate init(isIncoming: Bool) {
self.counter = isIncoming ? 1 : 0
}
public func receive(data: [Any]) {
if data.count == 2, let counter = data[0] as? Int, let gossipData = data[1] as? [String: Any] {
do {
let g = try GossipType(json: gossipData)
self.mutex.locked {
if counter != 0, let cb = callbacks[counter] {
self.callbacks.removeValue(forKey: counter)
DispatchQueue.global().async {
cb(g)
}
}
else {
// Unsolicited
Log.debug("[Gossip] Get \(counter): \(g)")
if let d = self.delegate {
DispatchQueue.global().async {
d.peer(connection: self, requests: g, counter: counter)
}
}
else {
Log.error("[Server] cannot handle gossip \(counter) for \(self): no delegate. Message is \(g.json)")
}
}
}
}
catch {
Log.warning("[Gossip] Received invalid gossip \(error.localizedDescription): \(gossipData)")
}
}
else {
Log.warning("[Gossip] Received malformed gossip: \(data)")
}
}
public final func reply(counter: Int, gossip: GossipType) throws {
try self.mutex.locked {
let d = try JSONSerialization.data(withJSONObject: [counter, gossip.json], options: [])
try self.send(data: d)
}
}
public final func request(gossip: GossipType, callback: Callback? = nil) throws {
let c = self.mutex.locked { () -> Int in
counter += 2
if let c = callback {
self.callbacks[counter] = c
}
return counter
}
try self.mutex.locked {
Log.debug("[PeerConnection] send request \(c)")
let d = try JSONSerialization.data(withJSONObject: [c, gossip.json], options: [])
try self.send(data: d)
}
}
public func send(data: Data) throws {
fatalError("Should be subclassed")
}
}
enum PeerConnectionError: LocalizedError {
case protocolVersionMissing
case protocolVersionUnsupported(version: String)
case notConnected
var errorDescription: String? {
switch self {
case .protocolVersionMissing: return "the client did not indicate a protocol version"
case .protocolVersionUnsupported(version: let v): return "protocol version '\(v)' is not supported"
case .notConnected: return "the peer is not connected"
}
}
}
public class PeerIncomingConnection<LedgerType: Ledger>: PeerConnection<LedgerType>, CustomDebugStringConvertible {
let connection: WebSocketConnection
init(connection: WebSocketConnection) throws {
guard let protocolVersion = connection.request.headers["Sec-WebSocket-Protocol"]?.first else { throw PeerConnectionError.protocolVersionMissing }
if protocolVersion != LedgerType.ParametersType.protocolVersion {
throw PeerConnectionError.protocolVersionUnsupported(version: protocolVersion)
}
self.connection = connection
super.init(isIncoming: true)
}
deinit {
self.connection.close()
}
/** Called by the Server class when the WebSocket connection is disconnected. */
fileprivate func disconnected() {
self.delegate?.peer(disconnected: self)
}
func close() {
self.connection.close()
}
public override func send(data: Data) throws {
self.connection.send(message: data, asBinary: false)
}
public var debugDescription: String {
return "PeerIncomingConnection(\(self.connection.request.remoteAddress) -> \(self.connection.request.urlURL.absoluteString)";
}
}
#if !os(Linux)
public class PeerOutgoingConnection<LedgerType: Ledger>: PeerConnection<LedgerType>, WebSocketDelegate {
let connection: Starscream.WebSocket
public init?(to url: URL, from uuid: UUID? = nil, at port: Int? = nil) {
assert((uuid != nil && port != nil) || (uuid == nil && port == nil), "either set both a port and uuid or set neither (passive mode)")
if var uc = URLComponents(url: url, resolvingAgainstBaseURL: false) {
// Set source peer port and UUID
if let uuid = uuid, let port = port {
if port <= 0 {
return nil
}
uc.queryItems = [
URLQueryItem(name: LedgerType.ParametersType.uuidRequestKey, value: uuid.uuidString),
URLQueryItem(name: LedgerType.ParametersType.portRequestKey, value: String(port))
]
}
self.connection = Starscream.WebSocket(url: uc.url!, protocols: [LedgerType.ParametersType.protocolVersion])
super.init(isIncoming: false)
}
else {
return nil
}
}
init(connection: Starscream.WebSocket) {
self.connection = connection
super.init(isIncoming: false)
}
public func connect() {
self.connection.delegate = self
self.connection.callbackQueue = DispatchQueue.global(qos: .background)
if !self.connection.isConnected {
self.connection.connect()
}
}
public override func send(data: Data) throws {
if self.connection.isConnected {
self.connection.write(data: data)
}
else {
throw PeerConnectionError.notConnected
}
}
public func websocketDidConnect(socket: Starscream.WebSocketClient) {
self.delegate?.peer(connected: self)
}
public func websocketDidReceiveData(socket: Starscream.WebSocketClient, data: Data) {
do {
if let obj = try JSONSerialization.jsonObject(with: data, options: []) as? [Any] {
self.receive(data: obj)
}
else {
Log.error("[Gossip] Outgoing socket received malformed data")
}
}
catch {
Log.error("[Gossip] Outgoing socket received malformed data: \(error)")
}
}
public func websocketDidDisconnect(socket: Starscream.WebSocketClient, error: Error?) {
self.delegate?.peer(disconnected: self)
self.delegate = nil
connection.delegate = nil
}
public func websocketDidReceiveMessage(socket: Starscream.WebSocketClient, text: String) {
self.websocketDidReceiveData(socket: socket, data: text.data(using: .utf8)!)
}
}
#endif
public class Peer<LedgerType: Ledger>: PeerConnectionDelegate, CustomDebugStringConvertible {
typealias BlockchainType = LedgerType.BlockchainType
typealias BlockType = BlockchainType.BlockType
typealias TransactionType = BlockType.TransactionType
public let url: URL
/** Time at which we last received a response or request from this peer. Nil when that never happened. */
public internal(set) var lastSeen: Date? = nil
/** The time difference observed during the last index request */
public internal(set) var lastIndexRequestLatency: TimeInterval? = nil
public internal(set) var timeDifference: TimeInterval? = nil
public internal(set) var state: PeerState
fileprivate(set) var connection: PeerConnection<LedgerType>? = nil
weak var node: Node<LedgerType>?
public let mutex = Mutex()
private struct Request: CustomStringConvertible {
let connection: PeerConnection<LedgerType>
let gossip: Gossip<LedgerType>
let counter: Int
var description: String {
return "#\(self.counter):\(gossip)"
}
}
public var debugDescription: String {
return "<\(self.url.absoluteString)>"
}
private lazy var queue = ThrottlingQueue<Request>(interval: LedgerType.ParametersType.maximumPeerRequestRate, maxQueuedRequests: LedgerType.ParametersType.maximumPeerRequestQueueSize) { [weak self] (request: Request) throws -> () in
try self?.process(request: request)
}
init(url: URL, state: PeerState, connection: PeerConnection<LedgerType>?, delegate: Node<LedgerType>) {
assert(Peer<LedgerType>.isValidPeerURL(url: url), "Peer URL must be valid")
self.url = url
self.state = state
self.connection = connection
self.node = delegate
connection?.delegate = self
}
public var uuid: UUID {
return UUID(uuidString: self.url.user!)!
}
static public func isValidPeerURL(url: URL) -> Bool {
if let uc = URLComponents(url: url, resolvingAgainstBaseURL: false) {
// URL must contain a port, host and user part
if uc.port == nil || uc.host == nil || uc.user == nil {
return false
}
// The user in the URL must be a valid node identifier (UUID)
if UUID(uuidString: uc.user!) == nil {
return false
}
return true
}
return false
}
/** Returns true when a peer action was performed, false when no action was required. */
public func advance() -> Bool {
return self.mutex.locked { () -> Bool in
Log.debug("Advance peer \(url) from state \(self.state)")
do {
if let n = node {
// If the connection has been disconnected since the last time we checked, reset state
if self.connection == nil {
switch self.state {
case .connected, .connecting(since: _), .queried, .querying(since: _), .passive:
self.state = .new(since: Date())
case .new(since: _), .failed(error: _, at: _), .ignored(reason: _):
break
}
}
switch self.state {
case .failed(error: _, at: let date):
// Failed peers become 'new' after a certain amount of time, so we can retry
if Date().timeIntervalSince(date) > LedgerType.ParametersType.peerRetryAfterFailureInterval {
self.connection = nil
self.state = .new(since: date)
}
return false
case .new:
// Perhaps reconnect to this peer
#if !os(Linux)
if url.port == nil || url.port! == 0 {
self.state = .ignored(reason: "disconnected, and peer does not accept incoming connections")
}
else if let pic = PeerOutgoingConnection<LedgerType>(to: url, from: n.uuid, at: n.server.port) {
pic.delegate = self
self.state = .connecting(since: Date())
self.connection = pic
Log.debug("[Peer] connect outgoing \(url)")
pic.connect()
}
#else
// Outgoing connections are not supported on Linux (yet!)
self.state = .ignored(reason: "disconnected, and cannot make outgoing connections")
#endif
return true
case .connected, .queried:
try self.query()
return true
case .passive, .ignored(reason: _):
// Do nothing (perhaps ping in the future?)
return false
case .connecting(since: let date), .querying(since: let date):
// Reset hung peers
if Date().timeIntervalSince(date) > LedgerType.ParametersType.peerRetryAfterFailureInterval {
self.connection = nil
self.state = .new(since: date)
}
return true
}
}
else {
return false
}
}
catch {
self.fail(error: "advance error: \(error.localizedDescription)")
return false
}
}
}
public func fail(error: String) {
self.mutex.locked {
Log.info("[Peer] \(self.url.absoluteString) failing: \(error)")
self.connection = nil
self.state = .failed(error: error, at: Date())
}
}
private func query() throws {
if let n = self.node, let c = self.connection {
self.mutex.locked {
self.state = .querying(since: Date())
}
let requestTime = Date()
try c.request(gossip: .query) { reply in
// Update last seen
self.mutex.locked {
self.lastSeen = Date()
// Update observed time difference
let requestEndTime = Date()
self.lastIndexRequestLatency = requestEndTime.timeIntervalSince(requestTime) / 2.0
}
if case .index(let index) = reply {
Log.debug("[Peer] Receive index reply: \(index)")
self.mutex.locked {
// Update peer status
if index.genesis != n.ledger.longest.genesis.signature! {
// Peer believes in another genesis, ignore him
self.connection = nil
self.state = .ignored(reason: "believes in other genesis")
}
else {
self.state = .queried
}
// Calculate time difference
// TODO: perhaps add (requestEndTime - requestTime) to make this more precise
let peerTime = Date(timeIntervalSince1970: TimeInterval(index.timestamp))
self.timeDifference = peerTime.timeIntervalSinceNow
}
// New peers?
for p in index.peers {
n.add(peer: p)
}
// Request the best block from this peer
n.receive(best: Candidate(hash: index.highest, height: index.height, peer: self.uuid))
}
else if case .passive = reply {
self.mutex.locked {
self.state = .passive
}
}
else {
self.fail(error: "Invalid reply received to query request")
}
}
}
}
private func process(request: Request) throws {
Log.debug("[Peer] process request \(request.counter) for peer \(self)")
switch request.gossip {
case .forget:
try self.node?.forget(peer: self)
self.state = .ignored(reason: "peer requested to be forgotten")
case .transaction(let trData):
let tr = try TransactionType(json: trData)
_ = try self.node?.receive(transaction: tr, from: self)
case .block(let blockData):
do {
let b = try BlockType.read(json: blockData)
try self.node?.receive(block: b, from: self, wasRequested: false)
}
catch {
self.fail(error: "Received invalid unsolicited block")
}
case .fetch(hash: let h, extra: let extraBlocksRequested):
if extraBlocksRequested > LedgerType.ParametersType.maximumExtraBlocks {
self.fail(error: "limit exceeded")
}
else {
try self.node?.ledger.mutex.locked {
if let n = node, let block = try n.ledger.longest.get(block: h) {
assert(block.isSignatureValid, "returning invalid blocks, that can't be good")
assert(try! BlockType.read(json: block.json).isSignatureValid, "JSON goes wild")
// Fetch predecessors
var extra: [BlockType.HashType: [String: Any]] = [:]
var last = block
for _ in 0..<extraBlocksRequested {
if last.index <= 0 {
break
}
if let block = try n.ledger.longest.get(block: last.previous) {
assert(block.signature! == last.previous)
extra[block.signature!] = block.json
last = block
}
else {
break
}
}
try request.connection.reply(counter: request.counter, gossip: .result(block: block.json, extra: extra))
}
else {
try request.connection.reply(counter: request.counter, gossip: .error("not found"))
}
}
}
case .query:
// We received a query from the other end
if let n = self.node {
let idx = n.ledger.mutex.locked {
return Index<BlockchainType.BlockType>(
genesis: n.ledger.longest.genesis.signature!,
peers: Array(n.validPeers),
highest: n.ledger.longest.highest.signature!,
height: n.ledger.longest.highest.index,
timestamp: BlockchainType.BlockType.TimestampType(Date().timeIntervalSince1970)
)
}
try request.connection.reply(counter: request.counter, gossip: .index(idx))
}
break
default:
// These are not requests we handle. Ignore clients that don't play by the rules
self.state = .ignored(reason: "peer sent invalid request \(request.gossip)")
break
}
}
public func peer(connection: PeerConnection<LedgerType>, requests gossip: Gossip<LedgerType>, counter: Int) {
self.lastSeen = Date()
Log.debug("[Peer] receive request \(counter)")
self.queue.enqueue(request: Request(connection: connection, gossip: gossip, counter: counter))
}
public func peer(connected _: PeerConnection<LedgerType>) {
self.mutex.locked {
if case .connecting = self.state {
Log.debug("[Peer] \(url) connected outgoing")
self.state = .connected
}
else {
Log.error("[Peer] \(url) connected while not connecting")
}
}
}
public func peer(disconnected _: PeerConnection<LedgerType>) {
self.mutex.locked {
Log.debug("[Peer] \(url) disconnected outgoing")
self.connection = nil
self.fail(error: "disconnected")
}
}
}
public enum PeerState {
case new(since: Date) // Peer has not yet connected
case connecting(since: Date)
case connected // The peer is connected but has not been queried yet
case querying(since: Date) // The peer is currently being queried
case queried // The peer has last been queried successfully
case passive // Peer is active, but should not be queried (only listens passively)
case ignored(reason: String) // The peer is ourselves or believes in another genesis, ignore it forever
case failed(error: String, at: Date) // Talking to the peer failed for some reason, ignore it for a while
}
| mit |
BenEmdon/swift-algorithm-club | Stack/Stack.playground/Contents.swift | 1 | 1432 | /*
Stack
A stack is like an array but with limited functionality. You can only push
to add a new element to the top of the stack, pop to remove the element from
the top, and peek at the top element without popping it off.
A stack gives you a LIFO or last-in first-out order. The element you pushed
last is the first one to come off with the next pop.
Push and pop are O(1) operations.
*/
public struct Stack<T> {
fileprivate var array = [T]()
public var count: Int {
return array.count
}
public var isEmpty: Bool {
return array.isEmpty
}
public mutating func push(_ element: T) {
array.append(element)
}
public mutating func pop() -> T? {
return array.popLast()
}
public func peek() -> T? {
return array.last
}
}
// Create a stack and put some elements on it already.
var stackOfNames = Stack(array: ["Carl", "Lisa", "Stephanie", "Jeff", "Wade"])
// Add an element to the top of the stack.
stackOfNames.push("Mike")
// The stack is now ["Carl", "Lisa", "Stephanie", "Jeff", "Wade", "Mike"]
print(stackOfNames.array)
// Remove and return the first element from the stack. This returns "Mike".
stackOfNames.pop()
// Look at the first element from the stack.
// Returns "Wade" since "Mike" was popped on the previous line.
stackOfNames.peek()
// Check to see if the stack is empty.
// Returns "false" since the stack still has elements in it.
stackOfNames.isEmpty
| mit |
3drobotics/SwiftIO | Sources/BasicTypes+BinaryOutputStreamable.swift | 2 | 2518 | //
// IntegerType+BinaryOutputStreamable.swift
// SwiftIO
//
// Created by Jonathan Wight on 12/5/15.
// Copyright © 2015 schwa.io. All rights reserved.
//
import SwiftUtilities
private func write <T: EndianConvertable> (stream: BinaryOutputStream, value: T) throws {
var value = value.toEndianness(stream.endianness)
let buffer = withUnsafePointer(&value) {
(pointer: UnsafePointer <T>) -> UnsafeBufferPointer <Void> in
return UnsafeBufferPointer(start: pointer, count: sizeof(T))
}
try stream.write(buffer)
}
// MARK: -
extension Int: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension Int8: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension Int16: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension Int32: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension Int64: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
// MARK: -
extension UInt: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension UInt8: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension UInt16: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension UInt32: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
extension UInt64: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
try write(stream, value: self)
}
}
// MARK: -
extension Float: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
let bitValue = unsafeBitCast(self, UInt32.self)
try write(stream, value: bitValue)
}
}
extension Double: BinaryOutputStreamable {
public func writeTo(stream: BinaryOutputStream) throws {
let bitValue = unsafeBitCast(self, UInt64.self)
try write(stream, value: bitValue)
}
}
| mit |
jay18001/brickkit-ios | Example/Source/Examples/Simple/FillBrickViewController.swift | 1 | 1703 | //
// FillBrickViewController.swift
// BrickKit-Example
//
// Created by Ruben Cagnie on 12/4/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
class FillBrickViewController: BrickViewController {
override class var brickTitle: String {
return "Fill Example"
}
override class var subTitle: String {
return "Example of using the Fill BrickDimension"
}
override func viewDidLoad() {
super.viewDidLoad()
self.registerBrickClass(LabelBrick.self)
self.view.backgroundColor = .brickBackground
let section = BrickSection(bricks: [
LabelBrick(width: .fixed(size: 100), backgroundColor: .brickGray1, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
LabelBrick(width: .fill, backgroundColor: .brickGray3, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
LabelBrick(width: .fill, backgroundColor: .brickGray5, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
LabelBrick(width: .fixed(size: 100), backgroundColor: .brickGray2, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
BrickSection(width: .fill, backgroundColor: .brickGray4, bricks: [
LabelBrick(width: .ratio(ratio: 1/3), backgroundColor: .brickGray1, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
LabelBrick(width: .fill, backgroundColor: .brickGray3, text: "BRICK", configureCellBlock: LabelBrickCell.configure),
])
], inset: 10, edgeInsets: UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10))
self.setSection(section)
}
}
| apache-2.0 |
ahoppen/swift | test/Inputs/resilient_struct.swift | 29 | 2031 | // Fixed-layout struct
@frozen public struct Point {
public var x: Int // read-write stored property
public let y: Int // read-only stored property
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public func method() {}
public mutating func mutantMethod() {}
}
// Resilient-layout struct
public struct Size {
public var w: Int // should have getter and setter
public let h: Int // getter only
public init(w: Int, h: Int) {
self.w = w
self.h = h
}
public func method() {}
public mutating func mutantMethod() {}
}
// Fixed-layout struct with resilient members
@frozen public struct Rectangle {
public let p: Point
public let s: Size
public let color: Int
public init(p: Point, s: Size, color: Int) {
self.p = p
self.s = s
self.color = color
}
}
// More complicated resilient structs for runtime tests
public struct ResilientBool {
public let b: Bool
public init(b: Bool) {
self.b = b
}
}
public struct ResilientInt {
public let i: Int
public init(i: Int) {
self.i = i
}
}
public struct ResilientDouble {
public let d: Double
public init(d: Double) {
self.d = d
}
}
@frozen public struct ResilientLayoutRuntimeTest {
public let b1: ResilientBool
public let i: ResilientInt
public let b2: ResilientBool
public let d: ResilientDouble
public init(b1: ResilientBool, i: ResilientInt, b2: ResilientBool, d: ResilientDouble) {
self.b1 = b1
self.i = i
self.b2 = b2
self.d = d
}
}
public class Referent {
public init() {}
}
public struct ResilientWeakRef {
public weak var ref: Referent?
public init (_ r: Referent) {
ref = r
}
}
public struct ResilientRef {
public var r: Referent
public init(r: Referent) { self.r = r }
}
public struct ResilientWithInternalField {
var x: Int
}
// Tuple parameters with resilient structs
public class Subject {}
public struct Container {
public var s: Subject
}
public struct PairContainer {
public var pair : (Container, Container)
}
| apache-2.0 |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift | 1 | 1501 | //#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Use a loop to keep Byte moving while not blocked.
This puzzle has a line of switches, with a different number of switches each time the puzzle runs. Instead of making Byte walk the entire line, checking each step for a switch to toggle open, you can use a form of [conditional code](glossary://conditional%20code) called a [``while`` loop](glossary://while%20loop).
Just like [`if` statements](glossary://if%20statement), `while` loops allow you to determine when your code will run. A `while` loop runs a code block for as long as a [Boolean](glossary://Boolean) condition is true. When the condition is false, the while loop stops running.
1. steps: Choose a Boolean condition for your `while` loop to determine when it will run.
2. Add commands to the `while` block to toggle open all the switches.
*/
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, isOnClosedSwitch, isBlocked, isBlockedLeft, &&, ||, !, isBlockedRight, if, while, func, for)
//#-hidden-code
playgroundPrologue()
//#-end-hidden-code
while /*#-editable-code enter your condition*/<#condition#>/*#-end-editable-code*/ {
//#-editable-code
//#-end-editable-code
}
//#-hidden-code
playgroundEpilogue()
//#-end-hidden-code
| mit |
daltonclaybrook/T-Minus | T-MinusTests/T_MinusTests.swift | 1 | 222 | //
// T_MinusTests.swift
// T-MinusTests
//
// Created by Dalton Claybrook on 4/3/17.
// Copyright © 2017 Claybrook Software. All rights reserved.
//
import XCTest
class LaunchTextProviderTests: XCTestCase {
}
| mit |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift100Tips/Swift100Tips/MarkController.swift | 1 | 621 | //
// MarkController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/26.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class MarkController: UIViewController {
// MARK: - --- interface 接口
// MARK: - --- lift cycle 生命周期 ---
// MARK: - --- delegate 视图委托 ---
// MARK: - --- event response 事件相应 ---
// MARK: - --- private methods 私有方法 ---
// MARK: - --- setters 属性 ---
// MARK: - --- getters 属性 ---
/// 12345678
// TODO: O(∩_∩)O~
// FIXME: (*^__^*) 嘻嘻……
// WARNING: (~ o ~)~zZ
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/25682-swift-modulefile-gettype.swift | 1 | 484 | // 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
{
{struct A{class a{
struct a{
class B{let a{
class p{func a{return{let c{class
case,
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/26309-swift-typebase-getimplicitlyunwrappedoptionalobjecttype.swift | 1 | 407 | // 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
{{{{}}()
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01202-swift-typechecker-validatedecl.swift | 1 | 507 | // 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
func a(b: Int = 0) {
class d<c>: NSObject {
init(b: c) {
var _ = d:b class b
st-> (((i, i) -> i) -> i) {
b {
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01326-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 1 | 497 | // 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
class b<T where T : b(seq
func x: T>) -> String {
let end = { c>(array: A() -> Any in
}
func c<T {
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/23086-swift-typechecker-validatedecl.swift | 1 | 500 | // 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
struct Q<T,j{
class a
struct D:Collection
enum S{
struct Q{
struct b{{
}class B<T{
class B<T{enum b:a
| apache-2.0 |
Leo19/swift_begin | test-swift/HanggeWebView/HanggeWebViewUITests/HanggeWebViewUITests.swift | 1 | 1258 | //
// HanggeWebViewUITests.swift
// HanggeWebViewUITests
//
// Created by liushun on 15/10/16.
// Copyright © 2015年 liushun. All rights reserved.
//
import XCTest
class HanggeWebViewUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| gpl-2.0 |
quangvu1994/Exchange | Exchange/Extension /UIViewControllerUtilities.swift | 1 | 1136 | //
// UIViewControllerUtilities.swift
// Exchange
//
// Created by Quang Vu on 7/7/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
extension UIViewController {
/**
Add a tap gesture to any UIViewController. The action is to hide the keyboard when tapping on the view itself
*/
func hideKeyboardOnTap() {
// Looking for a tap
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
// Do not interfere and cancel other interactions.
tap.cancelsTouchesInView = false
// Add the behavior
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
func displayWarningMessage(message: String){
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
| mit |
mrdepth/Neocom | Neocom/Neocom/Database/Cells/GroupCell.swift | 2 | 614 | //
// GroupCell.swift
// Neocom
//
// Created by Artem Shimanski on 11/28/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import SwiftUI
import CoreData
import Expressible
struct GroupCell: View {
var group: SDEInvGroup
var body: some View {
HStack {
Icon(group.image).cornerRadius(4)
Text(group.groupName ?? "")
}
}
}
#if DEBUG
struct GroupCell_Previews: PreviewProvider {
static var previews: some View {
List {
GroupCell(group: SDEInvType.dominix.group!)
}.listStyle(GroupedListStyle())
}
}
#endif
| lgpl-2.1 |
waywalker/HouseWarmer | HouseWarmer/Error.swift | 1 | 428 | import Foundation
enum DecodingError: LocalizedError {
case missingData(String)
}
extension DecodingError {
var errorDescription: String? {
switch self {
case .missingData(let data):
let format = NSLocalizedString("error.decoding.missingData", comment: "")
return String(format: format, data)
}
}
}
| unlicense |
google/JacquardSDKiOS | Example/JacquardSDK/ScanningView/ScanningTableViewCell.swift | 1 | 2828 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import JacquardSDK
import MaterialComponents
import UIKit
class ScanningTableViewCell: UITableViewCell {
static let reuseIdentifier = "tagCellIdentifier"
@IBOutlet private weak var title: UILabel!
@IBOutlet private weak var checkboxImageView: UIImageView!
func configure(with model: AdvertisingTagCellModel, isSelected: Bool) {
let tagPrefixText = NSMutableAttributedString(string: "Jacquard Tag ")
let tagName = NSMutableAttributedString(
string: model.tag.displayName,
attributes: [NSAttributedString.Key.font: UIFont.system16Medium]
)
layer.masksToBounds = true
layer.cornerRadius = 5
layer.borderWidth = 1
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor
if isSelected {
contentView.backgroundColor = .black
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
tagPrefixText.addAttributes(attributes, range: NSMakeRange(0, tagPrefixText.string.count))
tagName.addAttributes(attributes, range: NSMakeRange(0, tagName.string.count))
checkboxImageView.image = UIImage(named: "circularCheck")
} else {
contentView.backgroundColor = .white
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]
tagPrefixText.addAttributes(attributes, range: NSMakeRange(0, tagPrefixText.string.count))
tagName.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.black,
range: NSMakeRange(0, tagName.string.count)
)
checkboxImageView.image = UIImage(named: "circularUncheck")
}
tagPrefixText.append(tagName)
if let advertisingTag = model.tag as? AdvertisedTag {
let attributes = [
NSAttributedString.Key.font: UIFont.system14Medium,
NSAttributedString.Key.foregroundColor: UIColor.signalColor(advertisingTag.rssi),
]
let rssi = NSMutableAttributedString(
string: " (rssi: \(advertisingTag.rssi))",
attributes: attributes
)
tagPrefixText.append(rssi)
}
title.attributedText = tagPrefixText
let rippleTouchController = MDCRippleTouchController()
rippleTouchController.addRipple(to: self)
}
}
| apache-2.0 |
LoganWright/vapor | Sources/Vapor/Validation/And.swift | 1 | 3073 | /*
The MIT License (MIT) Copyright (c) 2016 Benjamin Encz
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.
*/
/**
This struct is used to encompass multiple Validators into one entity.
It is possible to access this struct directly using
And(validatorOne, validatorTwo)
But it is more common to create And objects using the `+` operator:
validatorOne + validatorTwo
*/
public struct And<
V: Validator,
U: Validator where V.InputType == U.InputType> {
private typealias Validator = (input: V.InputType) throws -> Void
private let validator: Validator
/**
Convenience only.
Must stay private.
*/
private init(_ lhs: Validator, _ rhs: Validator) {
validator = { value in
try lhs(input: value)
try rhs(input: value)
}
}
}
extension And: Validator {
/**
Validator conformance that allows the 'And' struct
to concatenate multiple Validator types.
- parameter value: the value to validate
- throws: an error on failed validation
*/
public func validate(input value: V.InputType) throws {
try validator(input: value)
}
}
extension And {
/**
Used to combine two Validator types
*/
public init(_ lhs: V, _ rhs: U) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where V: ValidationSuite {
/**
Used to combine two Validator types where one is a ValidationSuite
*/
public init(_ lhs: V.Type = V.self, _ rhs: U) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where U: ValidationSuite {
/**
Used to combine two Validators where one is a ValidationSuite
*/
public init(_ lhs: V, _ rhs: U.Type = U.self) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where V: ValidationSuite, U: ValidationSuite {
/**
Used to combine two ValidationSuite types
*/
public init(_ lhs: V.Type = V.self, _ rhs: U.Type = U.self) {
self.init(lhs.validate, rhs.validate)
}
}
| mit |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController+Export.swift | 1 | 1648 | //
// PhotoEditorViewController+Export.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension PhotoEditorViewController {
func exportResources() {
if imageView.canReset() ||
imageView.imageResizerView.hasCropping ||
imageView.canUndoDraw ||
imageView.canUndoMosaic ||
imageView.hasFilter ||
imageView.hasSticker {
imageView.deselectedSticker()
ProgressHUD.showLoading(addedTo: view, text: "正在处理...", animated: true)
imageView.cropping { [weak self] in
guard let self = self else { return }
if let result = $0 {
ProgressHUD.hide(forView: self.view, animated: false)
self.isFinishedBack = true
self.transitionalImage = result.editedImage
self.delegate?.photoEditorViewController(self, didFinish: result)
self.finishHandler?(self, result)
self.didBackClick()
}else {
ProgressHUD.hide(forView: self.view, animated: true)
ProgressHUD.showWarning(
addedTo: self.view,
text: "处理失败".localized,
animated: true,
delayHide: 1.5
)
}
}
}else {
transitionalImage = image
delegate?.photoEditorViewController(didFinishWithUnedited: self)
finishHandler?(self, nil)
didBackClick()
}
}
}
| mit |
ObserveSocial/Focus | Tests/FocusTests/WhenTestingSomethingToEqual.swift | 1 | 1861 | //
// WhenTestingSomethingToBeEqual.swift
// FocusPackageDescription
//
// Created by Sam Meech-Ward on 2018-01-14.
//
@testable import Focus
import XCTest
class WhenTestingSomethingToEqual: XCTestCase {
func toable<ItemType>(item: ItemType) -> To<ItemType> {
return Expect(item: item).to
}
var reporter: Reporter!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
reporter = Reporter()
reporter.resetData()
Focus.reporter = reporter
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func assertEqual<ItemType: Equatable>(item1: ItemType, item2: ItemType) {
let to = toable(item: item1)
to.equal(item2)
XCTAssertTrue(reporter.successData.used)
XCTAssertFalse(reporter.failureData.used)
}
func assertNotEqual<ItemType: Equatable>(item1: ItemType, item2: ItemType) {
let to = toable(item: item1)
to.equal(item2)
XCTAssertFalse(reporter.successData.used)
XCTAssertTrue(reporter.failureData.used)
}
func test_To_Equal_Passes_GivenTwoEqualInts() {
assertEqual(item1: 0, item2: 0)
assertEqual(item1: 1, item2: 1)
assertEqual(item1: 420, item2: 420)
}
func test_To_Equal_Passes_GivenTwoEqualStrings() {
assertEqual(item1: "", item2: "")
assertEqual(item1: "1", item2: "1")
assertEqual(item1: "🤗", item2: "🤗")
}
func test_To_Equal_Fails_GivenTwoEqualInts() {
assertNotEqual(item1: 0, item2: 1)
assertNotEqual(item1: 3.14, item2: 420)
}
func test_To_Equal_Fails_GivenTwoUnEqualStrings() {
assertNotEqual(item1: "", item2: "1")
assertNotEqual(item1: "💩", item2: "🤗")
}
}
| mit |
strongself/rambobot | Rambobot/Package.swift | 1 | 408 | import PackageDescription
let package = Package(
name: "sampleApi",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 5),
.Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 1, minor: 0)
],
exclude: [
"Config",
"Database",
"Localization",
"Public",
"Resources",
]
)
| mit |
Burning-Man-Earth/iBurn-iOS | iBurn/Tracks/Breadcrumb.swift | 1 | 1482 | //
// Breadcrumb.swift
// iBurn
//
// Created by Chris Ballinger on 7/29/19.
// Copyright © 2019 Burning Man Earth. All rights reserved.
//
import Foundation
import GRDB
struct Breadcrumb {
var id: Int64?
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
private var latitude: Double
private var longitude: Double
var timestamp: Date
static func from(_ location: CLLocation) -> Breadcrumb {
return Breadcrumb(id: nil, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, timestamp: location.timestamp)
}
}
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Breadcrumb: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let latitude = Column(CodingKeys.latitude)
static let longitude = Column(CodingKeys.longitude)
static let timestamp = Column(CodingKeys.timestamp)
}
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
| mpl-2.0 |
briandw/SwiftFighter | SwiftFighter/Quote.swift | 1 | 2829 | //
// Quote.swift
// SwiftFighter
//
// Created by Brian Williams on 4/9/16.
// Copyright © 2016 RL. All rights reserved.
//
import Foundation
var formatter = NSDateFormatter.init()
var formatterInit = false
class Quote
{
var venue : String = ""
var symbol : String = ""
var bid : Int = 0
var bidSize : Int = 0
var bidDepth : Int = 0
var ask : Int = 0
var askSize : Int = 0
var askDepth : Int = 0
var lastPrice : Int = 0
var lastSize : Int = 0
var lastTrade : String = ""
var quoteTime : NSDate?
init (json : NSDictionary)
{
if (!formatterInit)
{
formatterInit = true
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale.init(localeIdentifier: "en_US_POSIX")
}
var jsonObject = json["\(dictionaryKeys.symbol)"]
if let symbol = jsonObject as? String
{
self.symbol = symbol
}
jsonObject = json["\(dictionaryKeys.venue)"]
if let venue = jsonObject as? String
{
self.venue = venue
}
jsonObject = json["\(dictionaryKeys.bid)"]
if let bid = jsonObject as? Int
{
self.bid = bid
}
jsonObject = json["\(dictionaryKeys.ask)"]
if let ask = jsonObject as? Int
{
self.ask = ask
}
jsonObject = json["\(dictionaryKeys.bidSize)"]
if let bidSize = jsonObject as? Int
{
self.bidSize = bidSize
}
jsonObject = json["\(dictionaryKeys.askSize)"]
if let askSize = jsonObject as? Int
{
self.askSize = askSize
}
jsonObject = json["\(dictionaryKeys.bidDepth)"]
if let bidDepth = jsonObject as? Int
{
self.bidDepth = bidDepth
}
jsonObject = json["\(dictionaryKeys.askDepth)"]
if let askDepth = jsonObject as? Int
{
self.askDepth = askDepth
}
jsonObject = json["\(dictionaryKeys.last)"]
if let lastPrice = jsonObject as? Int
{
self.lastPrice = lastPrice
}
jsonObject = json["\(dictionaryKeys.lastSize)"]
if let lastSize = jsonObject as? Int
{
self.lastSize = lastSize
}
jsonObject = json["\(dictionaryKeys.lastTrade)"]
if let lastTrade = jsonObject as? String
{
self.lastTrade = lastTrade
}
jsonObject = json["\(dictionaryKeys.quoteTime)"]
if let quoteTime = jsonObject as? String
{
self.quoteTime = formatter.dateFromString(quoteTime)
}
}
}
| bsd-2-clause |
jandro-es/Evergreen | Evergreen/src/Extensions/NSURL+Parameter.swift | 1 | 1996 | //
// String+Page.swift
// Evergreen
//
// Created by Alejandro Barros Cuetos on 04/02/2016.
// Copyright © 2016 Alejandro Barros Cuetos. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// && and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension NSURL {
/**
Gets an array of values for the requires parameter name
- parameter key: The name of the parameter
- returns: An array of values
*/
func getQueryValues(key: String) -> [String]? {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false), items = components.queryItems else {
return nil
}
return items.filter { $0.name == key }.map({ $0.value! })
}
} | apache-2.0 |
TKU-MIS-TLMXB4P/ios-swift-first-demo-edwardinubuntu | FirstDemo/ViewController.swift | 26 | 511 | //
// ViewController.swift
// FirstDemo
//
// Created by Edward Chiang on 10/26/15.
// Copyright © 2015 Soleil Studio. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
strike65/SwiftyStats | SwiftyStats/Experimental Sources/Pearson.swift | 1 | 4822 | //
// Created by VT on 17.09.18.
// Copyright © 2018 strike65. All rights reserved.
//
/*
Copyright (2017-2019) strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
extension SSSpecialFunctions {
// see : https://people.maths.ox.ac.uk/porterm/research/pearson_final.pdf
internal static func h1f1taylora<T: SSComplexFloatElement>(_ a: Complex<T>, _ b: Complex<T>, _ x: Complex<T>, _ tol: T) -> (h: Complex<T>, mIter: Bool) {
var a1: Array<Complex<T>> = Array<Complex<T>>.init()
var sum: Complex<T> = Complex<T>.init(re: 1, im: 0)
a1.append(Complex<T>.init(re: 1, im: 0))
var e1, e2, e3, e4, e5: Complex<T>
var jf: Complex<T>
var maxIter: Bool = false
for j in stride(from: 1, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
e1 = (a &++ jf &-- 1)
e2 = (b &++ jf &-- 1)
e3 = e1 &% e2
e4 = x &% jf &** a1[j - 1]
e5 = e3 &** e4
a1.append(e5)
sum = sum &++ a1[j]
if ((a1[j - 1].abs / sum.abs) < tol && (a1[j].abs / sum.abs < tol)) {
break
}
if j == 500 {
maxIter = true
}
}
return (h: sum, mIter: maxIter)
}
internal static func h1f1taylorb<T: SSComplexFloatElement>(_ a: Complex<T>, _ b: Complex<T>, _ x: Complex<T>, _ tol: T) -> (h: Complex<T>, mIter: Bool) {
var r: Array<Complex<T>> = Array<Complex<T>>.init()
r.append(a &% b)
r.append((a &++ 1) &% 2 &% (b &++ 1))
var A: Array<Complex<T>> = Array<Complex<T>>.init()
A.append(1 &++ x &** r[0])
A.append(A[0] &++ pow(x, 2) &** a &% b &** r[1])
var jf: Complex<T>
var e1, e2, e3: Complex<T>
var maxIter: Bool = false
for j in stride(from: 3, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
e1 = (a &++ jf &-- 1) &% jf
e2 = (b &++ jf &-- 1)
e3 = e1 &% e2
r.append(e3)
e1 = A[j - 2] &++ (A[j - 2] &-- A[j - 3]) &** r[j - 2] &** x
A.append(e1)
if (((A[j - 1] &-- A[j - 2]).abs / A[j - 2].abs) < tol) && ((A[j - 2] &-- A[j - 3]).abs / A[j - 3].abs < tol) {
break
}
if j == 500 {
maxIter = true
}
}
return (h: A.last!, mIter: maxIter)
}
internal static func h1f1singleFraction<T: SSComplexFloatElement>(a: Complex<T>, b: Complex<T>, z: Complex<T>, tol: T) -> (h: Complex<T>, maxiter: Bool) {
var A1: Array<Complex<T>> = Array<Complex<T>>.init()
var B1: Array<Complex<T>> = Array<Complex<T>>.init()
var C1: Array<Complex<T>> = Array<Complex<T>>.init()
var D1: Array<Complex<T>> = Array<Complex<T>>.init()
var maxiter: Bool = false
A1.append(Complex<T>.zero)
A1.append(b)
B1.append(Complex<T>.init(re: 1, im: 0))
B1.append(a &** z)
C1.append(Complex<T>.init(re: 1, im: 0))
C1.append(b)
D1.append(Complex<T>.init(re: 1, im: 0))
D1.append((b &++ a &** z) &% b)
var jf: Complex<T>
var ex1: Complex<T>
var ex2: Complex<T>
var ex3: Complex<T>
var ex4: Complex<T>
for j in stride(from: 3, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
ex1 = A1[j - 2] &++ B1[j - 2]
ex2 = jf &-- 1
ex3 = b &++ jf &-- 2
ex4 = ex1 &** ex2
A1[j - 1] = ex4 &** ex3
B1[j - 1] = B1[j - 2] &** (a &++ jf &-- 2) &** z
C1[j - 1] = C1[j - 2] &** (jf &-- 1) &** (b &++ jf &-- 2)
if A1[j - 1].isInfinite || B1[j - 1].isInfinite || C1[j - 1].isInfinite {
break
}
D1[j - 1] = (A1[j - 1] &++ B1[j - 1] &% C1[j - 1])
if (((D1[j - 1] &-- D1[j - 2]).abs / D1[j - 2].abs) < tol) && (((D1[j - 2] &-- D1[j - 3]).abs / D1[j - 3].abs) < tol) {
break
}
if j == 500 {
maxiter = true
}
}
return (h: D1.last!, maxiter: maxiter)
}
}
| gpl-3.0 |
Darren-chenchen/yiyiTuYa | testDemoSwift/Category/String.swift | 1 | 722 | //
// String.swift
// CloudscmSwift
//
// Created by RexYoung on 2017/3/21.
// Copyright © 2017年 RexYoung. All rights reserved.
//
import Foundation
import UIKit
extension String{
//MARK: - 获取字符串的宽度高度
static func getTextSize(labelStr:String,font:UIFont,maxW:CGFloat,maxH:CGFloat) -> CGSize {
let statusLabelText: NSString = labelStr as NSString
let size = CGSize(width: maxW, height:maxH)
let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
return strSize
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/01864-swift-valuedecl-settype.swift | 11 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S{
var _=f
func f:U
}
protocol A{
func b{
{
}
}
typealias A:A | mit |
drmohundro/SWXMLHash | Tests/SWXMLHashTests/TypeConversionPrimitiveTypesTests.swift | 1 | 10610 | //
// TypeConversionPrimitiveTypesTests.swift
// SWXMLHash
//
// Copyright (c) 2016 David Mohundro
//
// 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 SWXMLHash
import XCTest
// swiftlint:disable line_length
class TypeConversionPrimitiveTypesTests: XCTestCase {
var parser: XMLIndexer?
let xmlWithArraysOfTypes = """
<root>
<arrayOfGoodInts>
<int>0</int> <int>1</int> <int>2</int> <int>3</int>
</arrayOfGoodInts>
<arrayOfBadInts>
<int></int> <int>boom</int>
</arrayOfBadInts>
<arrayOfMixedInts>
<int>0</int> <int>boom</int> <int>2</int> <int>3</int>
</arrayOfMixedInts>
<arrayOfAttributeInts>
<int value=\"0\"/> <int value=\"1\"/> <int value=\"2\"/> <int value=\"3\"/>
</arrayOfAttributeInts>
<empty></empty>
</root>
"""
override func setUp() {
super.setUp()
parser = XMLHash.parse(xmlWithArraysOfTypes)
}
func testShouldConvertArrayOfGoodIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldConvertArrayOfAttributeIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int]? = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int?] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["empty"]["int"].value()
XCTAssertEqual(value, [])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["empty"]["int"].value()
XCTAssertNil(value)
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["empty"]["int"].value()
XCTAssertEqual(value.count, 0)
} catch {
XCTFail("\(error)")
}
}
}
extension TypeConversionPrimitiveTypesTests {
static var allTests: [(String, (TypeConversionPrimitiveTypesTests) -> () throws -> Void)] {
[
("testShouldConvertArrayOfGoodIntsToNonOptional", testShouldConvertArrayOfGoodIntsToNonOptional),
("testShouldConvertArrayOfGoodIntsToOptional", testShouldConvertArrayOfGoodIntsToOptional),
("testShouldConvertArrayOfGoodIntsToArrayOfOptionals", testShouldConvertArrayOfGoodIntsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional", testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional),
("testShouldThrowWhenConvertingArrayOfBadIntsToOptional", testShouldThrowWhenConvertingArrayOfBadIntsToOptional),
("testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional", testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional),
("testShouldThrowWhenConvertingArrayOfMixedIntsToOptional", testShouldThrowWhenConvertingArrayOfMixedIntsToOptional),
("testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals),
("testShouldConvertArrayOfAttributeIntsToNonOptional", testShouldConvertArrayOfAttributeIntsToNonOptional),
("testShouldConvertArrayOfAttributeIntsToOptional", testShouldConvertArrayOfAttributeIntsToOptional),
("testShouldConvertArrayOfAttributeIntsToArrayOfOptionals", testShouldConvertArrayOfAttributeIntsToArrayOfOptionals),
("testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable),
("testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable),
("testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable),
("testShouldConvertEmptyArrayOfIntsToNonOptional", testShouldConvertEmptyArrayOfIntsToNonOptional),
("testShouldConvertEmptyArrayOfIntsToOptional", testShouldConvertEmptyArrayOfIntsToOptional),
("testShouldConvertEmptyArrayOfIntsToArrayOfOptionals", testShouldConvertEmptyArrayOfIntsToArrayOfOptionals)
]
}
}
| mit |
wolf81/Nimbl3Survey | Nimbl3Survey/SurveyInfoView.swift | 1 | 2445 | //
// SurveyInfoView.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 22/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
import AlamofireImage
protocol SurveyInfoViewDelegate: class {
func surveyInfoViewSurveyAction(_ surveyInfoView: SurveyInfoView)
}
class SurveyInfoView: UIView, InterfaceBuilderInstantiable {
weak var delegate: SurveyInfoViewDelegate?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var descriptionLabel: UILabel?
@IBOutlet weak var surveyButton: UIButton?
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var overlayView: UIView?
private(set) var survey: Survey? {
didSet {
self.titleLabel?.text = self.survey?.title
self.descriptionLabel?.text = self.survey?.description
if let imageUrl = self.survey?.imageUrl {
self.imageView?.af_setImage(withURL: imageUrl, placeholderImage: nil, filter: nil, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.5), runImageTransitionIfCached: true, completion: { response in
})
} else {
self.imageView?.image = nil
}
}
}
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
if let surveyButton = self.surveyButton {
let bgImage = UIImage.from(color: UIColor.red)
surveyButton.setBackgroundImage(bgImage, for: .normal)
let cornerRadius: CGFloat = surveyButton.frame.height / 2
self.surveyButton?.layer.cornerRadius = cornerRadius
self.surveyButton?.layer.masksToBounds = true
}
}
// MARK: - Public
@IBAction func surveyAction() {
self.delegate?.surveyInfoViewSurveyAction(self)
}
func updateWithSurvey(_ survey: Survey) {
self.survey = survey
applyTheme(survey.theme)
}
// MARK: - Private
private func applyTheme(_ theme: Theme) {
let bgImage = UIImage.from(color: theme.activeColor)
surveyButton?.setBackgroundImage(bgImage, for: .normal)
surveyButton?.setTitleColor(theme.questionColor, for: .normal)
self.descriptionLabel?.textColor = theme.questionColor
self.titleLabel?.textColor = theme.questionColor
}
}
| bsd-2-clause |
camdenfullmer/UnsplashSwift | Source/Serializers.swift | 1 | 18002 | // Serializers.swift
//
// Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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
import CoreGraphics
// TODO: Create struct to hold single instance for all serializers.
public enum JSON {
case Array([JSON])
case Dictionary([String: JSON])
case Str(String)
case Number(NSNumber)
case Null
}
public protocol JSONSerializer {
typealias ValueType
func deserialize(_: JSON) -> ValueType
}
public extension JSONSerializer {
func deserialize(json: JSON?) -> ValueType? {
if let j = json {
switch j {
case .Null:
return nil
default:
return deserialize(j)
}
}
return nil
}
}
func objectToJSON(json : AnyObject) -> JSON {
switch json {
case _ as NSNull:
return .Null
case let num as NSNumber:
return .Number(num)
case let str as String:
return .Str(str)
case let dict as [String : AnyObject]:
var ret = [String : JSON]()
for (k, v) in dict {
ret[k] = objectToJSON(v)
}
return .Dictionary(ret)
case let array as [AnyObject]:
return .Array(array.map(objectToJSON))
default:
fatalError("Unknown type trying to parse JSON.")
}
}
func parseJSON(data: NSData) -> JSON {
let obj: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
return objectToJSON(obj)
}
// MARK: - Common Serializers
public class ArraySerializer<T : JSONSerializer> : JSONSerializer {
var elementSerializer : T
init(_ elementSerializer: T) {
self.elementSerializer = elementSerializer
}
public func deserialize(json : JSON) -> Array<T.ValueType> {
switch json {
case .Array(let arr):
return arr.map { self.elementSerializer.deserialize($0) }
default:
fatalError("Type error deserializing")
}
}
}
public class UInt32Serializer : JSONSerializer {
public func deserialize(json : JSON) -> UInt32 {
switch json {
case .Number(let n):
return n.unsignedIntValue
default:
fatalError("Type error deserializing")
}
}
public func deserialize(json: JSON?) -> UInt32? {
if let j = json {
switch(j) {
case .Number(let n):
return n.unsignedIntValue
default:
break
}
}
return nil
}
}
public class BoolSerializer : JSONSerializer {
public func deserialize(json : JSON) -> Bool {
switch json {
case .Number(let b):
return b.boolValue
default:
fatalError("Type error deserializing")
}
}
}
public class DoubleSerializer : JSONSerializer {
public func deserialize(json: JSON) -> Double {
switch json {
case .Number(let n):
return n.doubleValue
default:
fatalError("Type error deserializing")
}
}
public func deserialize(json: JSON?) -> Double? {
if let j = json {
switch(j) {
case .Number(let n):
return n.doubleValue
default:
break
}
}
return nil
}
}
public class StringSerializer : JSONSerializer {
public func deserialize(json: JSON) -> String {
switch (json) {
case .Str(let s):
return s
default:
fatalError("Type error deserializing")
}
}
}
// Color comes in the following format: #000000
public class UIColorSerializer : JSONSerializer {
public func deserialize(json: JSON) -> UIColor {
switch (json) {
case .Str(let s):
return UIColor.colorWithHexString(s)
default:
fatalError("Type error deserializing")
}
}
}
public class NSURLSerializer : JSONSerializer {
public func deserialize(json: JSON) -> NSURL {
switch (json) {
case .Str(let s):
return NSURL(string: s)!
default:
fatalError("Type error deserializing")
}
}
}
// Date comes in the following format: 2015-06-17T11:53:00-04:00
public class NSDateSerializer : JSONSerializer {
var dateFormatter : NSDateFormatter
init() {
self.dateFormatter = NSDateFormatter()
self.dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
}
public func deserialize(json: JSON) -> NSDate {
switch json {
case .Str(let s):
return self.dateFormatter.dateFromString(s)!
default:
fatalError("Type error deserializing")
}
}
}
public class DeleteResultSerializer : JSONSerializer {
init(){}
public func deserialize(json: JSON) -> Bool {
switch json {
case .Null:
return true
default:
fatalError("Type error deserializing")
}
}
}
// MARK: Model Serializers
extension User {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> User {
switch json {
case .Dictionary(let dict):
let id = StringSerializer().deserialize(dict["id"])
let username = StringSerializer().deserialize(dict["username"] ?? .Null)
let name = StringSerializer().deserialize(dict["name"])
let firstName = StringSerializer().deserialize(dict["first_name"])
let lastName = StringSerializer().deserialize(dict["last_name"])
let downloads = UInt32Serializer().deserialize(dict["downloads"])
let profilePhoto = ProfilePhotoURL.Serializer().deserialize(dict["profile_image"])
let portfolioURL = NSURLSerializer().deserialize(dict["portfolio_url"])
let bio = StringSerializer().deserialize(dict["bio"])
let uploadsRemaining = UInt32Serializer().deserialize(dict["uploads_remaining"])
let instagramUsername = StringSerializer().deserialize(dict["instagram_username"])
let location = StringSerializer().deserialize(dict["location"])
let email = StringSerializer().deserialize(dict["email"])
return User(id: id, username: username, name: name, firstName: firstName, lastName: lastName, downloads: downloads, profilePhoto: profilePhoto, portfolioURL: portfolioURL, bio: bio, uploadsRemaining: uploadsRemaining, instagramUsername: instagramUsername, location: location, email: email)
default:
fatalError("error deserializing")
}
}
public func deserialize(json: JSON?) -> User? {
if let j = json {
return deserialize(j)
}
return nil
}
}
}
extension ProfilePhotoURL {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> ProfilePhotoURL {
switch json {
case .Dictionary(let dict):
let large = NSURLSerializer().deserialize(dict["large"] ?? .Null)
let medium = NSURLSerializer().deserialize(dict["medium"] ?? .Null)
let small = NSURLSerializer().deserialize(dict["small"] ?? .Null)
let custom = NSURLSerializer().deserialize(dict["custom"])
return ProfilePhotoURL(large: large, medium: medium, small: small, custom: custom)
default:
fatalError("error deserializing")
}
}
}
}
extension CollectionsResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> CollectionsResult {
switch json {
case .Array:
let collections = ArraySerializer(Collection.Serializer()).deserialize(json)
return CollectionsResult(collections: collections)
default:
fatalError("error deserializing")
}
}
}
}
extension Collection {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Collection {
switch json {
case .Dictionary(let dict):
let id = UInt32Serializer().deserialize(dict["id"] ?? .Null)
let title = StringSerializer().deserialize(dict["title"] ?? .Null)
let curated = BoolSerializer().deserialize(dict["curated"] ?? .Null)
let coverPhoto = Photo.Serializer().deserialize(dict["cover_photo"] ?? .Null)
let publishedAt = NSDateSerializer().deserialize(dict["published_at"] ?? .Null)
let user = User.Serializer().deserialize(dict["user"] ?? .Null)
return Collection(id: id, title: title, curated: curated, coverPhoto: coverPhoto, publishedAt: publishedAt, user: user)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoCollectionResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoCollectionResult {
switch json {
case .Dictionary(let dict):
let photo = Photo.Serializer().deserialize(dict["photo"] ?? .Null)
let collection = Collection.Serializer().deserialize(dict["collection"] ?? .Null)
return PhotoCollectionResult(photo: photo, collection: collection)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoUserResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoUserResult {
switch json {
case .Dictionary(let dict):
let photo = Photo.Serializer().deserialize(dict["photo"] ?? .Null)
let user = User.Serializer().deserialize(dict["user"] ?? .Null)
return PhotoUserResult(photo: photo, user: user)
default:
fatalError("error deserializing")
}
}
}
}
extension Photo {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Photo {
switch json {
case .Dictionary(let dict):
let id = StringSerializer().deserialize(dict["id"] ?? .Null)
let width = UInt32Serializer().deserialize(dict["width"])
let height = UInt32Serializer().deserialize(dict["height"])
let color = UIColorSerializer().deserialize(dict["color"])
let user = User.Serializer().deserialize(dict["user"])
let url = PhotoURL.Serializer().deserialize(dict["urls"] ?? .Null)
let categories = ArraySerializer(Category.Serializer()).deserialize(dict["categories"])
let exif = Exif.Serializer().deserialize(dict["exif"])
let downloads = UInt32Serializer().deserialize(dict["downloads"])
let likes = UInt32Serializer().deserialize(dict["likes"])
let location = Location.Serializer().deserialize(dict["location"])
return Photo(id: id, width: width, height: height, color: color, user: user, url: url, categories: categories, exif: exif, downloads: downloads, likes: likes, location: location)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotosResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotosResult {
switch json {
case .Array:
let photos = ArraySerializer(Photo.Serializer()).deserialize(json)
return PhotosResult(photos: photos)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoURL {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoURL {
switch json {
case .Dictionary(let dict):
let full = NSURLSerializer().deserialize(dict["full"] ?? .Null)
let regular = NSURLSerializer().deserialize(dict["regular"] ?? .Null)
let small = NSURLSerializer().deserialize(dict["small"] ?? .Null)
let thumb = NSURLSerializer().deserialize(dict["thumb"] ?? .Null)
let custom = NSURLSerializer().deserialize(dict["custom"])
return PhotoURL(full: full, regular: regular, small: small, thumb: thumb, custom: custom)
default:
fatalError("error deserializing")
}
}
}
}
extension Exif {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Exif {
switch json {
case .Dictionary(let dict):
let make = StringSerializer().deserialize(dict["make"])
let model = StringSerializer().deserialize(dict["model"])
let exposureTime = DoubleSerializer().deserialize(dict["exposure_time"])
let aperture = DoubleSerializer().deserialize(dict["aperture"])
let focalLength = UInt32Serializer().deserialize(dict["focal_length"])
let iso = UInt32Serializer().deserialize(dict["iso"])
return Exif(make: make, model: model, exposureTime: exposureTime, aperture: aperture, focalLength: focalLength, iso: iso)
default:
fatalError("error deserializing")
}
}
}
}
extension Location {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Location {
switch json {
case .Dictionary(let dict):
let position = Position.Serializer().deserialize(dict["position"] ?? .Null)
let city = StringSerializer().deserialize(dict["city"] ?? .Null)
let country = StringSerializer().deserialize(dict["country"] ?? .Null)
return Location(city: city, country: country, position: position)
default:
fatalError("error deserializing")
}
}
}
}
extension Position {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Position {
switch json {
case .Dictionary(let dict):
let latitude = DoubleSerializer().deserialize(dict["latitude"] ?? .Null)
let longitude = DoubleSerializer().deserialize(dict["longitude"] ?? .Null)
return Position(latitude: latitude, longitude: longitude)
default:
fatalError("error deserializing")
}
}
}
}
extension CategoriesResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> CategoriesResult {
switch json {
case .Array:
let categories = ArraySerializer(Category.Serializer()).deserialize(json)
return CategoriesResult(categories: categories)
default:
fatalError("error deserializing")
}
}
}
}
extension Category {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Category {
switch json {
case .Dictionary(let dict):
let id = UInt32Serializer().deserialize(dict["id"] ?? .Null)
let title = StringSerializer().deserialize(dict["title"] ?? .Null)
let photoCount = UInt32Serializer().deserialize(dict["photo_count"] ?? .Null)
return Category(id: id, title: title, photoCount: photoCount)
default:
fatalError("error deserializing")
}
}
}
}
extension Stats {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Stats {
switch json {
case .Dictionary(let dict):
let photoDownloads = UInt32Serializer().deserialize(dict["photo_downloads"] ?? .Null)
let batchDownloads = UInt32Serializer().deserialize(dict["batch_downloads"] ?? .Null)
return Stats(photoDownloads: photoDownloads, batchDownloads: batchDownloads)
default:
fatalError("error deserializing")
}
}
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/System/Floating Create Button/UIView+SpringAnimations.swift | 2 | 2542 | extension FloatingActionButton {
private enum Constants {
enum Maximize {
static let damping: CGFloat = 0.7
static let duration: TimeInterval = 0.5
static let initialScale: CGFloat = 0.0
static let finalScale: CGFloat = 1.0
}
enum Minimize {
static let damping: CGFloat = 0.9
static let duration: TimeInterval = 0.25
static let initialScale: CGFloat = 1.0
static let finalScale: CGFloat = 0.001
}
}
/// Animates the showing and hiding of a view using a spring animation
/// - Parameter toShow: Whether to show the view
func springAnimation(toShow: Bool) {
if toShow {
guard isHidden == true else { return }
maximizeSpringAnimation()
} else {
guard isHidden == false else { return }
minimizeSpringAnimation()
}
}
/// Applies a spring animation, from size 1 to 0
func minimizeSpringAnimation() {
let damping = Constants.Minimize.damping
let scaleInitial = Constants.Minimize.initialScale
let scaleFinal = Constants.Minimize.finalScale
let duration = Constants.Minimize.duration
scaleAnimation(duration: duration, damping: damping, scaleInitial: scaleInitial, scaleFinal: scaleFinal) { [weak self] success in
self?.transform = .identity
self?.isHidden = true
}
}
/// Applies a spring animation, from size 0 to 1
func maximizeSpringAnimation() {
let damping = Constants.Maximize.damping
let scaleInitial = Constants.Maximize.initialScale
let scaleFinal = Constants.Maximize.finalScale
let duration = Constants.Maximize.duration
scaleAnimation(duration: duration, damping: damping, scaleInitial: scaleInitial, scaleFinal: scaleFinal)
}
func scaleAnimation(duration: TimeInterval, damping: CGFloat, scaleInitial: CGFloat, scaleFinal: CGFloat, completion: ((Bool) -> Void)? = nil) {
setNeedsDisplay() // Make sure we redraw so that corners are rounded
transform = CGAffineTransform(scaleX: scaleInitial, y: scaleInitial)
isHidden = false
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: damping) {
self.transform = CGAffineTransform(scaleX: scaleFinal, y: scaleFinal)
}
animator.addCompletion { (position) in
completion?(true)
}
animator.startAnimation()
}
}
| gpl-2.0 |
tamanyan/PageTabViewController | Example/Example/AppDelegate.swift | 1 | 2463 | //
// AppDelegate.swift
// Example
//
// Created by svpcadmin on 11/11/16.
// Copyright © 2016 tamanyan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let navController = UINavigationController(rootViewController: ViewController())
navController.title = "PageTabController"
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
| mit |
jtbandes/swift-compiler-crashes | crashes-duplicates/27690-swift-typechecker-substituteinputsugartypeforresult.swift | 4 | 266 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func d{
{
let b{
struct c<T where g:a{
class A{
protocol B
class B<d{
{
}
let a=B
}
}}}}if true{
| mit |
the-blue-alliance/the-blue-alliance-ios | Frameworks/MyTBAKit/Sources/Models/MyTBAPreferences.swift | 1 | 2039 | import Foundation
public struct MyTBAPreferences: Codable {
var deviceKey: String?
var favorite: Bool
var modelKey: String
var modelType: MyTBAModelType
var notifications: [NotificationType]
}
public struct MyTBAPreferencesMessageResponse: Codable {
let favorite: MyTBABaseResponse
let subscription: MyTBABaseResponse
}
extension MyTBA {
// TODO: Android has some local rate limiting, which is probably smart
// https://github.com/the-blue-alliance/the-blue-alliance-ios/issues/174
public func updatePreferences(modelKey: String, modelType: MyTBAModelType, favorite: Bool, notifications: [NotificationType], completion: @escaping (_ favoriteResponse: MyTBABaseResponse?, _ subscriptionResponse: MyTBABaseResponse?, _ error: Error?) -> Void) -> MyTBAOperation? {
let preferences = MyTBAPreferences(deviceKey: fcmToken,
favorite: favorite,
modelKey: modelKey,
modelType: modelType,
notifications: notifications)
guard let encodedPreferences = try? MyTBA.jsonEncoder.encode(preferences) else {
return nil
}
let method = "model/setPreferences"
return callApi(method: method, bodyData: encodedPreferences, completion: { (preferencesResponse: MyTBABaseResponse?, error: Error?) in
if let preferencesResponse = preferencesResponse, let data = preferencesResponse.message.data(using: .utf8) {
guard let messageResponse = try? JSONDecoder().decode(MyTBAPreferencesMessageResponse.self, from: data) else {
completion(nil, nil, MyTBAError.error(nil, "Error decoding myTBA preferences response"))
return
}
completion(messageResponse.favorite, messageResponse.subscription, error)
} else {
completion(nil, nil, error)
}
})
}
}
| mit |
nishimao/FeedbackKit | FeedbackKit/Classes/Feedback.swift | 1 | 3995 | //
// Feedback.swift
// FeedbackKit
//
// Created by Mao Nishi on 8/17/16.
// Copyright © 2016 Mao Nishi. All rights reserved.
//
import Foundation
import UIKit
public enum Feedback {
public class EmailConfig {
var toList: [String]
var mailSubject: String?
var ccList: [String]?
var bccList: [String]?
public init(to: String) {
toList = [to]
}
public init(toList: [String], mailSubject: String? = nil, ccList: [String]? = nil, bccList: [String]? = nil) {
self.toList = toList
self.mailSubject = mailSubject
self.ccList = ccList
self.bccList = ccList
}
}
// feedback by email
case Email(emailConfig: EmailConfig)
// feedback by custom action. when custom action was finished successfully, need to call 'success' method.
case Custom(action: ((feedbackViewController: FeedbackViewController, sendInformation: SendInformation, success:(()->Void)) -> Void))
public func show(dismissed:(()->Void)) {
guard let callerViewController = UIApplication.sharedApplication().keyWindow?.rootViewController else {
return
}
switch self {
case .Email(let email):
let feedbackMail = FeedbackMail()
FeedbackViewController.presentFeedbackViewController(callerViewController, action: { (feedbackViewController: FeedbackViewController, sendInformation: SendInformation) in
// send mail
feedbackMail.send(email, sendInformation: sendInformation, callerViewController: feedbackViewController, mailSendCompletion: {
// complete send mail and dismiss feedbackview
feedbackViewController.dismissFeedbackViewController()
// callback
dismissed()
})
})
case .Custom(let action):
FeedbackViewController.presentFeedbackViewController(callerViewController, action: { (feedbackViewController: FeedbackViewController, sendInformation: SendInformation) in
let success: (()->Void) = {
dispatch_async(dispatch_get_main_queue(), {
// dismiss feedbackview
feedbackViewController.dismissFeedbackViewController()
// callback
dismissed()
})
}
// execute custom action
action(feedbackViewController: feedbackViewController, sendInformation: sendInformation, success: success)
})
}
}
public func addDoubleLongPressGestureRecognizer(dismissed:(()->Void)) {
GestureFeedback.gestureFeedback.dismissed = dismissed
GestureFeedback.gestureFeedback.feedback = self
let gesture = UILongPressGestureRecognizer(target: GestureFeedback.gestureFeedback, action: #selector(GestureFeedback.pressGesture(_:)))
gesture.numberOfTouchesRequired = 2
if let window = UIApplication.sharedApplication().delegate?.window {
if let recognizers = window?.gestureRecognizers {
for recognizer in recognizers {
if recognizer is UILongPressGestureRecognizer {
window?.removeGestureRecognizer(recognizer)
}
}
}
window?.addGestureRecognizer(gesture)
}
}
}
final class GestureFeedback: NSObject {
var feedback: Feedback?
var dismissed: (()->Void)?
static let gestureFeedback = GestureFeedback()
private override init() {
}
func pressGesture(sender: UIGestureRecognizer) {
guard let feedback = feedback else {
return
}
guard let dismissed = dismissed else {
feedback.show({
// none
})
return
}
feedback.show(dismissed)
}
}
| mit |
mrommel/TreasureDungeons | TreasureDungeons/Source/OpenGL/ObjModel.swift | 1 | 3387 | //
// ObjModel.swift
// TreasureDungeons
//
// Created by Michael Rommel on 07.09.17.
// Copyright © 2017 BurtK. All rights reserved.
//
import Foundation
import GLKit
public enum ObjModelError: Error {
case noObjectFound
}
class ObjModel : Model {
init(fileName: String, shader: BaseEffect) throws {
// load obj file named "key.obj"
let fixtureHelper = ObjLoading.FixtureHelper()
let source = try? fixtureHelper.loadObjFixture(name: fileName)
if let source = source {
let loader = ObjLoading.ObjLoader(source: source, basePath: fixtureHelper.resourcePath)
do {
let shapes = try loader.read()
if let shape = shapes.first {
let (vertices, indices) = ObjModel.verticesAndIndicesFrom(shape: shape)
super.init(name: shape.name!, shader: shader, vertices: vertices, indices: indices)
self.loadTexture((shape.material?.diffuseTextureMapFilePath?.lastPathComponent)! as String)
} else {
throw ObjModelError.noObjectFound
}
}
} else {
throw ObjModelError.noObjectFound
}
}
init(name: String, shape: ObjLoading.Shape, shader: BaseEffect) {
let (vertices, indices) = ObjModel.verticesAndIndicesFrom(shape: shape)
super.init(name: name, shader: shader, vertices: vertices, indices: indices)
self.loadTexture((shape.material?.diffuseTextureMapFilePath?.lastPathComponent)! as String)
}
static func verticesAndIndicesFrom(shape: ObjLoading.Shape) -> ([Vertex], [GLuint]) {
var vertices: [Vertex] = []
var indices: [GLuint] = []
var index: GLuint = 0
for vertexIndexes in shape.faces {
for vertexIndex in vertexIndexes {
// Will cause an out of bounds error
// if vIndex, nIndex or tIndex is not normalized
// to be local to the internal data of the shape
// instead of global to the file as per the
// .obj specification
let (vertexVector, normalVector, textureVector) = shape.dataForVertexIndex(vertexIndex)
var v = Vertex()
if let vertexVector = vertexVector {
v.x = GLfloat(vertexVector[0])
v.y = GLfloat(vertexVector[1])
v.z = GLfloat(vertexVector[2])
}
if let normalVector = normalVector {
v.nx = GLfloat(normalVector[0])
v.ny = GLfloat(normalVector[1])
v.nz = GLfloat(normalVector[2])
}
if let textureVector = textureVector {
v.u = GLfloat(textureVector[0])
v.v = GLfloat(textureVector[1])
}
vertices.append(v)
indices.append(index)
index = index + 1
}
}
return (vertices, indices)
}
override func updateWithDelta(_ dt: TimeInterval) {
self.rotationY = self.rotationY + Float(Double.pi * dt / 8)
}
}
| apache-2.0 |
bsmith11/ScoreReporter | ScoreReporter/Controllers/NavigationItemView.swift | 1 | 1270 | //
// NavigationItemView.swift
// ScoreReporter
//
// Created by Bradley Smith on 11/1/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import UIKit
class NavigationItemView: UIView {
fileprivate let titleLabel = UILabel(frame: .zero)
var title: String? {
return titleLabel.text
}
var centerPosition: CGPoint {
let x = (superview?.bounds.width ?? 0.0) / 2.0
let y = layer.position.y
return CGPoint(x: x, y: y)
}
init?(viewController: UIViewController) {
guard let title = viewController.title else {
return nil
}
let attributes = viewController.navigationController?.navigationBar.titleTextAttributes
titleLabel.attributedText = NSAttributedString(string: title, attributes: attributes)
titleLabel.sizeToFit()
let width = titleLabel.bounds.width
let height = max(27.0, titleLabel.bounds.height)
let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
super.init(frame: frame)
titleLabel.center = CGPoint(x: width / 2.0, y: height / 2.0)
addSubview(titleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
iSapozhnik/FamilyPocket | FamilyPocket/Data/WatchSessionManager.swift | 1 | 2456 | //
// WatchSessionManager.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/24/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import Foundation
import WatchConnectivity
class WatchSessionManager: NSObject, WCSessionDelegate {
static let sharedManager = WatchSessionManager()
private override init() {
super.init()
}
private let session: WCSession? = WCSession.isSupported() ? WCSession.default() : nil
fileprivate var validSession: WCSession? {
// paired - the user has to have their device paired to the watch
// watchAppInstalled - the user must have your watch app installed
// Note: if the device is paired, but your watch app is not installed
// consider prompting the user to install it for a better experience
if let session = session, session.isPaired && session.isWatchAppInstalled {
return session
}
return nil
}
func startSession() {
session?.delegate = self
session?.activate()
}
// public func updateApplicationContext(applicationContext: [String : Any]) throws {
// if let session = validSession {
// do {
// try session.updateApplicationContext(applicationContext)
// } catch let error {
// throw error
// }
// }
// }
//MARK: delegate
@available(iOS 9.3, *)
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("activationDidCompleteWith state \(activationState.rawValue)")
}
public func sessionDidBecomeInactive(_ session: WCSession) {
}
public func sessionDidDeactivate(_ session: WCSession) {
}
}
// MARK: Application Context
// use when your app needs only the latest information
// if the data was not sent, it will be replaced
extension WatchSessionManager {
// This is where the magic happens!
// Yes, that's it!
// Just updateApplicationContext on the session!
func updateApplicationContext(applicationContext: [String : Any]) throws {
if let session = validSession {
do {
try session.updateApplicationContext(applicationContext)
} catch let error {
throw error
}
}
}
}
| mit |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/iOS/Extensions/ItemViewController+iOS.swift | 1 | 3124 |
import Foundation
import struct PopcornKit.Show
import struct PopcornKit.Movie
import PopcornTorrent.PTTorrentDownloadManager
extension ItemViewController {
var watchlistButtonImage: UIImage? {
return media.isAddedToWatchlist ? UIImage(named: "Watchlist On") : UIImage(named: "Watchlist Off")
}
override func viewDidLoad() {
super.viewDidLoad()
PTTorrentDownloadManager.shared().add(self)
downloadButton.addTarget(self, action: #selector(stopDownload(_:)), for: .applicationReserved)
titleLabel.text = media.title
summaryTextView.text = media.summary
if let image = media.mediumCoverImage, let url = URL(string: image) {
imageView?.af_setImage(withURL: url)
}
if let movie = media as? Movie {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .short
formatter.allowedUnits = [.hour, .minute]
subtitleLabel.text = formatter.string(from: TimeInterval(movie.runtime) * 60) ?? "0 min"
genreLabel?.text = movie.genres.first?.localizedCapitalized.localized ?? ""
let info = NSMutableAttributedString(string: "\(movie.year)")
attributedString(with: 10, between: movie.certification, "HD", "CC").forEach({info.append($0)})
infoLabel.attributedText = info
ratingView.rating = Double(movie.rating)/20.0
movie.trailerCode == nil ? trailerButton.removeFromSuperview() : ()
} else if let show = media as? Show {
subtitleLabel.text = show.network ?? "TV"
genreLabel?.text = show.genres.first?.localizedCapitalized.localized ?? ""
let info = NSMutableAttributedString(string: "\(show.year)")
attributedString(with: 10, between: "HD", "CC").forEach({info.append($0)})
infoLabel.attributedText = info
ratingView.rating = Double(show.rating)/20.0
trailerButton.isHidden = true
downloadButton.isHidden = true
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
let isCompact = traitCollection.horizontalSizeClass == .compact
for constraint in compactConstraints {
constraint.priority = UILayoutPriority(rawValue: UILayoutPriority.RawValue(isCompact ? 999 : 240))
}
for constraint in regularConstraints {
constraint.priority = UILayoutPriority(rawValue: UILayoutPriority.RawValue(isCompact ? 240 : 999))
}
titleLabel.font = isCompact ? UIFont.systemFont(ofSize: 40, weight: UIFont.Weight.heavy) : UIFont.systemFont(ofSize: 50, weight: UIFont.Weight.heavy)
// Don't animate if when the view is being first presented.
if previousTraitCollection != nil {
UIView.animate(withDuration: .default, animations: {
self.view.layoutIfNeeded()
})
}
}
}
| gpl-3.0 |
myandy/shi_ios | shishi/Data/DataContainer.swift | 1 | 1643 | //
// DataContainer.swift
// shishi
//
// Created by tb on 2017/4/29.
// Copyright © 2017年 andymao. All rights reserved.
//
import UIKit
class DataContainer: NSObject {
open static let `default`: DataContainer = {
return DataContainer()
}()
lazy private(set) var duiShiNetwork: DuishiNetwork = {
return AppConfig.isStubbingNetwork ? Networking.newDuishiStubbingNetwork() : Networking.newDuishiNetwork()
}()
//字体变化每次步径
private let increaseFontStep: CGFloat = AppConfig.Constants.increaseFontStep
//调整字体大小
public var fontOffset: CGFloat = 0
override init() {
self.fontOffset = CGFloat(SSUserDefaults.standard.float(forKey: SSUserDefaults.Keys.fontOffset))
}
//增加字体大小
public func increaseFontOffset() -> CGFloat {
return self.updateFontOffset(pointSizeStep: increaseFontStep)
}
//减少字体大小
public func reduceFontOffset() -> CGFloat {
return self.updateFontOffset(pointSizeStep: -increaseFontStep)
}
public func updateFontOffset(pointSizeStep: CGFloat) -> CGFloat {
let newFontSize = self.fontOffset + pointSizeStep
self.fontOffset = newFontSize
self.saveFontOffset()
SSNotificationCenter.default.post(name: SSNotificationCenter.Names.updateFontSize, object: nil)
return newFontSize
}
fileprivate func saveFontOffset() {
SSUserDefaults.standard.set(self.fontOffset, forKey: SSUserDefaults.Keys.fontOffset)
SSUserDefaults.standard.synchronize()
}
}
| apache-2.0 |
material-motion/material-motion-swift | src/operators/rewriteRange.swift | 2 | 1345 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
extension MotionObservableConvertible where T: Subtractable, T: Lerpable {
/**
Linearly interpolate the incoming value along the given range to the destination range.
*/
public func rewriteRange<U>
( start: T,
end: T,
destinationStart: U,
destinationEnd: U
) -> MotionObservable<U>
where U: Lerpable, U: Subtractable, U: Addable {
return _map {
let position = $0 - start
let vector = end - start
let progress = position.progress(along: vector)
let destinationVector = destinationEnd - destinationStart
let destinationPosition = destinationVector.project(progress: progress)
return destinationStart + destinationPosition
}
}
}
| apache-2.0 |
fireflyexperience/TransitioningKit | Example/Example/ThirdViewController.swift | 2 | 437 | import UIKit
class ThirdViewController: UIViewController {
// MARK: Public
override var transitioningDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.strongTransitioningDelegate = transitioningDelegate
}
}
private var strongTransitioningDelegate: UIViewControllerTransitioningDelegate?
@IBAction func dismissViewController() {
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit |
TonyReet/AutoSQLite.swift | AutoSQLite.swift/AutoSQLite.swift/AppDelegate.swift | 1 | 2218 | //
// AppDelegate.swift
// AutoSQLite.swift
//
// Created by QJ Technology on 2017/5/11.
// Copyright © 2017年 TonyReet. All rights reserved.
//
import UIKit
import AutoSQLiteSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 打开打印
SQLiteManager.shared.printDebug = true
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:.
}
}
| mit |
Chaatz/iOSSwiftHelpers | Sources/DarwinNotification.swift | 1 | 2581 | //
// DarwinNotification.swift
// chaatz
//
// Created by Mingloan Chan on 2/16/17.
// Copyright © 2017 Chaatz. All rights reserved.
//
import Foundation
// MARK: - Darwin Notifications Setup
public func registerForDarwinNotifications(notificationName: CFNotificationName) {
/*
func CFNotificationCenterAddObserver(_ center: CFNotificationCenter!,
_ observer: UnsafeRawPointer!,
_ callBack: CoreFoundation.CFNotificationCallback!,
_ name: CFString!,
_ object: UnsafeRawPointer!,
_ suspensionBehavior: CFNotificationSuspensionBehavior)
*/
// CFNotificationCallback: (CFNotificationCenter?, UnsafeMutableRawPointer?, CFNotificationName?, UnsafeRawPointer?, CFDictionary?)
let callback: CFNotificationCallback = { center, observer, name, object, userInfo in
guard let notificationName = name else { return }
//debug_print("darwin callback")
//debug_print("darwin notification name: \(notificationName)")
DispatchQueue.main.async {
NotificationCenter.default.post(name: Notification.Name(rawValue: notificationName.notificationString()),
object: nil,
userInfo: nil)
}
}
let notificationCallback: CFNotificationCallback = callback
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
notificationCallback,
notificationName.rawValue,
nil,
CFNotificationSuspensionBehavior.deliverImmediately)
}
public func unregisterForDarwinNotifications(notificationName: CFNotificationName) {
CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
notificationName,
nil)
}
public func sendDarwinNotification(notificationName: CFNotificationName) {
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),
notificationName,
nil,
nil,
true)
}
| mit |
ScoutHarris/WordPress-iOS | WordPress/Classes/Services/RoleService.swift | 4 | 2144 | import Foundation
import WordPressKit
/// Service providing access to user roles
///
struct RoleService {
let blog: Blog
fileprivate let context: NSManagedObjectContext
fileprivate let remote: PeopleServiceRemote
fileprivate let siteID: Int
init?(blog: Blog, context: NSManagedObjectContext) {
guard let api = blog.wordPressComRestApi(), let dotComID = blog.dotComID as? Int else {
return nil
}
self.remote = PeopleServiceRemote(wordPressComRestApi: api)
self.siteID = dotComID
self.blog = blog
self.context = context
}
/// Returns a role from Core Data with the given slug.
///
func getRole(slug: String) -> Role? {
let predicate = NSPredicate(format: "slug = %@ AND blog = %@", slug, blog)
return context.firstObject(ofType: Role.self, matching: predicate)
}
/// Forces a refresh of roles from the api and stores them in Core Data.
///
func fetchRoles(success: @escaping ([Role]) -> Void, failure: @escaping (Error) -> Void) {
remote.getUserRoles(siteID, success: { (remoteRoles) in
let roles = self.mergeRoles(remoteRoles)
success(roles)
}, failure: failure)
}
}
private extension RoleService {
func mergeRoles(_ remoteRoles: [RemoteRole]) -> [Role] {
let existingRoles = blog.roles ?? []
var rolesToKeep = [Role]()
for (order, remoteRole) in remoteRoles.enumerated() {
let role: Role
if let existingRole = existingRoles.first(where: { $0.slug == remoteRole.slug }) {
role = existingRole
} else {
role = context.insertNewObject(ofType: Role.self)
}
role.blog = blog
role.slug = remoteRole.slug
role.name = remoteRole.name
role.order = order as NSNumber
rolesToKeep.append(role)
}
let rolesToDelete = existingRoles.subtracting(rolesToKeep)
rolesToDelete.forEach(context.delete(_:))
ContextManager.sharedInstance().save(context)
return rolesToKeep
}
}
| gpl-2.0 |
vapor-community/stripe | Tests/StripeTests/ProviderTests.swift | 1 | 21 | // TODO: - Implement
| mit |
mgadda/zig | Sources/MessagePackEncoder/MessagePackReferencingEncoder.swift | 1 | 1786 | //
// MessagePackReferencingEncoder.swift
// MessagePackEncoder
//
// Created by Matt Gadda on 9/27/17.
//
import Foundation
import MessagePack
internal class MessagePackReferencingEncoder : _MessagePackEncoder {
private enum Reference {
case array(MutableArrayReference<BoxedValue>, Int)
case dictionary(MutableDictionaryReference<BoxedValue, BoxedValue>, String)
}
let encoder: _MessagePackEncoder
private let reference: Reference
init(referencing encoder: _MessagePackEncoder, at index: Int, wrapping array: MutableArrayReference<BoxedValue>) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath)
codingPath.append(MessagePackKey(index: index))
}
init(referencing encoder: _MessagePackEncoder, at key: CodingKey, wrapping dictionary: MutableDictionaryReference<BoxedValue, BoxedValue>) {
self.encoder = encoder
self.reference = .dictionary(dictionary, key.stringValue)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
internal override var canEncodeNewValue: Bool {
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
deinit {
let value: BoxedValue
switch self.storage.count {
case 0: value = BoxedValue.map(MutableDictionaryReference<BoxedValue, BoxedValue>())
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let arrayRef, let index):
arrayRef.insert(value, at: index)
case .dictionary(let dictRef, let key):
dictRef[BoxedValue.string(key)] = value
}
}
}
| mit |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/Shops/PurchaseQuestCall.swift | 1 | 544 | //
// PurchaseQuestCall.swift
// Habitica API Client
//
// Created by Phillip Thelen on 21.05.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
public class PurchaseQuestCall: ResponseObjectCall<UserProtocol, APIUser> {
public init(key: String, stubHolder: StubHolderProtocol? = StubHolder(responseCode: 200, stubFileName: "user.json")) {
super.init(httpMethod: .POST, endpoint: "user/buy-quest/\(key)", postData: nil, stubHolder: stubHolder)
}
}
| gpl-3.0 |
madeatsampa/MacMagazine-iOS | MacMagazine/SplashViewController.swift | 1 | 1572 | //
// SplashViewController.swift
// MacMagazine
//
// Created by Cassio Rossi on 08/06/2019.
// Copyright © 2019 MacMagazine. All rights reserved.
//
import UIKit
class SplashViewController: UIViewController {
@IBOutlet private weak var logo: UIImageView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
view.backgroundColor = Settings().isDarkMode ? .black : .white
logo.image = UIImage(named: "splash\(Settings().isDarkMode ? "_dark" : "")")
delay(0.6) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let controller = storyboard.instantiateViewController(withIdentifier: "main") as? UITabBarController,
let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let splitViewController = controller.viewControllers?.first as? UISplitViewController,
let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
return
}
controller.delegate = appDelegate
splitViewController.delegate = appDelegate
splitViewController.preferredDisplayMode = .allVisible
splitViewController.preferredPrimaryColumnWidthFraction = 0.33
UIView.transition(with: window,
duration: 0.4,
options: .transitionCrossDissolve,
animations: {
window.rootViewController = controller
})
}
}
}
| mit |
mrscorpion/MRSwiftTarget | MSSwiftLessons/MSFundamentals/Day 04/08-News(解析展示数据)/News/Classes/Tools/NetworkTools.swift | 1 | 1147 | //
// NetworkTools.swift
// News
//
// Created by 1 on 16/9/28.
// Copyright © 2016年 mr. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetworkTools {
// class方法 --> OC +开头
class func requestData(URLString : String, type : MethodType, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 1.校验是否有结果
/*
if let result = response.result.value {
finishedCallback(result)
} else {
print(response.result.error)
}
*/
// 1.校验是否有结果
guard let result = response.result.value else {
print(response.result.error ?? "error")
return
}
// 2.将结果回调出去
finishedCallback(result)
}
}
}
| mit |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerAppTests/EyepetizerAppTests.swift | 1 | 996 | //
// EyepetizerAppTests.swift
// EyepetizerAppTests
//
// Created by 梁亦明 on 16/3/10.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import XCTest
@testable import EyepetizerApp
class EyepetizerAppTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
FabrizioBrancati/SwiftyBot | Sources/Telegram/Routes.swift | 1 | 1668 | //
// Routes.swift
// SwiftyBot
//
// The MIT License (MIT)
//
// Copyright (c) 2016 - 2019 Fabrizio Brancati.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Vapor
/// Registering Telegram's routes.
public func routes(_ router: Router) throws {
/// Setting up the POST request with Telegram secret key.
/// With a secret path to be sure that nobody else knows that URL.
/// More info [here](https://core.telegram.org/bots/api#setwebhook).
router.post("telegram", telegramSecret) { request -> HTTPResponse in
return try Response(for: request).create(on: request)
}
}
| mit |
shopgun/shopgun-ios-sdk | Sources/TjekPublicationViewer/PagedPublication/PagedPublicationView+Verso.swift | 1 | 7681 | ///
/// Copyright (c) 2018 Tjek. All rights reserved.
///
import UIKit
import Verso
// MARK: - Verso DataSource
extension PagedPublicationView: VersoViewDataSource {
// Return how many pages are on each spread
public func spreadConfiguration(with size: CGSize, for verso: VersoView) -> VersoSpreadConfiguration {
let pageCount = self.pageCount
let lastPageIndex = max(0, pageCount - 1)
var totalPageCount = pageCount
// there is an outro, and we have some pages, so add outro to the pages list
if self.outroPageIndex != nil {
totalPageCount += 1
}
// how far between the page spreads
let spreadSpacing: CGFloat = 20
// TODO: compare verso aspect ratio to publication aspect ratio
let isLandscape: Bool = size.width > size.height
return VersoSpreadConfiguration.buildPageSpreadConfiguration(pageCount: totalPageCount, spreadSpacing: spreadSpacing, spreadPropertyConstructor: { (_, nextPageIndex) in
// it's the outro (has an outro, we have some real pages, and next page is after the last pageIndex
if let outroProperties = self.outroViewProperties, nextPageIndex == self.outroPageIndex {
return (1, outroProperties.maxZoom, outroProperties.width)
}
let spreadPageCount: Int
if nextPageIndex == 0
|| nextPageIndex == lastPageIndex
|| isLandscape == false {
spreadPageCount = 1
} else {
spreadPageCount = 2
}
return (spreadPageCount, 3.0, 1.0)
})
}
public func pageViewClass(on pageIndex: Int, for verso: VersoView) -> VersoPageViewClass {
if let outroProperties = self.outroViewProperties, pageIndex == self.outroPageIndex {
return outroProperties.viewClass
} else {
return PagedPublicationView.PageView.self
}
}
public func configure(pageView: VersoPageView, for verso: VersoView) {
if let pubPageView = pageView as? PagedPublicationView.PageView {
pubPageView.imageLoader = self.imageLoader
pubPageView.delegate = self
let pageProperties = self.pageViewProperties(forPageIndex: pubPageView.pageIndex)
pubPageView.configure(with: pageProperties)
} else if type(of: pageView) === self.outroViewProperties?.viewClass {
dataSourceWithDefaults.configure(outroView: pageView, for: self)
}
}
public func spreadOverlayView(overlaySize: CGSize, pageFrames: [Int: CGRect], for verso: VersoView) -> UIView? {
// we have an outro and it is one of the pages we are being asked to add an overlay for
if let outroPageIndex = self.outroPageIndex, pageFrames[outroPageIndex] != nil {
return nil
}
let spreadHotspots = self.hotspotModels(onPageIndexes: IndexSet(pageFrames.keys))
// configure the overlay
self.hotspotOverlayView.isHidden = self.pageCount == 0
self.hotspotOverlayView.delegate = self
self.hotspotOverlayView.frame.size = overlaySize
self.hotspotOverlayView.updateWithHotspots(spreadHotspots, pageFrames: pageFrames)
// disable tap when double-tapping
if let doubleTap = contentsView.versoView.zoomDoubleTapGestureRecognizer {
self.hotspotOverlayView.tapGesture?.require(toFail: doubleTap)
}
return self.hotspotOverlayView
}
public func adjustPreloadPageIndexes(_ preloadPageIndexes: IndexSet, visiblePageIndexes: IndexSet, for verso: VersoView) -> IndexSet? {
guard let outroPageIndex = self.outroPageIndex, let lastIndex = visiblePageIndexes.last, outroPageIndex - lastIndex < 10 else {
return nil
}
// add outro to preload page indexes if we have scrolled close to it
var adjustedPreloadPages = preloadPageIndexes
adjustedPreloadPages.insert(outroPageIndex)
return adjustedPreloadPages
}
}
// MARK: - Verso Delegate
extension PagedPublicationView: VersoViewDelegate {
public func currentPageIndexesChanged(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) {
// this is a bit of a hack to cancel the touch-gesture when we start scrolling
self.hotspotOverlayView.touchGesture?.isEnabled = false
self.hotspotOverlayView.touchGesture?.isEnabled = true
// remove the outro index when refering to page indexes outside of PagedPub
var currentExOutro = currentPageIndexes
var oldExOutro = oldPageIndexes
if let outroIndex = self.outroPageIndex {
currentExOutro.remove(outroIndex)
oldExOutro.remove(outroIndex)
}
delegate?.pageIndexesChanged(current: currentExOutro, previous: oldExOutro, in: self)
// check if the outro has newly appeared or disappeared (not if it's in both old & current)
if let outroIndex = outroPageIndex, let outroView = verso.getPageViewIfLoaded(outroIndex) {
let addedIndexes = currentPageIndexes.subtracting(oldPageIndexes)
let removedIndexes = oldPageIndexes.subtracting(currentPageIndexes)
if addedIndexes.contains(outroIndex) {
delegate?.outroDidAppear(outroView, in: self)
outroOutsideTapGesture.isEnabled = true
} else if removedIndexes.contains(outroIndex) {
delegate?.outroDidDisappear(outroView, in: self)
outroOutsideTapGesture.isEnabled = false
}
}
updateContentsViewLabels(pageIndexes: currentPageIndexes, additionalLoading: contentsView.properties.showAdditionalLoading)
}
public func currentPageIndexesFinishedChanging(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) {
// make a new spreadEventHandler (unless it's the outro)
if self.isOutroPage(inPageIndexes: currentPageIndexes) == false {
self.eventHandler?.didOpenPublicationPages(currentPageIndexes)
}
// remove the outro index when refering to page indexes outside of PagedPub
var currentExOutro = currentPageIndexes
var oldExOutro = oldPageIndexes
if let outroIndex = self.outroPageIndex {
currentExOutro.remove(outroIndex)
oldExOutro.remove(outroIndex)
}
delegate?.pageIndexesFinishedChanging(current: currentExOutro, previous: oldExOutro, in: self)
// cancel the loading of the zoomimage after a page disappears
oldPageIndexes.subtracting(currentPageIndexes).forEach {
if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView {
pageView.clearZoomImage(animated: false)
}
}
}
public func didStartZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) {
hotspotOverlayView.isZooming = true
}
public func didEndZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) {
delegate?.didEndZooming(zoomScale: zoomScale)
pageIndexes.forEach {
if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView {
pageView.startLoadingZoomImageIfNotLoaded()
}
}
hotspotOverlayView.isZooming = false
}
}
| mit |
practicalswift/swift | test/SILGen/assignment.swift | 9 | 2095 | // RUN: %target-swift-emit-silgen -enforce-exclusivity=checked %s | %FileCheck %s
class C {}
struct A {}
struct B { var owner: C }
var a = A()
// CHECK-LABEL: sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
// CHECK: assign {{%.*}} to {{%.*}} : $*A
// CHECK: destroy_value {{%.*}} : $B
// CHECK: } // end sil function 'main'
(a, _) = (A(), B(owner: C()))
class D { var child: C = C() }
// Verify that the LHS is formally evaluated before the RHS.
// CHECK-LABEL: sil hidden [ossa] @$s10assignment5test1yyF : $@convention(thin) () -> () {
func test1() {
// CHECK: [[T0:%.*]] = metatype $@thick D.Type
// CHECK: [[CTOR:%.*]] = function_ref @$s10assignment1DC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[D:%.*]] = apply [[CTOR]]([[T0]])
// CHECK: [[T0:%.*]] = metatype $@thick C.Type
// CHECK: [[CTOR:%.*]] = function_ref @$s10assignment1CC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[C:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thick C.Type) -> @owned C
// CHECK: [[SETTER:%.*]] = class_method [[D]] : $D, #D.child!setter.1
// CHECK: apply [[SETTER]]([[C]], [[D]])
// CHECK: destroy_value [[D]]
D().child = C()
}
// rdar://32039566
protocol P {
var left: Int {get set}
var right: Int {get set}
}
// Verify that the access to the LHS does not begin until after the
// RHS is formally evaluated.
// CHECK-LABEL: sil hidden [ossa] @$s10assignment15copyRightToLeft1pyAA1P_pz_tF : $@convention(thin) (@inout P) -> () {
func copyRightToLeft(p: inout P) {
// CHECK: bb0(%0 : $*P):
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*P
// CHECK: [[READ_OPEN:%.*]] = open_existential_addr immutable_access [[READ]]
// CHECK: end_access [[READ]] : $*P
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*P
// CHECK: [[WRITE_OPEN:%.*]] = open_existential_addr mutable_access [[WRITE]]
// CHECK: end_access [[WRITE]] : $*P
p.left = p.right
}
// SR-5919
func stupidGames() -> ((), ()) {
return ((), ())
}
func assignToNestedVoid() {
let _: ((), ()) = stupidGames()
} | apache-2.0 |
FUNIKImegane/FunikiSDK | FunikiSDKExampleSwift/FunikiSDKExampleSwift/FunikiSDKMotionViewController.swift | 1 | 4652 | //
// Created by Matilde Inc.
// Copyright (c) 2015 FUN'IKI Project. All rights reserved.
//
import UIKit
class FunikiSDKMotionViewController: UIViewController, MAFunikiManagerDelegate, MAFunikiManagerDataDelegate {
let funikiManager = MAFunikiManager.sharedInstance()
var baseSize:CGRect!
var accXRect:CGRect!
var accYRect:CGRect!
var accZRect:CGRect!
var rotXRect:CGRect!
var rotYRect:CGRect!
var rotZRect:CGRect!
@IBOutlet var accXView:UIView!
@IBOutlet var accYView:UIView!
@IBOutlet var accZView:UIView!
@IBOutlet var rotXView:UIView!
@IBOutlet var rotYView:UIView!
@IBOutlet var rotZView:UIView!
@IBOutlet var sensorSwitch:UISwitch!
// MARK: - UIViewController
override func viewDidLoad() {
baseSize = accXView.frame
baseSize.size.width = baseSize.size.width / 2
accXRect = accXView.frame
accYRect = accYView.frame
accZRect = accZView.frame
rotXRect = rotXView.frame
rotYRect = rotYView.frame
rotZRect = rotZView.frame
setBarHidden(hidden: true)
}
override func viewWillAppear(_ animated: Bool) {
funikiManager?.delegate = self
funikiManager?.dataDelegate = self
self.updateSensorSwitch()
super.viewWillAppear(animated)
}
override var shouldAutorotate: Bool{
return false
}
// MARK: -
func setBarHidden(hidden:Bool) {
accXView.isHidden = hidden
accYView.isHidden = hidden
accZView.isHidden = hidden
rotXView.isHidden = hidden
rotYView.isHidden = hidden
rotZView.isHidden = hidden
}
func updateSensorSwitch() {
if (funikiManager?.isConnected)! {
sensorSwitch.isEnabled = true
}
else {
sensorSwitch.isEnabled = false
sensorSwitch.setOn(false, animated: true)
}
}
// MARK: - MAFunikiManagerDelegate
func funikiManagerDidConnect(_ manager: MAFunikiManager!) {
print("SDK Version\(String(describing: MAFunikiManager.funikiSDKVersionString()))")
print("Firmware Revision\(String(describing: manager.firmwareRevision))")
updateSensorSwitch()
}
func funikiManagerDidDisconnect(_ manager: MAFunikiManager!, error: Error!) {
if let actualError = error {
print(actualError)
}
updateSensorSwitch()
}
func funikiManager(_ manager: MAFunikiManager!, didUpdateCentralState state: CBCentralManagerState) {
updateSensorSwitch()
}
// MARK: - MAFunikiManagerDataDelegate
func funikiManager(_ manager: MAFunikiManager!, didUpdate motionData: MAFunikiMotionData!) {
accXRect.size.width = CGFloat(motionData.acceleration.x) * baseSize.size.width
accYRect.size.width = CGFloat(motionData.acceleration.y) * baseSize.size.width
accZRect.size.width = CGFloat(motionData.acceleration.z) * baseSize.size.width
rotXRect.size.width = ((CGFloat(motionData.rotationRate.x) * baseSize.size.width) / 250.0) * 2.0
rotYRect.size.width = ((CGFloat(motionData.rotationRate.y) * baseSize.size.width) / 250.0) * 2.0
rotZRect.size.width = ((CGFloat(motionData.rotationRate.z) * baseSize.size.width) / 250.0) * 2.0
self.accXView.frame = accXRect
self.accYView.frame = accYRect
self.accZView.frame = accZRect
self.rotXView.frame = rotXRect
self.rotYView.frame = rotYRect
self.rotZView.frame = rotZRect
}
func funikiManager(_ manager: MAFunikiManager!, didPushButton buttonEventType: MAFunikiManagerButtonEventType) {
var string = "ButtonEventType"
switch (buttonEventType){
case .singlePush:
string = "ButtonEventTypeSinglePush"
break
case .doublePush:
string = "ButtonEventTypeDoublePush"
default:
string = "ButtonEventTypeUnknown"
break
}
let alertView = UIAlertView(title: "DidPushButton", message: string, delegate: nil, cancelButtonTitle: "OK")
alertView.show()
}
// MARK: - Action
@IBAction func switchDidChange(_ sender:UISwitch) {
if sensorSwitch.isOn {
funikiManager?.startMotionSensor()
setBarHidden(hidden: false)
}
else {
funikiManager?.stopMotionSensor()
setBarHidden(hidden: true)
}
}
}
| mit |
Legoless/Saystack | Code/Extensions/Core/Log+Utilities.swift | 1 | 982 | //
// Log+Utilities.swift
// Demo
//
// Created by Dal Rupnik on 29/08/2017.
// Copyright © 2017 Unified Sense. All rights reserved.
//
import os.log
@available(iOS 10.0, OSX 10.12, *)
public extension OSLog {
func info (_ message: StaticString, _ args: Any...) {
let varArgs = args.map { $0 as! CVarArg }
print("\(varArgs)")
os_log(message, log: self, type: .info, varArgs)
}
func debug (_ message: StaticString, _ args: Any...) {
let varArgs = args.map { $0 as! CVarArg }
os_log(message, log: self, type: .debug, varArgs)
}
func error (_ message: StaticString, _ args: Any...) {
let varArgs = args.map { $0 as! CVarArg }
os_log(message, log: self, type: .error, varArgs)
}
func fault (_ message: StaticString, _ args: Any...) {
let varArgs = args.map { $0 as! CVarArg }
os_log(message, log: self, type: .fault, varArgs)
}
}
| mit |
FromF/MTSearchSwift | src/MyRecipe/AppDelegate.swift | 1 | 2114 | //
// AppDelegate.swift
// MyRecipe
//
// Created by FromF on 2016/09/15.
// Copyright © 2016年 Swift-Beginners. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:.
}
}
| mit |
NordicSemiconductor/IOS-Pods-DFU-Library | Example/iOSDFULibrary/View Controllers/MainNavigationViewController.swift | 1 | 2453 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
class MainNavigationViewController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.backgroundColor = UIColor.dynamicColor(light: .nordicBlue, dark: .black)
navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
navigationBar.standardAppearance = navBarAppearance
navigationBar.scrollEdgeAppearance = navBarAppearance
} else {
// Fallback on earlier versions
}
}
}
| bsd-3-clause |
fitpay/fitpay-ios-sdk | FitpaySDK/Rest/RestClient.swift | 1 | 16845 | import Foundation
import Alamofire
open class RestClient: NSObject {
typealias ResultCollectionHandler<T: Codable> = (_ result: ResultCollection<T>?, _ error: ErrorResponse?) -> Void
typealias RequestHandler = (_ resultValue: Any?, _ error: ErrorResponse?) -> Void
/**
FitPay uses conventional HTTP response codes to indicate success or failure of an API request. In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that resulted from the provided information (e.g. a required parameter was missing, etc.), and codes in the 5xx range indicate an error with FitPay servers.
Not all errors map cleanly onto HTTP response codes, however. When a request is valid but does not complete successfully (e.g. a card is declined), we return a 402 error code.
- OK: Everything worked as expected
- BadRequest: Often missing a required parameter
- Unauthorized: No valid API key provided
- RequestFailed: Parameters were valid but request failed
- NotFound: The requested item doesn't exist
- ServerError[0-3]: Something went wrong on FitPay's end
*/
public enum ErrorCode: Int, Error, RawIntValue {
case ok = 200
case badRequest = 400
case unauthorized = 401
case requestFailed = 402
case notFound = 404
case serverError0 = 500
case serverError1 = 502
case serverError2 = 503
case serverError3 = 504
}
static let fpKeyIdKey: String = "fp-key-id"
var session: RestSession
var keyPair: SECP256R1KeyPair = SECP256R1KeyPair()
var key: EncryptionKey?
var secret: Data {
let secret = self.keyPair.generateSecretForPublicKey(key?.serverPublicKey ?? "")
if secret == nil || secret?.count == 0 {
log.warning("REST_CLIENT: Encription secret is empty.")
}
return secret ?? Data()
}
var restRequest: RestRequestable = RestRequest()
/**
Completion handler
- parameter ErrorType?: Provides error object, or nil if no error occurs
*/
public typealias DeleteHandler = (_ error: ErrorResponse?) -> Void
/**
Completion handler
- parameter ErrorType?: Provides error object, or nil if no error occurs
*/
public typealias ConfirmHandler = (_ error: ErrorResponse?) -> Void
// MARK: - Lifecycle
public init(session: RestSession, restRequest: RestRequestable? = nil) {
self.session = session
if let restRequest = restRequest {
self.restRequest = restRequest
}
}
// MARK: - Public Functions
public func getRootLinks(completion: @escaping (_ rootLinks: RootLinks?, _ error: ErrorResponse?) -> Void) {
let url = FitpayConfig.apiURL
restRequest.makeRequest(url: url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in
guard let resultValue = resultValue as? [String: Any] else {
completion(nil, error)
return
}
let rootLinks = try? RootLinks(resultValue)
completion(rootLinks, error)
}
}
public func confirm(_ url: String, executionResult: NonAPDUCommitState, completion: @escaping ConfirmHandler) {
let params = ["result": executionResult.description]
makePostCall(url, parameters: params, completion: completion)
}
public func acknowledge(_ url: String, completion: @escaping ConfirmHandler) {
makePostCall(url, parameters: nil, completion: completion)
}
public func getPlatformConfig(completion: @escaping (_ platform: PlatformConfig?, _ error: ErrorResponse?) -> Void) {
restRequest.makeRequest(url: FitpayConfig.apiURL + "/mobile/config", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in
guard let resultValue = resultValue as? [String: Any] else {
completion(nil, error)
return
}
let config = try? PlatformConfig(resultValue["ios"])
completion(config, error)
}
}
public func getCountries(completion: @escaping (_ countries: CountryCollection?, _ error: ErrorResponse?) -> Void) {
let url = FitpayConfig.apiURL + "/iso/countries"
restRequest.makeRequest(url: url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in
guard let resultValue = resultValue as? [String: Any] else {
completion(nil, error)
return
}
let countryCollection = try? CountryCollection(["countries": resultValue])
countryCollection?.client = self
completion(countryCollection, error)
}
}
// MARK: - Internal
func collectionItems<T>(_ url: String, completion: @escaping (_ resultCollection: ResultCollection<T>?, _ error: ErrorResponse?) -> Void) -> T? {
makeGetCall(url, parameters: nil, completion: completion)
return nil
}
func makeDeleteCall(_ url: String, completion: @escaping DeleteHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(error) }
return
}
self?.restRequest.makeRequest(url: url, method: .delete, parameters: nil, encoding: URLEncoding.default, headers: headers) { (_, error) in
completion(error)
}
}
}
func makeGetCall<T: Codable>(_ url: String, limit: Int, offset: Int, overrideHeaders: [String: String]? = nil, completion: @escaping ResultCollectionHandler<T>) {
let parameters = ["limit": "\(limit)", "offset": "\(offset)"]
makeGetCall(url, parameters: parameters, overrideHeaders: overrideHeaders, completion: completion)
}
func makeGetCall<T: Serializable>(_ url: String, parameters: [String: Any]?, overrideHeaders: [String: String]? = nil, completion: @escaping (T?, ErrorResponse?) -> Void) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard var headers = headers else {
DispatchQueue.main.async { completion(nil, error) }
return
}
if let overrideHeaders = overrideHeaders {
for key in overrideHeaders.keys {
headers[key] = overrideHeaders[key]
}
}
self?.restRequest.makeRequest(url: url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) { (resultValue, error) in
guard let strongSelf = self else { return }
guard let resultValue = resultValue else {
completion(nil, error)
return
}
let result = try? T(resultValue)
(result as? ClientModel)?.client = self
(result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey])
completion(result, error)
}
}
}
func makePostCall(_ url: String, parameters: [String: Any]?, completion: @escaping ConfirmHandler) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(error) }
return
}
self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (_, error) in
completion(error)
}
}
}
func makePostCall<T: Serializable>(_ url: String, parameters: [String: Any]?, completion: @escaping (T?, ErrorResponse?) -> Void) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(nil, error) }
return
}
self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in
guard let strongSelf = self else { return }
guard let resultValue = resultValue else {
completion(nil, error)
return
}
let result = try? T(resultValue)
(result as? ClientModel)?.client = self
(result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey])
completion(result, error)
}
}
}
func makePatchCall<T: Serializable>(_ url: String, parameters: [String: Any]?, encoding: ParameterEncoding, completion: @escaping (T?, ErrorResponse?) -> Void) {
prepareAuthAndKeyHeaders { [weak self] (headers, error) in
guard let headers = headers else {
DispatchQueue.main.async { completion(nil, error) }
return
}
self?.restRequest.makeRequest(url: url, method: .patch, parameters: parameters, encoding: encoding, headers: headers) { (resultValue, error) in
guard let strongSelf = self else { return }
guard let resultValue = resultValue else {
completion(nil, error)
return
}
let result = try? T(resultValue)
(result as? ClientModel)?.client = self
(result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey])
completion(result, error)
}
}
}
}
// MARK: - Confirm package
extension RestClient {
/**
Endpoint to allow for returning responses to APDU execution
- parameter package: ApduPackage object
- parameter completion: ConfirmAPDUPackageHandler closure
*/
public func confirmAPDUPackage(_ url: String, package: ApduPackage, completion: @escaping ConfirmHandler) {
guard package.packageId != nil else {
completion(ErrorResponse(domain: RestClient.self, errorCode: ErrorCode.badRequest.rawValue, errorMessage: "packageId should not be nil"))
return
}
makePostCall(url, parameters: package.responseDictionary, completion: completion)
}
}
// MARK: - Transactions
extension RestClient {
/**
Completion handler
- parameter transactions: Provides ResultCollection<Transaction> object, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias TransactionsHandler = (_ result: ResultCollection<Transaction>?, _ error: ErrorResponse?) -> Void
}
// MARK: - Encryption
extension RestClient {
/**
Creates a new encryption key pair
- parameter clientPublicKey: client public key
- parameter completion: CreateEncryptionKeyHandler closure
*/
func createEncryptionKey(clientPublicKey: String, completion: @escaping EncryptionKeyHandler) {
let parameters = ["clientPublicKey": clientPublicKey]
restRequest.makeRequest(url: FitpayConfig.apiURL + "/config/encryptionKeys", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: session.defaultHeaders) { (resultValue, error) in
guard let resultValue = resultValue else {
completion(nil, error)
return
}
completion(try? EncryptionKey(resultValue), error)
}
}
/**
Completion handler
- parameter encryptionKey?: Provides EncryptionKey object, or nil if error occurs
- parameter error?: Provides error object, or nil if no error occurs
*/
typealias EncryptionKeyHandler = (_ encryptionKey: EncryptionKey?, _ error: ErrorResponse?) -> Void
/**
Retrieve and individual key pair
- parameter keyId: key id
- parameter completion: EncryptionKeyHandler closure
*/
func encryptionKey(_ keyId: String, completion: @escaping EncryptionKeyHandler) {
restRequest.makeRequest(url: FitpayConfig.apiURL + "/config/encryptionKeys/" + keyId, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: session.defaultHeaders) { (resultValue, error) in
guard let resultValue = resultValue else {
completion(nil, error)
return
}
completion(try? EncryptionKey(resultValue), error)
}
}
func createKeyIfNeeded(_ completion: @escaping EncryptionKeyHandler) {
if let key = key, !key.isExpired {
completion(key, nil)
} else {
createEncryptionKey(clientPublicKey: keyPair.publicKey!) { [weak self] (encryptionKey, error) in
if let error = error {
completion(nil, error)
} else if let encryptionKey = encryptionKey {
self?.key = encryptionKey
completion(self?.key, nil)
}
}
}
}
}
// MARK: - Request Signature Helpers
extension RestClient {
typealias AuthHeaderHandler = (_ headers: [String: String]?, _ error: ErrorResponse?) -> Void
func createAuthHeaders(_ completion: AuthHeaderHandler) {
if session.isAuthorized {
completion(session.defaultHeaders + ["Authorization": "Bearer " + session.accessToken!], nil)
} else {
completion(nil, ErrorResponse(domain: RestClient.self, errorCode: ErrorCode.unauthorized.rawValue, errorMessage: "\(ErrorCode.unauthorized)"))
}
}
func prepareAuthAndKeyHeaders(_ completion: @escaping AuthHeaderHandler) {
createAuthHeaders { [weak self] (headers, error) in
if let error = error {
completion(nil, error)
} else {
self?.createKeyIfNeeded { (encryptionKey, keyError) in
if let keyError = keyError {
completion(nil, keyError)
} else {
completion(headers! + [RestClient.fpKeyIdKey: encryptionKey!.keyId!], nil)
}
}
}
}
}
func preparKeyHeader(_ completion: @escaping AuthHeaderHandler) {
createKeyIfNeeded { (encryptionKey, keyError) in
if let keyError = keyError {
completion(nil, keyError)
} else {
completion(self.session.defaultHeaders + [RestClient.fpKeyIdKey: encryptionKey!.keyId!], nil)
}
}
}
}
// MARK: - Issuers
extension RestClient {
public typealias IssuersHandler = (_ issuers: Issuers?, _ error: ErrorResponse?) -> Void
public func issuers(completion: @escaping IssuersHandler) {
makeGetCall(FitpayConfig.apiURL + "/issuers", parameters: nil, completion: completion)
}
}
// MARK: - Assets
extension RestClient {
/**
Completion handler
- parameter asset: Provides Asset object, or nil if error occurs
- parameter error: Provides error object, or nil if no error occurs
*/
public typealias AssetsHandler = (_ asset: Asset?, _ error: ErrorResponse?) -> Void
func assets(_ url: String, completion: @escaping AssetsHandler) {
restRequest.makeDataRequest(url: url) { (resultValue, error) in
guard let resultValue = resultValue as? Data else {
completion(nil, error)
return
}
var asset: Asset?
if let image = UIImage(data: resultValue) {
asset = Asset(image: image)
} else if let string = resultValue.UTF8String {
asset = Asset(text: string)
} else {
asset = Asset(data: resultValue)
}
completion(asset, nil)
}
}
}
/**
Retrieve an individual asset (i.e. terms and conditions)
- parameter completion: AssetsHandler closure
*/
public protocol AssetRetrivable {
func retrieveAsset(_ completion: @escaping RestClient.AssetsHandler)
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Permission/CameraPrompting.swift | 1 | 3405 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Localization
import PlatformKit
import ToolKit
public protocol CameraPrompting: AnyObject {
var permissionsRequestor: PermissionsRequestor { get set }
var cameraPromptingDelegate: CameraPromptingDelegate? { get set }
// Call this when an action requires camera usage
func willUseCamera()
func requestCameraPermissions()
}
extension CameraPrompting where Self: MicrophonePrompting {
public func willUseCamera() {
guard PermissionsRequestor.cameraRefused() == false else {
cameraPromptingDelegate?.showCameraPermissionsDenied()
return
}
guard PermissionsRequestor.shouldDisplayCameraPermissionsRequest() else {
willUseMicrophone()
return
}
cameraPromptingDelegate?.promptToAcceptCameraPermissions(confirmHandler: {
self.requestCameraPermissions()
})
}
public func requestCameraPermissions() {
permissionsRequestor.requestPermissions([.camera]) { [weak self] in
guard let this = self else { return }
switch PermissionsRequestor.cameraEnabled() {
case true:
this.willUseMicrophone()
case false:
this.cameraPromptingDelegate?.showCameraPermissionsDenied()
}
}
}
}
public protocol CameraPromptingDelegate: AnyObject {
var analyticsRecorder: AnalyticsEventRecorderAPI { get }
func showCameraPermissionsDenied()
func promptToAcceptCameraPermissions(confirmHandler: @escaping (() -> Void))
}
extension CameraPromptingDelegate {
public func showCameraPermissionsDenied() {
let action = AlertAction(style: .confirm(LocalizationConstants.goToSettings))
let model = AlertModel(
headline: LocalizationConstants.Errors.cameraAccessDenied,
body: LocalizationConstants.Errors.cameraAccessDeniedMessage,
actions: [action]
)
let alert = AlertView.make(with: model) { output in
switch output.style {
case .confirm:
guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(settingsURL)
case .default,
.dismiss:
break
}
}
alert.show()
}
public func promptToAcceptCameraPermissions(confirmHandler: @escaping (() -> Void)) {
let okay = AlertAction(style: .confirm(LocalizationConstants.okString))
let notNow = AlertAction(style: .default(LocalizationConstants.KYC.notNow))
let model = AlertModel(
headline: LocalizationConstants.KYC.allowCameraAccess,
body: LocalizationConstants.KYC.enableCameraDescription,
actions: [okay, notNow]
)
let alert = AlertView.make(with: model) { [weak self] output in
switch output.style {
case .confirm:
self?.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreCameraApprove)
confirmHandler()
case .default,
.dismiss:
self?.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreCameraDecline)
}
}
alert.show()
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Models/Balance/PairExchangeService.swift | 1 | 2963 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import MoneyKit
import RxRelay
import RxSwift
public protocol PairExchangeServiceAPI: AnyObject {
/// The current fiat exchange price.
/// The implementer should implement this as a `.shared(replay: 1)`
/// resource for efficiency among multiple clients.
func fiatPrice(at time: PriceTime) -> Observable<FiatValue>
/// A trigger that force the service to fetch the updated price.
/// Handy to call on currency type and value changes
var fetchTriggerRelay: PublishRelay<Void> { get }
}
public final class PairExchangeService: PairExchangeServiceAPI {
// TODO: Network failure
/// Fetches the fiat price, and shares its stream with other
/// subscribers to keep external API usage count in check.
/// Also handles currency code change
public func fiatPrice(at time: PriceTime) -> Observable<FiatValue> {
Observable
.combineLatest(
fiatCurrencyService.displayCurrencyPublisher.asObservable(),
fetchTriggerRelay.asObservable().startWith(())
)
.throttle(.milliseconds(250), scheduler: ConcurrentDispatchQueueScheduler(qos: .background))
.map(\.0)
.flatMapLatest(weak: self) { (self, fiatCurrency) -> Observable<PriceQuoteAtTime> in
self.priceService
.price(of: self.currency, in: fiatCurrency, at: time)
.asSingle()
.catchAndReturn(
PriceQuoteAtTime(
timestamp: time.date,
moneyValue: .zero(currency: fiatCurrency),
marketCap: nil
)
)
.asObservable()
}
// There MUST be a fiat value here
.map { $0.moneyValue.fiatValue! }
.catchError(weak: self) { (self, _) -> Observable<FiatValue> in
self.zero
}
.distinctUntilChanged()
.share(replay: 1)
}
private var zero: Observable<FiatValue> {
fiatCurrencyService
.displayCurrencyPublisher
.map(FiatValue.zero)
.asObservable()
}
/// A trigger for a fetch
public let fetchTriggerRelay = PublishRelay<Void>()
// MARK: - Services
/// The exchange service
private let priceService: PriceServiceAPI
/// The currency service
private let fiatCurrencyService: FiatCurrencyServiceAPI
/// The associated currency
private let currency: Currency
// MARK: - Setup
public init(
currency: Currency,
priceService: PriceServiceAPI = resolve(),
fiatCurrencyService: FiatCurrencyServiceAPI
) {
self.currency = currency
self.priceService = priceService
self.fiatCurrencyService = fiatCurrencyService
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/Send/TradingToOnChainTransactionEngine.swift | 1 | 11901 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import MoneyKit
import PlatformKit
import RxSwift
import RxToolKit
import ToolKit
final class TradingToOnChainTransactionEngine: TransactionEngine {
/// This might need to be `1:1` as there isn't a transaction pair.
var transactionExchangeRatePair: Observable<MoneyValuePair> {
.empty()
}
var fiatExchangeRatePairs: Observable<TransactionMoneyValuePairs> {
sourceExchangeRatePair
.map { pair -> TransactionMoneyValuePairs in
TransactionMoneyValuePairs(
source: pair,
destination: pair
)
}
.asObservable()
}
let walletCurrencyService: FiatCurrencyServiceAPI
let currencyConversionService: CurrencyConversionServiceAPI
let isNoteSupported: Bool
var askForRefreshConfirmation: AskForRefreshConfirmation!
var sourceAccount: BlockchainAccount!
var transactionTarget: TransactionTarget!
var sourceTradingAccount: CryptoTradingAccount! {
sourceAccount as? CryptoTradingAccount
}
var target: CryptoReceiveAddress {
transactionTarget as! CryptoReceiveAddress
}
var targetAsset: CryptoCurrency { target.asset }
// MARK: - Private Properties
private let feeCache: CachedValue<CustodialTransferFee>
private let transferRepository: CustodialTransferRepositoryAPI
private let transactionLimitsService: TransactionLimitsServiceAPI
// MARK: - Init
init(
isNoteSupported: Bool = false,
walletCurrencyService: FiatCurrencyServiceAPI = resolve(),
currencyConversionService: CurrencyConversionServiceAPI = resolve(),
transferRepository: CustodialTransferRepositoryAPI = resolve(),
transactionLimitsService: TransactionLimitsServiceAPI = resolve()
) {
self.walletCurrencyService = walletCurrencyService
self.currencyConversionService = currencyConversionService
self.isNoteSupported = isNoteSupported
self.transferRepository = transferRepository
self.transactionLimitsService = transactionLimitsService
feeCache = CachedValue(
configuration: .periodic(
seconds: 20,
schedulerIdentifier: "TradingToOnChainTransactionEngine"
)
)
feeCache.setFetch(weak: self) { (self) -> Single<CustodialTransferFee> in
self.transferRepository.fees()
.asSingle()
}
}
func assertInputsValid() {
precondition(transactionTarget is CryptoReceiveAddress)
precondition(sourceAsset == targetAsset)
}
func restart(
transactionTarget: TransactionTarget,
pendingTransaction: PendingTransaction
) -> Single<PendingTransaction> {
let memoModel = TransactionConfirmations.Memo(
textMemo: target.memo,
required: false
)
return defaultRestart(
transactionTarget: transactionTarget,
pendingTransaction: pendingTransaction
)
.map { [sourceTradingAccount] pendingTransaction -> PendingTransaction in
guard sourceTradingAccount!.isMemoSupported else {
return pendingTransaction
}
var pendingTransaction = pendingTransaction
pendingTransaction.setMemo(memo: memoModel)
return pendingTransaction
}
}
func initializeTransaction() -> Single<PendingTransaction> {
let memoModel = TransactionConfirmations.Memo(
textMemo: target.memo,
required: false
)
let transactionLimits = transactionLimitsService
.fetchLimits(
source: LimitsAccount(
currency: sourceAccount.currencyType,
accountType: .custodial
),
destination: LimitsAccount(
currency: targetAsset.currencyType,
accountType: .nonCustodial // even exchange accounts are considered non-custodial atm.
)
)
return transactionLimits.eraseError()
.zip(walletCurrencyService.displayCurrencyPublisher.eraseError())
.map { [sourceTradingAccount, sourceAsset, predefinedAmount] transactionLimits, walletCurrency
-> PendingTransaction in
let amount: MoneyValue
if let predefinedAmount = predefinedAmount,
predefinedAmount.currencyType == sourceAsset
{
amount = predefinedAmount
} else {
amount = .zero(currency: sourceAsset)
}
var pendingTransaction = PendingTransaction(
amount: amount,
available: .zero(currency: sourceAsset),
feeAmount: .zero(currency: sourceAsset),
feeForFullAvailable: .zero(currency: sourceAsset),
feeSelection: .empty(asset: sourceAsset),
selectedFiatCurrency: walletCurrency,
limits: transactionLimits
)
if sourceTradingAccount!.isMemoSupported {
pendingTransaction.setMemo(memo: memoModel)
}
return pendingTransaction
}
.asSingle()
}
func update(amount: MoneyValue, pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
guard sourceTradingAccount != nil else {
return .just(pendingTransaction)
}
return
Single
.zip(
feeCache.valueSingle,
sourceTradingAccount.withdrawableBalance.asSingle()
)
.map { fees, withdrawableBalance -> PendingTransaction in
let fee = fees[fee: amount.currency]
let available = try withdrawableBalance - fee
var pendingTransaction = pendingTransaction.update(
amount: amount,
available: available.isNegative ? .zero(currency: available.currency) : available,
fee: fee,
feeForFullAvailable: fee
)
let transactionLimits = pendingTransaction.limits ?? .noLimits(for: amount.currency)
pendingTransaction.limits = TransactionLimits(
currencyType: transactionLimits.currencyType,
minimum: fees[minimumAmount: amount.currency],
maximum: transactionLimits.maximum,
maximumDaily: transactionLimits.maximumDaily,
maximumAnnual: transactionLimits.maximumAnnual,
effectiveLimit: transactionLimits.effectiveLimit,
suggestedUpgrade: transactionLimits.suggestedUpgrade
)
return pendingTransaction
}
}
func doBuildConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
fiatAmountAndFees(from: pendingTransaction)
.map { [sourceTradingAccount, target, isNoteSupported] fiatAmountAndFees -> [TransactionConfirmation] in
var confirmations: [TransactionConfirmation] = [
TransactionConfirmations.Source(value: sourceTradingAccount!.label),
TransactionConfirmations.Destination(value: target.label),
TransactionConfirmations.NetworkFee(
primaryCurrencyFee: fiatAmountAndFees.fees.moneyValue,
feeType: .withdrawalFee
),
TransactionConfirmations.Total(total: fiatAmountAndFees.amount.moneyValue)
]
if isNoteSupported {
confirmations.append(TransactionConfirmations.Destination(value: ""))
}
if sourceTradingAccount!.isMemoSupported {
confirmations.append(
TransactionConfirmations.Memo(textMemo: target.memo, required: false)
)
}
return confirmations
}
.map { confirmations -> PendingTransaction in
pendingTransaction.update(confirmations: confirmations)
}
}
func doOptionUpdateRequest(
pendingTransaction: PendingTransaction,
newConfirmation: TransactionConfirmation
) -> Single<PendingTransaction> {
defaultDoOptionUpdateRequest(pendingTransaction: pendingTransaction, newConfirmation: newConfirmation)
.map { pendingTransaction -> PendingTransaction in
var pendingTransaction = pendingTransaction
if let memo = newConfirmation as? TransactionConfirmations.Memo {
pendingTransaction.setMemo(memo: memo)
}
return pendingTransaction
}
}
func doValidateAll(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> {
validateAmount(pendingTransaction: pendingTransaction)
}
func execute(pendingTransaction: PendingTransaction) -> Single<TransactionResult> {
transferRepository
.transfer(
moneyValue: pendingTransaction.amount,
destination: target.address,
memo: pendingTransaction.memo?.value?.string
)
.map { identifier -> TransactionResult in
.hashed(txHash: identifier, amount: pendingTransaction.amount)
}
.asSingle()
}
func doUpdateFeeLevel(
pendingTransaction: PendingTransaction,
level: FeeLevel,
customFeeAmount: MoneyValue
) -> Single<PendingTransaction> {
.just(pendingTransaction)
}
// MARK: - Private Functions
private func fiatAmountAndFees(
from pendingTransaction: PendingTransaction
) -> Single<(amount: FiatValue, fees: FiatValue)> {
Single.zip(
sourceExchangeRatePair,
.just(pendingTransaction.amount.cryptoValue ?? .zero(currency: sourceCryptoCurrency)),
.just(pendingTransaction.feeAmount.cryptoValue ?? .zero(currency: sourceCryptoCurrency))
)
.map { (quote: $0.0.quote.fiatValue ?? .zero(currency: .USD), amount: $0.1, fees: $0.2) }
.map { (quote: FiatValue, amount: CryptoValue, fees: CryptoValue) -> (FiatValue, FiatValue) in
let fiatAmount = amount.convert(using: quote)
let fiatFees = fees.convert(using: quote)
return (fiatAmount, fiatFees)
}
.map { (amount: $0.0, fees: $0.1) }
}
private var sourceExchangeRatePair: Single<MoneyValuePair> {
walletCurrencyService
.displayCurrency
.flatMap { [currencyConversionService, sourceAsset] fiatCurrency in
currencyConversionService
.conversionRate(from: sourceAsset, to: fiatCurrency.currencyType)
.map { MoneyValuePair(base: .one(currency: sourceAsset), quote: $0) }
}
.asSingle()
}
}
extension CryptoTradingAccount {
fileprivate var isMemoSupported: Bool {
switch asset {
case .stellar:
return true
default:
return false
}
}
}
extension PendingTransaction {
fileprivate var memo: TransactionConfirmations.Memo? {
engineState.value[.xlmMemo] as? TransactionConfirmations.Memo
}
fileprivate mutating func setMemo(memo: TransactionConfirmations.Memo) {
engineState.mutate { $0[.xlmMemo] = memo }
}
}
| lgpl-3.0 |
hanangellove/Quick | Quick/DSL/World+DSL.swift | 31 | 4076 | /**
Adds methods to World to support top-level DSL functions (Swift) and
macros (Objective-C). These functions map directly to the DSL that test
writers use in their specs.
*/
extension World {
internal func beforeSuite(closure: BeforeSuiteClosure) {
suiteHooks.appendBefore(closure)
}
internal func afterSuite(closure: AfterSuiteClosure) {
suiteHooks.appendAfter(closure)
}
internal func sharedExamples(name: String, closure: SharedExampleClosure) {
registerSharedExample(name, closure: closure)
}
internal func describe(description: String, flags: FilterFlags, closure: () -> ()) {
let group = ExampleGroup(description: description, flags: flags)
currentExampleGroup!.appendExampleGroup(group)
currentExampleGroup = group
closure()
currentExampleGroup = group.parent
}
internal func context(description: String, flags: FilterFlags, closure: () -> ()) {
self.describe(description, flags: flags, closure: closure)
}
internal func fdescribe(description: String, flags: FilterFlags, closure: () -> ()) {
var focusedFlags = flags
focusedFlags[Filter.focused] = true
self.describe(description, flags: focusedFlags, closure: closure)
}
internal func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) {
var pendingFlags = flags
pendingFlags[Filter.pending] = true
self.describe(description, flags: pendingFlags, closure: closure)
}
internal func beforeEach(closure: BeforeExampleClosure) {
currentExampleGroup!.hooks.appendBefore(closure)
}
@objc(beforeEachWithMetadata:)
internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) {
currentExampleGroup!.hooks.appendBefore(closure)
}
internal func afterEach(closure: AfterExampleClosure) {
currentExampleGroup!.hooks.appendAfter(closure)
}
@objc(afterEachWithMetadata:)
internal func afterEach(closure closure: AfterExampleWithMetadataClosure) {
currentExampleGroup!.hooks.appendAfter(closure)
}
@objc(itWithDescription:flags:file:line:closure:)
internal func it(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) {
let callsite = Callsite(file: file, line: line)
let example = Example(description: description, callsite: callsite, flags: flags, closure: closure)
currentExampleGroup!.appendExample(example)
}
@objc(fitWithDescription:flags:file:line:closure:)
internal func fit(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) {
var focusedFlags = flags
focusedFlags[Filter.focused] = true
self.it(description, flags: focusedFlags, file: file, line: line, closure: closure)
}
@objc(xitWithDescription:flags:file:line:closure:)
internal func xit(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) {
var pendingFlags = flags
pendingFlags[Filter.pending] = true
self.it(description, flags: pendingFlags, file: file, line: line, closure: closure)
}
@objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:flags:file:line:)
internal func itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: Int) {
let callsite = Callsite(file: file, line: line)
let closure = World.sharedWorld().sharedExample(name)
let group = ExampleGroup(description: name, flags: flags)
currentExampleGroup!.appendExampleGroup(group)
currentExampleGroup = group
closure(sharedExampleContext)
currentExampleGroup!.walkDownExamples { (example: Example) in
example.isSharedExample = true
example.callsite = callsite
}
currentExampleGroup = group.parent
}
internal func pending(description: String, closure: () -> ()) {
print("Pending: \(description)")
}
}
| apache-2.0 |
Azurelus/Swift-Useful-Files | Sources/Helpers/ConnectionStatusHandler.swift | 1 | 1493 | //
// ConnectionStatusHandler.swift
// Swift-Useful-Files
//
// Created by Maksym Husar on 12/28/17.
// Copyright © 2017 Maksym Husar. All rights reserved.
//
import Foundation
import PKHUD // just delete if not using
class ConnectionStatusHandler {
static let instance = ConnectionStatusHandler()
private init() { }
// MARK: - Public methods
func start() {
addNotifications()
}
func stop() {
removeNotifications()
}
// MARK: - Private methods
private func addNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(internetNotAvailable(_:)), name: .InternetNotAvailable, object: nil)
}
private func removeNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc private func internetNotAvailable(_ notification: Notification) {
if let currentVC = UIApplication.topViewController(), currentVC is UIAlertController == false {
HUD.hide() // just delete if not using
let title = "No Internet Connection"
let message = "Make sure your device is connected to the Internet"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: { _ in })
alert.addAction(cancelAction)
currentVC.present(alert, animated: true, completion: nil)
}
}
}
| mit |
lukecharman/so-many-games | SoManyGames/Classes/View Controllers/ListViewController.swift | 1 | 14501 | //
// ListViewController.swift
// SoManyGames
//
// Created by Luke Charman on 18/03/2017.
// Copyright © 2017 Luke Charman. All rights reserved.
//
import UIKit
class ListViewController: UICollectionViewController {
@IBOutlet var gradientView: GradientView!
var games: [Game] = Backlog.manager.games {
didSet {
updateEmptyStateLabel()
}
}
var button = ActionButton(title: "add")
var sortButton = ActionButton(title: "sort")
var listButton = ActionButton(title: "playing")
var clearButton = ActionButton(title: "clear")
var selectedGames = [Game]()
var programmaticDeselection = false
var emptyStateLabel = UILabel()
}
// MARK: Setup
extension ListViewController {
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.allowsMultipleSelection = true
collectionView?.backgroundColor = .clear
button.titleLabel?.font = UIFont(name: fontName, size: Sizes.button)
makeAddButton()
makeSortButton()
makeListButton()
makeClearButton()
makeEmptyStateLabel()
updateEmptyStateLabel()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
games = Backlog.manager.games
collectionView?.reloadData()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
collectionView?.collectionViewLayout.invalidateLayout()
for cell in collectionView!.visibleCells {
guard let cell = cell as? GameCell else { continue }
cell.calculateProgressOnRotation()
}
coordinator.animate(alongsideTransition: { _ in
self.gradientView.resize()
}, completion: nil)
}
}
// MARK: Button
extension ListViewController {
func makeAddButton() {
guard let collectionView = collectionView else { return }
guard let superview = collectionView.superview else { return }
superview.addSubview(button)
button.anchor(to: collectionView, at: .bottomLeft)
button.addTarget(self, action: #selector(buttonTapped), for: UIControl.Event.touchUpInside)
}
func makeSortButton() {
guard let collectionView = collectionView else { return }
guard let superview = collectionView.superview else { return }
superview.addSubview(sortButton)
sortButton.anchor(to: collectionView, at: .bottomRight)
sortButton.addTarget(self, action: #selector(sortButtonTapped), for: UIControl.Event.touchUpInside)
}
func makeListButton() {
guard let collectionView = collectionView else { return }
guard let superview = collectionView.superview else { return }
superview.addSubview(listButton)
listButton.anchor(to: collectionView, at: .bottomCenter)
listButton.addTarget(self, action: #selector(listButtonTapped), for: UIControl.Event.touchUpInside)
}
func makeClearButton() {
guard let collectionView = collectionView else { return }
guard let superview = collectionView.superview else { return }
superview.addSubview(clearButton)
clearButton.anchor(to: collectionView, at: .bottomRight)
clearButton.addTarget(self, action: #selector(clearButtonTapped), for: UIControl.Event.touchUpInside)
clearButton.isHidden = true
}
@objc func buttonTapped() {
guard Backlog.manager.currentGameListType == .active else { return }
if button.title(for: UIControl.State.normal) == "add" {
performSegue(withIdentifier: "AddGame", sender: nil)
} else {
delete()
}
}
@objc func sortButtonTapped() {
guard Backlog.manager.currentGameListType == .active else { return }
Backlog.manager.sort()
collectionView?.performBatchUpdates({
self.animateReorder()
}, completion: { _ in
self.games = Backlog.manager.games
self.collectionView?.reloadData()
})
}
@objc func listButtonTapped() {
Backlog.manager.switchLists()
games = Backlog.manager.games
collectionView?.reloadData()
let active = Backlog.manager.currentGameListType == .active
let title = active ? "playing" : "finished"
listButton.setTitle(title, for: UIControl.State.normal)
button.isHidden = !active
clearButton.isHidden = active || games.count == 0
}
@objc func clearButtonTapped() {
let alert = UIAlertController(title: "Clear Completed?", message: "Are you sure you want to clear all your completed games?", preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { _ in self.confirmClear() }))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func confirmClear() {
Backlog.manager.clearCompleted()
games = Backlog.manager.games
collectionView?.reloadData()
}
func animateReorder() {
let old = self.games
let new = Backlog.manager.games
for index in 0..<old.count {
let fromIndexPath = IndexPath(item: index, section: 0)
let toIndexPath = IndexPath(item: new.index(of: old[index])!, section: 0)
collectionView?.moveItem(at: fromIndexPath, to: toIndexPath)
}
}
func updateButton() {
if selectedGames.count > 0 {
button.setTitle("delete", for: UIControl.State.normal)
sortButton.isHidden = true
listButton.isHidden = true
} else {
button.setTitle("add", for: UIControl.State.normal)
sortButton.isHidden = false
listButton.isHidden = false
}
}
func makeEmptyStateLabel() {
guard let collectionView = collectionView else { return }
guard let superview = collectionView.superview else { return }
superview.addSubview(button)
emptyStateLabel = UILabel()
emptyStateLabel.numberOfLines = 0
emptyStateLabel.translatesAutoresizingMaskIntoConstraints = false
emptyStateLabel.font = UIFont(name: fontName, size: Sizes.emptyState)
emptyStateLabel.textColor = Colors.darkest
superview.addSubview(emptyStateLabel)
emptyStateLabel.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
emptyStateLabel.centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: -41).isActive = true
emptyStateLabel.widthAnchor.constraint(equalTo: superview.widthAnchor, multiplier: 0.9).isActive = true
}
func updateEmptyStateLabel() {
emptyStateLabel.isHidden = games.count > 0
let active = Backlog.manager.currentGameListType == .active
if active {
emptyStateLabel.text = "Looks like your backlog is empty. Lucky you!\n\nIf you have games to add, tap the add button."
sortButton.isHidden = !emptyStateLabel.isHidden
} else {
emptyStateLabel.text = "Looks like your completed games list is empty.\n\nWhen you mark a game as 100% complete, it'll show up here."
sortButton.isHidden = true
return
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "ShowDetails" else { return }
guard let game = sender as? Game else { return }
guard let dest = segue.destination as? GameViewController else { return }
dest.game = game
}
}
// MARK:- Deletion
extension ListViewController {
func delete() {
let singular = "Would you like to delete this game?"
let plural = "Would you like to delete these games?"
let string = self.selectedGames.count > 1 ? plural : singular
let alert = UIAlertController(title: "Delete?", message: string, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { _ in self.confirmDelete() }))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { _ in self.cancelDelete() }))
present(alert, animated: true, completion: nil)
}
func markAsCompleted(game: Game) {
Backlog.manager.move(game, from: .active, to: .completed)
games = Backlog.manager.games
collectionView?.reloadData()
}
func markAsUncompleted(game: Game) {
Backlog.manager.move(game, from: .completed, to: .active)
games = Backlog.manager.games
collectionView?.reloadData()
}
func confirmDelete() {
guard let cv = collectionView, let indexPaths = collectionView!.indexPathsForSelectedItems else {
fatalError("You're trying to delete items that don't exist.")
}
indexPaths.forEach { collectionView?.deselectItem(at: $0, animated: false) }
cv.performBatchUpdates({
cv.deleteItems(at: indexPaths)
Backlog.manager.remove(self.selectedGames)
self.games = Backlog.manager.games
self.selectedGames = []
}, completion: { success in
cv.reloadData()
self.updateButton()
})
}
func cancelDelete() {
selectedGames = []
collectionView?.visibleCells.forEach {
programmaticDeselection = true
collectionView?.deselectItem(at: collectionView!.indexPath(for: $0)!, animated: false)
collectionView(collectionView!, didDeselectItemAt: collectionView!.indexPath(for: $0)!)
programmaticDeselection = false
}
updateButton()
}
}
// MARK:- Selection
extension ListViewController {
func select(cell: GameCell, at indexPath: IndexPath) {
selectedGames.append(games[indexPath.item])
updateButton()
}
func deselect(cell: GameCell, at indexPath: IndexPath) {
if !programmaticDeselection {
guard let index = selectedGames.index(of: games[indexPath.item]) else { return }
selectedGames.remove(at: index)
}
updateButton()
}
}
// MARK: UICollectionViewDataSource
extension ListViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return games.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCell", for: indexPath) as? GameCell else {
fatalError("Could not dequeue a reusable GameCell.")
}
cell.game = games[indexPath.item]
cell.delegate = self
return cell
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension ListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if traitCollection.horizontalSizeClass == .regular {
return CGSize(width: collectionView.bounds.size.width / 2, height: GameCell.height)
} else {
return CGSize(width: collectionView.bounds.size.width, height: GameCell.height)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
collectionView?.collectionViewLayout.invalidateLayout()
}
}
// MARK: UICollectionViewDelegate
extension ListViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// guard let cell = collectionView.cellForItem(at: indexPath) as? GameCell else { return }
// select(cell: cell, at: indexPath)
performSegue(withIdentifier: "ShowDetails", sender: games[indexPath.item])
}
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
// guard let cell = collectionView.cellForItem(at: indexPath) as? GameCell else { return }
// deselect(cell: cell, at: indexPath)
}
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard sourceIndexPath != destinationIndexPath else { return }
let swap = games[sourceIndexPath.item]
games[sourceIndexPath.item] = games[destinationIndexPath.item]
games[destinationIndexPath.item] = swap
Backlog.manager.reorder(sourceIndexPath.item, to: destinationIndexPath.item)
}
}
// MARK: GameCellDelegate
extension ListViewController: GameCellDelegate {
func game(_ game: Game, didUpdateProgress progress: Double) {
if progress >= 1 && Backlog.manager.currentGameListType == .active {
askToDelete(game: game)
} else if progress < 1 && Backlog.manager.currentGameListType == .completed {
askToMoveBack(game: game)
}
}
func askToDelete(game: Game) {
guard Backlog.manager.currentGameListType == .active else { return }
let alert = UIAlertController(title: "You're done?", message: "Want to move this game to your complete list?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in self.markAsCompleted(game: game) }))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
show(alert, sender: nil)
}
func askToMoveBack(game: Game) {
guard Backlog.manager.currentGameListType == .completed else { return }
let alert = UIAlertController(title: "Back into it?", message: "Want to move this game back to your active list?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in self.markAsUncompleted(game: game) }))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { _ in
Backlog.manager.update(game) { game.completionPercentage = 1 }
self.collectionView?.reloadData()
}))
show(alert, sender: nil)
}
}
| mit |
CNKCQ/oschina | Pods/SnapKit/Source/LayoutConstraintItem.swift | 1 | 2944 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol LayoutConstraintItem: class {
}
@available(iOS 9.0, OSX 10.11, *)
extension ConstraintLayoutGuide: LayoutConstraintItem {
}
extension ConstraintView: LayoutConstraintItem {
}
extension LayoutConstraintItem {
internal func prepare() {
if let view = self as? ConstraintView {
view.translatesAutoresizingMaskIntoConstraints = false
}
}
internal var superview: ConstraintView? {
if let view = self as? ConstraintView {
return view.superview
}
if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide {
return guide.owningView
}
return nil
}
internal var constraints: [Constraint] {
return constraintsSet.allObjects as! [Constraint]
}
internal func add(constraints: [Constraint]) {
let constraintsSet = self.constraintsSet
for constraint in constraints {
constraintsSet.add(constraint)
}
}
internal func remove(constraints: [Constraint]) {
let constraintsSet = self.constraintsSet
for constraint in constraints {
constraintsSet.remove(constraint)
}
}
private var constraintsSet: NSMutableSet {
let constraintsSet: NSMutableSet
if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet {
constraintsSet = existing
} else {
constraintsSet = NSMutableSet()
objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return constraintsSet
}
}
private var constraintsKey: UInt8 = 0
| mit |
meticulo3366/PNChart-Swift | PNChartSwift/PNChartDelegate.swift | 1 | 591 | //
// PNChartDelegate.swift
// PNChart-Swift
//
// Created by kevinzhow on 6/5/14.
// Copyright (c) 2014 Catch Inc. All rights reserved.
//
import UIKit
public protocol PNChartDelegate {
/**
* When user click on the chart line
*
*/
func userClickedOnLinePoint(point: CGPoint, lineIndex:Int)
/**
* When user click on the chart line key point
*
*/
func userClickedOnLineKeyPoint(point: CGPoint, lineIndex:Int, keyPointIndex:Int)
/**
* When user click on a chart bar
*
*/
func userClickedOnBarCharIndex(barIndex:Int)
} | mit |
chrisjmendez/swift-exercises | Video/SKVideoNode/SKVideoNode/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// SKVideoNode
//
// Created by Tommy Trojan on 10/2/15.
// Copyright © 2015 Chris Mendez. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
chrisjmendez/swift-exercises | Authentication/Firebase/Twitter/TwitterAuth/MainViewController.swift | 1 | 621 | //
// MainViewController.swift
// TwitterAuth
//
// Created by Tommy Trojan on 12/9/15.
// Copyright © 2015 Chris Mendez. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
var user:FAuthData!
var ref:Firebase!
var sender:String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
wangtongke/WTKMVVMRxSwift | WTKMVVMRx/Pods/RxOptional/Source/Driver+Occupiable.swift | 7 | 1152 | import Foundation
import RxCocoa
public extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy, E: Occupiable {
/**
Filters out empty elements.
- returns: `Driver` of source `Driver`'s elements, with empty elements filtered out.
*/
public func filterEmpty() -> Driver<E> {
return self.flatMap { element -> Driver<E> in
guard element.isNotEmpty else {
return Driver<E>.empty()
}
return Driver<E>.just(element)
}
}
/**
Replaces empty elements with result returned by `handler`.
- parameter handler: empty handler function that returns `Driver` of non-empty elements.
- returns: `Driver` of the source `Driver`'s elements, with empty elements replaced by the handler's returned non-empty elements.
*/
public func catchOnEmpty(_ handler: @escaping () -> Driver<E>) -> Driver<E> {
return self.flatMap { element -> Driver<E> in
guard element.isNotEmpty else {
return handler()
}
return Driver<E>.just(element)
}
}
}
| mit |
vexy/Fridge | Sources/Fridge/BSONConverter.swift | 1 | 2309 | //
// BSONConverter.swift
// Fridge
//
// Created by Veljko Tekelerovic on 19.2.22.
//
import Foundation
import BSONCoder
/// Internal helper struct that wraps generic array
fileprivate struct WrappedObject<T: Codable>: Codable, Identifiable {
var id = BSONObjectID.init()
var array: [T]
init(arrayObject: [T]) {
array = arrayObject
}
}
/// Utility class providing write/read BSON functionality
final class BSONConverter {
private let _rawFilePath: URL
init(compartment: FridgeCompartment) {
_rawFilePath = compartment.objectPath
}
/// Writes given object to a local system storage
func write<T: Encodable>(object: T) throws {
var rawData: Data
do {
rawData = try BSONEncoder().encode(object).toData()
} catch let err {
print("<BSONConverter> Error occured. Reason:\n\(err)")
throw err
}
// flush the data to a file
try rawData.write(to: _rawFilePath)
}
/// Writes given array of objects to a local system storage
func write<T: Codable>(objects: [T]) throws {
var rawData: Data
let wrappedObject = WrappedObject<T>.init(arrayObject: objects)
do {
rawData = try BSONEncoder().encode(wrappedObject).toData()
} catch let err {
print("<BSONConverter> Error occured. Reason:\n\(err)")
throw err
}
// flush the data to a file
try rawData.write(to: _rawFilePath)
}
/// Reads object from compartment data storage and returns Foundation counterpart
func read<T: Decodable>() throws -> T { //} -> BSONDoc {
// prepare input stream
let rawBSONData = try Data(contentsOf: _rawFilePath)
let realObject = try BSONDecoder().decode(T.self, from: rawBSONData)
return realObject
}
/// Reads array of objects from compartment data storage and returns Foundation counterpart
func read<T: Codable>() throws -> [T] {
// get raw data from the storage
let rawBSONData = try Data(contentsOf: _rawFilePath)
let wrappedObject = try BSONDecoder().decode(WrappedObject<T>.self, from: rawBSONData)
return wrappedObject.array
}
}
| mit |
yotao/YunkuSwiftSDKTEST | YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/HTTPStatusCodes.swift | 1 | 5011 | //
// HTTPStatusCodes.swift
//
// Created by Richard Hodgkins on 11/01/2015.
// Copyright (c) 2015 Richard Hodgkins. All rights reserved.
//
import Foundation
/**
HTTP status codes as per http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
The RF2616 standard is completely covered (http://www.ietf.org/rfc/rfc2616.txt)
*/
@objc public enum HTTPStatusCode : Int {
// Informational
case `continue` = 100
case switchingProtocols = 101
case processing = 102
// Success
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
case multiStatus = 207
case alreadyReported = 208
case imUsed = 226
// Redirections
case multipleChoices = 300
case movedPermanently = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case switchProxy = 306
case temporaryRedirect = 307
case permanentRedirect = 308
// Client Errors
case badRequest = 400
case unauthorized = 401
case paymentRequired = 402
case forbidden = 403
case notFound = 404
case methodNotAllowed = 405
case notAcceptable = 406
case proxyAuthenticationRequired = 407
case requestTimeout = 408
case conflict = 409
case gone = 410
case lengthRequired = 411
case preconditionFailed = 412
case requestEntityTooLarge = 413
case requestURITooLong = 414
case unsupportedMediaType = 415
case requestedRangeNotSatisfiable = 416
case expectationFailed = 417
case imATeapot = 418
case authenticationTimeout = 419
case unprocessableEntity = 422
case locked = 423
case failedDependency = 424
case upgradeRequired = 426
case preconditionRequired = 428
case tooManyRequests = 429
case requestHeaderFieldsTooLarge = 431
case loginTimeout = 440
case noResponse = 444
case retryWith = 449
case unavailableForLegalReasons = 451
case requestHeaderTooLarge = 494
case certError = 495
case noCert = 496
case httpToHTTPS = 497
case tokenExpired = 498
case clientClosedRequest = 499
// Server Errors
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
case variantAlsoNegotiates = 506
case insufficientStorage = 507
case loopDetected = 508
case bandwidthLimitExceeded = 509
case notExtended = 510
case networkAuthenticationRequired = 511
case networkTimeoutError = 599
}
public extension HTTPStatusCode {
/// Informational - Request received, continuing process.
// public var isInformational: Bool {
// return inRange(100...200)
// }
// /// Success - The action was successfully received, understood, and accepted.
// public var isSuccess: Bool {
// return inRange(200...299)
// }
// /// Redirection - Further action must be taken in order to complete the request.
// public var isRedirection: Bool {
// return inRange(300...399)
// }
// /// Client Error - The request contains bad syntax or cannot be fulfilled.
// public var isClientError: Bool {
// return inRange(400...499)
// }
// /// Server Error - The server failed to fulfill an apparently valid request.
// public var isServerError: Bool {
// return inRange(500...599)
// }
/// - returns: true if the status code is in the provided range, false otherwise.
fileprivate func inRange(_ range: Range<Int>) -> Bool {
return range.contains(rawValue)
}
}
public extension HTTPStatusCode {
public var localizedReasonPhrase: String {
return HTTPURLResponse.localizedString(forStatusCode: rawValue)
}
}
// MARK: - Printing
extension HTTPStatusCode: CustomDebugStringConvertible, CustomStringConvertible {
public var description: String {
return "\(rawValue) - \(localizedReasonPhrase)"
}
public var debugDescription: String {
return "HTTPStatusCode:\(description)"
}
}
// MARK: - HTTP URL Response
public extension HTTPStatusCode {
/// Obtains a possible status code from an optional HTTP URL response.
public init?(HTTPResponse: HTTPURLResponse?) {
if let value = HTTPResponse?.statusCode {
self.init(rawValue: value)
} else {
return nil
}
}
}
//public extension NSHTTPURLResponse {
// public var statusCodeValue: HTTPStatusCode? {
// return HTTPStatusCode(HTTPResponse: self)
// }
//
// @availability(iOS, introduced=7.0)
// public convenience init?(URL url: NSURL, statusCode: HTTPStatusCode, HTTPVersion: String?, headerFields: [NSObject : AnyObject]?) {
// self.init(URL: url, statusCode: statusCode.rawValue, HTTPVersion: HTTPVersion, headerFields: headerFields)
// }
//}
| mit |
vapor/vapor | Sources/Vapor/View/View.swift | 1 | 474 | public struct View: ResponseEncodable {
public var data: ByteBuffer
public init(data: ByteBuffer) {
self.data = data
}
public func encodeResponse(for request: Request) -> EventLoopFuture<Response> {
let response = Response()
response.headers.contentType = .html
response.body = .init(buffer: self.data, byteBufferAllocator: request.byteBufferAllocator)
return request.eventLoop.makeSucceededFuture(response)
}
}
| mit |
maitruonghcmus/QuickChat | QuickChat/ViewControllers/TouchIDVC.swift | 1 | 334 | import UIKit
class TouchIDVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
akio0911/handMadeCalendarAdvance | handMadeCalendarAdvance/ViewController.swift | 1 | 10834 | //
// ViewController.swift
// handMadeCalendarAdvance
//
// Created by 酒井文也 on 2016/04/23.
// Copyright © 2016年 just1factory. All rights reserved.
//
import UIKit
import CalculateCalendarLogic
//カレンダーに関する定数やメソッドを定義した構造体
struct CalendarSetting {
//カレンダーのセクション数やアイテム数に関するセッティング
static let sectionCount = 2
static let firstSectionItemCount = 7
static let secondSectionItemCount = 42
//カレンダーの日付に関するセッティング
static let weekList: [String] = ["日","月","火","水","木","金","土"]
//カレンダーのカラー表示に関するセッティング
static func getCalendarColor(weekdayIndex: Int, holiday: Bool) -> UIColor {
//日曜日または祝祭日の場合の色
if (weekdayIndex % 7 == Weekday.Sun.rawValue || holiday == true) {
return UIColor(red: CGFloat(0.831), green: CGFloat(0.349), blue: CGFloat(0.224), alpha: CGFloat(1.0))
//土曜日の場合の色
} else if (weekdayIndex % 7 == Weekday.Sat.rawValue) {
return UIColor(red: CGFloat(0.400), green: CGFloat(0.471), blue: CGFloat(0.980), alpha: CGFloat(1.0))
//平日の場合の色
} else {
return UIColor.darkGrayColor()
}
}
}
//カレンダー表示&計算用の値を取得するための構造体
struct TargetDateSetting {
static func getTargetYearAndMonthCalendar(year: Int, month: Int) -> (Int, Int) {
/*************
* (重要ポイント)
* 現在月の1日のdayOfWeek(曜日の値)を使ってカレンダーの始まる位置を決めるので'yyyy年mm月1日'のデータを作成する。
*************/
//NSCalendarクラスのインスタンスを初期化する
let targetCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let targetComps: NSDateComponents = NSDateComponents()
targetComps.year = year
targetComps.month = month
targetComps.day = 1
let targetDate: NSDate = targetCalendar.dateFromComponents(targetComps)!
//引数で渡されたNSCalendarクラスのインスタンスとNSDateクラスのインスタンスをもとに日付の情報を取得する
let range: NSRange = targetCalendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: targetDate)
let comps: NSDateComponents = targetCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Weekday],fromDate: targetDate)
//指定の年月の1日時点の日付と日数を取得してタプルで返す
return (Int(comps.weekday), Int(range.length))
}
}
//現在日付を取得するための構造体
struct CurrentDateSetting {
static func getCurrentYearAndMonth() -> (Int, Int) {
//NSCalendarクラスのインスタンスを初期化する
let currentCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
//引数で渡されたNSCalendarクラスのインスタンスとNSDateクラスのインスタンスをもとに日付の情報を取得する
let comps: NSDateComponents = currentCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month],fromDate: NSDate())
//年と月をタプルで返す
return (Int(comps.year), Int(comps.month))
}
}
class ViewController: UIViewController {
//ラベルに表示するための年と月の変数
var targetYear: Int! = CurrentDateSetting.getCurrentYearAndMonth().0
var targetMonth: Int! = CurrentDateSetting.getCurrentYearAndMonth().1
//カレンダー用のUICollectionView
@IBOutlet weak var calendarCollectionView: UICollectionView!
//Outlet接続をしたUI部品の一覧
@IBOutlet weak var prevMonthButton: UIButton!
@IBOutlet weak var nextMonthButton: UIButton!
@IBOutlet weak var currentMonthLabel: UILabel!
@IBOutlet weak var backgroundView: UIView!
//該当年月の日のリスト
var dayCellLists: [String?] = []
//日本の祝祭日判定用のインスタンス
var holidayObj: CalculateCalendarLogic = CalculateCalendarLogic()
override func viewDidLoad() {
super.viewDidLoad()
//Cellに使われるクラスを登録
calendarCollectionView.registerClass(CalendarCell.self, forCellWithReuseIdentifier: "CalendarCell")
//UICollectionViewDelegate,UICollectionViewDataSourceの拡張宣言
calendarCollectionView.delegate = self
calendarCollectionView.dataSource = self
changeCalendar()
}
//前の月のボタンが押された際のアクション
@IBAction func displayPrevMonth(sender: AnyObject) {
//現在の月に対して-1をする
if (targetMonth == 1) {
targetYear = targetYear - 1
targetMonth = 12
} else {
targetMonth = targetMonth - 1
}
changeCalendar()
}
//次の月のボタンが押された際のアクション
@IBAction func displayNextMonth(sender: AnyObject) {
//現在の月に対して+1をする
if (targetMonth == 12) {
targetYear = targetYear + 1
targetMonth = 1
} else {
targetMonth = targetMonth + 1
}
changeCalendar()
}
//カレンダー表記を変更する
private func changeCalendar() {
updateDataSource()
calendarCollectionView.reloadData()
displaySelectedCalendar()
}
//表示対象のカレンダーの年月を表示する
private func displaySelectedCalendar() {
currentMonthLabel.text = "\(targetYear)年\(targetMonth)月"
}
//CollectionViewCellに格納する日のデータを作成する
private func updateDataSource() {
var day = 1
dayCellLists = []
for i in 0..<(CalendarSetting.secondSectionItemCount) {
if isCellUsing(i) {
dayCellLists.append(String(day))
day += 1
} else {
dayCellLists.append(nil)
}
}
}
//セルに値が格納されるかを判定する
private func isCellUsing(index: Int) -> Bool {
//該当の年と月から1日の曜日と最大日数のタプルを取得する
let targetConcern: (Int, Int) = TargetDateSetting.getTargetYearAndMonthCalendar(targetYear, month: targetMonth)
let targetWeekdayIndex: Int = targetConcern.0
let targetMaxDay: Int = targetConcern.1
//CollectionViewの該当セルインデックスに値が入るかを判定する
if (index < targetWeekdayIndex - 1) {
return false
} else if (index == targetWeekdayIndex - 1 || index < targetWeekdayIndex + targetMaxDay - 1) {
return true
} else if (index == targetWeekdayIndex + targetMaxDay - 1 || index < CalendarSetting.secondSectionItemCount) {
return false
}
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
//配置したCollectionViewのセクション数を返す
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return CalendarSetting.sectionCount
}
//配置したCollectionViewの各セクションのアイテム数を返す
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return CalendarSetting.firstSectionItemCount
case 1:
return CalendarSetting.secondSectionItemCount
default:
return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CalendarCell", forIndexPath: indexPath) as! CalendarCell
switch indexPath.section {
case 0:
//曜日を表示する
cell.textLabel!.text = CalendarSetting.weekList[indexPath.row]
cell.textLabel!.textColor = CalendarSetting.getCalendarColor(indexPath.row, holiday: false)
return cell
case 1:
//該当年月の日付を表示する
let day: String? = dayCellLists[indexPath.row]
if isCellUsing(indexPath.row) {
let holiday: Bool = holidayObj.judgeJapaneseHoliday(targetYear, month: targetMonth, day: Int(day!)!)
cell.textLabel!.textColor = CalendarSetting.getCalendarColor(indexPath.row, holiday: holiday)
cell.textLabel!.text = day
} else {
cell.textLabel!.text = ""
}
return cell
default:
return cell
}
}
}
// MARK: - UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//日付が入るセルならば処理をする
if isCellUsing(indexPath.row) {
let day: String? = dayCellLists[indexPath.row]
print("\(targetYear)年\(targetMonth)月\(day!)日")
}
}
}
// MARK: - UIScrollViewDelegate
extension ViewController: UIScrollViewDelegate {
//セルのサイズを設定
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let numberOfMargin: CGFloat = 8.0
let width: CGFloat = (collectionView.frame.size.width - CGFloat(1.0) * numberOfMargin) / CGFloat(7)
let height: CGFloat = width * 1.0
return CGSizeMake(width, height)
}
//セルの垂直方向のマージンを設定
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return CGFloat(1.0)
}
//セルの水平方向のマージンを設定
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return CGFloat(1.0)
}
}
| mit |
cam-hop/APIUtility | RxSwiftFluxDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositories.swift | 4 | 5426 | //
// GitHubSearchRepositories.swift
// RxExample
//
// Created by Krunoslav Zaher on 3/18/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
enum GitHubCommand {
case changeSearch(text: String)
case loadMoreItems
case gitHubResponseReceived(SearchRepositoriesResponse)
}
struct GitHubSearchRepositoriesState {
// control
var searchText: String
var shouldLoadNextPage: Bool
var repositories: Version<[Repository]> // Version is an optimization. When something unrelated changes, we don't want to reload table view.
var nextURL: URL?
var failure: GitHubServiceError?
init(searchText: String) {
self.searchText = searchText
shouldLoadNextPage = true
repositories = Version([])
nextURL = URL(string: "https://api.github.com/search/repositories?q=\(searchText.URLEscaped)")
failure = nil
}
}
extension GitHubSearchRepositoriesState {
static let initial = GitHubSearchRepositoriesState(searchText: "")
static func reduce(state: GitHubSearchRepositoriesState, command: GitHubCommand) -> GitHubSearchRepositoriesState {
switch command {
case .changeSearch(let text):
return GitHubSearchRepositoriesState(searchText: text).mutateOne { $0.failure = state.failure }
case .gitHubResponseReceived(let result):
switch result {
case let .success((repositories, nextURL)):
return state.mutate {
$0.repositories = Version($0.repositories.value + repositories)
$0.shouldLoadNextPage = false
$0.nextURL = nextURL
$0.failure = nil
}
case let .failure(error):
return state.mutateOne { $0.failure = error }
}
case .loadMoreItems:
return state.mutate {
if $0.failure == nil {
$0.shouldLoadNextPage = true
}
}
}
}
}
import RxSwift
import RxCocoa
/**
This method contains the gist of paginated GitHub search.
*/
func githubSearchRepositories(
searchText: Driver<String>,
loadNextPageTrigger: @escaping (Driver<GitHubSearchRepositoriesState>) -> Driver<()>,
performSearch: @escaping (URL) -> Observable<SearchRepositoriesResponse>
) -> Driver<GitHubSearchRepositoriesState> {
let searchPerformerFeedback: (Driver<GitHubSearchRepositoriesState>) -> Driver<GitHubCommand> = { state in
// this is a general pattern how to model a most common feedback loop
// first select part of state describing feedback control
return state.map { (searchText: $0.searchText, shouldLoadNextPage: $0.shouldLoadNextPage, nextURL: $0.nextURL) }
// only propagate changed control values since there could be multiple feedback loops working in parallel
.distinctUntilChanged { $0 == $1 }
// perform feedback loop effects
.flatMapLatest { (searchText, shouldLoadNextPage, nextURL) -> Driver<GitHubCommand> in
if !shouldLoadNextPage {
return Driver.empty()
}
if searchText.isEmpty {
return Driver.just(GitHubCommand.gitHubResponseReceived(.success(repositories: [], nextURL: nil)))
}
guard let nextURL = nextURL else {
return Driver.empty()
}
return performSearch(nextURL)
.asDriver(onErrorJustReturn: .failure(GitHubServiceError.networkError))
.map(GitHubCommand.gitHubResponseReceived)
}
}
// this is degenerated feedback loop that doesn't depend on output state
let inputFeedbackLoop: (Driver<GitHubSearchRepositoriesState>) -> Driver<GitHubCommand> = { state in
let loadNextPage = loadNextPageTrigger(state).map { _ in GitHubCommand.loadMoreItems }
let searchText = searchText.map(GitHubCommand.changeSearch)
return Driver.merge(loadNextPage, searchText)
}
// Create a system with two feedback loops that drive the system
// * one that tries to load new pages when necessary
// * one that sends commands from user input
return Driver.system(GitHubSearchRepositoriesState.initial,
accumulator: GitHubSearchRepositoriesState.reduce,
feedback: searchPerformerFeedback, inputFeedbackLoop)
}
func == (
lhs: (searchText: String, shouldLoadNextPage: Bool, nextURL: URL?),
rhs: (searchText: String, shouldLoadNextPage: Bool, nextURL: URL?)
) -> Bool {
return lhs.searchText == rhs.searchText
&& lhs.shouldLoadNextPage == rhs.shouldLoadNextPage
&& lhs.nextURL == rhs.nextURL
}
extension GitHubSearchRepositoriesState {
var isOffline: Bool {
guard let failure = self.failure else {
return false
}
if case .offline = failure {
return true
}
else {
return false
}
}
var isLimitExceeded: Bool {
guard let failure = self.failure else {
return false
}
if case .githubLimitReached = failure {
return true
}
else {
return false
}
}
}
extension GitHubSearchRepositoriesState: Mutable {
}
| mit |
LearningSwift2/LearningApps | SimpleReminders/SimpleReminders/AppDelegate.swift | 1 | 2153 | //
// AppDelegate.swift
// SimpleReminders
//
// Created by Phil Wright on 12/8/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
dn-m/PathTools | PathToolsDemo-iOS/PathToolsDemo-iOS/AppDelegate.swift | 1 | 2156 | //
// AppDelegate.swift
// PathToolsDemo-iOS
//
// Created by James Bean on 6/10/16.
// Copyright © 2016 James Bean. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
NocturneZX/TTT-Pre-Internship-Exercises | Swift/fromSam/week_02/class4/Week2-Class4-3-StdLibrary-iTunesSearchSample/SwiftSortExample/SwiftSortExample/FunctionsAsObjects.swift | 2 | 698 | //
// FunctionsAsObjects.swift
// SwiftSortExample
//
// Created by Aditya Narayan on 6/10/14.
// Copyright (c) 2014 Aditya Narayan. All rights reserved.
//
import Foundation
func functionWithACounter() -> (() -> ()) {
var counter = 1
func implementSomeAlternatingBehavior() {
var s:Bool
s = false
if counter % 2 == 0 {
println("This function was called an EVEN number of times")
} else {
println("This function was called an ODD number of times")
}
counter++
}
return implementSomeAlternatingBehavior
} | gpl-2.0 |
threebytesfull/EasterDate | Tests/EasterDate/EasterDateTests.swift | 1 | 5267 | import XCTest
@testable import EasterDate
import Foundation
class EasterDateTests: XCTestCase {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
func testWesternEasterBeforeGregorianCalendar() {
for year in [1000, 1500, 1582] {
let easter = NSDate.westernEasterDateForYear(year)
XCTAssertNil(easter)
let easter2 = NSDate.westernEasterDate(year: year)
XCTAssertNil(easter2)
}
}
func testWesternEasterForGregorianCalendar() {
let gregorianEasterDates = [
1583: [1583, 4, 10],
2015: [2015, 4, 5],
2016: [2016, 3, 27],
2017: [2017, 4, 16],
]
gregorianEasterDates.forEach { year, expectedEaster in
let easter = NSDate.westernEasterDateForYear(year)
XCTAssertNotNil(easter)
if let easter = easter {
var components: NSDateComponents?
#if swift(>=3.0)
components = calendar.components([.year, .month, .day], from: easter)
#else
components = calendar.components([.Year, .Month, .Day], fromDate: easter)
#endif
XCTAssertNotNil(components)
if let components = components {
XCTAssertEqual([components.year, components.month, components.day], expectedEaster)
}
}
let easter2 = NSDate.westernEasterDate(year: year)
XCTAssertNotNil(easter2)
if let easter2 = easter2 {
var components: NSDateComponents?
#if swift(>=3.0)
components = calendar.components([.year, .month, .day], from: easter2)
#else
components = calendar.components([.Year, .Month, .Day], fromDate: easter2)
#endif
XCTAssertNotNil(components)
if let components = components {
XCTAssertEqual([components.year, components.month, components.day], expectedEaster)
}
}
}
}
func testOrthodoxEasterBefore1900() {
for year in [1000, 1500, 1583, 1899] {
let easter = NSDate.easternOrthodoxEasterDateForYear(year)
XCTAssertNil(easter)
let easter2 = NSDate.easternOrthodoxEasterDate(year: year)
XCTAssertNil(easter2)
}
}
func testOrthodoxEasterBetween1900And2099() {
let orthodoxEasterDates = [
2008: [2008, 4, 27],
2009: [2009, 4, 19],
2010: [2010, 4, 4],
2011: [2011, 4, 24],
2016: [2016, 5, 1],
]
orthodoxEasterDates.forEach { year, expectedEaster in
let easter = NSDate.easternOrthodoxEasterDateForYear(year)
XCTAssertNotNil(easter)
if let easter = easter {
var components: NSDateComponents?
#if swift(>=3.0)
components = calendar.components([.year, .month, .day], from: easter)
#else
components = calendar.components([.Year, .Month, .Day], fromDate: easter)
#endif
XCTAssertNotNil(components)
if let components = components {
XCTAssertEqual([components.year, components.month, components.day], expectedEaster)
}
}
let easter2 = NSDate.easternOrthodoxEasterDate(year: year)
XCTAssertNotNil(easter2)
if let easter2 = easter2 {
var components: NSDateComponents?
#if swift(>=3.0)
components = calendar.components([.year, .month, .day], from: easter2)
#else
components = calendar.components([.Year, .Month, .Day], fromDate: easter2)
#endif
XCTAssertNotNil(components)
if let components = components {
XCTAssertEqual([components.year, components.month, components.day], expectedEaster)
}
}
}
}
func testOrthodoxEasterAfter2099() {
for year in [2100, 2200] {
let easter = NSDate.easternOrthodoxEasterDateForYear(year)
XCTAssertNil(easter)
let easter2 = NSDate.easternOrthodoxEasterDate(year: year)
XCTAssertNil(easter2)
}
}
}
extension EasterDateTests {
static var allTests : [(String, (EasterDateTests) -> () throws -> Void)] {
return [
("testWesternEasterBeforeGregorianCalendar", testWesternEasterBeforeGregorianCalendar),
("testWesternEasterForGregorianCalendar", testWesternEasterForGregorianCalendar),
("testOrthodoxEasterBefore1900", testOrthodoxEasterBefore1900),
("testOrthodoxEasterBetween1900And2099", testOrthodoxEasterBetween1900And2099),
("testOrthodoxEasterAfter2099", testOrthodoxEasterAfter2099),
]
}
}
| mit |
madhusamuel/testStoryboard | teststoryboard/AppDelegate.swift | 1 | 2147 | //
// AppDelegate.swift
// teststoryboard
//
// Created by Madhu Samuel on 17/11/2015.
// Copyright © 2015 Madhu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 |
konduruvijaykumar/ios-sample-apps | SliderMenuDemo/SliderMenuDemo/AWSViewController.swift | 1 | 1250 | //
// AWSViewController.swift
// SliderMenuDemo
//
// Created by Vijay Konduru on 17/02/17.
// Copyright © 2017 PJay. All rights reserved.
//
import UIKit
class AWSViewController: UIViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Burger menu actions
if (revealViewController() != nil) {
menuButton.target = revealViewController();
menuButton.action = #selector(SWRevealViewController.revealToggle(_:));
view.addGestureRecognizer(self.revealViewController().panGestureRecognizer());
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 |
mitchtreece/Spider | Spider/Classes/Core/Helpers/Data+Size.swift | 1 | 1197 | //
// Data+Size.swift
// Spider-Web
//
// Created by Mitch Treece on 10/24/19.
//
import Foundation
public extension Data /* Size */ {
/// Representation of th size of `Data`.
struct Size: CustomStringConvertible, CustomDebugStringConvertible {
private var formatter: ByteCountFormatter {
let formatter = ByteCountFormatter()
formatter.allowedUnits = [.useAll]
formatter.countStyle = .file
return formatter
}
/// The byte count.
public let byteCount: Int64
/// The formatted size string.
public var string: String {
return self.formatter.string(fromByteCount: self.byteCount)
}
public var description: String {
return self.string
}
public var debugDescription: String {
return self.description
}
internal init(byteCount: Int64) {
self.byteCount = byteCount
}
}
/// The data's size descriptor.
var size: Size {
return Size(byteCount: Int64(self.count))
}
}
| mit |
richardpiazza/LCARSDisplayKit | Sources/LCARSDisplayKitUI/CommandSequencer.swift | 1 | 3433 | #if (os(iOS) || os(tvOS))
import UIKit
import LCARSDisplayKit
public protocol CommandSequencerDelegate {
func neutralBeep()
func successBeep()
func failureBeep()
}
public typealias CommandSequenceCompletion = () -> Void
public struct CommandSequence {
public var path: [Button]
public var completion: CommandSequenceCompletion?
public init(_ path: [Button], completion: CommandSequenceCompletion? = nil) {
self.path = path
self.completion = completion
}
}
public class CommandSequencer {
public static var `default`: CommandSequencer = CommandSequencer()
public var delegate: CommandSequencerDelegate?
private var commandSequences: [CommandSequence] = []
private var currentPath: [Button] = []
public func register(commandSequence sequence: CommandSequence) {
if commandSequences.contains(where: { (cs) -> Bool in
return cs.path == sequence.path
}) {
return
}
print("Registering Command Sequence")
commandSequences.append(sequence)
}
public func unregister(commandSequence sequence: CommandSequence) {
var index: Int = -1
for (idx, cs) in commandSequences.enumerated() {
if cs.path == sequence.path {
index = idx
break
}
}
guard index != -1 else {
return
}
print("Unregistering Comannd Sequence")
commandSequences.remove(at: index)
}
private func completion(for commandSequence: [Button]) -> CommandSequenceCompletion? {
let sequence = commandSequences.first(where: { (cs) -> Bool in
return cs.path == commandSequence
})
return sequence?.completion
}
private func sequencesContainingPrefix(_ commandSequence: [Button]) -> [CommandSequence] {
guard commandSequence.count > 0 else {
return []
}
var sequences = [CommandSequence]()
for sequence in commandSequences {
guard sequence.path.count >= commandSequence.count else {
break
}
var prefixed = true
for i in 0..<commandSequence.count {
if sequence.path[i] != commandSequence[i] {
prefixed = false
}
}
if prefixed {
sequences.append(sequence)
}
}
return sequences
}
public func didTouch(_ sender: Button) {
currentPath.append(sender)
guard commandSequences.count > 0 else {
print("No Command Sequences")
delegate?.failureBeep()
currentPath.removeAll()
return
}
if let completion = completion(for: currentPath) {
print("Command Sequence Complete")
completion()
delegate?.successBeep()
currentPath.removeAll()
return
}
guard sequencesContainingPrefix(currentPath).count > 0 else {
print("Command Sequence Failed")
delegate?.failureBeep()
currentPath.removeAll()
return
}
print("Command Sequence In Progress")
delegate?.neutralBeep()
}
}
#endif
| mit |
mbigatti/StatusApp | StatusApp/ZoomAnimatedController.swift | 1 | 4435 | //
// ZoomingViewControllerAnimatedTransitioning.swift
// StatusApp
//
// Created by Massimiliano Bigatti on 30/09/14.
// Copyright (c) 2014 Massimiliano Bigatti. All rights reserved.
//
import Foundation
class ZoomAnimatedController : NSObject, UIViewControllerAnimatedTransitioning
{
var presenting = true
var animatingIndexPath : NSIndexPath?
/// duration of the animation
private let animationDuration : Double = 0.35
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return animationDuration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if presenting {
animatePresenting(transitionContext)
} else {
animateDismissing(transitionContext)
}
}
func animatePresenting(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as UITableViewController!
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
//
// configure the destination controller initial frame
//
let tableView = fromViewController.tableView
animatingIndexPath = tableView.indexPathForSelectedRow()
if animatingIndexPath == nil {
let lastRow = tableView.dataSource!.tableView(tableView, numberOfRowsInSection: 0) - 1
animatingIndexPath = NSIndexPath(forRow: lastRow, inSection: 0)
toViewController.view.backgroundColor = UIColor.blackColor()
}
let originFrame = tableView.rectForRowAtIndexPath(animatingIndexPath!)
toViewController.view.frame = originFrame
//
// add destination controller to content view
//
toViewController.view.clipsToBounds = true
transitionContext.containerView().addSubview(toViewController.view)
//
// perform animation
//
tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 0
UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
toViewController.view.frame = transitionContext.finalFrameForViewController(toViewController)
//fromViewController.view.transform = CGAffineTransformMakeTranslation(-toViewController.view.frame.size.width, 0)
}) { (finished) -> Void in
//
// restore original properties and complete transition
//
//fromViewController.view.transform = CGAffineTransformIdentity
tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 1
toViewController.view.clipsToBounds = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
func animateDismissing(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as UITableViewController!
transitionContext.containerView().addSubview(toViewController.view)
transitionContext.containerView().bringSubviewToFront(fromViewController.view)
fromViewController.view.clipsToBounds = true
let tableView = toViewController.tableView
tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 0
//
// perform animation
//
UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in
let frame = tableView.rectForRowAtIndexPath(self.animatingIndexPath!)
fromViewController.view.frame = frame
}) { (finished) -> Void in
//
// restore original properties and complete transition
//
tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 1
fromViewController.view.clipsToBounds = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
} | mit |
stripe/stripe-ios | Tests/installation_tests/cocoapods/without_frameworks_objc/CocoapodsTest/Empty.swift | 1 | 155 | //
// Empty.swift
// CocoapodsTest
//
// Created by David Estes on 10/19/20.
// Copyright © 2020 jflinter. All rights reserved.
//
import Foundation
| mit |
Vostro162/VaporTelegram | Sources/App/File.swift | 1 | 944 | //
// File.swift
// VaporTelegramBot
//
// Created by Marius Hartig on 08.05.17.
//
//
import Foundation
/*
*
*
* This object represents a file ready to be downloaded.
* The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>.
* It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.
*
*/
public struct File: DataSet {
// Unique identifier for this file
public let fileId: FileId
// Optional. File size, if known
public let fileSize: Int?
// Optional. File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file.
public let filePath: String?
public init(fileId: FileId, fileSize: Int? = nil, filePath: String? = nil) {
self.fileId = fileId
self.fileSize = fileSize
self.filePath = filePath
}
}
| mit |
butterproject/butter-ios | Butter/UI/Views/PlaceholderTextView.swift | 1 | 4239 | //
// PlaceholderTextView.swift
//
// Copyright (c) 2015 Zhouqi Mo (https://github.com/MoZhouqi)
//
// 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
@IBDesignable
public class PlaceholderTextView: UITextView {
struct Constants {
static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
}
@IBInspectable public var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable public var placeholderColor: UIColor = PlaceholderTextView.Constants.defaultiOSPlaceholderColor {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
public let placeholderLabel: UILabel = UILabel()
override public var font: UIFont! {
didSet {
placeholderLabel.font = font
}
}
override public var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override public var text: String! {
didSet {
textDidChange()
}
}
override public var attributedText: NSAttributedString! {
didSet {
textDidChange()
}
}
override public var textContainerInset: UIEdgeInsets {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
var placeholderLabelConstraints = [NSLayoutConstraint]()
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "textDidChange",
name: UITextViewTextDidChangeNotification,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clearColor()
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
updateConstraintsForPlaceholderLabel()
}
func updateConstraintsForPlaceholderLabel() {
var newConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]-(\(textContainerInset.right + textContainer.lineFragmentPadding))-|",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-(\(textContainerInset.top))-[placeholder]-(>=\(textContainerInset.bottom))-|",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
removeConstraints(placeholderLabelConstraints)
addConstraints(newConstraints)
placeholderLabelConstraints = newConstraints
}
func textDidChange() {
placeholderLabel.hidden = !text.isEmpty
}
override public func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UITextViewTextDidChangeNotification,
object: nil)
}
} | gpl-3.0 |
mleiv/MEGameTracker | MEGameTracker/Models/Shepard/Shepard.Origin.swift | 1 | 621 | //
// Shepard.Origin.swift
// MEGameTracker
//
// Created by Emily Ivie on 8/15/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
extension Shepard {
/// Game options for Shepard's origin.
public enum Origin: String, Codable {
case earthborn = "Earthborn"
case spacer = "Spacer"
case colonist = "Colonist"
/// Creates an enum from a string value, if possible.
public init?(stringValue: String?) {
self.init(rawValue: stringValue ?? "")
}
/// Returns the string value of an enum.
public var stringValue: String {
return rawValue
}
}
}
// already Equatable
| mit |
alvinvarghese/Photo-Gallery | PhotoGallery/Classes/ALPhotoGalleryImageCell.swift | 1 | 472 | //
// ALPhotoGalleryImageCell.swift
// PhotoGallery
//
// Created by Alvin Varghese on 6/8/16.
// Copyright © 2016 Swift Coder. All rights reserved.
//
import UIKit
class ALPhotoGalleryImageCell: UITableViewCell {
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var totalCount: UILabel!
@IBOutlet weak var folderName: UILabel!
@IBOutlet weak var subImageSecond: UIImageView!
@IBOutlet weak var subImageThird: UIImageView!
}
| mit |
ello/ello-ios | Sources/Utilities/Onboarding.swift | 1 | 822 | ////
/// Onboarding.swift
//
import SwiftyUserDefaults
class Onboarding {
static let currentVersion = 3
static let minCreatorTypeVersion = 1
static let shared = Onboarding()
func updateVersionToLatest() {
ProfileService().updateUserProfile([.webOnboardingVersion: Onboarding.currentVersion])
.ignoreErrors()
}
// only show if onboardingVersion is nil
func shouldShowOnboarding(_ user: User) -> Bool {
return user.onboardingVersion == nil
}
// only show if onboardingVersion is set and < 3
// (if it isn't set, we will show the entire onboarding flow)
func shouldShowCreatorType(_ user: User) -> Bool {
if let onboardingVersion = user.onboardingVersion {
return onboardingVersion < 3
}
return false
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14018-swift-sourcemanager-getmessage.swift | 11 | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for b {
}
let {
struct d {
class
case ,
| mit |
qxuewei/XWPageView | XWPageViewDemo/XWPageViewDemo/XWPageView/XWTitleStyle.swift | 1 | 1317 | //
// XWTitleStyle.swift
// XWPageViewDemo
//
// Created by 邱学伟 on 2016/12/10.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class XWTitleStyle {
/// 是否是滚动的Title
var isScrollEnable : Bool = false
/// 普通Title颜色
var normalColor : UIColor = UIColor(R: 0, G: 0, B: 0)
/// 选中Title颜色
var selectedColor : UIColor = UIColor(R: 255, G: 127, B: 0)
/// Title字体大小
var font : UIFont = UIFont.systemFont(ofSize: 14.0)
/// 滚动Title的字体间距
var titleMargin : CGFloat = 20
/// title的高度
var titleHeight : CGFloat = 44
/// 是否显示底部滚动条
var isShowBottomLine : Bool = false
/// 底部滚动条的颜色
var bottomLineColor : UIColor = UIColor.orange
/// 底部滚动条的高度
var bottomLineH : CGFloat = 2
/// 是否进行缩放
var isNeedScale : Bool = false
var scaleRange : CGFloat = 1.2
/// 是否显示遮盖
var isShowCover : Bool = false
/// 遮盖背景颜色
var coverBgColor : UIColor = UIColor.lightGray
/// 文字&遮盖间隙
var coverMargin : CGFloat = 5
/// 遮盖的高度
var coverH : CGFloat = 25
/// 设置圆角大小
var coverRadius : CGFloat = 12
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | fixed/26724-clang-declvisitor-base-clang-declvisitor-make-const-ptr.swift | 7 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b
{<a}}{
{
class P{
extension{init{
({{
{{
var _=[[{
class
case,
| mit |
open-telemetry/opentelemetry-swift | Examples/Network Sample/main.swift | 1 | 1594 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetrySdk
import StdoutExporter
import URLSessionInstrumentation
func simpleNetworkCall() {
let url = URL(string: "http://httpbin.org/get")!
let request = URLRequest(url: url)
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
if let data = data {
let string = String(decoding: data, as: UTF8.self)
print(string)
}
semaphore.signal()
}
task.resume()
semaphore.wait()
}
class SessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {
let semaphore = DispatchSemaphore(value: 0)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
semaphore.signal()
}
}
let delegate = SessionDelegate()
func simpleNetworkCallWithDelegate() {
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue:nil)
let url = URL(string: "http://httpbin.org/get")!
let request = URLRequest(url: url)
let task = session.dataTask(with: request)
task.resume()
delegate.semaphore.wait()
}
let spanProcessor = SimpleSpanProcessor(spanExporter: StdoutExporter(isDebug: true))
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration())
simpleNetworkCall()
simpleNetworkCallWithDelegate()
sleep(1)
| apache-2.0 |
adamcohenrose/fastlane | fastlane/spec/fixtures/actions/get_version_number/get_version_numberTests/get_version_numberTests.swift | 3 | 1009 | //
// get_version_numberTests.swift
// get_version_numberTests
//
// Created by Josh Holtz on 3/12/18.
// Copyright © 2018 fastlane. All rights reserved.
//
import XCTest
@testable import get_version_number
class get_version_numberTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.