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 |
---|---|---|---|---|---|
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/SalcedoJose/39_C5Perinola.swift | 1 | 2892 | /*
Nombre del programa: Capitulo 5. Problema 39. Perinola.
Autor: Salcedo Morales Jose Manuel
Fecha de inicio: 2017-02-13
-Descripcion-
Suponer que giramos una perinola dividida equitativamente en tres regiones
numeradas 1, 2 y 3. En este experimento hay solo tres posibles resultados: 1,
2 y 3. La probabilidad teorica de obtener una cualquiera de ellas es 1/3.
Simular el giro de la perinola 1,000 veces. ¿El resultado calculado se
aproxima a la probabilidad teorica?
*/
// LIBRERIAS.
import Foundation
// CONSTANTES.
let REGIONES_PERINOLA: Int = 3
let PRUEBAS: Int = 1000
// FUNCIONES.
// Funcion para cambiar los numeros aleatorios a generar para una corrida.
func DeterminarNumerosAleatorios() {
// Alimentar numeros aleatorios distintos.
srand(UInt32(time(nil)))
}
// Funcion para generar un numero aleatorio.
func GenerarNumeroAleatorio(minimo: Int, maximo: Int) -> Int {
// Definir numero a regresar.
var numeroAleatorio = 0
// Generar numero aleatorio de acuerdo al numero minimo y maximo.
numeroAleatorio = (Int(rand()) % maximo) + minimo
// Retornar numero aleatorio.
return numeroAleatorio
}
// PRINCIPAL.
// Generar numeros aleatorios distintos para esta corrida.
DeterminarNumerosAleatorios()
// Coleccion para guardar las veces que se repitio una region de la perinola.
var repeticionesRegion = [Int: Int]()
for region in 1...REGIONES_PERINOLA {
repeticionesRegion[region] = 0
}
// Realizar y desplegar las pruebas realizadas.
let pruebaNuevaLinea: Int = 100
var prueba: Int = 1
while (prueba <= PRUEBAS) {
// Obtener una region de la perinola aleatoriamente.
let regionPerinola: Int = GenerarNumeroAleatorio(minimo: 1, maximo: REGIONES_PERINOLA)
repeticionesRegion[regionPerinola] = repeticionesRegion[regionPerinola]! + 1
// Determinar el fin de sentencia a utilizar.
var finDeSentencia: String = ""
// Si la prueba es una determinada, utilizar un terminador de sentencia distinto.
if ((prueba % pruebaNuevaLinea) == 0) {
finDeSentencia = "\n"
} else {
finDeSentencia = ", "
}
// Desplegar datos de la prueba.
print("P" + String(prueba) + ": " + String(regionPerinola), terminator: finDeSentencia)
prueba = prueba + 1
}
// Desplegar repeticiones de las regiones.
print("\nRepeticiones de las regiones:")
let probabilidadRegion: Double = (1.0 / Double(REGIONES_PERINOLA)) * 100.0
for region in 1...REGIONES_PERINOLA {
let probabilidadRegionCorrida: Double = (Double(repeticionesRegion[region]!) / Double(PRUEBAS)) * 100.0
let acercamientoProbabilidad: Double = (probabilidadRegionCorrida / probabilidadRegion) * 100.0
print("Region " + String(region) + ": " + String(repeticionesRegion[region]!))
print("Probabilidad de obtener region: " + String(probabilidadRegion) + "%.")
print("Probabilidad con respecto a corrida: " + String(acercamientoProbabilidad) + "%.")
}
// Indicar fin de ejecucion.
print("\nFIN DE EJECUCION.\n")
| gpl-3.0 |
turingcorp/gattaca | gattaca/View/ProfileEdit/VProfileEditListCellName.swift | 1 | 256 | import UIKit
class VProfileEditListCellName:VProfileEditListCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
backgroundColor = UIColor.white
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit |
kumabook/MusicFav | MusicFav/Index.swift | 1 | 215 | //
// Index.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 2017/12/25.
// Copyright © 2017 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import PlayerKit
typealias Index = PlayerKit.Index
| mit |
powerytg/Accented | Accented/Core/API/Requests/GetUserPhotosRequest.swift | 1 | 2484 | //
// GetUserPhotosRequest.swift
// Accented
//
// Get user photos request
//
// Created by Tiangong You on 5/31/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class GetUserPhotosRequest: APIRequest {
private var page : Int
private var userId : String
init(userId : String, page : Int = 1, params : [String : String], success : SuccessAction?, failure : FailureAction?) {
self.userId = userId
self.page = page
super.init(success: success, failure: failure)
cacheKey = "photos/\(userId)/\(page)"
url = "\(APIRequest.baseUrl)photos"
parameters = params
parameters[RequestParameters.feature] = "user"
parameters[RequestParameters.userId] = userId
parameters[RequestParameters.page] = String(page)
parameters[RequestParameters.includeStates] = "1"
if params[RequestParameters.imageSize] == nil {
parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in
return size.rawValue
}).joined(separator: ",")
}
if params[RequestParameters.exclude] == nil {
// Apply default filters
parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",")
}
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
let userInfo : [String : Any] = [RequestParameters.feature : StreamType.User.rawValue,
RequestParameters.userId : userId,
RequestParameters.page : page,
RequestParameters.response : data]
NotificationCenter.default.post(name: APIEvents.streamPhotosDidReturn, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.streamPhotosFailedReturn, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
| mit |
WildDogTeam/demo-ios-swiftchat | WildChat-Swift/AppDelegate.swift | 1 | 2295 | //
// AppDelegate.swift
// WildChat-Swift
//
// Created by Garin on 15/10/12.
// Copyright © 2015年 wilddog. All rights reserved.
//
import UIKit
import Wilddog
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//初始化 WDGApp
let options = WDGOptions.init(syncURL: "https://swift-chat.wilddogio.com")
WDGApp.configure(with: options)
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 |
nodes-ios/SerpentPerformanceComparison | SerpentComparisonTests/PerformanceTestSmallModel.swift | 1 | 1889 | //
// PerformanceTestModel.swift
// Serializable
//
// Created by Chris Combs on 25/02/16.
// Copyright © 2016 Nodes. All rights reserved.
//
import Serpent
import Freddy
import Gloss
import ObjectMapper
import JSONCodable
import Unbox
import Marshal
struct PerformanceTestSmallModel {
var id = ""
var name = ""
}
// Serpent
extension PerformanceTestSmallModel: Serializable {
init(dictionary: NSDictionary?) {
id <== (self, dictionary, "id")
name <== (self, dictionary, "name")
}
func encodableRepresentation() -> NSCoding {
let dict = NSMutableDictionary()
(dict, "id") <== id
(dict, "name") <== name
return dict
}
}
/////////////////////////////////////
/*
Other libraries
*/
// Freddy
extension PerformanceTestSmallModel: Freddy.JSONDecodable {
init(json value: Freddy.JSON) throws {
id = try value.getString(at: "id")
name = try value.getString(at: "name")
}
}
// Gloss
extension PerformanceTestSmallModel: Gloss.Decodable {
init?(json: Gloss.JSON) {
id = "id" <~~ json ?? id
name = "name" <~~ json ?? name
}
}
// ObjectMapper
extension PerformanceTestSmallModel: Mappable {
init?(map: Map) {
}
mutating func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
}
// JSONCodable
extension PerformanceTestSmallModel: JSONCodable {
init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
id = try decoder.decode("id")
name = try decoder.decode("name")
}
}
// Unbox
extension PerformanceTestSmallModel: Unboxable {
init(unboxer: Unboxer) throws {
id = try unboxer.unbox(key: "id")
name = try unboxer.unbox(key: "name")
}
}
// Marshal
extension PerformanceTestSmallModel: Unmarshaling {
init(object: MarshaledObject) throws {
id = try object.value(for: "id")
name = try object.value(for: "name")
}
}
| mit |
litleleprikon/udacity-ios-nanodegree | OffTheSeif/OffTheSeifUITests/OffTheSeifUITests.swift | 1 | 1264 | //
// OffTheSeifUITests.swift
// OffTheSeifUITests
//
// Created by Emil Sharifullin on 19/06/16.
// Copyright © 2016 Emil Sharifullin. All rights reserved.
//
import XCTest
class OffTheSeifUITests: 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.
}
}
| apache-2.0 |
turingcorp/kitkat | kitkat/Category/CategoryNSNotification.swift | 1 | 233 | import Foundation
extension NSNotification
{
enum NSNotificationName:String
{
case GandallersLoaded = "gandallersLoaded"
case GandallerImage = "gandallerImage"
case ImageLoaded = "imageLoaded"
}
} | mit |
ckhsponge/iairportsdb | iAirportsDB/Classes/IADBRunway.swift | 1 | 3969 | //
// IADBRunway.swift
// iAirportsDB
//
// Created by Christopher Hobbs on 8/21/16.
// Copyright © 2016 Toonsy Net. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
@objc(IADBRunway)
open class IADBRunway: IADBModel {
@NSManaged var airportId: Int32
@NSManaged open var closed: Bool
@NSManaged open var lighted: Bool
@NSManaged open var headingTrue: Float // runway 12 will have a magnetic heading of ~120
@NSManaged open var identifierA: String // e.g. 12
@NSManaged open var identifierB: String // e.g. 30
@NSManaged open var lengthFeet: Int32
@NSManaged open var surface: String
@NSManaged open var widthFeet: Int32
open weak var airport:IADBAirport? // weak to prevent strong reference cycle
static let HARD_SURFACES = ["ASP", "CON", "PEM", "ASF", "PAV", "BIT", "TAR"]
static let SOFT_SURFACES = ["UNPAVED"]
// if headingDegrees is valid add the deviation, otherwise return -1
// CoreLocation doesn't provide deviation :(
// use identifier to guess heading if there is no true heading
open func headingMagnetic(_ deviation: CLLocationDirection) -> CLLocationDirection {
return self.headingTrue >= 0.0 ? IADBConstants.withinZeroTo360(Double(self.headingTrue) - deviation) : self.headingMagneticFromIdentifier()
}
open func headingMagneticFromIdentifier() -> CLLocationDirection {
return IADBRunway.identifierDegrees(self.identifierA)
}
//guess the runway heading from the identifier e.g. 01R heads 10° and 04 or 4 heads 40°
//returns -1 if guessing fails
static func identifierDegrees(_ identifier:String) -> CLLocationDirection {
let digits = CharacterSet.decimalDigits
let unicodes = identifier.unicodeScalars
if !unicodes.isEmpty && digits.contains(UnicodeScalar(unicodes[unicodes.startIndex].value)!) {
if unicodes.count >= 2 && digits.contains(UnicodeScalar(unicodes[unicodes.index(unicodes.startIndex, offsetBy: 1)].value)!) {
return CDouble(identifier.substring(to: identifier.index(identifier.startIndex, offsetBy: 2)))! * 10.0
}
else {
return CDouble(identifier.substring(to: identifier.index(identifier.startIndex, offsetBy: 1)))! * 10.0
}
}
return -1.0
}
open func isHard() -> Bool {
return IADBRunway.isHard(surface: self.surface)
}
static func isHard(surface:String) -> Bool {
let surface = surface.uppercased()
return string(surface, containsAny: IADBRunway.HARD_SURFACES) && !string(surface, containsAny: IADBRunway.SOFT_SURFACES)
}
static func string(_ s:String, containsAny matches:[String]) -> Bool {
return matches.reduce(false) { (b, match) in b || s.contains(match)}
}
override open var description: String {
return "\(self.identifierA)/\(self.identifierB) \(self.lengthFeet)\(self.widthFeet) \(self.surface) \(self.headingTrue)"
}
override open func setCsvValues( _ values: [String: String] ) {
//"id","airport_ref","airport_ident","length_ft","width_ft","surface","lighted","closed","le_ident","le_latitude_deg","le_longitude_deg","le_elevation_ft","le_heading_degT","le_displaced_threshold_ft","he_ident","he_latitude_deg","he_longitude_deg","he_elevation_ft","he_heading_degT","he_displaced_threshold_ft",
//print(values)
self.airportId = Int32(values["airport_ref"]!)!
self.closed = "1" == values["closed"]
self.lighted = "1" == values["lighted"]
self.headingTrue = Float(values["le_heading_degT"]!) ?? -1
self.identifierA = values["le_ident"] ?? ""
self.identifierB = values["he_ident"] ?? ""
self.lengthFeet = Int32(values["length_ft"]!) ?? -1
self.surface = values["surface"] ?? ""
self.widthFeet = Int32(values["width_ft"]!) ?? -1
}
}
| mit |
simonkim/AVCapture | AVCapture/AVCaptureClient.swift | 1 | 2220 | //
// AVCapture.swift
// AVCapture
//
// Created by Simon Kim on 2016. 9. 11..
// Copyright © 2016 DZPub.com. All rights reserved.
//
import Foundation
import AVFoundation
public enum AVCaptureClientOptionKey {
case encodeVideo(Bool)
case videoBitrate(Int)
case encodeAudio(Bool)
case AVCaptureSessionPreset(String)
/// Overrides AVCaptureSessionPreset(String)
case videoDimensions(CMVideoDimensions)
/// Applicable only if videoDimensions(CMVideoDimensions) provided
case videoFrameRate(Float64)
}
public protocol AVCaptureClient {
var mediaType: CMMediaType { get }
func configure(session:AVCaptureSession)
func stop()
func reset(session:AVCaptureSession)
func setDataDelegate(_ delegate: AVCaptureClientDataDelegate?)
func set(options: [AVCaptureClientOptionKey])
}
public protocol AVCaptureClientDataDelegate {
func client(client: AVCaptureClient, output sampleBuffer: CMSampleBuffer )
func client(client: AVCaptureClient, didConfigureVideoSize videoSize: CGSize )
}
public class AVCaptureClientSimple: AVCaptureServiceClient {
public var dataDelegate: AVCaptureClientDataDelegate? {
didSet {
for client in clients {
client.setDataDelegate(dataDelegate)
}
}
}
public var options: [AVCaptureClientOptionKey] = [
.encodeVideo(true)
]
public var videoCapture: AVCaptureClient {
return clients[1]
}
private lazy var clients: [AVCaptureClient] = {
return [AudioCapture(), VideoCapture()]
}()
public init() {
}
public func captureService(_ service: AVCaptureService, configure session: AVCaptureSession) {
for client in clients {
client.set(options: options)
client.configure(session: session)
}
}
public func captureService(_ service: AVCaptureService, reset session: AVCaptureSession) {
for client in clients {
client.reset(session: session)
}
}
public func captureServiceDidStop(_ service: AVCaptureService) {
for client in clients {
client.stop()
}
}
}
| apache-2.0 |
soapyigu/LeetCode_Swift | DFS/ExpressionAddOperators.swift | 1 | 1978 | /**
* Question Link: https://leetcode.com/problems/expression-add-operators/
* Primary idea: Classic Depth-first Search, terminates at when position encounters the
* length of the string num, add to result when eval is equal to target
*
* Note:
* 1. String cast to Integer will make character loss, e.g. "05" -> 5
* 2. Multiplication's priority is higher than addiction
*
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/
class ExpressionAddOperators {
func addOperators(_ num: String, _ target: Int) -> [String] {
var res = [String]()
guard num.count > 0 else {
return res
}
dfs(&res, "", num, target, 0, 0, 0)
return res
}
private func dfs(_ res: inout [String], _ temp: String, _ num: String, _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
if pos == num.count {
if eval == target {
res.append(temp)
}
return
}
for i in pos..<num.count {
if i != pos && num[pos] == "0" {
break
}
let curt = Int(num[pos..<i + 1])!
if pos == 0 {
dfs(&res, temp + String(curt), num, target, i + 1, curt, curt)
} else {
dfs(&res, temp + "+" + String(curt), num, target, i + 1, eval + curt, curt)
dfs(&res, temp + "-" + String(curt), num, target, i + 1, eval - curt, -curt)
dfs(&res, temp + "*" + String(curt), num, target, i + 1, eval - mul + mul * curt, mul * curt)
}
}
}
}
extension String {
subscript(index: Int) -> String {
get {
assert(index < self.count)
return String(Array(self.characters)[index])
}
}
subscript(range: CountableRange<Int>) -> String {
get {
var result = ""
for i in range {
assert(i < self.count)
result.append(self[i])
}
return result
}
}
}
| mit |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Platform/watchOS Extension/ConnectedInterfaceController.swift | 1 | 1766 | //
// ConnectedInterfaceController.swift
// Bluefruit Connect
//
// Created by Antonio García on 01/05/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import WatchKit
import Foundation
class ConnectedInterfaceController: WKInterfaceController {
@IBOutlet var peripheralNameLabel: WKInterfaceLabel!
@IBOutlet var uartAvailableLabel: WKInterfaceLabel!
@IBOutlet var uartUnavailableLabel: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
// Update values
if let appContext = WatchSessionManager.sharedInstance.session?.receivedApplicationContext {
didReceiveApplicationContext(appContext)
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: - Session
func didReceiveApplicationContext(applicationContext: [String : AnyObject]) {
DLog("ConnectedInterfaceController didReceiveApplicationContext: \(applicationContext)")
// Name
var peripheralName = "{No Name}"
if let name = applicationContext["bleConnectedPeripheralName"] as? String {
peripheralName = name
}
peripheralNameLabel.setText( peripheralName )
// Uart
let hasUart = applicationContext["bleHasUart"]?.boolValue == true
uartAvailableLabel.setHidden(!hasUart)
uartUnavailableLabel.setHidden(hasUart)
}
}
| mit |
Harry-L/5-3-1 | 531old/531/FirstViewController.swift | 1 | 7127 | //
// FirstViewController.swift
// 531
//
// Created by Harry Liu on 2016-01-21.
// Copyright © 2016 HarryLiu. All rights reserved.
//
import UIKit
class FirstViewController: UITableViewController {
var workouts = [Workout]()
var schedule = [[[Int]]]()
var nextWorkout = [Int]()
var names = ["Overhead Press", "Squat", "Bench Press", "Deadlift"]
var maximums = [Int]()
@IBAction func unwindToFirstViewController(segue: UIStoryboardSegue) {
nextWorkout = [(nextWorkout[0] + nextWorkout[1] / names.count) % 4, (nextWorkout[1] % names.count) + 1]
if nextWorkout[0] == 0 {
nextWorkout[0] = 4
}
print(nextWorkout)
}
@IBAction func unwindFromSettings(segue: UIStoryboardSegue) {
let three = parentViewController
let two = three?.parentViewController
let one = two?.parentViewController
if let pvc = one as? ContainerViewController{
pvc.closeMenu()
}
let vc = segue.sourceViewController as! Settings
maximums = vc.maximums
}
@IBAction func toggleMenu(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("toggleMenu", object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
//basic settings
tableView.allowsSelection = false
//Pulls workouts for NSUserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
workouts = defaults.arrayForKey("history") as? [Workout] ?? [Workout]()
maximums = defaults.arrayForKey("maximums") as? [Int] ?? [0, 0, 0, 0]
nextWorkout = defaults.arrayForKey("nextWorkout") as? [Int] ?? [1, 1]
schedule = [[[65, 5], [75, 5], [85, 5]], [[70, 3], [80, 3], [90, 3]], [[75, 5], [85, 3], [95, 1]], [[40, 5], [50, 5], [60, 5]]]
//Sets title
title = "5/3/1"
//Sets UI Colors
navigationController!.navigationBar.barTintColor = UIColor.blackColor()
navigationController!.navigationBar.tintColor = UIColor.whiteColor()
navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
tableView.backgroundColor = UIColor.lightGrayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return workouts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("history", forIndexPath: indexPath) as! HistoryViewCell
let date = workouts[indexPath.row].date
let name = workouts[indexPath.row].exercises[0].movement
let week = workouts[indexPath.row].week
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
let dateString = formatter.stringFromDate(date)
cell.dateLabel.text! = dateString
cell.nameLabel.text! = "\(name): Week \(week)"
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.lightGrayColor()
let subview : UIView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 90))
subview.backgroundColor = UIColor.whiteColor()
cell.contentView.addSubview(subview)
cell.contentView.sendSubviewToBack(subview)
}
func addWorkout(workout: Workout) {
workouts.insert(workout, atIndex: 0)
tableView.reloadData()
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let back = UIBarButtonItem()
back.title = "Cancel"
navigationItem.backBarButtonItem = back
print(maximums)
if (segue.identifier == "Add") {
let vc = segue.destinationViewController as! AddWorkoutViewController
vc.week = nextWorkout[0]
let day = nextWorkout[1]
vc.movement = names[day-1]
for array in schedule[nextWorkout[0]-1] {
let current = exercise.init(movement: vc.movement, weight: maximums[day-1] * array[0] / 100, reps: array[1])
vc.exercises.append(current)
}
}
}
}
| mit |
HTWDD/HTWDresden-iOS | HTWDD/Core/Extensions/MoyaProvider+Rx.swift | 1 | 2584 | //
// MoyaProvider+Rx.swift
// HTWDD
//
// Created by Mustafa Karademir on 30.06.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
import Moya
extension MoyaProvider: ReactiveCompatible {}
public extension Reactive where Base: MoyaProviderType {
/// Designated request-making method.
///
/// - Parameters:
/// - token: Entity, which provides specifications necessary for a `MoyaProvider`.
/// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used.
/// - Returns: Single response object.
func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Single<Response> {
return Single.create { [weak base] single in
let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in
switch result {
case let .success(response):
single(.success(response))
case let .failure(error):
single(.error(error))
}
}
return Disposables.create {
cancellableToken?.cancel()
}
}
}
/// Designated request-making method with progress.
func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable<ProgressResponse> {
let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in
return { progress in
observer.onNext(progress)
}
}
let response: Observable<ProgressResponse> = Observable.create { [weak base] observer in
let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in
switch result {
case .success:
observer.onCompleted()
case let .failure(error):
observer.onError(error)
}
}
return Disposables.create {
cancellableToken?.cancel()
}
}
// Accumulate all progress and combine them when the result comes
return response.scan(ProgressResponse()) { last, progress in
let progressObject = progress.progressObject ?? last.progressObject
let response = progress.response ?? last.response
return ProgressResponse(progress: progressObject, response: response)
}
}
}
| gpl-2.0 |
iOSDevLog/iOSDevLog | 201. UI Test/Swift/Common/ListPresenterUtilities.swift | 1 | 3721 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Helper functions to perform common operations in `IncompleteListItemsPresenter` and `AllListItemsPresenter`.
*/
import Foundation
/**
Removes each list item found in `listItemsToRemove` from the `initialListItems` array. For each removal,
the function notifies the `listPresenter`'s delegate of the change.
*/
func removeListItemsFromListItemsWithListPresenter(listPresenter: ListPresenterType, inout initialListItems: [ListItem], listItemsToRemove: [ListItem]) {
let sortedListItemsToRemove = listItemsToRemove.sort { initialListItems.indexOf($0)! > initialListItems.indexOf($1)! }
for listItemToRemove in sortedListItemsToRemove {
// Use the index of the list item to remove in the current list's list items.
let indexOfListItemToRemoveInOldList = initialListItems.indexOf(listItemToRemove)!
initialListItems.removeAtIndex(indexOfListItemToRemoveInOldList)
listPresenter.delegate?.listPresenter(listPresenter, didRemoveListItem: listItemToRemove, atIndex: indexOfListItemToRemoveInOldList)
}
}
/**
Inserts each list item in `listItemsToInsert` into `initialListItems`. For each insertion, the function
notifies the `listPresenter`'s delegate of the change.
*/
func insertListItemsIntoListItemsWithListPresenter(listPresenter: ListPresenterType, inout initialListItems: [ListItem], listItemsToInsert: [ListItem]) {
for (idx, insertedIncompleteListItem) in listItemsToInsert.enumerate() {
initialListItems.insert(insertedIncompleteListItem, atIndex: idx)
listPresenter.delegate?.listPresenter(listPresenter, didInsertListItem: insertedIncompleteListItem, atIndex: idx)
}
}
/**
Replaces the stale list items in `presentedListItems` with the new ones found in `newUpdatedListItems`. For
each update, the function notifies the `listPresenter`'s delegate of the update.
*/
func updateListItemsWithListItemsForListPresenter(listPresenter: ListPresenterType, inout presentedListItems: [ListItem], newUpdatedListItems: [ListItem]) {
for newlyUpdatedListItem in newUpdatedListItems {
let indexOfListItem = presentedListItems.indexOf(newlyUpdatedListItem)!
presentedListItems[indexOfListItem] = newlyUpdatedListItem
listPresenter.delegate?.listPresenter(listPresenter, didUpdateListItem: newlyUpdatedListItem, atIndex: indexOfListItem)
}
}
/**
Replaces `color` with `newColor` if the colors are different. If the colors are different, the function
notifies the delegate of the updated color change. If `isForInitialLayout` is not `nil`, the function wraps
the changes in a call to `listPresenterWillChangeListLayout(_:isInitialLayout:)`
and a call to `listPresenterDidChangeListLayout(_:isInitialLayout:)` with the value `isForInitialLayout!`.
*/
func updateListColorForListPresenterIfDifferent(listPresenter: ListPresenterType, inout color: List.Color, newColor: List.Color, isForInitialLayout: Bool? = nil) {
// Don't trigger any updates if the new color is the same as the current color.
if color == newColor { return }
if isForInitialLayout != nil {
listPresenter.delegate?.listPresenterWillChangeListLayout(listPresenter, isInitialLayout: isForInitialLayout!)
}
color = newColor
listPresenter.delegate?.listPresenter(listPresenter, didUpdateListColorWithColor: newColor)
if isForInitialLayout != nil {
listPresenter.delegate?.listPresenterDidChangeListLayout(listPresenter, isInitialLayout: isForInitialLayout!)
}
} | mit |
payjp/payjp-ios | example-swift/example-swift-ui/AppDelegate.swift | 1 | 2093 | //
// AppDelegate.swift
// example-swift-ui
//
// Created by Tatsuya Kitagawa on 2020/07/21.
//
import UIKit
import PAYJP
let PAYJPPublicKey = "pk_test_0383a1b8f91e8a6e3ea0e2a9"
let App3DSRedirectURL = "exampleswift://tds/complete"
let App3DSRedirectURLKey = "swift-app"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
PAYJPSDK.publicKey = PAYJPPublicKey
PAYJPSDK.locale = Locale.current
PAYJPSDK.threeDSecureURLConfiguration =
ThreeDSecureURLConfiguration(redirectURL: URL(string: App3DSRedirectURL)!,
redirectURLKey: App3DSRedirectURLKey)
return true
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
return ThreeDSecureProcessHandler.shared.completeThreeDSecureProcess(url: url)
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| mit |
sjsoad/SKUtils | SKUtils/Flows/App Settings Showing Example/View/AppSettingsViewController.swift | 1 | 491 | //
// AppSettingsViewController.swift
// SKUtils
//
// Created by Sergey Kostyan on 20.05.2018.
//Copyright © 2018 Sergey Kostyan. All rights reserved.
//
import UIKit
class AppSettingsViewController: UIViewController, AppSettingsInterface {
var presenter: AppSettingsOutput?
// MARK: - IBActions -
@IBAction func showSettingsButtonPressed(_ sender: UIButton) {
presenter?.viewTriggeredShowSettingsEvent()
}
// MARK: - AppSettingsInterface -
}
| mit |
relayr/apple-sdk | Tests/CommonTests/ServicesTests/APITests/APIPublishersTest.swift | 1 | 3748 | import XCTest
import ReactiveSwift
@testable import Relayr
final class APIPublishersTest: XCTestCase {
// API instance pointing to the environment being tested.
fileprivate var api: Relayr.API!
override func setUp() {
super.setUp()
let (hostURL, token): (String, String) = (Test.variables.server.api, Test.variables.user.token)
self.api = API(withURLs: API.Addresses(root: hostURL, broker: hostURL), token: token)
}
override func tearDown() {
self.api = nil
super.tearDown()
}
static var allTests = [
("testPublishers", testPublishers),
("testPublisherLifecycle", testPublisherLifecycle)
]
}
extension APIPublishersTest {
/// Tests the publishers retrieval.
func testPublishers() {
let signal = self.api.publishers().on(value: { (response) in
XCTAssertFalse(response.identifier.isEmpty)
XCTAssertFalse(response.owner.isEmpty)
}).collect().on { (response) in
XCTAssertFalse(response.isEmpty)
}
Test.signal(signal, onTest: self, message: "Cloud's publishers", numEndpoints: 1, timeout: 2*Test.endPointTimeout)
}
func testPublisherLifecycle() {
let (api, user, publisher) = (self.api!, Test.variables.user, Test.variables.publisher)
var received: (identifier: String?, name: String) = (nil, "Manolo")
let signal = api.createPublisher(withName: publisher.name, ownedByUserWithID: user.identifier).flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in
Test.check(publisher: response, withIdentifier: nil, name: publisher.name, ownerID: user.identifier)
received.identifier = response.identifier
return api.setPublisherInfo(withID: response.identifier, name: received.name)
}.flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in
Test.check(publisher: response, withIdentifier: received.identifier!, name: received.name, ownerID: user.identifier)
return api.publisherInfo(withID: response.identifier)
}.flatMap(.latest) { (response) -> SignalProducer<API.Publisher,API.Error> in
Test.check(publisher: response, withIdentifier: received.identifier!, name: received.name, ownerID: user.identifier)
return api.publishersFromUser(withID: user.identifier)
}.on(value: { (response) in
XCTAssertFalse(response.identifier.isEmpty)
XCTAssertEqual(response.owner, user.identifier)
}).collect().flatMap(.latest) { (response) -> SignalProducer<(),API.Error> in
XCTAssertFalse(response.isEmpty)
let found = response.find { $0.identifier == received.identifier! && $0.name == received.name && $0.owner == user.identifier }
XCTAssertNotNil(found)
return api.delete(publisherWithID: received.identifier!)
}
Test.signal(signal, onTest: self, message: "Publisher lifecycle", numEndpoints: 5) {
guard let publisherID = received.identifier else { return SignalProducer.empty }
return api.delete(publisherWithID: publisherID)
}
}
}
fileprivate extension Test {
/// Checks that the given publisher is in a correct state
fileprivate static func check(publisher: API.Publisher, withIdentifier identifier: String?, name: String, ownerID: String) {
if let identifier = identifier {
XCTAssertEqual(publisher.identifier, identifier, "Received publisher identifier is not the same as before")
} else {
XCTAssertFalse(publisher.identifier.isEmpty, "The publisher identifier is empty")
}
XCTAssertEqual(publisher.name, name)
XCTAssertEqual(publisher.owner, ownerID)
}
}
| mit |
kopto/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationBallGridPulse.swift | 1 | 3679 | //
// KRActivityIndicatorAnimationBallGridPulse.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
class KRActivityIndicatorAnimationBallGridPulse: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations: [CFTimeInterval] = [0.72, 1.02, 1.28, 1.42, 1.45, 1.18, 0.87, 1.45, 1.06]
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [-0.06, 0.25, -0.17, 0.48, 0.31, 0.03, 0.46, 0.78, 0.45]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.5, 1]
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.timingFunctions = [timingFunction, timingFunction]
opacityAnimation.values = [1, 0.7, 1]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
| mit |
google/GoogleSignIn-iOS | GoogleSignInSwift/Sources/GoogleSignInButtonStrings.swift | 1 | 2243 | /*
* Copyright 2022 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.
*/
#if !arch(arm) && !arch(i386)
import Foundation
/// A type retrieving the localized strings for the sign-in button text.
@available(iOS 13.0, macOS 10.15, *)
struct GoogleSignInButtonString {
/// Button text used as both key in localized strings files and default value
/// for the standard button.
private let standardButtonText = "Sign in"
/// Button text used as both key in localized strings files and default value
/// for the wide button.
private let wideButtonText = "Sign in with Google"
/// The table name for localized strings (i.e. file name before .strings
/// suffix).
private let stringsTableName = "GoogleSignIn"
/// Returns the localized string for the key if available, or the supplied
/// default text if not.
/// - parameter key: A `String` key to look up.
/// - parameter text: The default `String` text.
/// - returns Either the found `String` or the provided default text.
private func localizedString(key: String, text: String) -> String {
guard let frameworkBundle = Bundle.gidFrameworkBundle() else { return text }
return frameworkBundle.localizedString(
forKey: key,
value: text,
table: stringsTableName
)
}
/// Localized text for the standard button.
@available(iOS 13.0, macOS 10.15, *)
var localizedStandardButtonText: String {
return localizedString(key: standardButtonText, text: "No translation")
}
/// Localized text for the wide button.
@available(iOS 13.0, macOS 10.15, *)
var localizedWideButtonText: String {
return localizedString(key: wideButtonText, text: "No translation")
}
}
#endif // !arch(arm) && !arch(i386)
| apache-2.0 |
airfight/GYProgressLineAndCircleView | GYProgressLineAndCircleView/GYProgressLineAndCircleView/ViewController.swift | 1 | 2879 | //
// ViewController.swift
// GYProgressLineAndCircleView
//
// Created by zhuguangyang on 2017/1/13.
// Copyright © 2017年 GYJade. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var arrTitls:Array<String>! = nil
var subView:GYLineView!
override func viewDidLoad() {
super.viewDidLoad()
let fps = YYFPSLabel(frame: CGRect(x: self.view.frame.maxX - 60, y: self.view.frame.maxY - 30, width: 60, height: 30))
self.navigationController?.view.addSubview(fps)
// view.backgroundColor = UIColor.init(hex: "0xFFEC8B")
//此View未完善
// arrTitls = ["你好","2","3","4"]
//
//
// let progressView = GYLineProgressView()
// progressView.frame = CGRect(x: 0, y: 100, width: self.view.frame.width, height: 170)
// progressView.delegate = self
// progressView.dataSource = self
//// progressView.backgroundColor = UIColor.red
// //
// view.addSubview(progressView)
//
// progressView.reloadData()
//
// progressView.currentProgress = 0
// 带进度标题的直线
subView = GYLineView()
subView.frame = CGRect(x: 10, y: 50, width: 300, height: 100)
subView.progressLevelArray = ["1","2","3","4","5","6"];
subView.lineMaxHeight = 4
subView.pointMaxRadius = 6
subView.textPosition = ProgressLevelTextPosition.Top
view.addSubview(subView)
// subView.currentLevel = 2
// subView.startAnimation()
//渐变进度条
// let progrssView = GYLineColorGradientView(frame: CGRect(x: 20.0, y: 100, width: 320 - 40, height: 45))
//
// progrssView.percent = 100
//
// self.view.addSubview(progrssView)
}
@IBAction func chageValue(_ sender: Any) {
subView.currentLevel = 4
// subView.layoutSubviews()
subView.startAnimation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
subView.startAnimation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: GYLineProgressViewDelegate,GYLineProgressViewDataSource {
func numberOfProgressInProgressView() -> NSInteger? {
return 4
}
func progressView(progressView: GYLineProgressView, titleAtIndex: NSInteger) -> String? {
return arrTitls[titleAtIndex]
}
func highlightColorForCircleViewInProgressView(progressView: GYLineProgressView) -> UIColor? {
return UIColor.blue
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/25615-swift-typechecker-coercepatterntotype.swift | 11 | 463 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a{struct S{class C{
class b{{}func a{
struct S<T where S=l
enum S
| apache-2.0 |
wikimedia/wikipedia-ios | Widgets/Utilities/UIColor+Extensions.swift | 1 | 86 | import SwiftUI
extension UIColor {
var asColor: Color {
return Color(self)
}
}
| mit |
mleiv/MEGameTracker | MEGameTracker/Views/Missions Tab/Missions Split View/MissionsSplitViewController.swift | 1 | 1329 | //
// MissionsSplitViewController.swift
// MEGameTracker
//
// Created by Emily Ivie on 2/24/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
final class MissionsSplitViewController: UIViewController, MESplitViewController {
@IBOutlet weak var mainPlaceholder: IBIncludedSubThing?
@IBOutlet weak var detailBorderLeftView: UIView?
@IBOutlet weak var detailPlaceholder: IBIncludedSubThing?
var ferriedSegue: FerriedPrepareForSegueClosure?
// set by parent, shared with child:
var missionsType: MissionType = .mission
var missionsCount: Int = 0
var missions: [Mission] = []
var deepLinkedMission: Mission?
var isLoadedSignal: Signal<(type: MissionType, values: [Mission])>?
var isPageLoaded = false
var dontSplitViewInPage = false
@IBAction func closeDetailStoryboard(_ sender: AnyObject?) {
closeDetailStoryboard()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
ferriedSegue?(segue.destination)
}
}
extension MissionsSplitViewController: DeepLinkable {
// MARK: DeepLinkable protocol
func deepLink(_ object: DeepLinkType?, type: String? = nil) {
DispatchQueue.global(qos: .background).async { [weak self] in
if let mission = object as? Mission {
self?.deepLinkedMission = mission // passthrough
// reload missions page?
}
}
}
}
| mit |
younata/SyntaxKit | SyntaxKit/Language.swift | 3 | 1347 | //
// Language.swift
// SyntaxKit
//
// Created by Sam Soffes on 9/18/14.
// Copyright © 2014-2015 Sam Soffes. All rights reserved.
//
import Foundation
public struct Language {
// MARK: - Properties
public let UUID: String
public let name: String
public let scopeName: String
let patterns: [Pattern]
// MARK: - Initializers
public init?(dictionary: [NSObject: AnyObject]) {
guard let UUID = dictionary["uuid"] as? String,
name = dictionary["name"] as? String,
scopeName = dictionary["scopeName"] as? String
else { return nil }
self.UUID = UUID
self.name = name
self.scopeName = scopeName
var repository = [String: Pattern]()
if let repo = dictionary["repository"] as? [String: [NSObject: AnyObject]] {
for (key, value) in repo {
if let pattern = Pattern(dictionary: value) {
repository[key] = pattern
}
}
}
var patterns = [Pattern]()
if let array = dictionary["patterns"] as? [[NSObject: AnyObject]] {
for value in array {
if let include = value["include"] as? String {
let key = include.substringFromIndex(include.startIndex.successor())
if let pattern = repository[key] {
patterns.append(pattern)
continue
}
}
if let pattern = Pattern(dictionary: value) {
patterns.append(pattern)
}
}
}
self.patterns = patterns
}
}
| mit |
bazelbuild/tulsi | src/TulsiGenerator/BazelLocator.swift | 1 | 2415 | // Copyright 2016 The Tulsi 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
/// Provides methods to locate the default Bazel instance.
public struct BazelLocator {
/// NSUserDefaults key for the default Bazel path if one is not found in the opened project's
/// workspace.
public static let DefaultBazelURLKey = "defaultBazelURL"
public static var bazelURL: URL? {
if let bazelURL = UserDefaults.standard.url(forKey: BazelLocator.DefaultBazelURLKey),
FileManager.default.fileExists(atPath: bazelURL.path) {
return bazelURL
}
// If no default set, check for bazel on the user's PATH.
let semaphore = DispatchSemaphore(value: 0)
var completionInfo: ProcessRunner.CompletionInfo?
let task = TulsiProcessRunner.createProcess("/bin/bash",
arguments: ["-l", "-c", "which bazel"]) {
processCompletionInfo in
defer { semaphore.signal() }
completionInfo = processCompletionInfo
}
task.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
guard let info = completionInfo else {
return nil
}
guard info.terminationStatus == 0 else {
return nil
}
guard let stdout = String(data: info.stdout, encoding: String.Encoding.utf8) else {
return nil
}
let bazelURL = URL(fileURLWithPath: stdout.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines),
isDirectory: false)
guard FileManager.default.fileExists(atPath: bazelURL.path) else {
return nil
}
UserDefaults.standard.set(bazelURL, forKey: BazelLocator.DefaultBazelURLKey)
return bazelURL
}
// MARK: - Private methods
private init() {
}
}
| apache-2.0 |
niklassaers/PackStream-Swift | Tests/PackStreamTests/BoolTests.swift | 1 | 972 | import XCTest
@testable import PackStream
class BoolTests: XCTestCase {
func testTrue() throws {
let val = true
let bytes = try val.pack()
let unpacked = try Bool.unpack(bytes[0..<bytes.count])
XCTAssertEqual(val, unpacked)
}
func testFalse() throws {
let val = false
let bytes = try val.pack()
let unpacked = try Bool.unpack(bytes[0..<bytes.count])
XCTAssertEqual(val, unpacked)
}
func testFailOnBadBytes() {
do {
let bytes = [ Byte(0x00) ]
let _ = try Bool.unpack(bytes[0..<bytes.count])
} catch {
return // Test success
}
XCTFail("Should have reached exception")
}
static var allTests : [(String, (BoolTests) -> () throws -> Void)] {
return [
("testTrue", testTrue),
("testFalse", testFalse),
("testFailOnBadBytes", testFailOnBadBytes),
]
}
}
| bsd-3-clause |
claudioredi/aerogear-ios-oauth2 | AeroGearOAuth2Tests/KeycloakOAuth2ModuleTest.swift | 1 | 4889 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import XCTest
import AeroGearOAuth2
import AeroGearHttp
import OHHTTPStubs
let KEYCLOAK_TOKEN = "eyJhbGciOiJSUzI1NiJ9.eyJuYW1lIjoiU2FtcGxlIFVzZXIiLCJlbWFpbCI6InNhbXBsZS11c2VyQGV4YW1wbGUiLCJqdGkiOiI5MTEwNjAwZS1mYTdiLTRmOWItOWEwOC0xZGJlMGY1YTY5YzEiLCJleHAiOjE0MTc2ODg1OTgsIm5iZiI6MCwiaWF0IjoxNDE3Njg4Mjk4LCJpc3MiOiJzaG9vdC1yZWFsbSIsImF1ZCI6InNob290LXJlYWxtIiwic3ViIjoiNzJhN2Q0NGYtZDcxNy00MDk3LWExMWYtN2FhOWIyMmM5ZmU3IiwiYXpwIjoic2hhcmVkc2hvb3QtdGhpcmQtcGFydHkiLCJnaXZlbl9uYW1lIjoiU2FtcGxlIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoidXNlciIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwic2Vzc2lvbl9zdGF0ZSI6Ijg4MTJlN2U2LWQ1ZGYtNDc4Yi1iNDcyLTNlYWU5YTI2ZDdhYSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1c2VyIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnt9fQ.ZcNu8C4yeo1ALqnLvEOK3NxnaKm2BR818B4FfqN3WQd3sc6jvtGmTPB1C0MxF6ku_ELVs2l_HJMjNdPT9daUoau5LkdCjSiTwS5KA-18M5AUjzZnVo044-jHr_JsjNrYEfKmJXX0A_Zdly7el2tC1uPjGoeBqLgW9GowRl3i4wE"
func setupStubKeycloakWithNSURLSessionDefaultConfiguration() {
// set up http stub
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest!) -> Bool in
return true
}, withStubResponse:( { (request: NSURLRequest!) -> OHHTTPStubsResponse in
var stubJsonResponse = ["name": "John", "family_name": "Smith"]
switch request.URL!.path! {
case "/auth/realms/shoot-realm/tokens/refresh":
var string = "{\"access_token\":\"NEWLY_REFRESHED_ACCESS_TOKEN\", \"refresh_token\":\"\(KEYCLOAK_TOKEN)\",\"expires_in\":23}"
var data = string.dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"])
case "/auth/realms/shoot-realm/tokens/logout":
var string = "{\"access_token\":\"NEWLY_REFRESHED_ACCESS_TOKEN\", \"refresh_token\":\"nnn\",\"expires_in\":23}"
var data = string.dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"])
default: return OHHTTPStubsResponse(data:NSData(), statusCode: 404, headers: ["Content-Type" : "text/json"])
}
}))
}
class KeycloakOAuth2ModuleTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
OHHTTPStubs.removeAllStubs()
}
func testRefreshAccessWithKeycloak() {
setupStubKeycloakWithNSURLSessionDefaultConfiguration()
let expectation = expectationWithDescription("KeycloakRefresh");
let keycloakConfig = KeycloakConfig(
clientId: "shoot-third-party",
host: "http://localhost:8080",
realm: "shoot-realm")
var mockedSession = MockOAuth2SessionWithRefreshToken()
var oauth2Module = KeycloakOAuth2Module(config: keycloakConfig, session: mockedSession)
oauth2Module.refreshAccessToken { (response: AnyObject?, error:NSError?) -> Void in
XCTAssertTrue("NEWLY_REFRESHED_ACCESS_TOKEN" == response as! String, "If access token not valid but refresh token present and still valid")
XCTAssertTrue(KEYCLOAK_TOKEN == mockedSession.savedRefreshedToken, "Saved newly issued refresh token")
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testRevokeAccess() {
setupStubKeycloakWithNSURLSessionDefaultConfiguration()
let expectation = expectationWithDescription("KeycloakRevoke");
let keycloakConfig = KeycloakConfig(
clientId: "shoot-third-party",
host: "http://localhost:8080",
realm: "shoot-realm")
var mockedSession = MockOAuth2SessionWithRefreshToken()
var oauth2Module = KeycloakOAuth2Module(config: keycloakConfig, session: mockedSession)
oauth2Module.revokeAccess({(response: AnyObject?, error:NSError?) -> Void in
XCTAssertTrue(mockedSession.initCalled == 1, "revoke token reset session")
expectation.fulfill()
})
waitForExpectationsWithTimeout(10, handler: nil)
}
} | apache-2.0 |
kosiara/swift-basic-example | FireLampades/FireLampades/View/LoginPanel/LoginPanelViewController.swift | 1 | 1778 | //
// LoginPanelViewController.swift
// FireLampades
//
// Created by Patryk Domagala on 16/01/2017.
// Copyright © 2017 Bartosz Kosarzycki. All rights reserved.
//
import UIKit
private let loggedInPageSegue = "LoggedInPageSegue"
class LoginPanelViewController: UIViewController, LoginPanelViewType {
var loginPanelPresenter: LoginPanelPresenterType!
@IBOutlet var username: LoginTextField!
@IBOutlet var password: LoginTextField!
@IBOutlet var mainView: UIView!
@IBOutlet var innerUserPassView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
loginPanelPresenter.view = self
mainView.backgroundColor = ColorUtil.colorWithHexString(hexString: "21314a")
innerUserPassView.backgroundColor = ColorUtil.colorWithHexString(hexString: "21314a")
username.backgroundColor = ColorUtil.colorWithHexString(hexString: "21314a")
password.backgroundColor = ColorUtil.colorWithHexString(hexString: "21314a")
username.textColor = UIColor.white
password.textColor = UIColor.white
username.attributedPlaceholder = NSAttributedString(string:"Email address:", attributes: [NSForegroundColorAttributeName: UIColor.white])
password.attributedPlaceholder = NSAttributedString(string:"Password:", attributes: [NSForegroundColorAttributeName: UIColor.white])
}
@IBAction func submitButtonTapped(sender: UIButton) {
loginPanelPresenter?.loginUser(username: username.text, password: password.text)
}
// MARK: LoginPanelViewType
func openUserDetailsPage() {
performSegue(withIdentifier: loggedInPageSegue, sender: nil)
}
func showUnauthorizedMessage() {
//TODO implement
}
}
| mit |
bencochran/LLVM.swift | LLVM/Builder.swift | 1 | 16430 | //
// Created by Ben Cochran on 11/12/15.
// Copyright © 2015 Ben Cochran. All rights reserved.
//
public class Builder {
internal let ref: LLVMBuilderRef
public init(inContext context: Context) {
ref = LLVMCreateBuilderInContext(context.ref)
}
deinit {
LLVMDisposeBuilder(ref)
}
public func position(block block: BasicBlock, instruction: InstructionType) {
LLVMPositionBuilder(ref, block.ref, instruction.ref)
}
public func positionBefore(instruction instruction: InstructionType) {
LLVMPositionBuilderBefore(ref, instruction.ref)
}
public func positionAtEnd(block block: BasicBlock) {
LLVMPositionBuilderAtEnd(ref, block.ref)
}
public var insertBlock: BasicBlock {
return BasicBlock(ref: LLVMGetInsertBlock(ref))
}
public func clearInsertionPosition() {
LLVMClearInsertionPosition(ref)
}
public func insert(instruction instruction: InstructionType, name: String? = nil) {
if let name = name {
LLVMInsertIntoBuilderWithName(ref, instruction.ref, name)
} else {
LLVMInsertIntoBuilder(ref, instruction.ref)
}
}
public func buildReturnVoid() -> ReturnInstruction {
return ReturnInstruction(ref: LLVMBuildRetVoid(ref))
}
public func buildReturn(value value: ValueType) -> ReturnInstruction {
return ReturnInstruction(ref: LLVMBuildRet(ref, value.ref))
}
public func buildBranch(destination destination: BasicBlock) -> BranchInstruction {
return BranchInstruction(ref: LLVMBuildBr(ref, destination.ref))
}
public func buildConditionalBranch(condition condition: ValueType, thenBlock: BasicBlock, elseBlock: BasicBlock) -> BranchInstruction {
return BranchInstruction(ref: LLVMBuildCondBr(ref, condition.ref, thenBlock.ref, elseBlock.ref))
}
public func buildSwitch(value value: ValueType, elseBlock: BasicBlock, numCases: UInt32) -> SwitchInstruction {
return SwitchInstruction(ref: LLVMBuildSwitch(ref, value.ref, elseBlock.ref, numCases))
}
public func buildIndirectBranch(address address: ValueType, destinationHint: UInt32) -> IndirectBranchInstruction {
return IndirectBranchInstruction(ref: LLVMBuildIndirectBr(ref, address.ref, destinationHint))
}
public func buildInvoke(function: Function, args: [Argument], thenBlock: BasicBlock, catchBlock: BasicBlock, name: String) -> InvokeInstruction {
var argValues = args.map { $0.ref }
return InvokeInstruction(ref: LLVMBuildInvoke(ref, function.ref, &argValues, UInt32(argValues.count), thenBlock.ref, catchBlock.ref, name))
}
// TODO: buildLandingPad
// TODO: buildResume
// TODO: addClause
// TODO: setCleanup
public func buildUnreachable() -> UnreachableInstruction {
return UnreachableInstruction(ref: LLVMBuildUnreachable(ref))
}
// MARK: Arithmetic
public func buildAdd(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildAdd(ref, left.ref, right.ref, name))
}
public func buildNSWAdd(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNSWAdd(ref, left.ref, right.ref, name))
}
public func buildNUWAdd(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNUWAdd(ref, left.ref, right.ref, name))
}
public func buildFAdd(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFAdd(ref, left.ref, right.ref, name))
}
public func buildSub(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSub(ref, left.ref, right.ref, name))
}
public func buildNSWSub(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNSWSub(ref, left.ref, right.ref, name))
}
public func buildNUWSub(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNUWSub(ref, left.ref, right.ref, name))
}
public func buildFSub(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFSub(ref, left.ref, right.ref, name))
}
public func buildMul(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildMul(ref, left.ref, right.ref, name))
}
public func buildNSWMul(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNSWMul(ref, left.ref, right.ref, name))
}
public func buildNUWMul(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNUWMul(ref, left.ref, right.ref, name))
}
public func buildFMul(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFMul(ref, left.ref, right.ref, name))
}
public func buildUDiv(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildUDiv(ref, left.ref, right.ref, name))
}
public func buildSDiv(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSDiv(ref, left.ref, right.ref, name))
}
public func buildExactSDiv(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildExactSDiv(ref, left.ref, right.ref, name))
}
public func buildFDiv(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFDiv(ref, left.ref, right.ref, name))
}
public func buildURem(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildURem(ref, left.ref, right.ref, name))
}
public func buildSRem(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSRem(ref, left.ref, right.ref, name))
}
public func buildFRem(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFRem(ref, left.ref, right.ref, name))
}
public func buildShl(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildShl(ref, left.ref, right.ref, name))
}
public func buildLShr(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildLShr(ref, left.ref, right.ref, name))
}
public func buildAShr(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildAShr(ref, left.ref, right.ref, name))
}
public func buildAnd(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildAnd(ref, left.ref, right.ref, name))
}
public func buildOr(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildOr(ref, left.ref, right.ref, name))
}
public func buildXor(left left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildXor(ref, left.ref, right.ref, name))
}
public func buildBinOp(op: LLVMOpcode, left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildBinOp(ref, op, left.ref, right.ref, name))
}
public func buildNeg(value: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNeg(ref, value.ref, name))
}
public func buildNSWNeg(value: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNSWNeg(ref, value.ref, name))
}
public func buildNUWNeg(value: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNUWNeg(ref, value.ref, name))
}
public func buildFNeg(value: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFNeg(ref, value.ref, name))
}
public func buildNot(value: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildNot(ref, value.ref, name))
}
// MARK: Memory
public func buildMalloc(type type: TypeType, name: String) -> InstructionType {
return AnyInstruction(ref: LLVMBuildMalloc(ref, type.ref, name))
}
public func buildArrayMalloc(type type: TypeType, value: ValueType, name: String) -> InstructionType {
return AnyInstruction(ref: LLVMBuildArrayMalloc(ref, type.ref, value.ref, name))
}
public func buildAlloca(type type: TypeType, name: String) -> AllocaInstruction {
return AllocaInstruction(ref: LLVMBuildAlloca(ref, type.ref, name))
}
public func buildArrayAlloca(type type: TypeType, value: ValueType, name: String) -> AllocaInstruction {
return AllocaInstruction(ref: LLVMBuildArrayAlloca(ref, type.ref, value.ref, name))
}
public func buildFree(pointer: ValueType) -> CallInstruction {
return CallInstruction(ref: LLVMBuildFree(ref, pointer.ref))
}
public func buildLoad(pointer: ValueType, name: String) -> LoadInstruction {
return LoadInstruction(ref: LLVMBuildLoad(ref, pointer.ref, name))
}
public func buildGEP(pointer: ValueType, indices: [ValueType], name: String) -> ValueType {
var indexRefs = indices.map { $0.ref }
return AnyValue(ref: LLVMBuildGEP(ref, pointer.ref, &indexRefs, UInt32(indexRefs.count), name))
}
public func buildInBoundsGEP(pointer: ValueType, indices: [ValueType], name: String) -> ValueType {
var indexRefs = indices.map { $0.ref }
return AnyValue(ref: LLVMBuildInBoundsGEP(ref, pointer.ref, &indexRefs, UInt32(indexRefs.count), name))
}
public func buildStructGEP(pointer: ValueType, index: UInt32, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildStructGEP(ref, pointer.ref, index, name))
}
public func buildGlobalString(string: String, name: String) -> GlobalVariableType {
return AnyGlobalVariable(ref: LLVMBuildGlobalString(ref, string, name))
}
public func buildGlobalStringPointer(string: String, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildGlobalStringPtr(ref, string, name))
}
// TODO: volatile get/set
public func buildTrunc(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildTrunc(ref, value.ref, type.ref, name))
}
public func buildZExt(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildZExt(ref, value.ref, type.ref, name))
}
public func buildSExt(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSExt(ref, value.ref, type.ref, name))
}
public func buildFPToUI(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFPToUI(ref, value.ref, type.ref, name))
}
public func buildFPToSI(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFPToSI(ref, value.ref, type.ref, name))
}
public func buildUIToFP(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildUIToFP(ref, value.ref, type.ref, name))
}
public func buildSIToFP(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSIToFP(ref, value.ref, type.ref, name))
}
public func buildFPTrunc(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFPTrunc(ref, value.ref, type.ref, name))
}
public func buildFPExt(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFPExt(ref, value.ref, type.ref, name))
}
public func buildIntToPointer(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildIntToPtr(ref, value.ref, type.ref, name))
}
public func buildBitCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildBitCast(ref, value.ref, type.ref, name))
}
public func buildAddressSpaceCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildAddrSpaceCast(ref, value.ref, type.ref, name))
}
public func buildZExtOrBitCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildZExtOrBitCast(ref, value.ref, type.ref, name))
}
public func buildSExtOrBitCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSExtOrBitCast(ref, value.ref, type.ref, name))
}
public func buildTrucOrBitCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildTruncOrBitCast(ref, value.ref, type.ref, name))
}
public func buildCast(op: LLVMOpcode, value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildCast(ref, op, value.ref, type.ref, name))
}
public func buildPointerCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildPointerCast(ref, value.ref, type.ref, name))
}
public func buildIntCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildIntCast(ref, value.ref, type.ref, name))
}
public func buildFPCast(value: ValueType, destinationType type: TypeType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFPCast(ref, value.ref, type.ref, name))
}
public func buildICmp(op: LLVMIntPredicate, left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildICmp(ref, op, left.ref, right.ref, name))
}
public func buildFCmp(op: LLVMRealPredicate, left: ValueType, right: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildFCmp(ref, op, left.ref, right.ref, name))
}
public func buildPhi(type: TypeType, name: String) -> PHINode {
return PHINode(ref: LLVMBuildPhi(ref, type.ref, name))
}
public func buildCall(function: Function, args: [ValueType], name: String) -> CallInstruction {
var argRefs = args.map { $0.ref }
return CallInstruction(ref: LLVMBuildCall(ref, function.ref, &argRefs, UInt32(argRefs.count), name))
}
public func buildSelect(condition: ValueType, trueValue: ValueType, falseValue: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildSelect(ref, condition.ref, trueValue.ref, falseValue.ref, name))
}
public func buildVAArg(list: ValueType, type: TypeType, name: String) -> VAArgInstruction {
return VAArgInstruction(ref: LLVMBuildVAArg(ref, list.ref, type.ref, name))
}
public func buildExtractElement(vec: ValueType, index: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildExtractElement(ref, vec.ref, index.ref, name))
}
public func buildInsertElement(vec: ValueType, value: ValueType, index: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildInsertElement(ref, value.ref, vec.ref, index.ref, name))
}
public func buildShuffleVector(vec1: ValueType, vec2: ValueType, mask: ValueType, name: String) -> ValueType {
return AnyValue(ref: LLVMBuildShuffleVector(ref, vec1.ref, vec2.ref, mask.ref, name))
}
} | mit |
JOCR10/iOS-Curso | Quices/Quiz #1.playground/Contents.swift | 1 | 326 | //: Playground - noun: a place where people can play
//1
var prueba = "Prueba"
//2
let const = 3
//3
var opcional:String?
//4
//Para poder realizar un unwrap de forma segura se debe asegurar que la variable contenga un valor. La validación se puede realizar mediante un if let para asegurarse que existe dicho valor.
| mit |
paulgriffiths/macplanetpos | MacAstro/J2000CenturyElements.swift | 1 | 4046 | //
// J2000CenturyElements.swift
// MacAstro
//
// Created by Paul Griffiths on 5/7/15.
// Copyright (c) 2015 Paul Griffiths. All rights reserved.
//
final class J2000CenturyElements: DeltaOrbitalElements {
class func newElementsForPlanet(planet: Planet) -> J2000CenturyElements {
switch ( planet ) {
case .Mercury:
return J2000CenturyElements(
sma: 0.00000037,
ecc: 0.00001906,
inc: toRadians(-0.00594749),
ml: toRadians(149472.67411175),
lp: toRadians(0.16047689),
lan: toRadians(-0.12534081)
)
case .Venus:
return J2000CenturyElements(
sma: 0.00000390,
ecc: -0.00004107,
inc: toRadians(-0.00078890),
ml: toRadians(58517.81538729),
lp: toRadians(0.00268329),
lan: toRadians(-0.27769418)
)
case .Earth:
return J2000CenturyElements(
sma: 0.00000562,
ecc: -0.00004392,
inc: toRadians(-0.01294668),
ml: toRadians(35999.37244981),
lp: toRadians(0.32327364),
lan: toRadians(0.0)
)
case .Sun:
return J2000CenturyElements(
sma: 0.00000562,
ecc: -0.00004392,
inc: toRadians(-0.01294668),
ml: toRadians(35999.37244981),
lp: toRadians(0.32327364),
lan: toRadians(0.0)
)
case .Mars:
return J2000CenturyElements(
sma: 0.00001847,
ecc: 0.00007882,
inc: toRadians(-0.00813131),
ml: toRadians(19140.30268499),
lp: toRadians(0.44441088),
lan: toRadians(-0.29257343)
)
case .Jupiter:
return J2000CenturyElements(
sma: -0.00011607,
ecc: -0.00013253,
inc: toRadians(-0.00183714),
ml: toRadians(3034.74612775),
lp: toRadians(0.21252668),
lan: toRadians(0.20469106)
)
case .Saturn:
return J2000CenturyElements(
sma: -0.00125060,
ecc: -0.00050991,
inc: toRadians(0.00193609),
ml: toRadians(1222.49362201),
lp: toRadians(-0.41897216),
lan: toRadians(-0.28867794)
)
case .Uranus:
return J2000CenturyElements(
sma: -0.00196176,
ecc: -0.00004397,
inc: toRadians(-0.00242939),
ml: toRadians(428.48202785),
lp: toRadians(0.40805281),
lan: toRadians(0.04240589)
)
case .Neptune:
return J2000CenturyElements(
sma: 0.00026291,
ecc: 0.00005105,
inc: toRadians(0.00035372),
ml: toRadians(218.45945325),
lp: toRadians(-0.32241464),
lan: toRadians(-0.00508664)
)
case .Pluto:
return J2000CenturyElements(
sma: -0.00031596,
ecc: 0.00005170,
inc: toRadians(0.00004818),
ml: toRadians(145.20780515),
lp: toRadians(-0.04062942),
lan: toRadians(-0.01183482)
)
case .Moon, .EMBary:
fatalError("J2000 century orbital elements not available for \(planet.description)")
}
}
// Private initializer to enforce use of factory function
private override init(sma: Double, ecc: Double, inc: Double, ml: Double, lp: Double, lan: Double) {
super.init(sma: sma, ecc: ecc, inc: inc, ml: ml, lp: lp, lan: lan)
}
}
| gpl-3.0 |
usbong/UsbongKit | UsbongKit/Usbong/XML/XMLIdentifier.swift | 2 | 685 | //
// XMLIdentifier.swift
// UsbongKit
//
// Created by Chris Amanse on 26/05/2016.
// Copyright © 2016 Usbong Social Systems, Inc. All rights reserved.
//
import Foundation
/// XML identifiers for tags
internal struct XMLIdentifier {
static let processDefinition = "process-definition"
static let startState = "start-state"
static let endState = "end-state"
static let taskNode = "task-node"
static let decision = "decision"
static let transition = "transition"
static let task = "task"
static let to = "to"
static let name = "name"
static let resources = "resources"
static let string = "string"
static let lang = "lang"
}
| apache-2.0 |
FAU-Inf2/kwikshop-ios | Kwik Shop/ItemTableViewCell.swift | 1 | 683 | //
// ItemTableViewCell.swift
//
//
// Created by Adrian Kretschmer on 06.08.15.
//
//
import UIKit
class ItemTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var brandCommentLabel: UILabel!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var groupLabel: UILabel!
@IBOutlet weak var groupBackgroundLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
iccub/freestyle-timer-ios | freestyle-timer-iosTests/TimerTypesPageVCTests.swift | 1 | 2558 | /*
Copyright © 2017 Michał Buczek.
This file is part of Freestyle Timer.
Freestyle Timer 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, either version 3 of the License, or
(at your option) any later version.
Freestyle Timer 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 Freestyle Timer. If not, see <http://www.gnu.org/licenses/>.
*/
import XCTest
@testable import freestyle_timer_ios
class TimerTypesPageVCTests: XCTestCase {
var vc: TimerModesPageVC!
var storyboard: UIStoryboard!
override func setUp() {
super.setUp()
storyboard = UIStoryboard.init(name: "Main", bundle: nil)
vc = storyboard.instantiateViewController(withIdentifier: "TimerTypesPageVC") as! TimerModesPageVC
let _ = vc.view
}
override func tearDown() {
vc = nil
super.tearDown()
}
func testPagesLoadCorrectly() {
XCTAssertEqual(vc.pages.count, 2)
XCTAssert(vc.delegate != nil)
XCTAssert(vc.dataSource != nil)
XCTAssertNotNil(vc.viewControllers?.first)
XCTAssertNotNil(vc.pages.first)
XCTAssertEqual(vc.viewControllers!.first!, vc.pages.first!)
}
func testPageVCSetting() {
let firstVC = vc.pages.first!
let lastVC = vc.pages.last!
let randomVC = UIViewController()
// First element, should return second
XCTAssertEqual(vc.pageViewController(vc, viewControllerAfter: firstVC), vc.pages[1])
// Last element, should return nil
XCTAssertNil(vc.pageViewController(vc, viewControllerAfter: lastVC))
// Wrong element should return nil
XCTAssertNil(vc.pageViewController(vc, viewControllerAfter: randomVC))
// Test VC before
// First element, should return nil
XCTAssertNil(vc.pageViewController(vc, viewControllerBefore: firstVC))
// Last element, should return last - 1
XCTAssertEqual(vc.pageViewController(vc, viewControllerBefore: lastVC), vc.pages[vc.pages.count - 2])
// Wrong element should return nil
XCTAssertNil(vc.pageViewController(vc, viewControllerBefore: randomVC))
}
}
| gpl-3.0 |
sharath-cliqz/browser-ios | Utils/Extensions/UIColorExtensions.swift | 2 | 918 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct Color {
var red: CGFloat
var green: CGFloat
var blue: CGFloat
};
extension UIColor {
/**
* Initializes and returns a color object for the given RGB hex integer.
*/
public convenience init(rgb: Int) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((rgb & 0x0000FF) >> 0) / 255.0,
alpha: 1)
}
public convenience init(colorString: String) {
var colorInt: UInt32 = 0
Scanner(string: colorString).scanHexInt32(&colorInt)
self.init(rgb: (Int) (colorInt ?? 0xaaaaaa))
}
}
| mpl-2.0 |
joshualay/QuickTestingExample | QuickTestingExample/AppDelegate.swift | 1 | 2102 | //
// AppDelegate.swift
// QuickTestingExample
//
// Created by Joshua Lay on 3/12/2014.
//
//
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 |
red-spotted-newts-2014/rest-less-ios | Rest Less/Rest Less/HttpPost.swift | 1 | 1264 | //
// HttpPost.swift
// Rest Less
//
// Created by Dylan Krause on 8/16/14.
// Copyright (c) 2014 newts. All rights reserved.
//
import Foundation
func HTTPostJSON(url: String,
jsonObj: AnyObject)
{
var request = NSMutableURLRequest(URL: NSURL(string: url))
var session = NSURLSession.sharedSession()
var jsonError:NSError?
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject( jsonObj, options: nil, error: &jsonError)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var subTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var jsonRError: NSError?
var json_response = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &jsonRError) as? NSDictionary
println(jsonRError)
jsonRError?
if jsonRError? != nil {
println(jsonRError!.localizedDescription)
}
else {
println(json_response)
}
})
subTask.resume()
println("hello")
}
| mit |
wordpress-mobile/WordPress-Aztec-iOS | WordPressEditor/WordPressEditor/Classes/ViewControllers/OptionsTableViewController/OptionsTableViewController.swift | 2 | 5590 | import UIKit
/// Encapsulates data for a row in an `OptionsTableView`.
///
public struct OptionsTableViewOption: Equatable {
let image: UIImage?
let title: NSAttributedString
let accessibilityLabel: String?
// MARK: - Initializer
public init(image: UIImage?, title: NSAttributedString, accessibilityLabel: String? = nil) {
self.image = image
self.title = title
self.accessibilityLabel = accessibilityLabel
}
// MARK: - Equatable
public static func ==(lhs: OptionsTableViewOption, rhs: OptionsTableViewOption) -> Bool {
return lhs.title == rhs.title
}
}
public class OptionsTableViewController: UITableViewController {
enum Constants {
static var cellBackgroundColor: UIColor = {
if #available(iOS 13.0, *) {
return .systemBackground
} else {
return .white
}
}()
static var cellSelectedBackgroundColor: UIColor = {
if #available(iOS 13.0, *) {
return .secondarySystemBackground
} else {
return .lightGray
}
}()
}
private static let rowHeight: CGFloat = 44.0
public typealias OnSelectHandler = (_ selected: Int) -> Void
public var options = [OptionsTableViewOption]()
public var onSelect: OnSelectHandler?
public var cellBackgroundColor: UIColor = Constants.cellBackgroundColor {
didSet {
tableView.backgroundColor = cellBackgroundColor
tableView?.reloadData()
}
}
public var cellSelectedBackgroundColor: UIColor = Constants.cellSelectedBackgroundColor
public var cellDeselectedTintColor: UIColor? {
didSet {
tableView?.reloadData()
}
}
public init(options: [OptionsTableViewOption]) {
self.options = options
super.init(style: .plain)
}
public override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = cellBackgroundColor
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.register(OptionsTableViewCell.self, forCellReuseIdentifier: OptionsTableViewCell.reuseIdentifier)
preferredContentSize = CGSize(width: 0, height: min(CGFloat(options.count), 7.5) * OptionsTableViewController.rowHeight)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func selectRow(at index: Int) {
let indexPath = IndexPath(row: index, section: 0)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .middle)
}
}
extension OptionsTableViewController {
public override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
cell.accessoryType = .none
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
cell.accessoryType = .checkmark
onSelect?(indexPath.row)
}
public override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = cellBackgroundColor
let selectedView = UIView()
selectedView.backgroundColor = cellSelectedBackgroundColor
cell.selectedBackgroundView = selectedView
}
}
extension OptionsTableViewController {
public override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseCell = tableView.dequeueReusableCell(withIdentifier: OptionsTableViewCell.reuseIdentifier, for: indexPath) as! OptionsTableViewCell
let option = options[indexPath.row]
reuseCell.textLabel?.attributedText = option.title
reuseCell.imageView?.image = option.image
reuseCell.deselectedTintColor = cellDeselectedTintColor
reuseCell.accessibilityLabel = option.accessibilityLabel
let isSelected = indexPath.row == tableView.indexPathForSelectedRow?.row
reuseCell.isSelected = isSelected
return reuseCell
}
}
class OptionsTableViewCell: UITableViewCell {
static let reuseIdentifier = "OptionCell"
var deselectedTintColor: UIColor?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Our Gridicons look slightly better if shifted down one px
imageView?.frame.origin.y += 1
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Icons should always appear deselected
imageView?.tintColor = deselectedTintColor
accessoryType = selected ? .checkmark : .none
}
}
| gpl-2.0 |
anilkumarbp/ringcentral-swift-NEW | src/SDK.swift | 1 | 2618 | //
// SDK.swift
// src
//
// Created by Anil Kumar BP on 11/1/15.
// Copyright (c) 2015 Anil Kumar BP. All rights reserved.
//
import Foundation
// Object representation of a Standard Development Kit for RingCentral
class SDK {
// Set constants for SANDBOX and PRODUCTION servers.
static var VERSION: String = ""
static var RC_SERVER_PRODUCTION: String = "https://platform.ringcentral.com"
static var RC_SERVER_SANDBOX: String = "https://platform.devtest.ringcentral.com"
// Platform variable, version, and current Subscriptions
var platform: Platform
// var subscription: Subscription?
let server: String
var client: Client
var serverVersion: String!
var versionString: String!
var logger: Bool = false
init(appKey: String, appSecret: String, server: String) {
self.client = Client()
platform = Platform(appKey: appKey, appSecret: appSecret, server: server)
self.server = server
// setVersion()
}
/// Sets version to the version of the current SDK
private func setVersion() {
let url = NSURL(string: server + "/restapi/")
// Sets up the request
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
var response: NSURLResponse?
var error: NSError?
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
let readdata = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
let dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
self.serverVersion = dict["serverVersion"] as! String
self.versionString = (dict["apiVersions"] as! NSArray)[0]["versionString"] as! String
}
/// Returns the server version.
///
/// :returns: String of current version
func getServerVersion() -> String {
return serverVersion
}
/// Returns the Platform with the specified appKey and appSecret.
///
/// :returns: A Platform to access the methods of the SDK
func getPlatform() -> Platform {
return self.platform
}
/// Returns the current Subscription.
///
/// :returns: A Subscription that the user is currently following
// func getSubscription() -> Subscription? {
// return self.subscription
// }
} | mit |
Intercambio/CloudService | CloudService/CloudService/Resource.swift | 1 | 1019 | //
// Resource.swift
// CloudService
//
// Created by Tobias Kraentzer on 21.02.17.
// Copyright © 2017 Tobias Kräntzer. All rights reserved.
//
import Foundation
public struct Resource: Hashable, Equatable {
public let resourceID: ResourceID
public let dirty: Bool
public let updated: Date?
public let properties: Properties
public let fileURL: URL?
let fileVersion: String?
public static func ==(lhs: Resource, rhs: Resource) -> Bool {
return lhs.resourceID == rhs.resourceID
}
public var hashValue: Int {
return resourceID.hashValue
}
}
extension Resource {
public enum FileState {
case none
case outdated
case valid
}
public var fileState: FileState {
switch (properties.version, fileVersion) {
case (_, nil): return .none
case (let version, let fileVersion) where version == fileVersion: return .valid
default: return .outdated
}
}
}
| gpl-3.0 |
react-native-kit/react-native-track-player | ios/RNTrackPlayer/RNTrackPlayer.swift | 1 | 21168 | //
// RNTrackPlayer.swift
// RNTrackPlayer
//
// Created by David Chavez on 13.08.17.
// Copyright © 2017 David Chavez. All rights reserved.
//
import Foundation
import MediaPlayer
@objc(RNTrackPlayer)
public class RNTrackPlayer: RCTEventEmitter {
// MARK: - Attributes
private var hasInitialized = false
private lazy var player: RNTrackPlayerAudioPlayer = {
let player = RNTrackPlayerAudioPlayer(reactEventEmitter: self)
player.bufferDuration = 1
return player
}()
// MARK: - Lifecycle Methods
deinit {
reset(resolve: { _ in }, reject: { _, _, _ in })
}
// MARK: - RCTEventEmitter
override public static func requiresMainQueueSetup() -> Bool {
return true;
}
@objc(constantsToExport)
override public func constantsToExport() -> [AnyHashable: Any] {
return [
"STATE_NONE": AVPlayerWrapperState.idle.rawValue,
"STATE_READY": AVPlayerWrapperState.ready.rawValue,
"STATE_PLAYING": AVPlayerWrapperState.playing.rawValue,
"STATE_PAUSED": AVPlayerWrapperState.paused.rawValue,
"STATE_STOPPED": AVPlayerWrapperState.idle.rawValue,
"STATE_BUFFERING": AVPlayerWrapperState.loading.rawValue,
"TRACK_PLAYBACK_ENDED_REASON_END": PlaybackEndedReason.playedUntilEnd.rawValue,
"TRACK_PLAYBACK_ENDED_REASON_JUMPED": PlaybackEndedReason.jumpedToIndex.rawValue,
"TRACK_PLAYBACK_ENDED_REASON_NEXT": PlaybackEndedReason.skippedToNext.rawValue,
"TRACK_PLAYBACK_ENDED_REASON_PREVIOUS": PlaybackEndedReason.skippedToPrevious.rawValue,
"TRACK_PLAYBACK_ENDED_REASON_STOPPED": PlaybackEndedReason.playerStopped.rawValue,
"PITCH_ALGORITHM_LINEAR": PitchAlgorithm.linear.rawValue,
"PITCH_ALGORITHM_MUSIC": PitchAlgorithm.music.rawValue,
"PITCH_ALGORITHM_VOICE": PitchAlgorithm.voice.rawValue,
"CAPABILITY_PLAY": Capability.play.rawValue,
"CAPABILITY_PLAY_FROM_ID": "NOOP",
"CAPABILITY_PLAY_FROM_SEARCH": "NOOP",
"CAPABILITY_PAUSE": Capability.pause.rawValue,
"CAPABILITY_STOP": Capability.stop.rawValue,
"CAPABILITY_SEEK_TO": Capability.seek.rawValue,
"CAPABILITY_SKIP": "NOOP",
"CAPABILITY_SKIP_TO_NEXT": Capability.next.rawValue,
"CAPABILITY_SKIP_TO_PREVIOUS": Capability.previous.rawValue,
"CAPABILITY_SET_RATING": "NOOP",
"CAPABILITY_JUMP_FORWARD": Capability.jumpForward.rawValue,
"CAPABILITY_JUMP_BACKWARD": Capability.jumpBackward.rawValue,
"CAPABILITY_LIKE": Capability.like.rawValue,
"CAPABILITY_DISLIKE": Capability.dislike.rawValue,
"CAPABILITY_BOOKMARK": Capability.bookmark.rawValue,
]
}
@objc(supportedEvents)
override public func supportedEvents() -> [String] {
return [
"playback-queue-ended",
"playback-state",
"playback-error",
"playback-track-changed",
"remote-stop",
"remote-pause",
"remote-play",
"remote-duck",
"remote-next",
"remote-seek",
"remote-previous",
"remote-jump-forward",
"remote-jump-backward",
"remote-like",
"remote-dislike",
"remote-bookmark",
]
}
func setupInterruptionHandling() {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
notificationCenter.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: nil)
}
@objc func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}
if type == .began {
// Interruption began, take appropriate actions (save state, update user interface)
self.sendEvent(withName: "remote-duck", body: [
"paused": true
])
}
else if type == .ended {
guard let optionsValue =
userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else {
return
}
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
if options.contains(.shouldResume) {
// Interruption Ended - playback should resume
self.sendEvent(withName: "remote-duck", body: [
"paused": false
])
} else {
// Interruption Ended - playback should NOT resume
self.sendEvent(withName: "remote-duck", body: [
"paused": true,
"permanent": true
])
}
}
}
// MARK: - Bridged Methods
@objc(setupPlayer:resolver:rejecter:)
public func setupPlayer(config: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
if hasInitialized {
resolve(NSNull())
return
}
setupInterruptionHandling();
// configure if player waits to play
let autoWait: Bool = config["waitForBuffer"] as? Bool ?? false
player.automaticallyWaitsToMinimizeStalling = autoWait
// configure audio session - category, options & mode
var sessionCategory: AVAudioSession.Category = .playback
var sessionCategoryOptions: AVAudioSession.CategoryOptions = []
var sessionCategoryMode: AVAudioSession.Mode = .default
if
let sessionCategoryStr = config["iosCategory"] as? String,
let mappedCategory = SessionCategory(rawValue: sessionCategoryStr) {
sessionCategory = mappedCategory.mapConfigToAVAudioSessionCategory()
}
let sessionCategoryOptsStr = config["iosCategoryOptions"] as? [String]
let mappedCategoryOpts = sessionCategoryOptsStr?.compactMap { SessionCategoryOptions(rawValue: $0)?.mapConfigToAVAudioSessionCategoryOptions() } ?? []
sessionCategoryOptions = AVAudioSession.CategoryOptions(mappedCategoryOpts)
if
let sessionCategoryModeStr = config["iosCategoryMode"] as? String,
let mappedCategoryMode = SessionCategoryMode(rawValue: sessionCategoryModeStr) {
sessionCategoryMode = mappedCategoryMode.mapConfigToAVAudioSessionCategoryMode()
}
// Progressively opt into AVAudioSession policies for background audio
// and AirPlay 2.
if #available(iOS 13.0, *) {
try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longFormAudio, options: sessionCategoryOptions)
} else if #available(iOS 11.0, *) {
try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longForm, options: sessionCategoryOptions)
} else {
try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, options: sessionCategoryOptions)
}
// setup event listeners
player.remoteCommandController.handleChangePlaybackPositionCommand = { [weak self] event in
if let event = event as? MPChangePlaybackPositionCommandEvent {
self?.sendEvent(withName: "remote-seek", body: ["position": event.positionTime])
return MPRemoteCommandHandlerStatus.success
}
return MPRemoteCommandHandlerStatus.commandFailed
}
player.remoteCommandController.handleNextTrackCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-next", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handlePauseCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-pause", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handlePlayCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-play", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handlePreviousTrackCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-previous", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handleSkipBackwardCommand = { [weak self] event in
if let command = event.command as? MPSkipIntervalCommand,
let interval = command.preferredIntervals.first {
self?.sendEvent(withName: "remote-jump-backward", body: ["interval": interval])
return MPRemoteCommandHandlerStatus.success
}
return MPRemoteCommandHandlerStatus.commandFailed
}
player.remoteCommandController.handleSkipForwardCommand = { [weak self] event in
if let command = event.command as? MPSkipIntervalCommand,
let interval = command.preferredIntervals.first {
self?.sendEvent(withName: "remote-jump-forward", body: ["interval": interval])
return MPRemoteCommandHandlerStatus.success
}
return MPRemoteCommandHandlerStatus.commandFailed
}
player.remoteCommandController.handleStopCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-stop", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handleTogglePlayPauseCommand = { [weak self] _ in
if self?.player.playerState == .paused {
self?.sendEvent(withName: "remote-play", body: nil)
return MPRemoteCommandHandlerStatus.success
}
self?.sendEvent(withName: "remote-pause", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handleLikeCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-like", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handleDislikeCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-dislike", body: nil)
return MPRemoteCommandHandlerStatus.success
}
player.remoteCommandController.handleBookmarkCommand = { [weak self] _ in
self?.sendEvent(withName: "remote-bookmark", body: nil)
return MPRemoteCommandHandlerStatus.success
}
hasInitialized = true
resolve(NSNull())
}
@objc(destroy)
public func destroy() {
print("Destroying player")
}
@objc(updateOptions:resolver:rejecter:)
public func update(options: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
var capabilitiesStr = options["capabilities"] as? [String] ?? []
if (capabilitiesStr.contains("play") && capabilitiesStr.contains("pause")) {
capabilitiesStr.append("togglePlayPause");
}
let capabilities = capabilitiesStr.compactMap { Capability(rawValue: $0) }
let remoteCommands = capabilities.map { capability in
capability.mapToPlayerCommand(jumpInterval: options["jumpInterval"] as? NSNumber,
likeOptions: options["likeOptions"] as? [String: Any],
dislikeOptions: options["dislikeOptions"] as? [String: Any],
bookmarkOptions: options["bookmarkOptions"] as? [String: Any])
}
player.enableRemoteCommands(remoteCommands)
resolve(NSNull())
}
@objc(add:before:resolver:rejecter:)
public func add(trackDicts: [[String: Any]], before trackId: String?, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
UIApplication.shared.beginReceivingRemoteControlEvents();
}
var tracks = [Track]()
for trackDict in trackDicts {
guard let track = Track(dictionary: trackDict) else {
reject("invalid_track_object", "Track is missing a required key", nil)
return
}
tracks.append(track)
}
print("Adding tracks:", tracks)
if let trackId = trackId {
guard let insertIndex = player.items.firstIndex(where: { ($0 as! Track).id == trackId })
else {
reject("track_not_in_queue", "Given track ID was not found in queue", nil)
return
}
try? player.add(items: tracks, at: insertIndex)
} else {
try? player.add(items: tracks, playWhenReady: false)
}
resolve(NSNull())
}
@objc(remove:resolver:rejecter:)
public func remove(tracks ids: [String], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Removing tracks:", ids)
// Look through queue for tracks that match one of the provided ids.
// Do this in reverse order so that as they are removed,
// it will not affect other indices that will be removed.
for (index, element) in player.items.enumerated().reversed() {
// skip the current index
if index == player.currentIndex { continue }
let track = element as! Track
if ids.contains(track.id) {
try? player.removeItem(at: index)
}
}
resolve(NSNull())
}
@objc(removeUpcomingTracks:rejecter:)
public func removeUpcomingTracks(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Removing upcoming tracks")
player.removeUpcomingItems()
resolve(NSNull())
}
@objc(skip:resolver:rejecter:)
public func skip(to trackId: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let trackIndex = player.items.firstIndex(where: { ($0 as! Track).id == trackId })
else {
reject("track_not_in_queue", "Given track ID was not found in queue", nil)
return
}
print("Skipping to track:", trackId)
try? player.jumpToItem(atIndex: trackIndex, playWhenReady: player.playerState == .playing)
resolve(NSNull())
}
@objc(skipToNext:rejecter:)
public func skipToNext(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Skipping to next track")
do {
try player.next()
resolve(NSNull())
} catch (_) {
reject("queue_exhausted", "There is no tracks left to play", nil)
}
}
@objc(skipToPrevious:rejecter:)
public func skipToPrevious(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Skipping to next track")
do {
try player.previous()
resolve(NSNull())
} catch (_) {
reject("no_previous_track", "There is no previous track", nil)
}
}
@objc(reset:rejecter:)
public func reset(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Resetting player.")
player.stop()
resolve(NSNull())
DispatchQueue.main.async {
UIApplication.shared.endReceivingRemoteControlEvents();
}
}
@objc(play:rejecter:)
public func play(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Starting/Resuming playback")
try? AVAudioSession.sharedInstance().setActive(true)
player.play()
resolve(NSNull())
}
@objc(pause:rejecter:)
public func pause(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Pausing playback")
player.pause()
resolve(NSNull())
}
@objc(stop:rejecter:)
public func stop(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Stopping playback")
player.stop()
resolve(NSNull())
}
@objc(seekTo:resolver:rejecter:)
public func seek(to time: Double, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Seeking to \(time) seconds")
player.seek(to: time)
resolve(NSNull())
}
@objc(setVolume:resolver:rejecter:)
public func setVolume(level: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Setting volume to \(level)")
player.volume = level
resolve(NSNull())
}
@objc(getVolume:rejecter:)
public func getVolume(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Getting current volume")
resolve(player.volume)
}
@objc(setRate:resolver:rejecter:)
public func setRate(rate: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Setting rate to \(rate)")
player.rate = rate
resolve(NSNull())
}
@objc(getRate:rejecter:)
public func getRate(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
print("Getting current rate")
resolve(player.rate)
}
@objc(getTrack:resolver:rejecter:)
public func getTrack(id: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let track = player.items.first(where: { ($0 as! Track).id == id })
else {
reject("track_not_in_queue", "Given track ID was not found in queue", nil)
return
}
resolve((track as? Track)?.toObject())
}
@objc(getQueue:rejecter:)
public func getQueue(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
let serializedQueue = player.items.map { ($0 as! Track).toObject() }
resolve(serializedQueue)
}
@objc(getCurrentTrack:rejecter:)
public func getCurrentTrack(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve((player.currentItem as? Track)?.id)
}
@objc(getDuration:rejecter:)
public func getDuration(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(player.duration)
}
@objc(getBufferedPosition:rejecter:)
public func getBufferedPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(player.bufferedPosition)
}
@objc(getPosition:rejecter:)
public func getPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(player.currentTime)
}
@objc(getState:rejecter:)
public func getState(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(player.playerState.rawValue)
}
@objc(updateMetadataForTrack:properties:resolver:rejecter:)
public func updateMetadata(for trackId: String, properties: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let track = player.items.first(where: { ($0 as! Track).id == trackId }) as? Track
else {
reject("track_not_in_queue", "Given track ID was not found in queue", nil)
return
}
track.updateMetadata(dictionary: properties)
if (player.currentItem as! Track).id == track.id {
player.nowPlayingInfoController.set(keyValues: [
MediaItemProperty.artist(track.artist),
MediaItemProperty.title(track.title),
MediaItemProperty.albumTitle(track.album),
])
player.updateNowPlayingPlaybackValues();
track.getArtwork { [weak self] image in
if let image = image {
let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (size) -> UIImage in
return image
})
self?.player.nowPlayingInfoController.set(keyValue: MediaItemProperty.artwork(artwork))
self?.player.updateNowPlayingPlaybackValues();
}
}
}
resolve(NSNull())
}
}
| apache-2.0 |
RiotKit/RiotKit | RiotKit/RiotKitTests/RegionTests.swift | 1 | 1922 | //
// RegionTests.swift
// RiotKit
//
// Created by Grant Douglas on 19/03/2016.
// Copyright © 2016 Reconditorium Ltd. All rights reserved.
//
import XCTest
@testable import RiotKit
class RegionTests: 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 testRegionHostNameGeneration() {
XCTAssertEqual(Region.getHostname(forRegion: "BR"), "br.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "EUNE"), "eune.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "EUW"), "euw.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "KR"), "kr.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "LAN"), "lan.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "LAS"), "las.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "NA"), "na.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "OCE"), "oce.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "TR"), "tr.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "RU"), "ru.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "PBE"), "pbe.api.riotgames.com");
XCTAssertEqual(Region.getHostname(forRegion: "GLOBAL"), "global.api.riotgames.com");
}
func testGetRegionMap() {
XCTAssertNotNil(Region.getRegions());
XCTAssertNotNil(Region.getRegions()["NA"]);
}
func testGetInvalidRegion() {
XCTAssertEqual(Region.getHostname(forRegion: "FOOBAR"), "");
}
}
| mit |
AnarchyTools/atpm | atpm/src/dependency.swift | 1 | 3132 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import atpkg
import atfoundation
import atpm_tools
///Choose a version
///- parameter versions: The set of legal versions we could choose
///- parameter versionRange: Version specifiers such as are provided in a build.atpkg
///- parameter lockedPayload: Use this payload to choose a version if possible
///- parameter update: Whether to update the package, or only fetch
func chooseVersion(versions: [Version], versionRange: VersionRange, lockedPayload: LockedPayload?, update: Bool) throws -> Version? {
if lockedPayload?.pinned == true || !update {
if let v = lockedPayload?.usedVersion {
guard let lockedVersion = try versions.filter({ version throws -> Bool in
return version.description == v
}).first else {
fatalError("Can't find version \(v) to fetch. Use update and/or unpin to resolve.")
}
return lockedVersion
}
}
var versions = versions
versions = try versions.filter { version throws -> Bool in
return versionRange.versionInRange(version)
}
versions.sort(by: { (v1, v2) -> Bool in
return v1 < v2
})
if versions.count > 0 {
print("Valid versions: \(versions), using \(versions.last!)")
return versions.last!
} else {
print("No valid versions!")
return nil
}
}
func updateDependency(_ pkg: ExternalDependency, lock: LockedPackage?, firstTime: Bool = false) throws {
switch(pkg.dependencyType) {
case .Git:
try updateGitDependency(pkg, lock: lock, firstTime: firstTime)
case .Manifest:
try fetchHTTPDependency(pkg, lock: lock, update: true)
break
}
}
//- returns: The name of the depency we downloaded
func fetchDependency(_ pkg: ExternalDependency, lock: LockedPackage?) throws {
//note that this check only works for git dependencies –
//binary dependencies names are defined in the manifest
//additionally, this does not segregate by "channels" as would be needed for that case
if let name = pkg.name {
if FS.fileExists(path: Path("external/\(name)")) {
print("Already downloaded")
return
}
}
let ext = Path("external")
if !FS.fileExists(path: ext) {
try FS.createDirectory(path: ext)
}
switch(pkg.dependencyType) {
case .Git:
try fetchGitDependency(pkg, lock: lock)
case .Manifest:
try fetchHTTPDependency(pkg, lock: lock, update: false)
}
}
| apache-2.0 |
PSPDFKit-labs/ReactiveCocoa | ReactiveCocoa/Swift/SignalProducer.swift | 1 | 53792 | import Result
/// A SignalProducer creates Signals that can produce values of type `T` and/or
/// error out with errors of type `E`. If no errors should be possible, NoError
/// can be specified for `E`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of start() will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of start(), different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<T, E: ErrorType> {
public typealias ProducedSignal = Signal<T, E>
private let startHandler: (Signal<T, E>.Observer, CompositeDisposable) -> ()
/// Initializes a SignalProducer that will invoke the given closure once
/// for each invocation of start().
///
/// The events that the closure puts into the given sink will become the
/// events sent by the started Signal to its observers.
///
/// If the Disposable returned from start() is disposed or a terminating
/// event is sent to the observer, the given CompositeDisposable will be
/// disposed, at which point work should be interrupted and any temporary
/// resources cleaned up.
public init(_ startHandler: (Signal<T, E>.Observer, CompositeDisposable) -> ()) {
self.startHandler = startHandler
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete.
public init(value: T) {
self.init({ observer, disposable in
sendNext(observer, value)
sendCompleted(observer)
})
}
/// Creates a producer for a Signal that will immediately send an error.
public init(error: E) {
self.init({ observer, disposable in
sendError(observer, error)
})
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately send an error, depending on the given
/// Result.
public init(result: Result<T, E>) {
switch result {
case let .Success(value):
self.init(value: value)
case let .Failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
public init<S: SequenceType where S.Generator.Element == T>(values: S) {
self.init({ observer, disposable in
for value in values {
sendNext(observer, value)
if disposable.disposed {
break
}
}
sendCompleted(observer)
})
}
/// A producer for a Signal that will immediately complete without sending
/// any values.
public static var empty: SignalProducer {
return self.init { observer, disposable in
sendCompleted(observer)
}
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { _ in () }
}
/// Creates a queue for events that replays them when new signals are
/// created from the returned producer.
///
/// When values are put into the returned observer (sink), they will be
/// added to an internal buffer. If the buffer is already at capacity,
/// the earliest (oldest) value will be dropped to make room for the new
/// value.
///
/// Signals created from the returned producer will stay alive until a
/// terminating event is added to the queue. If the queue does not contain
/// such an event when the Signal is started, all values sent to the
/// returned observer will be automatically forwarded to the Signal’s
/// observers until a terminating event is received.
///
/// After a terminating event has been added to the queue, the observer
/// will not add any further events. This _does not_ count against the
/// value capacity so no buffered values will be dropped on termination.
public static func buffer(capacity: Int = Int.max) -> (SignalProducer, Signal<T, E>.Observer) {
precondition(capacity >= 0)
// This is effectively used as a synchronous mutex, but permitting
// limited recursive locking (see below).
//
// The queue is a "variable" just so we can use its address as the key
// and the value for dispatch_queue_set_specific().
var queue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.SignalProducer.buffer", DISPATCH_QUEUE_SERIAL)
dispatch_queue_set_specific(queue, &queue, &queue, nil)
// Used as an atomic variable so we can remove observers without needing
// to run on the queue.
let state: Atomic<BufferState<T, E>> = Atomic(BufferState())
let producer = self.init { observer, disposable in
// Assigned to when replay() is invoked synchronously below.
var token: RemovalToken?
let replay: () -> () = {
let originalState = state.modify { (var state) in
token = state.observers?.insert(observer)
return state
}
for value in originalState.values {
sendNext(observer, value)
}
if let terminationEvent = originalState.terminationEvent {
observer(terminationEvent)
}
}
// Prevent other threads from sending events while we're replaying,
// but don't deadlock if we're replaying in response to a buffer
// event observed elsewhere.
//
// In other words, this permits limited signal recursion for the
// specific case of replaying past events.
if dispatch_get_specific(&queue) != nil {
replay()
} else {
dispatch_sync(queue, replay)
}
if let token = token {
disposable.addDisposable {
state.modify { (var state) in
state.observers?.removeValueForToken(token)
return state
}
}
}
}
let bufferingObserver: Signal<T, E>.Observer = { event in
// Send serially with respect to other senders, and never while
// another thread is in the process of replaying.
dispatch_sync(queue) {
let originalState = state.modify { (var state) in
if let value = event.value {
state.addValue(value, upToCapacity: capacity)
} else {
// Disconnect all observers and prevent future
// attachments.
state.terminationEvent = event
state.observers = nil
}
return state
}
if let observers = originalState.observers {
for observer in observers {
observer(event)
}
}
}
}
return (producer, bufferingObserver)
}
/// Creates a SignalProducer that will attempt the given operation once for
/// each invocation of start().
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will send the error that
/// occurred.
public static func attempt(operation: () -> Result<T, E>) -> SignalProducer {
return self.init { observer, disposable in
operation().analysis(ifSuccess: { value in
sendNext(observer, value)
sendCompleted(observer)
}, ifFailure: { error in
sendError(observer, error)
})
}
}
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
///
/// The closure will also receive a disposable which can be used to
/// interrupt the work associated with the signal and immediately send an
/// `Interrupted` event.
public func startWithSignal(@noescape setUp: (Signal<T, E>, Disposable) -> ()) {
let (signal, sink) = Signal<T, E>.pipe()
// Disposes of the work associated with the SignalProducer and any
// upstream producers.
let producerDisposable = CompositeDisposable()
// Directly disposed of when start() or startWithSignal() is disposed.
let cancelDisposable = ActionDisposable {
sendInterrupted(sink)
producerDisposable.dispose()
}
setUp(signal, cancelDisposable)
if cancelDisposable.disposed {
return
}
let wrapperObserver: Signal<T, E>.Observer = { event in
sink(event)
if event.isTerminating {
// Dispose only after notifying the Signal, so disposal
// logic is consistently the last thing to run.
producerDisposable.dispose()
}
}
startHandler(wrapperObserver, producerDisposable)
}
}
private struct BufferState<T, Error: ErrorType> {
// All values in the buffer.
var values: [T] = []
// Any terminating event sent to the buffer.
//
// This will be nil if termination has not occurred.
var terminationEvent: Event<T, Error>?
// The observers currently attached to the buffered producer, or nil if the
// producer was terminated.
var observers: Bag<Signal<T, Error>.Observer>? = Bag()
// Appends a new value to the buffer, trimming it down to the given capacity
// if necessary.
mutating func addValue(value: T, upToCapacity capacity: Int) {
values.append(value)
while values.count > capacity {
values.removeAtIndex(0)
}
}
}
public protocol SignalProducerType {
/// The type of values being sent on the producer
typealias T
/// The type of error that can occur on the producer. If errors aren't possible
/// then `NoError` can be used.
typealias E: ErrorType
/// Extracts a signal producer from the receiver.
var producer: SignalProducer<T, E> { get }
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
func startWithSignal(@noescape setUp: (Signal<T, E>, Disposable) -> ())
}
extension SignalProducer: SignalProducerType {
public var producer: SignalProducer {
return self
}
}
extension SignalProducerType {
/// Creates a Signal from the producer, then attaches the given sink to the
/// Signal as an observer.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the signal and immediately send an `Interrupted` event.
public func start(sink: Event<T, E>.Sink) -> Disposable {
var disposable: Disposable!
startWithSignal { signal, innerDisposable in
signal.observe(sink)
disposable = innerDisposable
}
return disposable
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callbacks when events are
/// received.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the Signal, and prevent any future callbacks from being invoked.
public func start(error error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil) -> Disposable {
return start(Event.sink(next: next, error: error, completed: completed, interrupted: interrupted))
}
/// Lifts an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new SignalProducer which will apply
/// the given Signal operator to _every_ created Signal, just as if the
/// operator had been applied to each Signal yielded from start().
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func lift<U, F>(transform: Signal<T, E> -> Signal<U, F>) -> SignalProducer<U, F> {
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, innerDisposable in
outerDisposable.addDisposable(innerDisposable)
transform(signal).observe(observer)
}
}
}
/// Lifts a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new SignalProducer which will apply
/// the given Signal operator to _every_ Signal created from the two
/// producers, just as if the operator had been applied to each Signal
/// yielded from start().
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func lift<U, F, V, G>(transform: Signal<U, F> -> Signal<T, E> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.addDisposable(disposable)
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable.addDisposable(otherDisposable)
transform(otherSignal)(signal).observe(observer)
}
}
}
}
}
/// Maps each value in the producer to a new value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func map<U>(transform: T -> U) -> SignalProducer<U, E> {
return lift { $0.map(transform) }
}
/// Maps errors in the producer to a new error.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func mapError<F>(transform: E -> F) -> SignalProducer<T, F> {
return lift { $0.mapError(transform) }
}
/// Preserves only the values of the producer that pass the given predicate.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func filter(predicate: T -> Bool) -> SignalProducer<T, E> {
return lift { $0.filter(predicate) }
}
/// Returns a producer that will yield the first `count` values from the
/// input producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func take(count: Int) -> SignalProducer<T, E> {
return lift { $0.take(count) }
}
/// Returns a signal that will yield an array of values when `signal` completes.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func collect() -> SignalProducer<[T], E> {
return lift { $0.collect() }
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func observeOn(scheduler: SchedulerType) -> SignalProducer<T, E> {
return lift { $0.observeOn(scheduler) }
}
/// Combines the latest value of the receiver with the latest value from
/// the given producer.
///
/// The returned producer will not send a value until both inputs have sent at
/// least one value each. If either producer is interrupted, the returned producer
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatestWith<U>(otherProducer: SignalProducer<U, E>) -> SignalProducer<(T, U), E> {
return lift(ReactiveCocoa.combineLatestWith)(otherProducer)
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Error` and `Interrupted` events are always scheduled immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<T, E> {
return lift { $0.delay(interval, onScheduler: scheduler) }
}
/// Returns a producer that will skip the first `count` values, then forward
/// everything afterward.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skip(count: Int) -> SignalProducer<T, E> {
return lift { $0.skip(count) }
}
/// Treats all Events from the input producer as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// When a Completed or Error event is received, the resulting producer will send
/// the Event itself and then complete. When an Interrupted event is received,
/// the resulting producer will send the Event itself and then interrupt.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func materialize() -> SignalProducer<Event<T, E>, NoError> {
return lift { $0.materialize() }
}
/// Forwards the latest value from `self` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a producer that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input producers have
/// completed, or interrupt if either input producer is interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func sampleOn(sampler: SignalProducer<(), NoError>) -> SignalProducer<T, E> {
return lift(ReactiveCocoa.sampleOn)(sampler)
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned producer will complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntil(trigger: SignalProducer<(), NoError>) -> SignalProducer<T, E> {
return lift(ReactiveCocoa.takeUntil)(trigger)
}
/// Forwards events from `self` with history: values of the returned producer
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combinePrevious(initial: T) -> SignalProducer<(T, T), E> {
return lift { $0.combinePrevious(initial) }
}
/// Like `scan`, but sends only the final value and then immediately completes.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func reduce<U>(initial: U, _ combine: (U, T) -> U) -> SignalProducer<U, E> {
return lift { $0.reduce(initial, combine) }
}
/// Aggregates `self`'s values into a single combined value. When `self` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// producer returned from `scan`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func scan<U>(initial: U, _ combine: (U, T) -> U) -> SignalProducer<U, E> {
return lift { $0.scan(initial, combine) }
}
/// Forwards only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipRepeats(isRepeat: (T, T) -> Bool) -> SignalProducer<T, E> {
return lift { $0.skipRepeats(isRepeat) }
}
/// Does not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipWhile(predicate: T -> Bool) -> SignalProducer<T, E> {
return lift { $0.skipWhile(predicate) }
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a producer which passes through `Next`, `Error`, and `Interrupted`
/// events from `self` until `replacement` sends an event, at which point the
/// returned producer will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntilReplacement(replacement: SignalProducer<T, E>) -> SignalProducer<T, E> {
return lift(ReactiveCocoa.takeUntilReplacement)(replacement)
}
/// Waits until `self` completes and then forwards the final `count` values
/// on the returned producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeLast(count: Int) -> SignalProducer<T, E> {
return lift { $0.takeLast(count) }
}
/// Forwards any values from `self` until `predicate` returns false,
/// at which point the returned producer will complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeWhile(predicate: T -> Bool) -> SignalProducer<T, E> {
return lift { $0.takeWhile(predicate) }
}
/// Zips elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zipWith<U>(otherProducer: SignalProducer<U, E>) -> SignalProducer<(T, U), E> {
return lift(ReactiveCocoa.zipWith)(otherProducer)
}
/// Applies `operation` to values from `self` with `Success`ful results
/// forwarded on the returned producer and `Failure`s sent as `Error` events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func attempt(operation: T -> Result<(), E>) -> SignalProducer<T, E> {
return lift { $0.attempt(operation) }
}
/// Applies `operation` to values from `self` with `Success`ful results mapped
/// on the returned producer and `Failure`s sent as `Error` events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func attemptMap<U>(operation: T -> Result<U, E>) -> SignalProducer<U, E> {
return lift { $0.attemptMap(operation) }
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If `self` terminates while a value is being throttled, that value
/// will be discarded and the returned producer will terminate immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<T, E> {
return lift { $0.throttle(interval, onScheduler: scheduler) }
}
/// Forwards events from `self` until `interval`. Then if producer isn't completed yet,
/// errors with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The producer
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timeoutWithError(error: E, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<T, E> {
return lift { $0.timeoutWithError(error, afterInterval: interval, onScheduler: scheduler) }
}
}
extension SignalProducer where T: OptionalType {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func ignoreNil() -> SignalProducer<T.T, E> {
return lift { $0.ignoreNil() }
}
}
extension SignalProducer where T: EventType, E: NoError {
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func dematerialize() -> SignalProducer<T.T, T.E> {
return lift { $0.dematerialize() }
}
}
extension SignalProducerType where E: NoError {
/// Promotes a producer that does not generate errors into one that can.
///
/// This does not actually cause errors to be generated for the given producer,
/// but makes it easier to combine with other producers that may error; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func promoteErrors<F: ErrorType>(_: F.Type) -> SignalProducer<T, F> {
return lift { $0.promoteErrors(F) }
}
}
extension SignalProducerType where T: Equatable {
/// Forwards only those values from `self` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipRepeats() -> SignalProducer<T, E> {
return lift { $0.skipRepeats() }
}
}
/// Creates a repeating timer of the given interval, with a reasonable
/// default leeway, sending updates on the given scheduler.
///
/// This timer will never complete naturally, so all invocations of start() must
/// be disposed to avoid leaks.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<NSDate, NoError> {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return timer(interval, onScheduler: scheduler, withLeeway: interval * 0.1)
}
/// Creates a repeating timer of the given interval, sending updates on the
/// given scheduler.
///
/// This timer will never complete naturally, so all invocations of start() must
/// be disposed to avoid leaks.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType, withLeeway leeway: NSTimeInterval) -> SignalProducer<NSDate, NoError> {
precondition(interval >= 0)
precondition(leeway >= 0)
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.scheduleAfter(scheduler.currentDate.dateByAddingTimeInterval(interval), repeatingEvery: interval, withLeeway: leeway) {
sendNext(observer, scheduler.currentDate)
}
}
}
extension SignalProducerType {
/// Injects side effects to be performed upon the specified signal events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func on(started started: (() -> ())? = nil, event: (Event<T, E> -> ())? = nil, error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (T -> ())? = nil) -> SignalProducer<T, E> {
return SignalProducer { observer, compositeDisposable in
started?()
disposed.map(compositeDisposable.addDisposable)
self.startWithSignal { signal, disposable in
compositeDisposable.addDisposable(disposable)
signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .Next(value):
next?(value)
case let .Error(err):
error?(err)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer(receivedEvent)
}
}
}
}
/// Starts the returned signal on the given Scheduler.
///
/// This implies that any side effects embedded in the producer will be
/// performed on the given scheduler as well.
///
/// Events may still be sent upon other schedulers—this merely affects where
/// the `start()` method is run.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func startOn(scheduler: SchedulerType) -> SignalProducer<T, E> {
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.schedule {
self.startWithSignal { signal, signalDisposable in
compositeDisposable.addDisposable(signalDisposable)
signal.observe(observer)
}
}
}
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> {
return a.combineLatestWith(b)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> {
return combineLatest(a, b)
.combineLatestWith(c)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatestWith(d)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatestWith(e)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatestWith(f)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatestWith(g)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatestWith(h)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatestWith(i)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatestWith(j)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<S: SequenceType, T, Error where S.Generator.Element == SignalProducer<T, Error>>(producers: S) -> SignalProducer<[T], Error> {
var generator = producers.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { producer, next in
producer.combineLatestWith(next).map { $0.0 + [$0.1] }
}
}
return .empty
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> {
return a.zipWith(b)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> {
return zip(a, b)
.zipWith(c)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> {
return zip(a, b, c)
.zipWith(d)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
.zipWith(e)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zipWith(f)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zipWith(g)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zipWith(h)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zipWith(i)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zipWith(j)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<S: SequenceType, T, Error where S.Generator.Element == SignalProducer<T, Error>>(producers: S) -> SignalProducer<[T], Error> {
var generator = producers.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { producer, next in
producer.zipWith(next).map { $0.0 + [$0.1] }
}
}
return .empty
}
extension SignalProducerType {
/// Catches any error that may occur on the input producer, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMapError<F>(handler: E -> SignalProducer<T, F>) -> SignalProducer<T, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe(next: { value in
sendNext(observer, value)
}, error: { error in
handler(error).startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe(observer)
}
}, completed: {
sendCompleted(observer)
}, interrupted: {
sendInterrupted(observer)
})
}
}
}
}
extension SignalProducer {
/// `concat`s `next` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(next: SignalProducer) -> SignalProducer {
return SignalProducer<SignalProducer, E>(values: [self, next]).concat()
}
}
extension SignalProducerType {
/// Repeats `self` a total of `count` times. Repeating `1` times results in
/// an equivalent signal producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func times(count: Int) -> SignalProducer<T, E> {
precondition(count >= 0)
if count == 0 {
return .empty
} else if count == 1 {
return producer
}
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
func iterate(current: Int) {
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe { event in
switch event {
case .Completed:
let remainingTimes = current - 1
if remainingTimes > 0 {
iterate(remainingTimes)
} else {
sendCompleted(observer)
}
default:
observer(event)
}
}
}
}
iterate(count)
}
}
/// Ignores errors up to `count` times.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func retry(count: Int) -> SignalProducer<T, E> {
precondition(count >= 0)
if count == 0 {
return producer
} else {
return flatMapError { _ in
self.retry(count - 1)
}
}
}
/// Waits for completion of `producer`, *then* forwards all events from
/// `replacement`. Any error sent from `producer` is forwarded immediately, in
/// which case `replacement` will not be started, and none of its events will be
/// be forwarded. All values sent from `producer` are ignored.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func then<U>(replacement: SignalProducer<U, E>) -> SignalProducer<U, E> {
let relay = SignalProducer<U, E> { observer, observerDisposable in
self.startWithSignal { signal, signalDisposable in
observerDisposable.addDisposable(signalDisposable)
signal.observe(error: { error in
sendError(observer, error)
}, completed: {
sendCompleted(observer)
}, interrupted: {
sendInterrupted(observer)
})
}
}
return relay.concat(replacement)
}
/// Starts the producer, then blocks, waiting for the first value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func first() -> Result<T, E>? {
return take(1).single()
}
/// Starts the producer, then blocks, waiting for events: Next and Completed.
/// When a single value or error is sent, the returned `Result` will represent
/// those cases. However, when no values are sent, or when more than one value
/// is sent, `nil` will be returned.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func single() -> Result<T, E>? {
let semaphore = dispatch_semaphore_create(0)
var result: Result<T, E>?
take(2).start(next: { value in
if result != nil {
// Move into failure state after recieving another value.
result = nil
return
}
result = .success(value)
}, error: { error in
result = .failure(error)
dispatch_semaphore_signal(semaphore)
}, completed: {
dispatch_semaphore_signal(semaphore)
}, interrupted: {
dispatch_semaphore_signal(semaphore)
})
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return result
}
/// Starts the producer, then blocks, waiting for the last value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func last() -> Result<T, E>? {
return takeLast(1).single()
}
/// Starts the producer, then blocks, waiting for completion.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func wait() -> Result<(), E> {
return then(SignalProducer<(), E>(value: ())).last() ?? .success(())
}
}
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have completed.
case Merge
/// The producers should be concatenated, so that their values are sent in the
/// order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed of.
///
/// The resulting producer will complete only when the producer-of-producers and
/// the latest producer has completed.
case Latest
}
extension FlattenStrategy: CustomStringConvertible {
public var description: String {
switch self {
case .Merge:
return "merge"
case .Concat:
return "concatenate"
case .Latest:
return "latest"
}
}
}
extension SignalProducer where T: SignalProducerType, E == T.E {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner producer emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<T.T, E> {
switch strategy {
case .Merge:
return producer.merge()
case .Concat:
return producer.concat()
case .Latest:
return producer.switchToLatest()
}
}
}
extension SignalProducer {
/// Maps each event from `producer` to a new producer, then flattens the
/// resulting producers (into a single producer of values), according to the
/// semantics of the given strategy.
///
/// If `producer` or any of the created producers emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: T -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
}
extension SignalProducer where T: SignalProducerType, E == T.E {
/// Returns a producer which sends all the values from each producer emitted from
/// `producer`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers emit an error, the returned producer will emit
/// that error.
///
/// The returned producer completes only when `producer` and all producers
/// emitted from `producer` complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func concat() -> SignalProducer<T.T, E> {
return SignalProducer<T.T, E> { observer, disposable in
let state = ConcatState(observer: observer, disposable: disposable)
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observe(next: {
state.enqueueSignalProducer($0.producer)
}, error: { error in
sendError(observer, error)
}, completed: {
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
let completion = SignalProducer<T.T, E> { innerObserver, _ in
sendCompleted(innerObserver)
sendCompleted(observer)
}
state.enqueueSignalProducer(completion)
}, interrupted: {
sendInterrupted(observer)
})
}
}
}
}
private final class ConcatState<T, E: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Signal<T, E>.Observer
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<T, E>]> = Atomic([])
init(observer: Signal<T, E>.Observer, disposable: CompositeDisposable) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<T, E>) {
if disposable.disposed {
return
}
var shouldStart = true
queuedSignalProducers.modify { (var queue) in
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<T, E>? {
if disposable.disposed {
return nil
}
var nextSignalProducer: SignalProducer<T, E>?
queuedSignalProducers.modify { (var queue) in
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<T, E>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable.addDisposable(disposable)
signal.observe { event in
switch event {
case .Completed, .Interrupted:
handle.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
default:
self.observer(event)
}
}
}
}
}
extension SignalProducer where T: SignalProducerType, E == T.E {
/// Merges a `producer` of SignalProducers down into a single producer, biased toward the producers
/// added earlier. Returns a SignalProducer that will forward events from the inner producers as they arrive.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func merge() -> SignalProducer<T.T, E> {
return SignalProducer<T.T, E> { relayObserver, disposable in
let inFlight = Atomic(1)
let decrementInFlight: () -> () = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
sendCompleted(relayObserver)
}
}
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observe(next: { producer in
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable.addDisposable(innerDisposable)
innerSignal.observe { event in
switch event {
case .Completed, .Interrupted:
if event.isTerminating {
handle.remove()
}
decrementInFlight()
default:
relayObserver(event)
}
}
}
}, error: { error in
sendError(relayObserver, error)
}, completed: {
decrementInFlight()
}, interrupted: {
sendInterrupted(relayObserver)
})
}
}
}
/// Returns a producer that forwards values from the latest producer sent on
/// `producer`, ignoring values sent on previous inner producers.
///
/// An error sent on `producer` or the latest inner producer will be sent on the
/// returned producer.
///
/// The returned producer completes when `producer` and the latest inner
/// producer have both completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func switchToLatest() -> SignalProducer<T.T, E> {
return SignalProducer<T.T, E> { sink, disposable in
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
let state = Atomic(LatestState<T, E>())
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observe(next: { innerProducer in
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify { (var state) in
// When we replace the disposable below, this prevents the
// generated Interrupted event from doing any work.
state.replacingInnerSignal = true
return state
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify { (var state) in
state.replacingInnerSignal = false
state.innerSignalComplete = false
return state
}
innerSignal.observe { event in
switch event {
case .Interrupted:
// If interruption occurred as a result of a new signal
// arriving, we don't want to notify our observer.
let original = state.modify { (var state) in
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return state
}
if !original.replacingInnerSignal && original.outerSignalComplete {
sendCompleted(sink)
}
case .Completed:
let original = state.modify { (var state) in
state.innerSignalComplete = true
return state
}
if original.outerSignalComplete {
sendCompleted(sink)
}
default:
sink(event)
}
}
}
}, error: { error in
sendError(sink, error)
}, completed: {
let original = state.modify { (var state) in
state.outerSignalComplete = true
return state
}
if original.innerSignalComplete {
sendCompleted(sink)
}
}, interrupted: {
sendInterrupted(sink)
})
}
}
}
}
private struct LatestState<T, E: ErrorType> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
// These free functions are to workaround compiler crashes when attempting
// to lift binary signal operators directly with closures.
private func combineLatestWith<T, U, E>(otherSignal: Signal<U, E>) -> Signal<T, E> -> Signal<(T, U), E> {
return { $0.combineLatestWith(otherSignal) }
}
private func zipWith<T, U, E>(otherSignal: Signal<U, E>) -> Signal<T, E> -> Signal<(T, U), E> {
return { $0.zipWith(otherSignal) }
}
private func sampleOn<T, E>(sampler: Signal<(), NoError>) -> Signal<T, E> -> Signal<T, E> {
return { $0.sampleOn(sampler) }
}
private func takeUntil<T, E>(trigger: Signal<(), NoError>) -> Signal<T, E> -> Signal<T, E> {
return { $0.takeUntil(trigger) }
}
private func takeUntilReplacement<T, E>(replacement: Signal<T, E>) -> Signal<T, E> -> Signal<T, E> {
return { $0.takeUntilReplacement(replacement) }
}
| mit |
noppoMan/SwiftJNChatApp | Sources/SwiftJNChatApp/Middlewares/JWTAuthenticatableMiddleware.swift | 1 | 1477 | import Foundation
import WebAppKit
import JWT
enum JWTAuthenticatableMiddlewareError: Error {
case invalidClaims
case resourceNotFound
case authorizationRequired
}
struct JWTAuthenticatableMiddleware: Middleware {
public func respond(to request: Request, response: Response) throws -> Chainer {
guard let authrozation = request.headers["Authorization"] else {
throw JWTAuthenticatableMiddlewareError.authorizationRequired
}
let separated = authrozation.components(separatedBy: " ")
guard separated.count >= 2 else {
throw JWTAuthenticatableMiddlewareError.authorizationRequired
}
guard separated[0] == "JWT" else {
throw JWTAuthenticatableMiddlewareError.authorizationRequired
}
let token = separated[1]
let claims: ClaimSet = try JWT.decode(token, algorithm: .hs256(Config.default.jwtSecret.data(using: .utf8)!))
guard let userId = claims["user_id"] as? Int else {
throw JWTAuthenticatableMiddlewareError.invalidClaims
}
guard let user: User = try knex().table("users").where("id" == userId).fetch().first else {
throw JWTAuthenticatableMiddlewareError.resourceNotFound
}
var request = request
request.currentUser = user
return .next(request, response)
}
}
| mit |
davidahouse/chute | chute/Output/DifferenceReport/DifferenceReportHeader.swift | 1 | 960 | //
// DifferenceReportHeader.swift
// chute
//
// Created by David House on 11/16/17.
// Copyright © 2017 David House. All rights reserved.
//
import Foundation
struct DifferenceReportHeader: ChuteOutputDifferenceRenderable {
enum Constants {
static let Template = """
<div class="jumbotron">
<h1>Chute Difference Report</h1>
<div>
<p>Project: {{project}}</p>
<p>Origin Branch: {{origin_branch}}</p>
<p>Compared Branch: {{compared_branch}}</p>
</div>
</div>
"""
}
func render(difference: DataCaptureDifference) -> String {
let parameters: [String: CustomStringConvertible] = [
"project": difference.detail.project,
"origin_branch": difference.comparedTo.branch,
"compared_branch": difference.detail.branch
]
return Constants.Template.render(parameters: parameters)
}
}
| mit |
Yummypets/YPImagePicker | Source/Helpers/Permissions/YPPermissionCheckable.swift | 1 | 1404 | //
// PermissionCheckable.swift
// YPImagePicker
//
// Created by Sacha DSO on 25/01/2018.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
internal protocol YPPermissionCheckable {
func doAfterLibraryPermissionCheck(block: @escaping () -> Void)
func doAfterCameraPermissionCheck(block: @escaping () -> Void)
func checkLibraryPermission()
func checkCameraPermission()
}
internal extension YPPermissionCheckable where Self: UIViewController {
func doAfterLibraryPermissionCheck(block: @escaping () -> Void) {
YPPermissionManager.checkLibraryPermissionAndAskIfNeeded(sourceVC: self) { hasPermission in
if hasPermission {
block()
} else {
ypLog("Not enough permissions.")
}
}
}
func doAfterCameraPermissionCheck(block: @escaping () -> Void) {
YPPermissionManager.checkCameraPermissionAndAskIfNeeded(sourceVC: self) { hasPermission in
if hasPermission {
block()
} else {
ypLog("Not enough permissions.")
}
}
}
func checkLibraryPermission() {
YPPermissionManager.checkLibraryPermissionAndAskIfNeeded(sourceVC: self) { _ in }
}
func checkCameraPermission() {
YPPermissionManager.checkCameraPermissionAndAskIfNeeded(sourceVC: self) { _ in }
}
}
| mit |
nguyenantinhbk77/practice-swift | Apps/YikYak Clone/YikYak Clone/AppDelegate.swift | 2 | 2593 | //
// AppDelegate.swift
// YikYak Clone
//
// Created by Domenico on 07/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navbar = UINavigationBar.appearance()
navbar.barTintColor = UIColor(red: 168.0/255, green: 215.0/255, blue: 111.0/255, alpha: 1)
let tabbar = UITabBar.appearance()
tabbar.barTintColor = UIColor(red: 168.0/255, green: 215.0/255, blue: 111.0/255, alpha: 1)
tabbar.tintColor = UIColor.whiteColor()
// Parse authentication
var applicationId = "xxx"
var clientKey = "xx"
Parse.setApplicationId(applicationId, clientKey: clientKey)
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 |
Ashok28/Kingfisher | Sources/General/Kingfisher.swift | 1 | 3407 | //
// Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 16/9/14.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ImageIO
#if os(macOS)
import AppKit
public typealias KFCrossPlatformImage = NSImage
public typealias KFCrossPlatformView = NSView
public typealias KFCrossPlatformColor = NSColor
public typealias KFCrossPlatformImageView = NSImageView
public typealias KFCrossPlatformButton = NSButton
#else
import UIKit
public typealias KFCrossPlatformImage = UIImage
public typealias KFCrossPlatformColor = UIColor
#if !os(watchOS)
public typealias KFCrossPlatformImageView = UIImageView
public typealias KFCrossPlatformView = UIView
public typealias KFCrossPlatformButton = UIButton
#if canImport(TVUIKit)
import TVUIKit
#endif
#else
import WatchKit
#endif
#endif
/// Wrapper for Kingfisher compatible types. This type provides an extension point for
/// convenience methods in Kingfisher.
public struct KingfisherWrapper<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a
/// value in the namespace of Kingfisher.
public protocol KingfisherCompatible: AnyObject { }
/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a
/// value in the namespace of Kingfisher.
public protocol KingfisherCompatibleValue {}
extension KingfisherCompatible {
/// Gets a namespace holder for Kingfisher compatible types.
public var kf: KingfisherWrapper<Self> {
get { return KingfisherWrapper(self) }
set { }
}
}
extension KingfisherCompatibleValue {
/// Gets a namespace holder for Kingfisher compatible types.
public var kf: KingfisherWrapper<Self> {
get { return KingfisherWrapper(self) }
set { }
}
}
extension KFCrossPlatformImage: KingfisherCompatible { }
#if !os(watchOS)
extension KFCrossPlatformImageView: KingfisherCompatible { }
extension KFCrossPlatformButton: KingfisherCompatible { }
extension NSTextAttachment: KingfisherCompatible { }
#else
extension WKInterfaceImage: KingfisherCompatible { }
#endif
#if os(tvOS) && canImport(TVUIKit)
@available(tvOS 12.0, *)
extension TVMonogramView: KingfisherCompatible { }
#endif
| mit |
fortmarek/Supl | SuplUITests/SuplUITests.swift | 1 | 2133 | //
// SuplUITests.swift
// SuplUITests
//
// Created by Marek Fořt on 11.08.15.
// Copyright © 2015 Marek Fořt. All rights reserved.
//
import XCTest
class SuplUITests: 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()
}
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.
setupSnapshot(XCUIApplication())
_ = self.expectation(
for: NSPredicate(format: "self.count = 1"),
evaluatedWith: XCUIApplication().tables,
handler: nil)
self.waitForExpectations(timeout: 5.0, handler: nil)
snapshot("main")
XCUIApplication().navigationBars["Supl"].buttons["Settings"].tap()
snapshot("settings")
_ = self.expectation(
for: NSPredicate(format: "self.count = 1"),
evaluatedWith: XCUIApplication().tables,
handler: nil)
self.waitForExpectations(timeout: 5.0, handler: nil)
let cells = XCUIApplication().tables.cells
XCTAssertEqual(cells.count, 6)
cells.element(boundBy: 4).tap()
XCUIApplication().buttons["DALŠÍ"].tap()
XCUIApplication().buttons["DALŠÍ"].tap()
XCUIApplication().buttons["DALŠÍ"].tap()
snapshot("walkthrough_login")
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/07624-swift-sourcemanager-getmessage.swift | 11 | 278 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
func a<T where f.h = Swift.c {
enum B : a {
let v: AnyObject.c {
(e: A {
class
case c,
extension N
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/08339-swift-sourcemanager-getmessage.swift | 11 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension g {
class B {
let : {
if c {
{
func g {
enum b {
class
case ,
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/13648-swift-type-walk.swift | 11 | 423 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let b {
struct A { func b(
let v: A.b
class A {
func b<f : b {
{
func i( ) {
var P {
protocol A {
enum b : B< b(
(
{
{
( (
{
{
(
{
{ {
{
[ {
(
{
{
{
{
{
{
{
{
{
{
( {
{
{
( (
(
{
{
{
{
{
{ {
{
[ {
{
[ {
( {
{ {
{
[ {
{
{
{
{
{
{
(
{
( {
{
{
{
{
{
{
{
B<
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/01806-swift-typechecker-validatedecl.swift | 1 | 251 | // 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 a {
protocol f : a {
typealias b
enum b : Range<d>
protocol a {
{
}
struct d
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00851-std-function-func-swift-type-subst.swift | 1 | 261 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A
protocol P {
init( )
}
protocol C {
var f : A
}
func compose<T
{
{
}
class A : P
| mit |
iWeslie/Ant | Ant/Ant/Main/NewsHotCommondCell.swift | 2 | 764 | //
// NewsHotCommondCell.swift
// Ant
//
// Created by LiuXinQiang on 2017/7/27.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class NewsHotCommondCell: UITableViewCell {
@IBOutlet weak var userPicImage: UIImageView!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var zanLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var areaLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
RunsCode/API-Swift | API_Swift/RunsTests/RunsTests.swift | 1 | 952 | //
// RunsTests.swift
// RunsTests
//
// Created by Dev_Wang on 2017/5/5.
// Copyright © 2017年 Giant. All rights reserved.
//
import XCTest
@testable import Runs
class RunsTests: 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 |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Services/PXServicesURLConfigs.swift | 1 | 2893 | import Foundation
enum PX_ENVIRONMENTS: CaseIterable {
case alpha
case beta
case gamma
case prod
}
class PXServicesURLConfigs {
static let MP_ALPHA_ENV = "/alpha"
static let MP_BETA_ENV = "/beta"
static let MP_GAMMA_ENV = "/gamma"
static let MP_PROD_ENV = "/v1"
static let NEW_API_ALPHA_ENV = "/alpha"
static let NEW_API_BETA_ENV = "/beta"
static let NEW_API_GAMMA_ENV = "/gamma"
static let NEW_API_PROD_ENV = "/production"
static let API_VERSION = "2.0"
static let MP_API_BASE_URL: String = "https://api.mercadopago.com"
static let MP_DEFAULT_PROCESSING_MODE = "aggregator"
static let MP_DEFAULT_PROCESSING_MODES = [MP_DEFAULT_PROCESSING_MODE]
static let MP_CREATE_TOKEN_URI = "/v1/card_tokens"
var MP_REMEDY_URI: String
var MP_PAYMENTS_URI: String
var MP_INIT_URI: String
var MP_RESET_ESC_CAP: String
var MP_POINTS_URI: String
private static var sharedPXServicesURLConfigs: PXServicesURLConfigs = {
let pxServicesURLConfigs = PXServicesURLConfigs()
return pxServicesURLConfigs
}()
private init() {
var MP_SELECTED_ENV = PXServicesURLConfigs.MP_PROD_ENV
var NEW_API_SELECTED_ENV = PXServicesURLConfigs.NEW_API_PROD_ENV
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let infoPlist = NSDictionary(contentsOfFile: path),
let pxEnvironment = infoPlist["PX_ENVIRONMENT"] as? String,
let environment = PX_ENVIRONMENTS.allCases.first(where: { "\($0)" == pxEnvironment }) {
// Initialize values from config
switch environment {
case .alpha:
MP_SELECTED_ENV = PXServicesURLConfigs.MP_ALPHA_ENV
NEW_API_SELECTED_ENV = PXServicesURLConfigs.NEW_API_ALPHA_ENV
case .beta:
MP_SELECTED_ENV = PXServicesURLConfigs.MP_BETA_ENV
NEW_API_SELECTED_ENV = PXServicesURLConfigs.NEW_API_BETA_ENV
case .gamma:
MP_SELECTED_ENV = PXServicesURLConfigs.MP_GAMMA_ENV
NEW_API_SELECTED_ENV = PXServicesURLConfigs.NEW_API_GAMMA_ENV
case .prod:
MP_SELECTED_ENV = PXServicesURLConfigs.MP_PROD_ENV
NEW_API_SELECTED_ENV = PXServicesURLConfigs.NEW_API_PROD_ENV
}
}
self.MP_REMEDY_URI = NEW_API_SELECTED_ENV + "/px_mobile/v1/remedies/${payment_id}"
self.MP_PAYMENTS_URI = MP_SELECTED_ENV + "/px_mobile/payments"
self.MP_INIT_URI = NEW_API_SELECTED_ENV + "/px_mobile/v2/checkout"
self.MP_RESET_ESC_CAP = NEW_API_SELECTED_ENV + "/px_mobile/v1/esc_cap"
self.MP_POINTS_URI = MP_SELECTED_ENV + "/px_mobile/congrats"
}
class func shared() -> PXServicesURLConfigs {
return sharedPXServicesURLConfigs
}
}
| mit |
intelygenz/App2WebHandoff | App2WebHandoff/UIHandoffWebViewDelegate.swift | 1 | 1196 | //
// UIHandoffWebViewDelegate.swift
// App2WebHandoff
//
// Created by alexruperez on 28/12/16.
// Copyright © 2016 Intelygenz.
//
import UIKit
open class UIHandoffWebViewDelegate: NSObject {
}
extension UIHandoffWebViewDelegate: UIWebViewDelegate {
open func webViewDidStartLoad(_ webView: UIWebView) {
if webView.userActivity == nil && webView.request?.url?.scheme != nil {
webView.userActivity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
webView.userActivity?.isEligibleForHandoff = true
webView.userActivity?.webpageURL = webView.request?.url
}
webView.userActivity?.becomeCurrent()
}
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if webView.userActivity == nil && request.url?.scheme != nil {
webView.userActivity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
webView.userActivity?.isEligibleForHandoff = true
webView.userActivity?.webpageURL = request.url
}
webView.userActivity?.becomeCurrent()
return true
}
}
| mit |
gribozavr/swift | test/Driver/Dependencies/malformed-but-valid-yaml-fine.swift | 1 | 3484 | // RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/malformed-but-valid-yaml-fine/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST-NOT: Handled
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: Handled other.swift
// CHECK-SECOND: Handled main.swift
// RUN: touch -t 201401240007 %t/other.swift
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
// CHECK-THIRD: Handled main.swift
// CHECK-THIRD: Handled other.swift
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/malformed-but-valid-yaml-fine/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: touch -t 201401240006 %t/main.swift
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s
// RUN: touch -t 201401240007 %t/main.swift
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s
// CHECK-FOURTH-NOT: Handled other.swift
// CHECK-FOURTH: Handled main.swift
// CHECK-FOURTH-NOT: Handled other.swift
| apache-2.0 |
iwasrobbed/LazyObject | Tests/DateFormatterTests.swift | 1 | 606 | //
// DateFormatterTests.swift
// LazyObject
//
// Created by Rob Phillips on 5/25/16.
// Copyright © 2016 Glazed Donut, LLC. All rights reserved.
//
import Foundation
import XCTest
@testable import LazyObject
final class DateFormatterTests: XCTestCase {
func testFormatterToString() {
XCTAssertTrue(DateFormatter.Lazy.iso8601.toString() == "ISO 8601")
XCTAssertTrue(DateFormatter.Lazy.rfc3339.toString() == "RFC 3339")
XCTAssertTrue(DateFormatter.Lazy.rfc1123.toString() == "RFC 1123")
XCTAssertTrue(DateFormatter.Lazy.rfc850.toString() == "RFC 850")
}
}
| mit |
theodinspire/FingerBlade | FingerBlade/FileHandler.swift | 1 | 162 | //
// FileHandler.swift
// FingerBlade
//
// Created by Eric T Cormack on 2/15/17.
// Copyright © 2017 the Odin Spire. All rights reserved.
//
import Cocoa
| gpl-3.0 |
glessard/timing | Tests/timingTests/TimingTests.swift | 1 | 1441 | import XCTest
import struct Foundation.Date
import struct Foundation.TimeInterval
#if os(Linux)
import func Glibc.usleep
#endif
import timing
let iterations = 1_000_000
class TimingTests: XCTestCase
{
func testSince()
{
let t1 = Tic()
let i = TimingInterval.since(t1)
XCTAssertGreaterThanOrEqual(i.ns, 0)
XCTAssertGreaterThanOrEqual(i.interval, TimeInterval())
}
func testCustomString()
{
var i = TimingInterval(300)
XCTAssertEqual(String(describing: i), "300 ns")
i = TimingInterval(Int64(3002))
XCTAssertEqual(String(describing: i), "3.002 µs")
i = TimingInterval(seconds: 12.555e-6)
XCTAssertEqual(String(describing: i), "12.55 µs")
i = TimingInterval(22.111e6)
XCTAssertEqual(String(describing: i), "22.111 ms")
i = TimingInterval(seconds: 0.5555555) - TimingInterval(1)
XCTAssertEqual(String(describing: i), "555.555 ms")
i = TimingInterval(seconds: 10)/9
XCTAssertEqual(String(describing: i), "1111.11 ms")
i = TimingInterval(seconds: 8.2222222)
XCTAssertEqual(String(describing: i), "8.222 s")
i = TimingInterval(seconds: 1899.4444)
XCTAssertEqual(String(describing: i), "1899.444 s")
}
func testPrintExample()
{
let tic = Tic()
usleep(1)
let dt1 = tic.toc
usleep(100)
let dt2 = tic.toc
print(dt1)
print(dt2)
usleep(1000)
print(tic.toc)
usleep(1_000_000)
print(tic.toc)
}
}
| mit |
BrisyIOS/zhangxuWeiBo | zhangxuWeiBo/zhangxuWeiBo/classes/Home/Model/ZXStatusManager.swift | 1 | 2134 | //
// ZXStatusManager.swift
// zhangxuWeiBo
//
// Created by zhangxu on 16/6/18.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ZXStatusManager: NSObject {
// 加载首页数据
class func homeStatusesWithParam(param : ZXHomeStatusParam? , success : ((ZXHomeStatusesResult) -> Void)? , failure : ((NSError) -> Void)?) -> Void {
HttpManager.shareInstance.request(RequestType.GET, urlString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: param?.mj_keyValues()) { (result, error) in
if error != nil {
print(error);
return;
}
// 获取可选类型中的数据
guard let result = result else {
return;
}
let model = ZXHomeStatusesResult.mj_objectWithKeyValues(result);
success!(model);
let filePath = (kDocumentPath as NSString).stringByAppendingPathComponent("homeStatus");
result.mj_keyValues().writeToFile(filePath, atomically: true);
}
}
// 发微博
class func sendStatusWithParam(param : ZXSendStatusParam? , success : ((ZXSendStatusResult) -> Void)? , failure : ((NSError) -> Void)?) -> Void {
HttpManager.shareInstance.request(RequestType.POST, urlString: "https://api.weibo.com/2/statuses/update.json", parameters: param?.mj_keyValues()) { (result, error) in
// let json = try!NSJSONSerialization.JSONObjectWithData(data as! NSData, options: NSJSONReadingOptions.MutableContainers) as?NSDictionary;
if error != nil {
return;
}
// 获取可选类型中的数据
guard let result = result else {
return;
}
let model = ZXSendStatusResult.mj_objectWithKeyValues(result);
success!(model);
}
}
}
| apache-2.0 |
halo/LinkLiar | LinkLiar/Classes/MACAddressFormatter.swift | 1 | 2112 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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
class MACAddressFormatter : Formatter {
let disallowedCharacters = CharacterSet(charactersIn: "0123456789:abcdefABCDEF").inverted
override func string(for obj: Any?) -> String? {
guard let string = obj as? String else { return nil }
return string
}
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
guard obj != nil else { return false }
obj?.pointee = string as AnyObject
return true
}
override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
if partialString.count > 17 {
return false
}
if partialString.rangeOfCharacter(from: disallowedCharacters) != nil {
return false
}
return true
}
}
| mit |
imjerrybao/SocketIO-Kit | Source/SocketIOJSONHandshake.swift | 2 | 1044 | //
// SocketIOJSONHandshake.swift
// Smartime
//
// Created by Ricardo Pereira on 02/05/2015.
// Copyright (c) 2015 Ricardo Pereira. All rights reserved.
//
import Foundation
extension SocketIOHandshake: SocketIOJSON {
static func parse(json: String) -> (Bool, SocketIOHandshake) {
// Parse JSON
if let parsed = SocketIOJSONParser(json: json),
let sid = parsed["sid"] as? String,
let transports = parsed["upgrades"] as? [String],
var pingInterval = parsed["pingInterval"] as? Int,
var pingTimeout = parsed["pingTimeout"] as? Int
{
pingInterval = pingInterval / 1000
pingTimeout = pingTimeout / 1000
// Valid
return (true, SocketIOHandshake(sid: sid, transport: transports, pingInterval: pingInterval, pingTimeout: pingTimeout))
}
// Invalid
return (false, SocketIOHandshake(sid: "", transport: [""], pingInterval: defaultPingInterval, pingTimeout: defaultPingTimeout))
}
} | mit |
argon/mas | MasKit/Commands/Version.swift | 1 | 700 | //
// Version.swift
// mas-cli
//
// Created by Andrew Naylor on 20/09/2015.
// Copyright © 2015 Andrew Naylor. All rights reserved.
//
import Commandant
/// Command which displays the version of the mas tool.
public struct VersionCommand: CommandProtocol {
public typealias Options = NoOptions<MASError>
public let verb = "version"
public let function = "Print version number"
public init() {}
/// Runs the command.
public func run(_: Options) -> Result<(), MASError> {
let plist = Bundle.main.infoDictionary
if let versionString = plist?["CFBundleShortVersionString"] {
print(versionString)
}
return .success(())
}
}
| mit |
Codility-BMSTU/Codility | Codility/Codility/OBCreateQRViewController.swift | 1 | 951 | //
// OBCreateQRViewController.swift
// Codility
//
// Created by Кирилл Володин on 17.09.17.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import UIKit
import QRCode
class OBCreateQRViewController: UIViewController {
@IBOutlet weak var QRImage: UIImageView!
@IBOutlet weak var pushButton: UIButton!
var encodedData: String = ""
override func viewDidLoad() {
super.viewDidLoad()
pushButton.layer.cornerRadius = 10
pushButton.clipsToBounds = true
generateQR()
}
func generateQR() {
let url = encodedData
let prefix = "bank://"
let fullUrl = URL(string: prefix.appending(url))
let qrCode = QRCode(fullUrl!)
QRImage.image = qrCode?.image
}
@IBAction func goBack(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
}
| apache-2.0 |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Sources/AccessibilityExtensions.swift | 2 | 7862 | //
// AccessibilityExtensions.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import UIKit
import SceneKit
class CoordinateAccessibilityElement: UIAccessibilityElement {
let coordinate: Coordinate
weak var world: GridWorld?
/// Override `accessibilityLabel` to always return updated information about world state.
override var accessibilityLabel: String? {
get {
return world?.speakableContents(of: coordinate)
}
set {}
}
init(coordinate: Coordinate, inWorld world: GridWorld, view: UIView) {
self.coordinate = coordinate
self.world = world
super.init(accessibilityContainer: view)
}
}
class GridWorldAccessibilityElement: UIAccessibilityElement {
weak var world: GridWorld?
init(world: GridWorld, view: UIView) {
self.world = world
super.init(accessibilityContainer: view)
}
override var accessibilityLabel: String? {
get {
return world?.speakableDescription
}
set {}
}
}
// MARK: WorldViewController Accessibility
extension WorldViewController {
func registerForAccessibilityNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(voiceOverStatusChanged), name: Notification.Name(rawValue: UIAccessibilityVoiceOverStatusChanged), object: nil)
}
func unregisterForAccessibilityNotifications() {
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: UIAccessibilityVoiceOverStatusChanged), object: nil)
}
func voiceOverStatusChanged() {
DispatchQueue.main.async { [unowned self] in
self.setVoiceOverForCurrentStatus()
}
}
func setVoiceOverForCurrentStatus() {
if UIAccessibilityIsVoiceOverRunning() {
scnView.gesturesEnabled = false
cameraController?.switchToOverheadView()
configureAccessibilityElementsForGrid()
// Add an AccessibilityComponent to each actor.
for actor in scene.actors {
actor.addComponent(AccessibilityComponent.self)
}
}
else {
// Set for UITesting.
view.isAccessibilityElement = true
view.accessibilityLabel = "The world is running."
scnView.gesturesEnabled = true
cameraController?.resetFromVoiceOver()
for actor in scene.actors {
actor.removeComponent(AccessibilityComponent.self)
}
}
}
func configureAccessibilityElementsForGrid() {
view.isAccessibilityElement = false
view.accessibilityElements = []
for coordinate in scene.gridWorld.columnRowSortedCoordinates {
let gridPosition = coordinate.position
let rootPosition = scene.gridWorld.grid.scnNode.convertPosition(gridPosition, to: nil)
let offset = WorldConfiguration.coordinateLength / 2
let upperLeft = scnView.projectPoint(SCNVector3Make(rootPosition.x - offset, rootPosition.y, rootPosition.z - offset))
let lowerRight = scnView.projectPoint(SCNVector3Make(rootPosition.x + offset, rootPosition.y, rootPosition.z + offset))
let point = CGPoint(x: CGFloat(upperLeft.x), y: CGFloat(upperLeft.y))
let size = CGSize (width: CGFloat(lowerRight.x - upperLeft.x), height: CGFloat(lowerRight.y - upperLeft.y))
let element = CoordinateAccessibilityElement(coordinate: coordinate, inWorld: scene.gridWorld, view: view)
element.accessibilityFrame = CGRect(origin: point, size: size)
view.accessibilityElements?.append(element)
}
let container = GridWorldAccessibilityElement(world: scene.gridWorld, view: view)
container.accessibilityFrame = view.bounds
view.accessibilityElements?.append(container)
}
}
extension GridWorld {
func speakableContents(of coordinate: Coordinate) -> String {
let prefix = "\(coordinate.description), "
let contents = excludingNodes(ofType: Block.self, at: coordinate).reduce("") { str, node in
var tileDescription = str
switch node.identifier {
case .actor:
let actor = node as? Actor
let name = actor?.type.rawValue ?? "Actor"
tileDescription.append("\(name) at height \(node.level), facing \(node.heading), ")
case .stair:
tileDescription.append("stair, facing \(node.heading), from level \(node.level - 1) to \(node.level), ")
case .switch:
let switchItem = node as! Switch
let switchState = switchItem.isOn ? "open" : "closed"
tileDescription.append("\(switchState) switch at height \(node.level)")
case .water:
tileDescription.append("water, ")
default:
tileDescription.append("\(node.identifier.rawValue) at height \(node.level), ")
}
return tileDescription
}
let suffix = contents.isEmpty ? "is empty." : contents
return prefix + suffix
}
func columnRowSortPredicate(_ coor1: Coordinate, _ coor2: Coordinate) -> Bool {
if coor1.column == coor2.column {
return coor1.row < coor2.row
}
return coor1.column < coor2.column
}
var columnRowSortedCoordinates: [Coordinate] {
return allPossibleCoordinates.sorted(by: columnRowSortPredicate)
}
var speakableDescription: String {
let sortedItems = grid.allItemsInGrid.sorted { item1, item2 in
return columnRowSortPredicate(item1.coordinate, item2.coordinate)
}
let actors = sortedItems.flatMap { $0 as? Actor }
let randomItems = sortedItems.filter { $0.identifier == .randomNode }
let goals = sortedItems.filter {
switch $0.identifier {
case .switch, .portal, .item, .platformLock: return true
default: return false
}
}
var description = "The world is \(columnCount) columns by \(rowCount) rows. "
if actors.isEmpty {
description += "There is no character placed in this world. You must place your own."
}
else {
for node in actors {
let name = node.type.rawValue
description += "\(name) starts at \(node.locationDescription)."
}
}
if !goals.isEmpty {
description += " The important locations are: "
for (index, goalNode) in goals.enumerated() {
description += "\(goalNode.identifier.rawValue) at \(goalNode.locationDescription)"
description += index == goals.endIndex ? "." : "; "
}
}
if !randomItems.isEmpty {
for (index, item) in randomItems.enumerated() {
let object = item as! RandomNode
let nodeType = object.resemblingNode.identifier.rawValue
description += "random \(nodeType) marker at \(item.locationDescription)"
description += index == randomItems.endIndex ? "." : "; "
}
}
return description + " To repeat this description, tap outside of the world grid."
}
}
extension Actor {
var speakableName: String {
return type.rawValue
}
}
extension Item {
var locationDescription: String{
return "\(coordinate.description), height \(level)"
}
}
| mit |
DAloG/BlueCap | BlueCapKit/Central/CentralManager.swift | 1 | 11441 | //
// CentralManager.swift
// BlueCap
//
// Created by Troy Stribling on 6/4/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreBluetooth
///////////////////////////////////////////
// CentralManagerImpl
public protocol CentralManagerWrappable {
typealias WrappedPeripheral
var poweredOn : Bool {get}
var poweredOff : Bool {get}
var peripherals : [WrappedPeripheral] {get}
var state: CBCentralManagerState {get}
func scanForPeripheralsWithServices(uuids:[CBUUID]?)
func stopScan()
}
public struct CentralQueue {
private static let queue = dispatch_queue_create("com.gnos.us.central.main", DISPATCH_QUEUE_SERIAL)
public static func sync(request:()->()) {
dispatch_sync(self.queue, request)
}
public static func async(request:()->()) {
dispatch_async(self.queue, request)
}
public static func delay(delay:Double, request:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Float(delay)*Float(NSEC_PER_SEC)))
dispatch_after(popTime, self.queue, request)
}
}
public class CentralManagerImpl<Wrapper where Wrapper:CentralManagerWrappable,
Wrapper.WrappedPeripheral:PeripheralWrappable> {
private var afterPowerOnPromise = Promise<Void>()
private var afterPowerOffPromise = Promise<Void>()
internal var afterPeripheralDiscoveredPromise = StreamPromise<Wrapper.WrappedPeripheral>()
private var _isScanning = false
public var isScanning : Bool {
return self._isScanning
}
public init() {
}
public func startScanning(central:Wrapper, capacity:Int? = nil) -> FutureStream<Wrapper.WrappedPeripheral> {
return self.startScanningForServiceUUIDs(central, uuids:nil, capacity:capacity)
}
public func startScanningForServiceUUIDs(central:Wrapper, uuids:[CBUUID]!, capacity:Int? = nil) -> FutureStream<Wrapper.WrappedPeripheral> {
if !self._isScanning {
Logger.debug("UUIDs \(uuids)")
self._isScanning = true
if let capacity = capacity {
self.afterPeripheralDiscoveredPromise = StreamPromise<Wrapper.WrappedPeripheral>(capacity:capacity)
} else {
self.afterPeripheralDiscoveredPromise = StreamPromise<Wrapper.WrappedPeripheral>()
}
central.scanForPeripheralsWithServices(uuids)
}
return self.afterPeripheralDiscoveredPromise.future
}
public func stopScanning(central:Wrapper) {
if self._isScanning {
Logger.debug()
self._isScanning = false
central.stopScan()
}
}
// connection
public func disconnectAllPeripherals(central:Wrapper) {
Logger.debug()
for peripheral in central.peripherals {
peripheral.disconnect()
}
}
// power up
public func powerOn(central:Wrapper) -> Future<Void> {
Logger.debug()
CentralQueue.sync {
self.afterPowerOnPromise = Promise<Void>()
if central.poweredOn {
self.afterPowerOnPromise.success()
}
}
return self.afterPowerOnPromise.future
}
public func powerOff(central:Wrapper) -> Future<Void> {
Logger.debug()
CentralQueue.sync {
self.afterPowerOffPromise = Promise<Void>()
if central.poweredOff {
self.afterPowerOffPromise.success()
}
}
return self.afterPowerOffPromise.future
}
public func didDiscoverPeripheral(peripheral:Wrapper.WrappedPeripheral) {
self.afterPeripheralDiscoveredPromise.success(peripheral)
}
// central manager state
public func didUpdateState(central:Wrapper) {
switch(central.state) {
case .Unauthorized:
Logger.debug("Unauthorized")
break
case .Unknown:
Logger.debug("Unknown")
break
case .Unsupported:
Logger.debug("Unsupported")
break
case .Resetting:
Logger.debug("Resetting")
break
case .PoweredOff:
Logger.debug("PoweredOff")
if !self.afterPowerOffPromise.completed {
self.afterPowerOffPromise.success()
}
break
case .PoweredOn:
Logger.debug("PoweredOn")
if !self.afterPowerOnPromise.completed {
self.afterPowerOnPromise.success()
}
break
}
}
}
// CentralManagerImpl
///////////////////////////////////////////
public class CentralManager : NSObject, CBCentralManagerDelegate, CentralManagerWrappable {
private static var instance : CentralManager!
internal let impl = CentralManagerImpl<CentralManager>()
// CentralManagerWrappable
public var poweredOn : Bool {
return self.cbCentralManager.state == CBCentralManagerState.PoweredOn
}
public var poweredOff : Bool {
return self.cbCentralManager.state == CBCentralManagerState.PoweredOff
}
public var peripherals : [Peripheral] {
return self.discoveredPeripherals.values.sort() {(p1:Peripheral, p2:Peripheral) -> Bool in
switch p1.discoveredAt.compare(p2.discoveredAt) {
case .OrderedSame:
return true
case .OrderedDescending:
return false
case .OrderedAscending:
return true
}
}
}
public var state: CBCentralManagerState {
return self.cbCentralManager.state
}
public func scanForPeripheralsWithServices(uuids:[CBUUID]?) {
self.cbCentralManager.scanForPeripheralsWithServices(uuids,options:nil)
}
public func stopScan() {
self.cbCentralManager.stopScan()
}
// CentralManagerWrappable
private var cbCentralManager : CBCentralManager! = nil
internal var discoveredPeripherals = [CBPeripheral: Peripheral]()
public class var sharedInstance : CentralManager {
self.instance = self.instance ?? CentralManager()
return self.instance
}
public class func sharedInstance(options:[String:AnyObject]) -> CentralManager {
self.instance = self.instance ?? CentralManager(options:options)
return self.instance
}
public var isScanning : Bool {
return self.impl.isScanning
}
// scanning
public func startScanning(capacity:Int? = nil) -> FutureStream<Peripheral> {
return self.impl.startScanning(self, capacity:capacity)
}
public func startScanningForServiceUUIDs(uuids:[CBUUID]!, capacity:Int? = nil) -> FutureStream<Peripheral> {
return self.impl.startScanningForServiceUUIDs(self, uuids:uuids, capacity:capacity)
}
public func stopScanning() {
self.impl.stopScanning(self)
}
public func removeAllPeripherals() {
self.discoveredPeripherals.removeAll(keepCapacity:false)
}
// connection
public func disconnectAllPeripherals() {
self.impl.disconnectAllPeripherals(self)
}
public func connectPeripheral(peripheral:Peripheral, options:[String:AnyObject]?=nil) {
Logger.debug()
self.cbCentralManager.connectPeripheral(peripheral.cbPeripheral, options:options)
}
internal func cancelPeripheralConnection(peripheral:Peripheral) {
Logger.debug()
self.cbCentralManager.cancelPeripheralConnection(peripheral.cbPeripheral)
}
// power up
public func powerOn() -> Future<Void> {
return self.impl.powerOn(self)
}
public func powerOff() -> Future<Void> {
return self.impl.powerOff(self)
}
// CBCentralManagerDelegate
public func centralManager(_:CBCentralManager, didConnectPeripheral peripheral:CBPeripheral) {
Logger.debug("peripheral name \(peripheral.name)")
if let bcPeripheral = self.discoveredPeripherals[peripheral] {
bcPeripheral.didConnectPeripheral()
}
}
public func centralManager(_:CBCentralManager, didDisconnectPeripheral peripheral:CBPeripheral, error:NSError?) {
Logger.debug("peripheral name \(peripheral.name)")
if let bcPeripheral = self.discoveredPeripherals[peripheral] {
bcPeripheral.didDisconnectPeripheral()
}
}
public func centralManager(_:CBCentralManager, didDiscoverPeripheral peripheral:CBPeripheral, advertisementData:[String:AnyObject], RSSI:NSNumber) {
if self.discoveredPeripherals[peripheral] == nil {
let bcPeripheral = Peripheral(cbPeripheral:peripheral, advertisements:self.unpackAdvertisements(advertisementData), rssi:RSSI.integerValue)
Logger.debug("peripheral name \(bcPeripheral.name)")
self.discoveredPeripherals[peripheral] = bcPeripheral
self.impl.didDiscoverPeripheral(bcPeripheral)
}
}
public func centralManager(_:CBCentralManager, didFailToConnectPeripheral peripheral:CBPeripheral, error:NSError?) {
Logger.debug()
if let bcPeripheral = self.discoveredPeripherals[peripheral] {
bcPeripheral.didFailToConnectPeripheral(error)
}
}
public func centralManager(_:CBCentralManager!, didRetrieveConnectedPeripherals peripherals:[AnyObject]!) {
Logger.debug()
}
public func centralManager(_:CBCentralManager!, didRetrievePeripherals peripherals:[AnyObject]!) {
Logger.debug()
}
// central manager state
public func centralManager(_:CBCentralManager, willRestoreState dict:[String:AnyObject]) {
Logger.debug()
}
public func centralManagerDidUpdateState(_:CBCentralManager) {
self.impl.didUpdateState(self)
}
private override init() {
super.init()
self.cbCentralManager = CBCentralManager(delegate:self, queue:CentralQueue.queue)
}
private init(options:[String:AnyObject]?) {
super.init()
self.cbCentralManager = CBCentralManager(delegate:self, queue:CentralQueue.queue, options:options)
}
internal func unpackAdvertisements(advertDictionary:[String:AnyObject]) -> [String:String] {
Logger.debug("number of advertisements found \(advertDictionary.count)")
var advertisements = [String:String]()
func addKey(key:String, andValue value:AnyObject) -> () {
if value is NSString {
advertisements[key] = (value as? String)
} else {
advertisements[key] = value.stringValue
}
Logger.debug("advertisement key=\(key), value=\(advertisements[key])")
}
for key in advertDictionary.keys {
if let value : AnyObject = advertDictionary[key] {
if value is NSArray {
for valueItem : AnyObject in (value as! NSArray) {
addKey(key, andValue:valueItem)
}
} else {
addKey(key, andValue:value)
}
}
}
return advertisements
}
}
| mit |
artemkalinovsky/PhotoMemories | PhotoMemories/ViewControllers/MomentsViewController/MyPhotoMemoriesViewController+UIImagePicker.swift | 1 | 2841 | //
// Created by Artem Kalinovsky on 2/9/15.
// Copyright (c) 2015 Artem Kalinovsky. All rights reserved.
//
import UIKit
import MobileCoreServices
import PKHUD
extension MyPhotoMemoriesViewController: UIImagePickerControllerDelegate {
// MARK: - UIImagePickerDelegate
func pickPhotoFromSource(soureName: String) {
switch soureName {
case "Photo Library":
self.imagePickerController.sourceType = .PhotoLibrary
case "Camera":
if CameraUtilities.isCameraAvailable() && CameraUtilities.doesCameraSupportTakingPhotos() {
self.imagePickerController.sourceType = .Camera
} else {
self.showAlert()
return
}
default:
break
}
self.imagePickerController.mediaTypes = [kUTTypeImage as NSString as String]
self.imagePickerController.allowsEditing = true
dispatch_async(dispatch_get_main_queue()) {
self.imagePickerController.delegate = self
self.presentViewController(self.imagePickerController, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String:AnyObject]) {
self.dismissViewControllerAnimated(true, completion: {
() -> Void in
})
self.selectedPhotoMemory = PhotoMemory()
if self.imagePickerController.sourceType == .Camera {
self.selectedPhotoMemory!.address = self.myCurrentAddress
}
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let tmpImagePath = self.selectedPhotoMemory!.photoPath!
FileSystemUtilities.copySelectedImage(image, imagePath: self.selectedPhotoMemory!.photoPath!)
HUD.show(.Progress)
PhotoMemoriesFirebaseController.sharedInstance.postNewPhotoMemory(selectedPhotoMemory!) { [unowned self] success in
if success {
HUD.flash(.Success, delay: 1.0)
FileSystemUtilities.removeImageAtPath(tmpImagePath)
self.performSegueWithIdentifier("ShowPhotoMemoryDetails", sender: nil)
} else {
HUD.flash(.Error, delay: 1.0)
}
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("Picker was cancelled")
picker.dismissViewControllerAnimated(true, completion: nil)
}
func showAlert() {
let createAccountErrorAlert: UIAlertView = UIAlertView()
createAccountErrorAlert.delegate = self
createAccountErrorAlert.title = "Information"
createAccountErrorAlert.message = "Camera Unavailable."
createAccountErrorAlert.addButtonWithTitle("OK")
createAccountErrorAlert.show()
}
} | gpl-2.0 |
hermantai/samples | ios/SwiftUI-Cookbook-2nd-Edition/Chapter03-Advanced-Components/06-Creating-Widgets/StartingPoint/TodoList/TodoList/ContentView.swift | 2 | 334 | //
// ContentView.swift
// TodoList
//
// Created by Edgar Nzokwe on 8/15/21.
//
import SwiftUI
struct ContentView: View {
@State var t = tasks
var body: some View {
TaskListView(tasks: $t)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| apache-2.0 |
takuran/CoreAnimationLesson | CoreAnimationLesson/Lesson2_2ConfigurationView.swift | 1 | 9698 | //
// Lesson2_1ConfigurationView.swift
// CoreAnimationLesson
//
// Created by Naoyuki Takura on 2016/04/23.
// Copyright © 2016年 Naoyuki Takura. All rights reserved.
//
import UIKit
class Lesson2_2ConfigurationView: UIView, UIGestureRecognizerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
// duration
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var durationSlider: UISlider!
// delay
@IBOutlet weak var delayLabel: UILabel!
@IBOutlet weak var delaySlider: UISlider!
// option
@IBOutlet weak var optionPicker: UIPickerView!
// struct UIViewAnimationOptions : OptionSetType {
// init(rawValue rawValue: UInt)
// static var LayoutSubviews: UIViewAnimationOptions { get }
// static var AllowUserInteraction: UIViewAnimationOptions { get }
// static var BeginFromCurrentState: UIViewAnimationOptions { get }
// static var Repeat: UIViewAnimationOptions { get }
// static var Autoreverse: UIViewAnimationOptions { get }
// static var OverrideInheritedDuration: UIViewAnimationOptions { get }
// static var OverrideInheritedCurve: UIViewAnimationOptions { get }
// static var AllowAnimatedContent: UIViewAnimationOptions { get }
// static var ShowHideTransitionViews: UIViewAnimationOptions { get }
// static var OverrideInheritedOptions: UIViewAnimationOptions { get }
//
// static var CurveEaseInOut: UIViewAnimationOptions { get }
// static var CurveEaseIn: UIViewAnimationOptions { get }
// static var CurveEaseOut: UIViewAnimationOptions { get }
// static var CurveLinear: UIViewAnimationOptions { get }
//
// static var TransitionNone: UIViewAnimationOptions { get }
// static var TransitionFlipFromLeft: UIViewAnimationOptions { get }
// static var TransitionFlipFromRight: UIViewAnimationOptions { get }
// static var TransitionCurlUp: UIViewAnimationOptions { get }
// static var TransitionCurlDown: UIViewAnimationOptions { get }
// static var TransitionCrossDissolve: UIViewAnimationOptions { get }
// static var TransitionFlipFromTop: UIViewAnimationOptions { get }
// static var TransitionFlipFromBottom: UIViewAnimationOptions { get }
// }
enum AnimationOptions {
case Curve(String, UIViewAnimationOptions)
case Transition(String, UIViewAnimationOptions)
case Other(String, UIViewAnimationOptions?)
}
// options
let animationOptions:[[AnimationOptions]] = [
// for curve
[
.Curve("CurveLinear", .CurveLinear) ,
.Curve("CurveEaseInOut", .CurveEaseInOut),
.Curve("CurveEaseIn", .CurveEaseIn),
.Curve("CurveEaseOut", .CurveEaseOut)
],
// for transition
// not implements
// for others
[
.Other("not specify", nil),
.Other("LayoutSubviews", .LayoutSubviews),
.Other("AllowUserInteraction", .AllowUserInteraction),
.Other("BeginFromCurrentState", .BeginFromCurrentState),
.Other("Repeat", .Repeat),
.Other("Autoreverse", .Autoreverse),
.Other("OverrideInheritedDuration", .OverrideInheritedDuration),
.Other("OverrideInheritedCurve", .OverrideInheritedCurve),
.Other("AllowAnimatedContent", .AllowAnimatedContent),
.Other("ShowHideTransitionViews", .ShowHideTransitionViews),
.Other("OverrideInheritedOptions", .OverrideInheritedOptions)
]
]
var animationOption: UIViewAnimationOptions = .CurveLinear
private var optionCurve: UIViewAnimationOptions? = .CurveLinear
private var optionOther: UIViewAnimationOptions?
// overlay
var overlay: UIView = UIView()
// tap gesture
var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer()
// display contidion
enum Condition {
case Hide
case Show
case Processing
}
// condition my view
var condition: Condition = .Show
// initialize view
override func awakeFromNib() {
// duration
durationLabel.text = "0.5"
durationSlider.addTarget(self, action: #selector(Lesson2_2ConfigurationView.valueChangedDurationSlider), forControlEvents: UIControlEvents.ValueChanged)
// delay
delayLabel.text = "0.0"
delaySlider.addTarget(self, action: #selector(Lesson2_2ConfigurationView.valueChangedDelaySlider), forControlEvents: UIControlEvents.ValueChanged)
// options
optionPicker.delegate = self
optionPicker.dataSource = self
}
// duration slider event handler
func valueChangedDurationSlider(sender: AnyObject?) {
guard let slider = sender as? UISlider else {
return
}
var durationValue = slider.value
durationValue = durationValue * 100
durationValue = roundf(durationValue) / 100
durationLabel.text = String(durationValue)
}
// delay slider event handler
func valueChangedDelaySlider(sender: AnyObject?) {
guard let slider = sender as? UISlider else {
return
}
var delay = slider.value
delay = delay * 100
delay = roundf(delay) / 100
delayLabel.text = String(delay)
}
// hide configuration view
func hide() {
guard condition == .Show else {
return
}
// condition to processing
condition = .Processing
// origin of x
let originX = frame.origin.x
// width for sliding to right
let slideWidth = frame.width
// move to right with animationg
UIView.animateWithDuration(0.3, animations: {
//
self.frame.origin.x = originX + slideWidth
self.overlay.alpha = 0.0
}) { (complete) in
//
self.condition = .Hide
// remove overlay
self.overlay.removeFromSuperview()
// remove gesture
self.overlay.removeGestureRecognizer(self.tapGesture)
}
}
// show configuration view
func show() {
guard condition == .Hide else {
return
}
// condition to processing
condition = .Processing
// show overlay
if let superView = self.superview {
overlay.frame = superView.frame
overlay.backgroundColor = UIColor.grayColor()
overlay.alpha = 0.0
overlay.opaque = false
// add to superview
// superView.addSubview(overlay)
superView.insertSubview(overlay, atIndex: 1)
// gesture
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
tapGesture.addTarget(self, action:#selector(Lesson2_2ConfigurationView.hide))
overlay.addGestureRecognizer(tapGesture)
}
// origin of x
let originX = frame.origin.x
// width for sliding to left
let slideWidth = frame.width
// move to left with animating
UIView.animateWithDuration(0.3, animations: {
//
self.frame.origin.x = originX - slideWidth
self.overlay.alpha = 0.7
}) { (complete) in
//
self.condition = .Show
}
}
// MARK: - UIPickerViewDelegate implements
// not in use now.
// func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
// //
// switch component {
// case 0:
// // curve option
// return curveOptions[row]
//
// case 1:
// // other options
// return otherOptions[row]
//
// default:
// // other case
// return ""
// }
//
// }
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
// change font size
let label = UILabel()
label.font = UIFont(name: "Arial", size: 11.0)
let option = animationOptions[component][row]
switch option {
case let .Curve(name, _):
label.text = name
case let .Other(name, _):
label.text = name
default:
label.text = ""
// nothing. to do
}
return label
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//
let option = animationOptions[component][row]
switch option {
case let .Curve(_, option):
optionCurve = option
case let .Other(_, option):
optionOther = option
default:
// nothing. to do
break
}
if optionOther != nil {
animationOption = [optionCurve!, optionOther!]
} else {
animationOption = optionCurve!
}
}
// MARK: - UIPickerViewDataSource implements
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
//
return 2
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// UIViewAnimationOptions
return animationOptions[component].count
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/00153-swift-parser-parsetypesimple.swift | 1 | 479 | // 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 i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01383-swift-clangmoduleunit-getimportedmodules.swift | 1 | 519 | // 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
import CoreData
let d>(g> [0.E == c()
}
let c {
protocol A {
func f<D> {
enum b in return "
class B {
}
typealias B : B,
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/01441-swift-constraints-constraintgraph-removeconstraint.swift | 1 | 470 | // 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 g<l : a {
return """
}
}
class A {
protocol b {
typealias B : B, A
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/00731-swift-typebase-isequal.swift | 1 | 481 | // 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 f<T>Bool)
func f: String {
f = {
self.a(n: NSObject {
}
}
}
import Foundation
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/27107-swift-typeloc-iserror.swift | 4 | 258 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{enum S<T where B:d{enum T{
let a=f
var f:
| apache-2.0 |
nextcloud/ios | iOSClient/Share/NCShareUserCell.swift | 1 | 7442 | //
// NCShareUserCell.swift
// Nextcloud
//
// Created by Henrik Storch on 15.11.2021.
// Copyright © 2021 Henrik Storch. All rights reserved.
//
// Author Henrik Storch <henrik.storch@nextcloud.com>
//
// 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, either version 3 of the License, or
// (at your option) any later version.
//
// 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 UIKit
import DropDown
import NextcloudKit
class NCShareUserCell: UITableViewCell, NCCellProtocol {
@IBOutlet weak var imageItem: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var buttonMenu: UIButton!
@IBOutlet weak var imageStatus: UIImageView!
@IBOutlet weak var status: UILabel!
@IBOutlet weak var btnQuickStatus: UIButton!
@IBOutlet weak var labelQuickStatus: UILabel!
@IBOutlet weak var imageDownArrow: UIImageView!
var tableShare: tableShare?
weak var delegate: NCShareUserCellDelegate?
var fileAvatarImageView: UIImageView? {
return imageItem
}
var fileUser: String? {
get { return tableShare?.shareWith }
set {}
}
func setupCellUI(userId: String) {
guard let tableShare = tableShare else {
return
}
self.accessibilityCustomActions = [UIAccessibilityCustomAction(
name: NSLocalizedString("_show_profile_", comment: ""),
target: self,
selector: #selector(tapAvatarImage))]
labelTitle.text = tableShare.shareWithDisplayname
labelTitle.textColor = .label
isUserInteractionEnabled = true
labelQuickStatus.isHidden = false
imageDownArrow.isHidden = false
buttonMenu.isHidden = false
buttonMenu.accessibilityLabel = NSLocalizedString("_more_", comment: "")
imageItem.image = NCShareCommon.shared.getImageShareType(shareType: tableShare.shareType)
let status = NCUtility.shared.getUserStatus(userIcon: tableShare.userIcon, userStatus: tableShare.userStatus, userMessage: tableShare.userMessage)
imageStatus.image = status.onlineStatus
self.status.text = status.statusMessage
// If the initiator or the recipient is not the current user, show the list of sharees without any options to edit it.
if tableShare.uidOwner != userId && tableShare.uidFileOwner != userId {
isUserInteractionEnabled = false
labelQuickStatus.isHidden = true
imageDownArrow.isHidden = true
buttonMenu.isHidden = true
}
btnQuickStatus.accessibilityHint = NSLocalizedString("_user_sharee_footer_", comment: "")
btnQuickStatus.setTitle("", for: .normal)
btnQuickStatus.contentHorizontalAlignment = .left
if tableShare.permissions == NCGlobal.shared.permissionCreateShare {
labelQuickStatus.text = NSLocalizedString("_share_file_drop_", comment: "")
} else {
// Read Only
if CCUtility.isAnyPermission(toEdit: tableShare.permissions) {
labelQuickStatus.text = NSLocalizedString("_share_editing_", comment: "")
} else {
labelQuickStatus.text = NSLocalizedString("_share_read_only_", comment: "")
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapAvatarImage))
imageItem?.addGestureRecognizer(tapGesture)
buttonMenu.setImage(UIImage(named: "shareMenu")?.image(color: .gray, size: 50), for: .normal)
labelQuickStatus.textColor = NCBrandColor.shared.customer
imageDownArrow.image = NCUtility.shared.loadImage(named: "arrowtriangle.down.fill", color: NCBrandColor.shared.customer)
}
@objc func tapAvatarImage(_ sender: UITapGestureRecognizer) {
delegate?.showProfile(with: tableShare, sender: sender)
}
@IBAction func touchUpInsideMenu(_ sender: Any) {
delegate?.tapMenu(with: tableShare, sender: sender)
}
@IBAction func quickStatusClicked(_ sender: Any) {
delegate?.quickStatus(with: tableShare, sender: sender)
}
}
protocol NCShareUserCellDelegate: AnyObject {
func tapMenu(with tableShare: tableShare?, sender: Any)
func showProfile(with tableComment: tableShare?, sender: Any)
func quickStatus(with tableShare: tableShare?, sender: Any)
}
// MARK: - NCSearchUserDropDownCell
class NCSearchUserDropDownCell: DropDownCell, NCCellProtocol {
@IBOutlet weak var imageItem: UIImageView!
@IBOutlet weak var imageStatus: UIImageView!
@IBOutlet weak var status: UILabel!
@IBOutlet weak var imageShareeType: UIImageView!
@IBOutlet weak var centerTitle: NSLayoutConstraint!
private var user: String = ""
var fileAvatarImageView: UIImageView? {
return imageItem
}
var fileUser: String? {
get { return user }
set { user = newValue ?? "" }
}
func setupCell(sharee: NKSharee, baseUrl: NCUserBaseUrl) {
imageItem.image = NCShareCommon.shared.getImageShareType(shareType: sharee.shareType)
imageShareeType.image = NCShareCommon.shared.getImageShareType(shareType: sharee.shareType)
let status = NCUtility.shared.getUserStatus(userIcon: sharee.userIcon, userStatus: sharee.userStatus, userMessage: sharee.userMessage)
imageStatus.image = status.onlineStatus
self.status.text = status.statusMessage
if self.status.text?.count ?? 0 > 0 {
centerTitle.constant = -5
} else {
centerTitle.constant = 0
}
imageItem.image = NCUtility.shared.loadUserImage(
for: sharee.shareWith,
displayName: nil,
userBaseUrl: baseUrl)
let fileName = baseUrl.userBaseUrl + "-" + sharee.shareWith + ".png"
if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil {
let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
NextcloudKit.shared.downloadAvatar(
user: sharee.shareWith,
fileNameLocalPath: fileNameLocalPath,
sizeImage: NCGlobal.shared.avatarSize,
avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
etag: etag) { _, imageAvatar, _, etag, error in
if error == .success, let etag = etag, let imageAvatar = imageAvatar {
NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
self.imageItem.image = imageAvatar
} else if error.errorCode == NCGlobal.shared.errorNotModified, let imageAvatar = NCManageDatabase.shared.setAvatarLoaded(fileName: fileName) {
self.imageItem.image = imageAvatar
}
}
}
}
}
| gpl-3.0 |
TheDarkCode/Example-Swift-Apps | Playgrounds/Polymorphism.playground/Contents.swift | 1 | 1337 | //: Playground - noun: a place where people can play
import UIKit
// Base Class
class Shape {
var area: Double?
func calculateArea() {
// calc
}
func printArea() {
print("The area is: \(area)")
}
}
class Rectangle: Shape {
var width = 1.0
var height = 1.0
init(width: Double, height: Double) {
self.width = width
self.height = height
}
override func calculateArea() {
area = width * height
}
}
class Circle: Shape {
var radius = 1.0
init(radius: Double) {
self.radius = radius
}
override func calculateArea() {
area = 3.14 * radius * radius
}
}
var circle = Circle(radius: 5.0)
var rectangle = Rectangle(width: 20, height: 5)
circle.calculateArea()
rectangle.calculateArea()
print(circle.area)
print(rectangle.area)
class Enemy {
var hp = 100
var attackPower = 10
init(hp: Int, attack: Int) {
self.hp = hp
self.attackPower = attack
}
func defendAttack(incAttPwr: Int) {
hp -= incAttPwr
}
}
class AngryTroll: Enemy {
var immunity = 10
override func defendAttack(incAttPwr: Int) {
if incAttPwr <= immunity {
hp++
} else {
super.defendAttack(incAttPwr)
}
}
} | mit |
MaddTheSane/SwiftXPC | SwiftXPC/Transport/Service.swift | 1 | 1548 | //
// Service.swift
// DOS Prompt
//
// Created by William Kent on 7/28/14.
// Copyright (c) 2014 William Kent. All rights reserved.
//
import Foundation
import XPC
public final class XPCService {
@noreturn public class func run(handler: (XPCConnection) -> ()) {
XPCShimMain {
ptr in
handler(XPCConnection(nativePointer: ptr))
}
}
/// `beginTransaction()` and `endTransaction()` can be used as a "keep-alive" mechanism
/// to avoid the runtime killing an XPC service while it is performing background work.
/// You must make sure that you remember to call `endTransaction()`, as otherwise the
/// XPC service will *never* die. Note that you can use `performTransaction()` to ensure that
/// `endTransaction()` is called automatically.
public class func beginTransaction() {
xpc_transaction_begin()
}
/// `beginTransaction()` and `endTransaction()` can be used as a "keep-alive" mechanism
/// to avoid the runtime killing an XPC service while it is performing background work.
/// You must make sure that you remember to call `endTransaction()`, as otherwise the
/// XPC service will *never* die. Note that you can use `performTransaction()` to ensure that
/// `endTransaction()` is called automatically.
public class func endTransaction() {
xpc_transaction_end()
}
public class func performTransaction(callback: () -> ()) {
beginTransaction()
callback()
endTransaction()
}
}
| mit |
CallMeMrAlex/DYTV | DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Home(首页)/ViewModel/AmuseViewModel.swift | 1 | 457 | //
// AmuseViewModel.swift
// DYTV-AlexanderZ-Swift
//
// Created by Alexander Zou on 2016/10/17.
// Copyright © 2016年 Alexander Zou. All rights reserved.
//
import UIKit
class AmuseViewModel : BaseViewModel {
}
extension AmuseViewModel {
func loadAmuseData(finishedCallback : @escaping () -> ()) {
loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotRoom/2", finishedCallback: finishedCallback)
}
}
| mit |
Aazure/Mr-Ride-iOS | Mr-Ride-iOS/Mr-Ride-iOS/Model/BikeYouBikeModel.swift | 1 | 349 | //
// BikeYouBikeModel.swift
// Mr-Ride-iOS
//
// Created by Allegretto on 2016/6/24.
// Copyright © 2016年 AppWorks School Jocy Hsiao. All rights reserved.
//
import CoreLocation
struct BikeYouBikeModel{
let name: String
let area: String
let availableYB: Int
let coordinate: CLLocationCoordinate2D
let address: String
}
| mit |
mzp/OctoEye | Sources/OctoEye/DataSource/SearchRepositoriesDataSource.swift | 1 | 1966 | //
// SearchRepositoriesDataSource.swift
// OctoEye
//
// Created by mzp on 2017/08/11.
// Copyright © 2017 mzp. All rights reserved.
//
import Ikemen
import ReactiveSwift
import Result
internal class SearchRepositoriesDataSource: NSObject, PagingDataSource {
let reactive: Signal<PagingEvent, AnyError>
private let repositories: PagingRepositories = PagingRepositories()
private let queryObserver: Signal<String, AnyError>.Observer
init(github: GithubClient) {
self.reactive = repositories.eventSignal
let (querySignal, queryObserver) = Signal<String, AnyError>.pipe()
self.queryObserver = queryObserver
super.init()
let searchRepositories = SearchRepositories(github: github)
repositories.observe(signal:
Signal.combineLatest(
querySignal.throttle(0.5, on: QueueScheduler.main).on(event: { _ in
self.repositories.clear()
}),
repositories.cursor
)) { (query, cursor) in
searchRepositories.call(query: query, after: cursor)
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repositories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell(style: .default, reuseIdentifier: nil) ※ {
let repository = repositories[indexPath.row]
$0.textLabel?.text = "\(repository.owner.login)/\(repository.name)"
}
}
// MARK: - paging
func invokePaging() {
repositories.invokePaging()
}
func search(query: String) {
queryObserver.send(value: query)
}
subscript(index: Int) -> RepositoryObject {
return repositories[index]
}
}
| mit |
tkremenek/swift | test/Generics/canonicalization.swift | 5 | 640 | // RUN: %target-typecheck-verify-swift
// rdar://problem/23149063
protocol P0 { }
protocol P {
associatedtype A
}
protocol Q : P {
associatedtype A
}
func f<T>(t: T) where T : P, T : Q, T.A : P0 { } // expected-note{{'f(t:)' previously declared here}}
// expected-warning@-1{{redundant conformance constraint 'T' : 'P'}}
// expected-note@-2{{conformance constraint 'T' : 'P' implied here}}
func f<T>(t: T) where T : Q, T : P, T.A : P0 { } // expected-error{{invalid redeclaration of 'f(t:)'}}
// expected-warning@-1{{redundant conformance constraint 'T' : 'P'}}
// expected-note@-2{{conformance constraint 'T' : 'P' implied here}}
| apache-2.0 |
StevenMasini/Maskarade | Example/Maskarade/Demos/ImageMaskViewController.swift | 1 | 382 | //
// ImageMaskViewController.swift
// Maskarade
//
// Created by Steven Masini on 02/05/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import Maskarade
@IBDesignable class ImageMaskViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Image Mask"
}
}
| mit |
TouchInstinct/LeadKit | TISwiftUICore/Sources/Presenter/SwiftUIPresenter.swift | 1 | 1384 | //
// Copyright (c) 2022 Touch Instinct
//
// 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 SwiftUI
import Combine
@MainActor
@available(iOS 13.0, *)
public protocol SwiftUIPresenter: ObservableObject {
associatedtype View: SwiftUI.View
func createView() -> View
#if DEBUG
static func assembleForPreview() -> Self
#endif
}
| apache-2.0 |
morpheby/aTarantula | Plugins/ATARCrawlExampleWebsite/ATARCrawlExampleWebsite/core-data/DrugCategory+CoreDataClass.swift | 1 | 257 | //
// DrugCategory+CoreDataClass.swift
// ATARCrawlExampleWebsite
//
// Created by Ilya Mikhaltsou on 9/18/17.
// Copyright © 2017 morpheby. All rights reserved.
//
//
import Foundation
import CoreData
@objc
public class DrugCategory: Crawlable {
}
| gpl-3.0 |
WEIHOME/SimpleDraw-Swift | TryDraw/UIViewForDraw.swift | 1 | 812 | //
// UIViewForDraw.swift
// TryDraw
//
// Created by Weihong Chen on 06/02/2015.
// Copyright (c) 2015 Weihong. All rights reserved.
//
import UIKit
class UIViewForDraw: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let path = UIBezierPath()
path.lineWidth = 2.0
path.moveToPoint(CGPoint(x: 100,y: 200))
path.addLineToPoint(CGPoint(x: 150, y: 300))
path.addLineToPoint(CGPoint(x: 50, y: 300))
path.closePath()
UIColor.blackColor().setStroke()
UIColor.greenColor().setFill()
path.fill()
}
}
| mit |
pinterest/tulsi | src/Tulsi/UISelectableOutlineViewNode.swift | 1 | 3247 | // Copyright 2016 The Tulsi 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 Cocoa
protocol Selectable: class {
var selected: Bool { get set }
}
/// Models a UIRuleEntry as a node suitable for an outline view controller.
class UISelectableOutlineViewNode: NSObject {
/// The display name for this node.
@objc let name: String
/// The object contained by this node (only valid for leaf nodes).
var entry: Selectable? {
didSet {
if let entry = entry {
state = entry.selected ? NSControl.StateValue.on.rawValue : NSControl.StateValue.off.rawValue
}
}
}
/// This node's children.
@objc var children: [UISelectableOutlineViewNode] {
return _children
}
private var _children = [UISelectableOutlineViewNode]()
/// This node's parent.
weak var parent: UISelectableOutlineViewNode?
/// This node's checkbox state in the UI (NSOnState/NSOffState/NSMixedState)
@objc dynamic var state: Int {
get {
if children.isEmpty {
return (entry?.selected ?? false) ? NSControl.StateValue.on.rawValue : NSControl.StateValue.off.rawValue
}
var stateIsValid = false
var state = NSControl.StateValue.off
for node in children {
if !stateIsValid {
state = NSControl.StateValue(rawValue: node.state)
stateIsValid = true
continue
}
if state.rawValue != node.state {
return NSControl.StateValue.mixed.rawValue
}
}
return state.rawValue
}
set {
let newSelectionState = (newValue == NSControl.StateValue.on.rawValue)
let selected = entry?.selected
if selected == newSelectionState {
return
}
willChangeValue(forKey: "state")
if let entry = entry {
entry.selected = newSelectionState
}
for node in children {
node.state = newValue
}
didChangeValue(forKey: "state")
// Notify KVO that this node's ancestors have also changed state.
var ancestor = parent
while ancestor != nil {
ancestor!.willChangeValue(forKey: "state")
ancestor!.didChangeValue(forKey: "state")
ancestor = ancestor!.parent
}
}
}
init(name: String) {
self.name = name
super.init()
}
func addChild(_ child: UISelectableOutlineViewNode) {
_children.append(child)
child.parent = self
}
@objc func validateState(_ ioValue: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
if let value = ioValue.pointee as? NSNumber {
if value.intValue == NSControl.StateValue.mixed.rawValue {
ioValue.pointee = NSNumber(value: NSControl.StateValue.on.rawValue as Int)
}
}
}
}
| apache-2.0 |
jkolb/Shkadov | Shkadov/main.swift | 1 | 1275 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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.
*/
macOSBootstrap(
factory: { (engine, loggerFactory) in
return LotsOfCubes(engine: engine, logger: loggerFactory.makeLogger())
}
).makeEngine().startup()
| mit |
qualaroo/QualarooSDKiOS | Qualaroo/Model/UserInfo/CustomProperties.swift | 1 | 692 | //
// CustomProperties.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
struct CustomProperties {
var dictionary: [String: String]
init(_ dictionary: [String: String]) {
self.dictionary = dictionary
}
func checkForMissing(withKeywords keywords: [String]) -> [String] {
var missingProperties = [String]()
for keyword in keywords {
if !dictionary.keys.contains(keyword) {
missingProperties.append(keyword)
}
}
return missingProperties
}
}
| mit |
arsonik/OrangeTv | OrangeTv/ViewController.swift | 1 | 656 | //
// ViewController.swift
// OrangeTv
//
// Created by Florian Morello on 06/11/14.
// Copyright (c) 2014 Florian Morello. 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.
let device = OrangeTv(host: "192.168.0.200")
device.tv()
device.sendCommand(OrangeTv.Command.ChannelUp) // Channel Up
device.setChannel(152) // Go to channel 152
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
ThunderAnimal/BBPhobia_ios | BBPhobia/HistoriePresenter.swift | 1 | 298 | //
// HistoriePresenter.swift
// BBPhobia
//
// Created by Martin Weber on 25/03/2017.
// Copyright © 2017 Martin Weber. All rights reserved.
//
import Foundation
class HistoriePresenter{
private let view: HistorieView!
init(view: HistorieView){
self.view = view
}
}
| apache-2.0 |
ykyouhei/KYWheelTabController | Example/AppDelegate.swift | 1 | 2206 | //
// AppDelegate.swift
// Example
//
// Created by kyo__hei on 2016/02/21.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import UIKit
import KYWheelTabController
@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 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 |
WeltN24/Carlos | Tests/CarlosTests/Fakes/CacheLevelFake.swift | 1 | 1744 | import Foundation
import Carlos
import Combine
class CacheLevelFake<A: Hashable, B>: CacheLevel {
typealias KeyType = A
typealias OutputType = B
init() {}
// MARK: Get
var numberOfTimesCalledGet = 0
var didGetKey: KeyType?
var getSubject: PassthroughSubject<OutputType, Error>?
var getPublishers: [KeyType: PassthroughSubject<OutputType, Error>] = [:]
func get(_ key: KeyType) -> AnyPublisher<OutputType, Error> {
numberOfTimesCalledGet += 1
didGetKey = key
if let getSubject = getSubject {
return getSubject.eraseToAnyPublisher()
}
if let subject = getPublishers[key] {
return subject.eraseToAnyPublisher()
}
let newSubject = PassthroughSubject<OutputType, Error>()
getPublishers[key] = newSubject
return newSubject.eraseToAnyPublisher()
}
// MARK: Set
var numberOfTimesCalledSet = 0
var didSetValue: OutputType?
var didSetKey: KeyType?
var setSubject: PassthroughSubject<Void, Error>?
var setPublishers: [KeyType: PassthroughSubject<Void, Error>] = [:]
func set(_ value: OutputType, forKey key: KeyType) -> AnyPublisher<Void, Error> {
numberOfTimesCalledSet += 1
didSetKey = key
didSetValue = value
if let setSubject = setSubject {
return setSubject.eraseToAnyPublisher()
}
if let subject = setPublishers[key] {
return subject.eraseToAnyPublisher()
}
let newSubject = PassthroughSubject<Void, Error>()
setPublishers[key] = newSubject
return newSubject.eraseToAnyPublisher()
}
var numberOfTimesCalledClear = 0
func clear() {
numberOfTimesCalledClear += 1
}
var numberOfTimesCalledOnMemoryWarning = 0
func onMemoryWarning() {
numberOfTimesCalledOnMemoryWarning += 1
}
}
| mit |
kyouko-taiga/anzen | Sources/AST/Constraint.swift | 1 | 4049 | import Utils
public enum ConstraintKind: Int {
/// An equality constraint `T ~= U` that requires `T` to match `U`.
case equality = 10
/// A conformance constraint `T <= U` that requires `T` to be identical to or conforming `U`.
///
/// If the types aren't, there are two ways `T` can still conform to `U`.
/// * `T` is a nominal type that implements or extends an interface `U`.
/// * `T` and `U` are function whose domains and codomains conform to each other. For instance if
/// `T = (l0: A0, ..., tn: An) -> B` and `U = (l0: C0, ..., Cn) -> D`, then `T <= U` holds if
/// `Ai <= Ci` and `B <= D`.
case conformance = 8
/// A construction constraint `T <+ U` requires `U` to be the metatype of a nominal type, and `T`
/// to be a constructor of said type.
case construction = 6
/// A member constraint `T[.name] ~= U` that requires `T` to have a member `name` whose type
/// matches `U`.
case member = 4
/// A disjunction of constraints
case disjunction = 0
}
public struct Constraint {
public init(
kind: ConstraintKind,
types: (t: TypeBase, u: TypeBase)? = nil,
member: String? = nil,
choices: [Constraint] = [],
location: ConstraintLocation)
{
self.kind = kind
self.types = types
self.member = member
self.choices = choices
self.location = location
}
/// Creates an equality constraint.
public static func equality(t: TypeBase, u: TypeBase, at location: ConstraintLocation)
-> Constraint
{
return Constraint(kind: .equality, types: (t, u), location: location)
}
/// Creates a conformance constraint.
public static func conformance(t: TypeBase, u: TypeBase, at location: ConstraintLocation)
-> Constraint
{
return Constraint(kind: .conformance, types: (t, u), location: location)
}
/// Creates a member constraint.
public static func member(
t: TypeBase,
member: String,
u: TypeBase,
at location: ConstraintLocation) -> Constraint
{
return Constraint(kind: .member, types: (t, u), member: member, location: location)
}
/// Creates a construction constraint.
public static func construction(t: TypeBase, u: TypeBase, at location: ConstraintLocation)
-> Constraint
{
return Constraint(kind: .construction, types: (t, u), location: location)
}
/// Creates a disjunction constraint.
public static func disjunction(_ choices: [Constraint], at location: ConstraintLocation)
-> Constraint
{
return Constraint(kind: .disjunction, choices: choices, location: location)
}
/// The kind of the constraint.
public let kind: ConstraintKind
/// The location of the constraint.
public let location: ConstraintLocation
/// The types `T` and `U` of a match-relation constraint.
public let types: (t: TypeBase, u: TypeBase)?
/// The name in `T[.name]` of a member constraint.
public let member: String?
/// The choices of a disjunction constraint.
public let choices: [Constraint]
public static func < (lhs: Constraint, rhs: Constraint) -> Bool {
return lhs.kind.rawValue < rhs.kind.rawValue
}
}
extension Constraint: CustomStringConvertible {
public var description: String {
var buffer = ""
dump(to: &buffer)
return buffer
}
public func dump<OutputStream>(to outputStream: inout OutputStream, level: Int = 0)
where OutputStream: TextOutputStream
{
let ident = String(repeating: " ", count: level * 2)
outputStream.write(ident + location.anchor.range.start.description.styled("< 6") + ": ")
switch kind {
case .equality:
outputStream.write("\(types!.t) ≡ \(types!.u)\n")
case .conformance:
outputStream.write("\(types!.t) ≤ \(types!.u)\n")
case .member:
outputStream.write("\(types!.t).\(member!) ≡ \(types!.u)\n")
case .construction:
outputStream.write("\(types!.t) <+ \(types!.u)\n")
case .disjunction:
outputStream.write("\n")
for constraint in choices {
constraint.dump(to: &outputStream, level: level + 1)
}
}
}
}
| apache-2.0 |
victor-pavlychko/SwiftyTasks | SwiftyTasksTests/AsyncTaskTests.swift | 1 | 5060 | //
// AsyncTaskTests.swift
// SwiftyTasks
//
// Created by Victor Pavlychko on 9/23/16.
// Copyright © 2016 address.wtf. All rights reserved.
//
import XCTest
@testable import SwiftyTasks
class AsyncTaskTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testSuccess() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(.success(dummyResult))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let result = try task.getResult()
XCTAssertEqual(result, dummyResult)
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testError() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(DemoTaskResult<String>.error(dummyError))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let _ = try task.getResult()
XCTFail()
} catch {
XCTAssertEqual(error as? DemoError, dummyError)
}
}
}
func testSuccessOrError_Success() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(.successOrError(dummyResult, nil))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let result = try task.getResult()
XCTAssertEqual(result, dummyResult)
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testSuccessOrError_Error() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(DemoTaskResult<String>.successOrError(nil, dummyError))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let _ = try task.getResult()
XCTFail()
} catch {
XCTAssertEqual(error as? DemoError, dummyError)
}
}
}
func testOptionalSuccess_Some() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(.optionalSuccess(dummyResult))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let result = try task.getResult()
XCTAssertEqual(result, dummyResult)
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testOptionalSuccess_None() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(DemoTaskResult<String>.optionalSuccess(nil))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let _ = try task.getResult()
XCTFail()
} catch {
XCTAssertEqual(error as? TaskError, TaskError.badResult)
}
}
}
func testResultBlock_Success() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(.resultBlock({ return dummyResult }))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let result = try task.getResult()
XCTAssertEqual(result, dummyResult)
} catch {
XCTFail(error.localizedDescription)
}
}
}
func testResultBlock_Error() {
let xp = expectation(description: "")
let queue = OperationQueue()
let task = DemoAsyncTask(DemoTaskResult<String>.resultBlock({ throw dummyError }))
task.completionBlock = {
xp.fulfill()
}
queue.addOperation(task)
waitForExpectations {
do {
let _ = try task.getResult()
XCTFail()
} catch {
XCTAssertEqual(error as? DemoError, dummyError)
}
}
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Site Management/SiteTagsViewController.swift | 1 | 19367 | import UIKit
import Gridicons
import WordPressShared
final class SiteTagsViewController: UITableViewController {
private struct TableConstants {
static let cellIdentifier = "TitleBadgeDisclosureCell"
static let accesibilityIdentifier = "SiteTagsList"
static let numberOfSections = 1
}
private let blog: Blog
private lazy var noResultsViewController = NoResultsViewController.controller()
private var isSearching = false
fileprivate lazy var context: NSManagedObjectContext = {
return ContextManager.sharedInstance().mainContext
}()
fileprivate lazy var defaultPredicate: NSPredicate = {
return NSPredicate(format: "blog.blogID = %@", blog.dotComID!)
}()
private let sortDescriptors: [NSSortDescriptor] = {
return [NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
}()
fileprivate lazy var resultsController: NSFetchedResultsController<NSFetchRequestResult> = {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostTag")
request.sortDescriptors = self.sortDescriptors
let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
return frc
}()
fileprivate lazy var searchController: UISearchController = {
let returnValue = UISearchController(searchResultsController: nil)
returnValue.hidesNavigationBarDuringPresentation = false
returnValue.obscuresBackgroundDuringPresentation = false
returnValue.searchResultsUpdater = self
returnValue.delegate = self
WPStyleGuide.configureSearchBar(returnValue.searchBar)
return returnValue
}()
private var isPerformingInitialSync = false
@objc
public init(blog: Blog) {
self.blog = blog
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
noResultsViewController.delegate = self
setAccessibilityIdentifier()
applyStyleGuide()
applyTitle()
setupTable()
refreshTags()
refreshResultsController(predicate: defaultPredicate)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchController.searchBar.isHidden = false
refreshNoResultsView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// HACK: Normally, to hide the scroll bars we'd define a presentation context.
// This is impacting layout when navigating back from a detail. As a work
// around we can simply hide the search bar.
if searchController.isActive {
searchController.searchBar.isHidden = true
}
}
private func setAccessibilityIdentifier() {
tableView.accessibilityIdentifier = TableConstants.accesibilityIdentifier
}
private func applyStyleGuide() {
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
}
private func applyTitle() {
title = NSLocalizedString("Tags", comment: "Label for the Tags Section in the Blog Settings")
}
private func setupTable() {
tableView.tableFooterView = UIView(frame: .zero)
let nibName = UINib(nibName: TableConstants.cellIdentifier, bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: TableConstants.cellIdentifier)
setupRefreshControl()
}
private func setupRefreshControl() {
if refreshControl == nil {
refreshControl = UIRefreshControl()
refreshControl?.backgroundColor = .basicBackground
refreshControl?.addTarget(self, action: #selector(refreshTags), for: .valueChanged)
}
}
private func deactivateRefreshControl() {
refreshControl = nil
}
@objc private func refreshResultsController(predicate: NSPredicate) {
resultsController.fetchRequest.predicate = predicate
resultsController.fetchRequest.sortDescriptors = sortDescriptors
do {
try resultsController.performFetch()
tableView.reloadData()
refreshNoResultsView()
} catch {
tagsFailedLoading(error: error)
}
}
@objc private func refreshTags() {
isPerformingInitialSync = true
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
tagsService.syncTags(for: blog, success: { [weak self] tags in
self?.isPerformingInitialSync = false
self?.refreshControl?.endRefreshing()
self?.refreshNoResultsView()
}) { [weak self] error in
self?.tagsFailedLoading(error: error)
}
}
private func showRightBarButton(_ show: Bool) {
if show {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(createTag))
} else {
navigationItem.rightBarButtonItem = nil
}
}
private func setupSearchBar() {
guard tableView.tableHeaderView == nil else {
return
}
tableView.tableHeaderView = searchController.searchBar
}
private func removeSearchBar() {
tableView.tableHeaderView = nil
}
@objc private func createTag() {
navigate(to: nil)
}
func tagsFailedLoading(error: Error) {
DDLogError("Tag management. Error loading tags for \(String(describing: blog.url)): \(error)")
}
}
// MARK: - Table view datasource
extension SiteTagsViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return resultsController.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableConstants.cellIdentifier, for: indexPath) as? TitleBadgeDisclosureCell, let tag = tagAtIndexPath(indexPath) else {
return TitleBadgeDisclosureCell()
}
cell.name = tag.name?.stringByDecodingXMLCharacters()
if let count = tag.postCount?.intValue, count > 0 {
cell.count = count
}
return cell
}
fileprivate func tagAtIndexPath(_ indexPath: IndexPath) -> PostTag? {
return resultsController.object(at: indexPath) as? PostTag
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard let selectedTag = tagAtIndexPath(indexPath) else {
return
}
delete(selectedTag)
}
private func delete(_ tag: PostTag) {
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
refreshControl?.beginRefreshing()
tagsService.delete(tag, for: blog, success: { [weak self] in
self?.refreshControl?.endRefreshing()
self?.tableView.reloadData()
}, failure: { [weak self] error in
self?.refreshControl?.endRefreshing()
})
}
private func save(_ tag: PostTag) {
let tagsService = PostTagService(managedObjectContext: ContextManager.sharedInstance().mainContext)
refreshControl?.beginRefreshing()
tagsService.save(tag, for: blog, success: { [weak self] tag in
self?.refreshControl?.endRefreshing()
self?.tableView.reloadData()
}, failure: { error in
self.refreshControl?.endRefreshing()
})
}
}
// MARK: - Table view delegate
extension SiteTagsViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let selectedTag = tagAtIndexPath(indexPath) else {
return
}
navigate(to: selectedTag)
}
}
// MARK: - Fetched results delegate
extension SiteTagsViewController: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
refreshNoResultsView()
}
}
// MARK: - Navigation to Tag details
extension SiteTagsViewController {
fileprivate func navigate(to tag: PostTag?) {
let titleSectionHeader = NSLocalizedString("Tag", comment: "Section header for tag name in Tag Details View.")
let subtitleSectionHeader = NSLocalizedString("Description", comment: "Section header for tag name in Tag Details View.")
let titleErrorFooter = NSLocalizedString("Name Required", comment: "Error to be displayed when a tag is empty")
let content = SettingsTitleSubtitleController.Content(title: tag?.name,
subtitle: tag?.tagDescription,
titleHeader: titleSectionHeader,
subtitleHeader: subtitleSectionHeader,
titleErrorFooter: titleErrorFooter)
let confirmationContent = confirmation()
let tagDetailsView = SettingsTitleSubtitleController(content: content, confirmation: confirmationContent)
tagDetailsView.setAction { [weak self] updatedData in
self?.navigationController?.popViewController(animated: true)
guard let tag = tag else {
return
}
self?.delete(tag)
}
tagDetailsView.setUpdate { [weak self] updatedData in
guard let tag = tag else {
self?.addTag(data: updatedData)
return
}
guard self?.tagWasUpdated(tag: tag, updatedTag: updatedData) == true else {
return
}
self?.updateTag(tag, updatedData: updatedData)
}
navigationController?.pushViewController(tagDetailsView, animated: true)
}
private func addTag(data: SettingsTitleSubtitleController.Content) {
if let existingTag = existingTagForData(data) {
displayAlertForExistingTag(existingTag)
return
}
guard let newTag = NSEntityDescription.insertNewObject(forEntityName: "PostTag", into: ContextManager.sharedInstance().mainContext) as? PostTag else {
return
}
newTag.name = data.title
newTag.tagDescription = data.subtitle
save(newTag)
WPAnalytics.trackSettingsChange("site_tags", fieldName: "add_tag")
}
private func updateTag(_ tag: PostTag, updatedData: SettingsTitleSubtitleController.Content) {
// Lets check that we are not updating a tag to a name that already exists
if let existingTag = existingTagForData(updatedData),
existingTag != tag {
displayAlertForExistingTag(existingTag)
return
}
tag.name = updatedData.title
tag.tagDescription = updatedData.subtitle
save(tag)
WPAnalytics.trackSettingsChange("site_tags", fieldName: "edit_tag")
}
private func existingTagForData(_ data: SettingsTitleSubtitleController.Content) -> PostTag? {
guard let title = data.title else {
return nil
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostTag")
request.predicate = NSPredicate(format: "blog.blogID = %@ AND name = %@", blog.dotComID!, title)
request.fetchLimit = 1
guard let results = (try? context.fetch(request)) as? [PostTag] else {
return nil
}
return results.first
}
fileprivate func displayAlertForExistingTag(_ tag: PostTag) {
let title = NSLocalizedString("Tag already exists",
comment: "Title of the alert indicating that a tag with that name already exists.")
let tagName = tag.name ?? ""
let message = String(format: NSLocalizedString("A tag named '%@' already exists.",
comment: "Message of the alert indicating that a tag with that name already exists. The placeholder is the name of the tag"),
tagName)
let acceptTitle = NSLocalizedString("OK", comment: "Alert dismissal title")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(acceptTitle)
present(alertController, animated: true)
}
private func tagWasUpdated(tag: PostTag, updatedTag: SettingsTitleSubtitleController.Content) -> Bool {
if tag.name == updatedTag.title && tag.tagDescription == updatedTag.subtitle {
return false
}
return true
}
private func confirmation() -> SettingsTitleSubtitleController.Confirmation {
let confirmationTitle = NSLocalizedString("Delete this tag", comment: "Delete Tag confirmation action title")
let confirmationSubtitle = NSLocalizedString("Are you sure you want to delete this tag?", comment: "Message asking for confirmation on tag deletion")
let actionTitle = NSLocalizedString("Delete", comment: "Delete")
let cancelTitle = NSLocalizedString("Cancel", comment: "Alert dismissal title")
let trashIcon = UIImage.gridicon(.trash)
return SettingsTitleSubtitleController.Confirmation(title: confirmationTitle,
subtitle: confirmationSubtitle,
actionTitle: actionTitle,
cancelTitle: cancelTitle,
icon: trashIcon,
isDestructiveAction: true)
}
}
// MARK: - Empty state handling
private extension SiteTagsViewController {
func refreshNoResultsView() {
let noResults = resultsController.fetchedObjects?.count == 0
showRightBarButton(!noResults)
if noResults {
showNoResults()
} else {
hideNoResults()
}
}
func showNoResults() {
if isSearching {
showNoSearchResultsView()
return
}
if isPerformingInitialSync {
showLoadingView()
return
}
showEmptyResultsView()
}
func showLoadingView() {
configureAndDisplayNoResults(title: NoResultsText.loadingTitle, accessoryView: NoResultsViewController.loadingAccessoryView())
removeSearchBar()
}
func showEmptyResultsView() {
configureAndDisplayNoResults(title: NoResultsText.noTagsTitle, subtitle: NoResultsText.noTagsMessage, buttonTitle: NoResultsText.createButtonTitle)
removeSearchBar()
}
func showNoSearchResultsView() {
// If already shown, don't show again. To prevent the view from "flashing" as the user types.
guard !noResultsShown else {
return
}
configureAndDisplayNoResults(title: NoResultsText.noResultsTitle, forNoSearchResults: true)
}
func configureAndDisplayNoResults(title: String,
subtitle: String? = nil,
buttonTitle: String? = nil,
accessoryView: UIView? = nil,
forNoSearchResults: Bool = false) {
if forNoSearchResults {
noResultsViewController.configureForNoSearchResults(title: title)
} else {
noResultsViewController.configure(title: title, buttonTitle: buttonTitle, subtitle: subtitle, accessoryView: accessoryView)
}
displayNoResults()
}
func displayNoResults() {
addChild(noResultsViewController)
noResultsViewController.view.frame = tableView.frame
// Since the tableView doesn't always start at the top, adjust the NRV accordingly.
if isSearching {
noResultsViewController.view.frame.origin.y = searchController.searchBar.frame.height
} else {
noResultsViewController.view.frame.origin.y = 0
}
tableView.addSubview(withFadeAnimation: noResultsViewController.view)
noResultsViewController.didMove(toParent: self)
}
func hideNoResults() {
noResultsViewController.removeFromView()
setupSearchBar()
tableView.reloadData()
}
var noResultsShown: Bool {
return noResultsViewController.parent != nil
}
struct NoResultsText {
static let noTagsTitle = NSLocalizedString("You don't have any tags", comment: "Empty state. Tags management (Settings > Writing > Tags)")
static let noTagsMessage = NSLocalizedString("Tags created here can be quickly added to new posts", comment: "Displayed when the user views tags in blog settings and there are no tags")
static let createButtonTitle = NSLocalizedString("Create a Tag", comment: "Title of the button in the placeholder for an empty list of blog tags.")
static let loadingTitle = NSLocalizedString("Loading...", comment: "Loading tags.")
static let noResultsTitle = NSLocalizedString("No tags matching your search", comment: "Displayed when the user is searching site tags and there are no matches.")
}
}
// MARK: - NoResultsViewControllerDelegate
extension SiteTagsViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
createTag()
}
}
// MARK: - SearchResultsUpdater
extension SiteTagsViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text, text != "" else {
refreshResultsController(predicate: defaultPredicate)
return
}
let filterPredicate = NSPredicate(format: "blog.blogID = %@ AND name contains [cd] %@", blog.dotComID!, text)
refreshResultsController(predicate: filterPredicate)
}
}
// MARK: - UISearchControllerDelegate Conformance
extension SiteTagsViewController: UISearchControllerDelegate {
func willPresentSearchController(_ searchController: UISearchController) {
isSearching = true
deactivateRefreshControl()
}
func willDismissSearchController(_ searchController: UISearchController) {
isSearching = false
setupRefreshControl()
}
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.