hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
5b725b11e2d007c292ad77352152223ad6ff653b | 457 | //
// BaseButton.swift
// mh824appWithSwift
//
// Created by wangyuanfei on 16/9/8.
// Copyright © 2016年 www.16lao.com. All rights reserved.
//
import UIKit
class BaseButton: UIButton {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
func didMo() {
}
}
| 19.041667 | 78 | 0.63895 |
2fc2d46d985455a39f710a36475192fc0241ce15 | 383 | //
// ViewController.swift
// iOS-Faire-Take-Home-Assignment
//
// Created by Rafael Brandão on 21/03/2019.
// Copyright © 2019 Rafael Brandão. 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.
}
}
| 18.238095 | 80 | 0.681462 |
8f695f5afb2f7ae3e4706295295ab0a4dc8b7d87 | 21,018 | /* 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 Shared
import XCGLogger
import SwiftKeychainWrapper
import SwiftyJSON
private let log = Logger.syncLogger
/*
* This file includes types that manage intra-sync and inter-sync metadata
* for the use of synchronizers and the state machine.
*
* See docs/sync.md for details on what exactly we need to persist.
*/
public struct Fetched<T: Equatable>: Equatable {
let value: T
let timestamp: Timestamp
}
public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value
}
public enum LocalCommand: CustomStringConvertible, Hashable {
// We've seen something (a blank server, a changed global sync ID, a
// crypto/keys with a different meta/global) that requires us to reset all
// local engine timestamps (save the ones listed) and possibly re-upload.
case resetAllEngines(except: Set<String>)
// We've seen something (a changed engine sync ID, a crypto/keys with a
// different per-engine bulk key) that requires us to reset our local engine
// timestamp and possibly re-upload.
case resetEngine(engine: String)
// We've seen a change in meta/global: an engine has come or gone.
case enableEngine(engine: String)
case disableEngine(engine: String)
public func toJSON() -> JSON {
switch self {
case let .resetAllEngines(except):
return JSON(["type": "ResetAllEngines", "except": Array(except).sorted()])
case let .resetEngine(engine):
return JSON(["type": "ResetEngine", "engine": engine])
case let .enableEngine(engine):
return JSON(["type": "EnableEngine", "engine": engine])
case let .disableEngine(engine):
return JSON(["type": "DisableEngine", "engine": engine])
}
}
public static func fromJSON(_ json: JSON) -> LocalCommand? {
if json.isError() {
return nil
}
guard let type = json["type"].string else {
return nil
}
switch type {
case "ResetAllEngines":
if let except = json["except"].array, except.every({$0.isString()}) {
return .resetAllEngines(except: Set(except.map({$0.stringValue})))
}
return nil
case "ResetEngine":
if let engine = json["engine"].string {
return .resetEngine(engine: engine)
}
return nil
case "EnableEngine":
if let engine = json["engine"].string {
return .enableEngine(engine: engine)
}
return nil
case "DisableEngine":
if let engine = json["engine"].string {
return .disableEngine(engine: engine)
}
return nil
default:
return nil
}
}
public var description: String {
return self.toJSON().description
}
public var hashValue: Int {
return self.description.hashValue
}
}
public func ==(lhs: LocalCommand, rhs: LocalCommand) -> Bool {
switch (lhs, rhs) {
case (let .resetAllEngines(exceptL), let .resetAllEngines(exceptR)):
return exceptL == exceptR
case (let .resetEngine(engineL), let .resetEngine(engineR)):
return engineL == engineR
case (let .enableEngine(engineL), let .enableEngine(engineR)):
return engineL == engineR
case (let .disableEngine(engineL), let .disableEngine(engineR)):
return engineL == engineR
default:
return false
}
}
/*
* Persistence pref names.
* Note that syncKeyBundle isn't persisted by us.
*
* Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"),
* and we keep a 'label'. This label is used to find the real fetched keys in the Keychain.
*/
private let PrefVersion = "_v"
private let PrefGlobal = "global"
private let PrefGlobalTS = "globalTS"
private let PrefKeyLabel = "keyLabel"
private let PrefKeysTS = "keysTS"
private let PrefLastFetched = "lastFetched"
private let PrefLocalCommands = "localCommands"
private let PrefClientName = "clientName"
private let PrefClientGUID = "clientGUID"
private let PrefHashedUID = "hashedUID"
private let PrefEngineConfiguration = "engineConfiguration"
/*
* Keys for values that originate from prefs set when the account is first established.
*/
public let PrefDeviceRegistration = "deviceRegistration"
class PrefsBackoffStorage: BackoffStorage {
let prefs: Prefs
fileprivate let key = "timestamp"
init(prefs: Prefs) {
self.prefs = prefs
}
var serverBackoffUntilLocalTimestamp: Timestamp? {
get {
return self.prefs.unsignedLongForKey(self.key)
}
set(value) {
if let value = value {
self.prefs.setLong(value, forKey: self.key)
} else {
self.prefs.removeObjectForKey(self.key)
}
}
}
func clearServerBackoff() {
self.prefs.removeObjectForKey(self.key)
}
func isInBackoff(_ now: Timestamp) -> Timestamp? {
if let ts = self.serverBackoffUntilLocalTimestamp, now < ts {
return ts
}
return nil
}
}
/**
* The scratchpad consists of the following:
*
* 1. Cached records. We cache meta/global and crypto/keys until they change.
* 2. Metadata like timestamps, both for cached records and for server fetches.
* 3. User preferences -- engine enablement.
* 4. Client record state.
* 5. Local commands that have yet to be processed.
*
* Note that the scratchpad itself is immutable, but is a class passed by reference.
* Its mutable fields can be mutated, but you can't accidentally e.g., switch out
* meta/global and get confused.
*
* TODO: the Scratchpad needs to be loaded from persistent storage, and written
* back at certain points in the state machine (after a replayable action is taken).
*/
open class Scratchpad {
open class Builder {
var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too!
fileprivate var global: Fetched<MetaGlobal>?
fileprivate var keys: Fetched<Keys>?
fileprivate var keyLabel: String
var localCommands: Set<LocalCommand>
var engineConfiguration: EngineConfiguration?
var clientGUID: String
var clientName: String
var fxaDeviceId: String
var hashedUID: String?
var prefs: Prefs
init(p: Scratchpad) {
self.syncKeyBundle = p.syncKeyBundle
self.prefs = p.prefs
self.global = p.global
self.keys = p.keys
self.keyLabel = p.keyLabel
self.localCommands = p.localCommands
self.engineConfiguration = p.engineConfiguration
self.clientGUID = p.clientGUID
self.clientName = p.clientName
self.fxaDeviceId = p.fxaDeviceId
self.hashedUID = p.hashedUID
}
open func clearLocalCommands() -> Builder {
self.localCommands.removeAll()
return self
}
open func addLocalCommandsFromKeys(_ keys: Fetched<Keys>?) -> Builder {
// Getting new keys can force local collection resets.
guard let freshKeys = keys?.value, let staleKeys = self.keys?.value, staleKeys.valid else {
// Removing keys, or new keys and either we didn't have old keys or they weren't valid. Everybody gets a reset!
self.localCommands.insert(LocalCommand.resetAllEngines(except: []))
return self
}
// New keys, and we have valid old keys.
if freshKeys.defaultBundle != staleKeys.defaultBundle {
// Default bundle has changed. Reset everything but collections that have unchanged bulk keys.
var except: Set<String> = Set()
// Symmetric difference, like an animal. Swift doesn't allow Hashable tuples; don't fight it.
for (collection, keyBundle) in staleKeys.collectionKeys {
if keyBundle == freshKeys.forCollection(collection) {
except.insert(collection)
}
}
for (collection, keyBundle) in freshKeys.collectionKeys {
if keyBundle == staleKeys.forCollection(collection) {
except.insert(collection)
}
}
self.localCommands.insert(.resetAllEngines(except: except))
} else {
// Default bundle is the same. Reset collections that have changed bulk keys.
for (collection, keyBundle) in staleKeys.collectionKeys {
if keyBundle != freshKeys.forCollection(collection) {
self.localCommands.insert(.resetEngine(engine: collection))
}
}
for (collection, keyBundle) in freshKeys.collectionKeys {
if keyBundle != staleKeys.forCollection(collection) {
self.localCommands.insert(.resetEngine(engine: collection))
}
}
}
return self
}
open func setKeys(_ keys: Fetched<Keys>?) -> Builder {
self.keys = keys
return self
}
open func setGlobal(_ global: Fetched<MetaGlobal>?) -> Builder {
self.global = global
if let global = global {
// We always take the incoming meta/global's engine configuration.
self.engineConfiguration = global.value.engineConfiguration()
}
return self
}
open func setEngineConfiguration(_ engineConfiguration: EngineConfiguration?) -> Builder {
self.engineConfiguration = engineConfiguration
return self
}
open func build() -> Scratchpad {
return Scratchpad(
b: self.syncKeyBundle,
m: self.global,
k: self.keys,
keyLabel: self.keyLabel,
localCommands: self.localCommands,
engines: self.engineConfiguration,
clientGUID: self.clientGUID,
clientName: self.clientName,
fxaDeviceId: self.fxaDeviceId,
hashedUID: self.hashedUID,
persistingTo: self.prefs
)
}
}
open lazy var backoffStorage: BackoffStorage = {
return PrefsBackoffStorage(prefs: self.prefs.branch("backoff.storage"))
}()
open func evolve() -> Scratchpad.Builder {
return Scratchpad.Builder(p: self)
}
// This is never persisted.
let syncKeyBundle: KeyBundle
// Cached records.
// This cached meta/global is what we use to add or remove enabled engines. See also
// engineConfiguration, below.
// We also use it to detect when meta/global hasn't changed -- compare timestamps.
//
// Note that a Scratchpad held by a Ready state will have the current server meta/global
// here. That means we don't need to track syncIDs separately (which is how desktop and
// Android are implemented).
// If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't
// synced with this server before, and we'll do a fresh sync.
let global: Fetched<MetaGlobal>?
// We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs.
// Instead, we store a label, which is seeded when you first create a Scratchpad.
// This label is used to retrieve the real keys from your Keychain.
//
// Note that we also don't store the syncKeyBundle here. That's always created from kB,
// provided by the Firefox Account.
//
// Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to
// clean up without having your key. Secondly, we don't want to accidentally load keys
// from the Keychain just because the Sync Key is the same -- e.g., after a node
// reassignment. Randomly generating a label offers all of the benefits with none of the
// problems, with only the cost of persisting that label alongside the rest of the state.
let keys: Fetched<Keys>?
let keyLabel: String
// Local commands.
var localCommands: Set<LocalCommand>
// Enablement states.
let engineConfiguration: EngineConfiguration?
// What's our client name?
let clientName: String
let clientGUID: String
let fxaDeviceId: String
let hashedUID: String?
var hashedDeviceID: String? {
guard let hashedUID = hashedUID else {
return nil
}
return (fxaDeviceId + hashedUID).sha256.hexEncodedString
}
// Where do we persist when told?
let prefs: Prefs
init(b: KeyBundle,
m: Fetched<MetaGlobal>?,
k: Fetched<Keys>?,
keyLabel: String,
localCommands: Set<LocalCommand>,
engines: EngineConfiguration?,
clientGUID: String,
clientName: String,
fxaDeviceId: String,
hashedUID: String?,
persistingTo prefs: Prefs
) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = k
self.keyLabel = keyLabel
self.global = m
self.engineConfiguration = engines
self.localCommands = localCommands
self.clientGUID = clientGUID
self.clientName = clientName
self.fxaDeviceId = fxaDeviceId
self.hashedUID = hashedUID
}
// This should never be used in the end; we'll unpickle instead.
// This should be a convenience initializer, but... Swift compiler bug?
init(b: KeyBundle, persistingTo prefs: Prefs) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = nil
self.keyLabel = Bytes.generateGUID()
self.global = nil
self.engineConfiguration = nil
self.localCommands = Set()
self.clientGUID = Bytes.generateGUID()
self.clientName = DeviceInfo.defaultClientName()
self.fxaDeviceId = {
guard let string = prefs.stringForKey(PrefDeviceRegistration) else {
return nil
}
let json = JSON(parseJSON: string)
return json["id"].string
}() ?? "unknown_fxaDeviceId"
self.hashedUID = nil
}
func freshStartWithGlobal(_ global: Fetched<MetaGlobal>) -> Scratchpad {
// TODO: I *think* a new keyLabel is unnecessary.
return self.evolve()
.setGlobal(global)
.addLocalCommandsFromKeys(nil)
.setKeys(nil)
.build()
}
fileprivate class func unpickleV1FromPrefs(_ prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad {
let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve()
if let mg = prefs.stringForKey(PrefGlobal) {
if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) {
if let global = MetaGlobal.fromJSON(JSON(parseJSON: mg)) {
_ = b.setGlobal(Fetched(value: global, timestamp: mgTS))
} else {
log.error("Malformed meta/global in prefs. Ignoring.")
}
} else {
// This should never happen.
log.error("Found global in prefs, but not globalTS!")
}
}
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
b.keyLabel = keyLabel
if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) {
if let keys = KeychainWrapper.sharedAppContainerKeychain.string(forKey: "keys." + keyLabel) {
// We serialize as JSON.
let keys = Keys(payload: KeysPayload(keys))
if keys.valid {
log.debug("Read keys from Keychain with label \(keyLabel).")
_ = b.setKeys(Fetched(value: keys, timestamp: ckTS))
} else {
log.error("Invalid keys extracted from Keychain. Discarding.")
}
} else {
log.error("Found keysTS in prefs, but didn't find keys in Keychain!")
}
}
}
b.clientGUID = prefs.stringForKey(PrefClientGUID) ?? {
log.error("No value found in prefs for client GUID! Generating one.")
return Bytes.generateGUID()
}()
b.clientName = prefs.stringForKey(PrefClientName) ?? {
log.error("No value found in prefs for client name! Using default.")
return DeviceInfo.defaultClientName()
}()
b.hashedUID = prefs.stringForKey(PrefHashedUID)
if let localCommands: [String] = prefs.stringArrayForKey(PrefLocalCommands) {
b.localCommands = Set(localCommands.flatMap({LocalCommand.fromJSON(JSON(parseJSON: $0))}))
}
if let engineConfigurationString = prefs.stringForKey(PrefEngineConfiguration) {
if let engineConfiguration = EngineConfiguration.fromJSON(JSON(parseJSON: engineConfigurationString)) {
b.engineConfiguration = engineConfiguration
} else {
log.error("Invalid engineConfiguration found in prefs. Discarding.")
}
}
return b.build()
}
/**
* Remove anything that might be left around after prefs is wiped.
*/
open class func clearFromPrefs(_ prefs: Prefs) {
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
log.debug("Removing saved key from keychain.")
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: keyLabel)
} else {
log.debug("No key label; nothing to remove from keychain.")
}
}
open class func restoreFromPrefs(_ prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? {
if let ver = prefs.intForKey(PrefVersion) {
switch ver {
case 1:
return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle)
default:
return nil
}
}
log.debug("No scratchpad found in prefs.")
return nil
}
/**
* Persist our current state to our origin prefs.
* Note that calling this from multiple threads with either mutated or evolved
* scratchpads will cause sadness — individual writes are thread-safe, but the
* overall pseudo-transaction is not atomic.
*/
open func checkpoint() -> Scratchpad {
return pickle(self.prefs)
}
func pickle(_ prefs: Prefs) -> Scratchpad {
prefs.setInt(1, forKey: PrefVersion)
if let global = global {
prefs.setLong(global.timestamp, forKey: PrefGlobalTS)
prefs.setString(global.value.asPayload().json.stringValue()!, forKey: PrefGlobal)
} else {
prefs.removeObjectForKey(PrefGlobal)
prefs.removeObjectForKey(PrefGlobalTS)
}
// We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs.
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
if let keys = self.keys,
let payload = keys.value.asPayload().json.stringValue() {
let label = "keys." + self.keyLabel
log.debug("Storing keys in Keychain with label \(label).")
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
prefs.setLong(keys.timestamp, forKey: PrefKeysTS)
// TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here.
KeychainWrapper.sharedAppContainerKeychain.set(payload, forKey: label)
} else {
log.debug("Removing keys from Keychain.")
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: self.keyLabel)
}
prefs.setString(clientName, forKey: PrefClientName)
prefs.setString(clientGUID, forKey: PrefClientGUID)
if let uid = hashedUID {
prefs.setString(uid, forKey: PrefHashedUID)
}
let localCommands: [String] = Array(self.localCommands).map({$0.toJSON().stringValue()!})
prefs.setObject(localCommands, forKey: PrefLocalCommands)
if let engineConfiguration = self.engineConfiguration {
prefs.setString(engineConfiguration.toJSON().stringValue()!, forKey: PrefEngineConfiguration)
} else {
prefs.removeObjectForKey(PrefEngineConfiguration)
}
return self
}
}
| 36.873684 | 128 | 0.611571 |
d7fd4455a613317d97ebb4573b86af07e11db14c | 195 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let tmp = "Hello again"
var list = ["cat", "dog"]
var empty = [String]()
empty.append("hello")
| 16.25 | 52 | 0.661538 |
28b8b02e1d565ffd39ab33ab86db2ac847e5159b | 3,840 | //
// UILabel+Extensions.swift
// OceanDesignSystem
//
// Created by Alex Gomes on 23/07/20.
// Copyright © 2020 Blu Pagamentos. All rights reserved.
//
import Foundation
import UIKit
import OceanTokens
extension UILabel {
public func setLineHeight(lineHeight: CGFloat) {
let text = self.text
if let text = text {
let attributeString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, text.count))
self.attributedText = attributeString
}
}
private func createMutableAttributedString(string: String? = nil) -> NSMutableAttributedString? {
let text = string ?? self.text
guard let labelText = text else {
return nil
}
let attributedString: NSMutableAttributedString
if let labelattributedText = self.attributedText, labelattributedText.string == labelText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
return attributedString
}
/**
Mudar a color de uma parte do texto.
*/
public func changeColorOfPartOfText(_ fullText: String, coloredText: String, color: UIColor, fonte: UIFont? = nil) {
let texto: NSString = fullText as NSString
let range = (texto).range(of: coloredText)
guard let attributedText = createMutableAttributedString(string: fullText) else {
return
}
attributedText.addAttribute(.foregroundColor, value: color, range: range)
if let fonte = fonte {
attributedText.addAttribute(.font, value: fonte, range: range)
}
self.attributedText = attributedText
}
/**
Alterar a fonte de parte do texto.
*/
public func setPartOfTextInBold(_ fullText: String, boldText: String, boldFont: UIFont? = nil, boldColor: UIColor? = nil) {
let font = boldFont ?? UIFont.baseBold(size: self.font.pointSize)
changeColorOfPartOfText(fullText, coloredText: boldText, color: boldColor ?? self.textColor, fonte: font)
}
/**
Sublinha o texto.
*/
public func underlineText(fullText: String? = nil, underlinedText: String, underlinedTextColor: UIColor, lineColor: UIColor? = nil, lineStyle: Int = NSUnderlineStyle.single.rawValue) {
let text: NSString = (fullText ?? self.text ?? "") as NSString
let range = (text).range(of: underlinedText)
guard let attributedText = createMutableAttributedString(string: fullText) else {
return
}
let attributes: [NSAttributedString.Key : Any] = [
.underlineColor: lineColor ?? underlinedTextColor,
.foregroundColor: underlinedTextColor,
.underlineStyle: lineStyle
]
attributedText.addAttributes(attributes, range: range)
self.attributedText = attributedText
}
/**
Altera a fonte dos textos que estão entre a tag <b></b>
*/
public func setTextWithBoldTag(_ fullText: String, boldFont: UIFont? = nil, boldColor: UIColor? = nil) {
self.text = fullText
guard fullText.contains("<b>") else {
return
}
fullText.extractSupposedBoldWords { (boldWords) in
let textoPuro = fullText.replacingOccurrences(of: "<b>", with: "").replacingOccurrences(of: "</b>", with: "")
for word in boldWords {
self.setPartOfTextInBold(textoPuro, boldText: word, boldFont: boldFont, boldColor: boldColor)
}
}
}
}
| 34.285714 | 188 | 0.642969 |
ccd0234e041401ee72aa0becc4053954b7164deb | 1,353 | //
// CallLater.swift
// xianzhan
//
// Created by crl on 2018/11/21.
// Copyright © 2018 lingyu. All rights reserved.
//
import UIKit
class CRLCallLater: NSObject,ITickable {
static let Instance:CRLCallLater=CRLCallLater();
func tick(now: DispatchTime) {
}
static var list:[RFListenerItemRef<DispatchTime>]=[];
static func AddItem(_ handle:Selector,selfObj:AnyObject,_ delay:DispatchTimeInterval) -> Bool{
let t=DispatchTime.now()+delay;
let hasItem = list.first{$0.equal(handle, selfObj)};
if let h=hasItem{
h.data=t;
return true;
}
let item=RFListenerItemRef<DispatchTime>();
item.handle=handle;
item.selfObj=selfObj;
item.data=t;
if(list.count==1){
CRLTickManager.AddItem(Instance);
}
return true;
}
static func RemoveItem(_ handle:Selector,selfObj:AnyObject?)->Bool{
let index=list.firstIndex{ $0.equal(handle, selfObj)};
if let index=index{
list.remove(at: index);
if(list.count==0){
CRLTickManager.RemoveItem(Instance);
}
return true;
}
return false;
}
}
| 22.180328 | 98 | 0.534368 |
4bf636d556760c34f4c1ba56d3bf0da6423a3a9f | 184 | //
// ExposureLevel.swift
// exposure-vic
//
// Created by Mark Battistella on 6/9/21.
//
import Foundation
enum ExposureLevel {
case tier0
case tier1
case tier2
case tier3
}
| 11.5 | 42 | 0.695652 |
dbddbc320e159262af8af52eda0fa10bdf8e264d | 2,199 | //
// AppDelegate.swift
// Loteria
//
// Created by Vinícius Rodrigues Duarte on 19/08/18.
// Copyright © 2018 Vinícius Rodrigues Duarte. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.787234 | 285 | 0.757162 |
147ed8def28b75a87adf03f8f0a0fc7432ae1dea | 793 | /*
* Copyright 2019 Google
*
* 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.
*/
public enum FirestoreDecodingError: Error {
case decodingIsNotSupported(String)
case fieldNameConfict(String)
}
public enum FirestoreEncodingError: Error {
case encodingIsNotSupported(String)
}
| 31.72 | 75 | 0.755359 |
c1f3e66cd958e464c96343797ff869e17c4903cf | 1,040 | //
// GeneradorDeEtapasDelDia.swift
// TDDIntro
//
// Created by Carlos Saldana on 6/21/16.
// Copyright © 2016 Jaguar Labs. All rights reserved.
//
import UIKit
class GeneradorDeEtapasDelDia: NSObject {
func calcularEtapaDelDia(dateTime: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let date = dateTime
let components = calendar.components([.Hour], fromDate: date)
if components.hour > 7 && components.hour < 12 {
return "De mañana"
}
if components.hour == 12 {
return "Medio día"
}
if components.hour > 12 && components.hour < 19 {
return "Tarde"
}
if components.hour > 19 && components.hour < 24 {
return "Noche"
}
if components.hour == 24 {
return "Media noche"
}
if components.hour > 0 && components.hour < 7 {
return "Madrugada"
}
return "Error en calculo de etapa del día"
}
}
| 26 | 69 | 0.553846 |
113ee8f0151cb4d3aaaecdfe5dc298582bd602a2 | 1,169 | //
// EnglistWordsUITests.swift
// EnglistWordsUITests
//
// Created by Alexluan on 2019/9/29.
// Copyright © 2019 Alexluan. All rights reserved.
//
import XCTest
class EnglistWordsUITests: XCTestCase {
override func 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.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.4 | 182 | 0.693755 |
fee980cea0cd5d91755d1be314e99ac904d87fee | 2,508 | //
// LightRow.swift
// Tisym
//
// Created by Hadrien Barbat on 2020-03-19.
// Copyright © 2020 Hadrien Barbat. All rights reserved.
//
import SwiftUI
struct LightRow: View {
@ObservedObject var hueDelegate: HueDelegate
@Binding var light: Light
var lastUpdate = Date()
func red() {
self.hueDelegate.setColor(to: light, red: 255, green: 0, blue: 0)
}
func blue() {
self.hueDelegate.setColor(to: light, red: 0, green: 0, blue: 255)
}
func green() {
self.hueDelegate.setColor(to: light, red: 0, green: 255, blue: 0)
}
var body: some View {
let lightDetails = LigthDetail(
hueDelegate: hueDelegate,
light: $light,
rgbColour: Colors.cieToRGBPercent(light.cieColor ?? CieColor(x: 0, y: 0)),
brightness: CGFloat(light.brightness ?? 255) / 255
)
return NavigationLink(destination: lightDetails) {
Toggle(isOn: $light.isOn) {
VStack(alignment: .leading, spacing: 10) {
Text(light.name)
.font(.headline)
if light.isBulb() && light.isColor() {
HStack {
Button(action: self.red) {
Circle()
.fill(Color.red)
.frame(width: 50, height: 50)
}
.buttonStyle(PlainButtonStyle())
Button(action: self.blue) {
Circle()
.fill(Color.blue)
.frame(width: 50, height: 50)
}
.buttonStyle(PlainButtonStyle())
Button(action: self.green) {
Circle()
.fill(Color.green)
.frame(width: 50, height: 50)
}
.buttonStyle(PlainButtonStyle())
}
}
}
.padding()
}
}
}
}
struct LightRow_Previews: PreviewProvider {
static var previews: some View {
LightRow(
hueDelegate: HueDelegate(),
light: .constant(lightData[0])
)
}
}
| 30.962963 | 86 | 0.423046 |
bb263a828233cf69d3f35d2674086964d5fee15a | 612 | //
// LogViewer.swift
// PinpointKit
//
// Created by Brian Capps on 2/5/16.
// Copyright © 2016 Lickability. All rights reserved.
//
/// A protocol describing an interface to an object that can view a console log.
public protocol LogViewer: InterfaceCustomizable {
/**
Displays a log from a given view controller.
- parameter collector: The collector which has the logs to view.
- parameter viewController: A view controller from which to present an interface for log viewing.
*/
func viewLog(in collector: LogCollector, from viewController: UIViewController)
}
| 30.6 | 102 | 0.705882 |
d50f0f0925fb9d65b6019c1a8a6e15aea8bf10d3 | 1,267 | //
// JetLayout
//
// Copyright © 2020 Vladimir Benkevich
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
open class Switch: Widget<UISwitch> {
public init() {
super.init(UISwitch())
}
}
| 37.264706 | 82 | 0.735596 |
ebca961e7af090254e2965fc4fea6656823fa84b | 310 | //
// RightComponentProtocol.swift
// AndesUI
//
// Created by Nicolas Rostan Talasimov on 3/23/20.
//
import UIKit
/// Component that can be placed on the right side of an AndesTextField
@objc public protocol AndesTextFieldRightComponent {
var visibility: AndesTextFieldComponentVisibility { get }
}
| 22.142857 | 71 | 0.754839 |
901af85feb79de13b000c4963e03cadbfb24b5f9 | 288 | //
// CGFloat+MathOperationProvider.swift
// CocoaCore
//
// Created by Manish Pandey on 31/05/21.
//
import UIKit
import FoundationCore
extension CGFloat: MathOperationProvider {
public var half: CGFloat { self / 2 }
public var double: CGFloat { self * 2 }
}
| 16 | 43 | 0.663194 |
d540482e3c06b45fd916bda90b9626c190204000 | 1,008 | //
// UIColor+Hex.swift
// KB-iOS
//
// Created by Denny on 2020/08/25.
// Copyright © 2020 KakaoTalk. All rights reserved.
//
import UIKit
import Foundation
extension String {
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
}
public extension UIColor {
convenience init(hex: String, alpha: CGFloat = 1.0) {
var hex = hex.deletingPrefix("#")
hex = hex.deletingPrefix("0x")
if hex.count != 6 {
print("")
}
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let red = (rgbValue & 0xff0000) >> 16
let green = (rgbValue & 0xff00) >> 8
let blue = rgbValue & 0xff
self.init(red: CGFloat(red) / 0xff, green: CGFloat(green) / 0xff, blue: CGFloat(blue) / 0xff, alpha: alpha)
}
}
| 25.846154 | 115 | 0.584325 |
20e5112eeed4552e07426df24f975d2068bba7d2 | 126 | import XCTest
import PublishedKVOTests
var tests = [XCTestCaseEntry]()
tests += PublishedKVOTests.allTests()
XCTMain(tests)
| 15.75 | 37 | 0.793651 |
cc4bb75114ee21364cd653bad97eada4a34828f7 | 5,114 | //
// UIApplicationExtension.swift
// UIKitExtensions
//
// Created by 张鹏 on 2019/4/26.
// Copyright © 2019 [email protected]. All rights reserved.
//
import UIKit
// MARK: - UIApplication Infos
@objc
public extension UIApplication {
/// 包ID
var bundleIdentifier: String {
// 已经存在,直接返回对应的bundleIdentifier
if let bundleIdentifierAssociatedObject = objc_getAssociatedObject(self, &UIApplication.bundleIdentifierAssociatedObjectKey) as? String {
return bundleIdentifierAssociatedObject
}
// 不存在的话去获取bundleIdentifier
guard let fetchedBundleIdentifier = infos?[UIApplication.InfoDictionaryKey.bundleIdentifier] as? String else {
return "Unknown"
}
objc_setAssociatedObject(self, &UIApplication.bundleIdentifierAssociatedObjectKey, fetchedBundleIdentifier, .OBJC_ASSOCIATION_COPY_NONATOMIC)
return fetchedBundleIdentifier
}
/// 包名
var bundleDisplayName: String {
// 已经存在,直接返回对应的bundleDisplayName
if let bundleDisplayNameAssociatedObject = objc_getAssociatedObject(self, &UIApplication.bundleDisplayNameAssociatedObjectKey) as? String {
return bundleDisplayNameAssociatedObject
}
// 不存在的话去获取bundleDisplayName
var fetchedBundleDisplayName = "Unknown"
if let bundleDisplayName = infos?[UIApplication.InfoDictionaryKey.bundleDisplayName] as? String {
fetchedBundleDisplayName = bundleDisplayName
} else if let bundleName = infos?[UIApplication.InfoDictionaryKey.bundleName] as? String {
fetchedBundleDisplayName = bundleName
}
objc_setAssociatedObject(self, &UIApplication.bundleDisplayNameAssociatedObjectKey, fetchedBundleDisplayName, .OBJC_ASSOCIATION_COPY_NONATOMIC)
return fetchedBundleDisplayName
}
/// 包版本
var bundleVersion: String {
// 已经存在,直接返回对应的bundleDisplayName
if let bundleVersionAssociatedObject = objc_getAssociatedObject(self, &UIApplication.bundleVersionAssociatedObjectKey) as? String {
return bundleVersionAssociatedObject
}
// 不存在的话去获取bundleDisplayName
guard let fetchedBundleVersion = infos?[UIApplication.InfoDictionaryKey.bundleShortVersionString] as? String else {
return "Unknown"
}
objc_setAssociatedObject(self, &UIApplication.bundleVersionAssociatedObjectKey, fetchedBundleVersion, .OBJC_ASSOCIATION_COPY_NONATOMIC)
return fetchedBundleVersion
}
/// Info.plist中的信息
var infos: [String: Any]? {
return Bundle.main.infoDictionary
}
}
// MARK: - Types
public extension UIApplication {
/// InfoDictionary中对应的key
enum InfoDictionaryKey: String {
case bundleNumericVersion = "CFBundleNumericVersion"
case buildMachineOSBuild = "BuildMachineOSBuild"
case platformBuild = "DTPlatformBuild"
case sdkName = "DTSDKName"
case supportedInterfaceOrientations = "UISupportedInterfaceOrientations"
case bundleInfoDictionaryVersion = "CFBundleInfoDictionaryVersion"
case deviceFamily = "UIDeviceFamily"
case bundleIdentifier = "CFBundleIdentifier"
case compiler = "DTCompiler"
case bundlePackageType = "CFBundlePackageType"
case xcode = "DTXcode"
case platformVersion = "DTPlatformVersion"
case bundleExecutable = "CFBundleExecutable"
case launchStoryboardName = "UILaunchStoryboardName"
case bundleShortVersionString = "CFBundleShortVersionString"
case bundleVersion = "CFBundleVersion"
case viewControllerBasedStatusBarAppearance = "UIViewControllerBasedStatusBarAppearance"
case xcodeBuild = "DTXcodeBuild"
case bundleDevelopmentRegion = "CFBundleDevelopmentRegion"
case sdkBuild = "DTSDKBuild"
case bundleName = "CFBundleName"
case bundleDisplayName = "CFBundleDisplayName"
case bundleSupportedPlatforms = "CFBundleSupportedPlatforms"
case requiredDeviceCapabilities = "UIRequiredDeviceCapabilities"
case mainStoryboardFile = "UIMainStoryboardFile"
case platformName = "DTPlatformName"
case requiresIPhoneOS = "LSRequiresIPhoneOS"
case minimumOSVersion = "MinimumOSVersion"
}
}
// MARK: - InfoDictionaryKey subscript
public extension Dictionary where Key == String, Value == Any {
/// InfoDictionaryKey类型的下标
subscript(key: UIApplication.InfoDictionaryKey) -> Value? {
return self[key.rawValue]
}
}
// MARK: - Constants
private extension UIApplication {
/// bundleIdentifier关联对象的key
private static var bundleIdentifierAssociatedObjectKey = "UIDevice.bundleIdentifierAssociatedObjectKey"
/// bundleDisplayName关联对象的key
private static var bundleDisplayNameAssociatedObjectKey = "UIDevice.bundleDisplayNameAssociatedObjectKey"
/// bundleVersio关联对象的key
private static var bundleVersionAssociatedObjectKey = "bundleVersionAssociatedObjectKey"
}
| 38.164179 | 151 | 0.715096 |
fb5ec4d7c287c96e5646addde352ecb942e56643 | 310 | //
// UIRoundImageView.swift
// VoxeetUXKit
//
// Created by Corentin Larroque on 23/07/2019.
// Copyright © 2019 Voxeet. All rights reserved.
//
class UIRoundImageView: UIImageView {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.width / 2
}
}
| 20.666667 | 49 | 0.670968 |
f95f170d2f6f9cd7fd6f023bd6d021886f95d1e0 | 1,920 | //
// BaseTestCase.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class BaseTestCase: XCTestCase {
let timeout: TimeInterval = 5
static var testDirectoryURL: URL { return FileManager.temporaryDirectoryURL.appendingPathComponent("org.alamofire.tests") }
var testDirectoryURL: URL { return BaseTestCase.testDirectoryURL }
override func setUp() {
super.setUp()
FileManager.removeAllItemsInsideDirectory(at: testDirectoryURL)
FileManager.createDirectory(at: testDirectoryURL)
}
func url(forResource fileName: String, withExtension ext: String) -> URL {
let bundle = Bundle(for: BaseTestCase.self)
return bundle.url(forResource: fileName, withExtension: ext)!
}
}
| 40.851064 | 127 | 0.74375 |
233775641fe6e2075e03ffd3aa6786ea06292863 | 15,211 | //
// UIViewController.swift
// AptoSDK
//
// Created by Ivan Oliver Martínez on 13/02/16.
//
//
import Foundation
import AptoSDK
import SnapKit
public enum SubviewPosition {
case topCenter
case center
case bottomCenter
case custom(coordinates: CGPoint)
}
public protocol ViewControllerProtocol {
func set(title: String)
func showNavPreviousButton(_ tintColor: UIColor?)
func showNavNextButton(title: String, tintColor: UIColor?)
func showNavNextButton(icon: UIImage, tintColor: UIColor?)
func showNavNextButton(tintColor: UIColor?)
func hideNavNextButton()
func showNavCancelButton(_ tintColor: UIColor?)
func activateNavNextButton(_ tintColor: UIColor?)
func deactivateNavNextButton(_ deactivatedTintColor: UIColor?)
func show(error: Error, uiConfig: UIConfig?)
func showNetworkNotReachableError(_ uiConfig: UIConfig?)
func hideNetworkNotReachableError()
func showServerMaintenanceError()
func showMessage(_ message: String, uiConfig: UIConfig?)
// swiftlint:disable:next function_parameter_count
func show(message: String, title: String, animated: Bool, isError: Bool, uiConfig: UIConfig,
tapHandler: (() -> Void)?)
func showLoadingSpinner(tintColor: UIColor, position: SubviewPosition)
func hideLoadingSpinner()
func showLoadingView(uiConfig: UIConfig)
func hideLoadingView()
func configureLeftNavButton(mode: UIViewControllerLeftButtonMode?, uiConfig: UIConfig?)
var navigationController: UINavigationController? { get }
func askPermissionToOpenExternalUrl(_ completion: @escaping Result<Bool, NSError>.Callback)
}
public extension ViewControllerProtocol {
func showLoadingSpinner(tintColor: UIColor, position: SubviewPosition = .center) {
showLoadingSpinner(tintColor: tintColor, position: position)
}
func showNavPreviousButton(_ tintColor: UIColor?) {
showNavPreviousButton(tintColor)
}
func showNavCancelButton(_ tintColor: UIColor?) {
showNavCancelButton(tintColor)
}
}
extension ViewControllerProtocol where Self: ShiftViewController {
func show(error: Error, uiConfig: UIConfig? = nil) {
show(error: error, uiConfig: uiConfig ?? uiConfiguration)
}
func showMessage(_ message: String, uiConfig: UIConfig? = nil) {
showMessage(message, uiConfig: uiConfig ?? uiConfiguration)
}
func show(message: String, title: String, animated: Bool = true, isError: Bool = false,
tapHandler: (() -> Void)? = nil) {
show(message: message, title: title, animated: animated, isError: isError, uiConfig: uiConfiguration,
tapHandler: tapHandler)
}
}
extension ShiftViewController {
func show(error: Error) {
show(error: error, uiConfig: uiConfiguration)
}
func showMessage(_ message: String) {
showMessage(message, uiConfig: uiConfiguration)
}
func showLoadingView() {
showLoadingView(uiConfig: uiConfiguration)
}
}
extension UIViewController: ViewControllerProtocol {
public func showNavPreviousButton(_ tintColor: UIColor? = nil) {
self.installNavLeftButton(UIImage.imageFromPodBundle("top_back_default"),
tintColor: tintColor,
accessibilityLabel: "Navigation Previous Button",
target: self,
action: #selector(UIViewController.closeTapped))
}
public func showNavNextButton(title: String, tintColor: UIColor?) {
self.installNavRightButton(nil,
tintColor: tintColor,
title: title,
accessibilityLabel: "Navigation Next Button",
target: self,
action: #selector(UIViewController.nextTapped))
}
public func showNavNextButton(icon: UIImage, tintColor: UIColor?) {
self.installNavRightButton(icon,
tintColor: tintColor,
title: nil,
accessibilityLabel: "Navigation Next Button",
target: self,
action: #selector(UIViewController.nextTapped))
}
public func showNavNextButton(tintColor: UIColor?) {
self.installNavRightButton(UIImage.imageFromPodBundle("top_next_default.png"),
tintColor: tintColor,
title: nil,
accessibilityLabel: "Navigation Next Button",
target: self,
action: #selector(UIViewController.nextTapped))
}
public func showNavCancelButton(_ tintColor: UIColor? = nil) {
self.installNavLeftButton(UIImage.imageFromPodBundle("top_close_default"),
tintColor: tintColor,
accessibilityLabel: "Navigation Close Button",
target: self,
action: #selector(UIViewController.closeTapped))
}
public func showNavDummyNextButton() {
self.installNavRightButton(nil,
tintColor: nil,
title: nil,
accessibilityLabel: nil,
target: nil,
action: #selector(UIViewController.nextTapped))
}
func installNavLeftButton(_ image: UIImage?,
tintColor: UIColor? = nil,
accessibilityLabel: String? = nil,
target: AnyObject?,
action: Selector) {
let finalImage = tintColor != nil ? image?.asTemplate() : image
var uiButtonItem: UIBarButtonItem
uiButtonItem = UIBarButtonItem(
image: finalImage,
style: .plain,
target: target,
action: action)
if let accessibilityLabel = accessibilityLabel {
uiButtonItem.accessibilityLabel = accessibilityLabel
}
if tintColor != nil {
uiButtonItem.tintColor = tintColor
}
navigationItem.leftBarButtonItem = uiButtonItem
}
func installNavRightButton(_ image: UIImage?,
tintColor: UIColor? = nil,
title: String? = nil,
accessibilityLabel: String? = nil,
target: AnyObject?,
action: Selector) {
var uiButtonItem: UIBarButtonItem
if let title = title {
uiButtonItem = UIBarButtonItem(
title: title,
style: .plain,
target: target,
action: action)
}
else {
let finalImage = tintColor != nil ? image?.asTemplate() : image
uiButtonItem = UIBarButtonItem(
image: finalImage,
style: .plain,
target: target,
action: action)
}
if let accessibilityLabel = accessibilityLabel {
uiButtonItem.accessibilityLabel = accessibilityLabel
}
if let tintColor = tintColor {
uiButtonItem.tintColor = tintColor
uiButtonItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: tintColor.withAlphaComponent(0.4)],
for: .disabled)
}
navigationItem.rightBarButtonItem = uiButtonItem
}
public func hideNavNextButton() {
navigationItem.rightBarButtonItem = nil
}
func hideNavCancelButton() {
navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true
}
func hideNavPreviousButton() {
navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true
}
func hideNavBarBackButton() {
self.navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true
}
func showNavBarBackButton() {
self.navigationItem.hidesBackButton = false
}
public func deactivateNavNextButton(_ deactivatedTintColor: UIColor?) {
navigationItem.rightBarButtonItem?.isEnabled = false
if deactivatedTintColor != nil {
navigationItem.rightBarButtonItem?.tintColor = deactivatedTintColor
}
}
public func activateNavNextButton(_ tintColor: UIColor?) {
navigationItem.rightBarButtonItem?.isEnabled = true
if tintColor != nil {
navigationItem.rightBarButtonItem?.tintColor = tintColor
}
}
public func show(error: Error, uiConfig: UIConfig?) {
self.hideLoadingSpinner()
let backgroundColor = uiConfig?.uiErrorColor ?? UIColor.colorFromHex(0xDC4337)
let font = uiConfig?.fontProvider.mainItemRegularFont
let textColor = uiConfig?.textMessageColor
let toast = Toast(text: error.localizedDescription, textAlignment: .left, backgroundColor: backgroundColor,
textColor: textColor, font: font, duration: 5, minimumHeight: 100, style: .bottomToTop)
present(toast, animated: true)
}
public func showNetworkNotReachableError(_ uiConfig: UIConfig?) {
let viewController = NetworkNotReachableErrorViewControllerTheme2(uiConfig: uiConfig)
present(viewController, animated: true)
}
public func hideNetworkNotReachableError() {
dismiss(animated: true)
}
public func showServerMaintenanceError() {
let serviceLocator = ServiceLocator.shared
let module = serviceLocator.moduleLocator.serverMaintenanceErrorModule()
module.initialize { [weak self] result in
guard let self = self else { return }
switch result {
case .failure(let error):
self.show(error: error, uiConfig: serviceLocator.uiConfig )
case .success(let viewController):
self.present(viewController, animated: true)
}
}
module.onClose = { _ in
UIApplication.topViewController()?.dismiss(animated: false)
}
}
public func showMessage(_ message: String, uiConfig: UIConfig?) {
let backgroundColor = uiConfig?.uiSuccessColor ?? UIColor.colorFromHex(0xDC4337)
let font = uiConfig?.fontProvider.mainItemRegularFont
let textColor = uiConfig?.textMessageColor
let toast = Toast(text: message, textAlignment: .left, backgroundColor: backgroundColor, textColor: textColor,
font: font, duration: 5, minimumHeight: 100, style: .bottomToTop)
present(toast, animated: true)
}
public func show(message: String, title: String, animated: Bool = true, isError: Bool = false, uiConfig: UIConfig,
tapHandler: (() -> Void)?) {
let toastView = TitleSubtitleToastView(uiConfig: uiConfig)
let backgroundColor = isError ? uiConfig.uiErrorColor : uiConfig.uiPrimaryColor
let toast = TitleSubtitleToast(title: uiConfig.showToastTitle ? title : nil, message: message,
backgroundColor: backgroundColor, duration: tapHandler == nil ? 5 : nil,
delegate: toastView)
toastView.tapHandler = tapHandler
present(toast, withCustomToastView: toastView, animated: animated)
}
public func showLoadingSpinner(tintColor: UIColor, position: SubviewPosition) {
let activityIndicator = UIActivityIndicatorView(style: .white)
activityIndicator.color = tintColor
addSubview(activityIndicator, at: position)
activityIndicator.startAnimating()
}
private func addSubview(_ subview: UIView, at position: SubviewPosition) {
let container = UIView()
container.backgroundColor = .clear
view.addSubview(container)
switch position {
case .topCenter:
container.snp.makeConstraints { make in
make.left.top.right.equalToSuperview()
make.height.equalToSuperview().dividedBy(3.0)
}
case .center:
container.snp.makeConstraints { make in
make.center.equalToSuperview()
}
case .bottomCenter:
container.snp.makeConstraints { make in
make.left.bottom.right.equalToSuperview()
make.height.equalToSuperview().dividedBy(3.0)
}
case .custom(let coordinates):
container.snp.makeConstraints { make in
make.centerX.equalTo(coordinates.x)
make.centerY.equalTo(coordinates.y)
}
}
container.addSubview(subview)
subview.snp.makeConstraints { make in
make.center.equalToSuperview()
}
}
public func hideLoadingSpinner() {
for subview in view.subviews.reversed() {
// The spinner is inside a container
if subview.subviews.first is UIActivityIndicatorView { // swiftlint:disable:this for_where
subview.removeFromSuperview()
return
}
}
}
public func showLoadingView(uiConfig: UIConfig) {
if let window = UIApplication.shared.keyWindow {
let loadingView = UIView(frame: .zero)
loadingView.backgroundColor = view.backgroundColor?.withAlphaComponent(0.9)
let activityIndicator = UIActivityIndicatorView(style: .white)
activityIndicator.color = uiConfig.uiPrimaryColor
loadingView.addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { make in
make.center.equalToSuperview()
}
window.addSubview(loadingView)
loadingView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
activityIndicator.startAnimating()
}
}
public func hideLoadingView() {
if let window = UIApplication.shared.keyWindow {
for subview in window.subviews.reversed() {
// The spinner is inside a container
if subview.subviews.first is UIActivityIndicatorView { // swiftlint:disable:this for_where
subview.removeFromSuperview()
return
}
}
}
}
public func set(title: String) {
self.title = title
}
@objc func nextTapped() {
// To be overriden in child classes
}
@objc func closeTapped() {
// To be overriden in child classes
}
func setNavigationBar(tintColor: UIColor) {
guard let navigationController = self.navigationController else {
return
}
let textAttributes = [NSAttributedString.Key.foregroundColor: tintColor]
navigationController.navigationBar.titleTextAttributes = textAttributes
navigationController.navigationBar.tintColor = tintColor
}
public func askPermissionToOpenExternalUrl(_ completion: @escaping Result<Bool, NSError>.Callback) {
let optionMenu = UIAlertController(title: nil,
message: "offer-list.continue-application-in-web-browser".podLocalized(),
preferredStyle: .alert)
let okAction = UIAlertAction(title: "alert-controller.button.yes".podLocalized(),
style: .default) { _ in
completion(.success(true))
}
optionMenu.addAction(okAction)
let cancelAction = UIAlertAction(title: "alert-controller.button.no".podLocalized(),
style: .cancel) { _ in
completion(.success(false))
}
optionMenu.addAction(cancelAction)
present(optionMenu, animated: true, completion: nil)
}
public var edgesConstraint: ConstraintItem {
if #available(iOS 11, *) {
return view.safeAreaLayoutGuide.snp.edges
}
return view.snp.edges
}
}
public enum UIViewControllerLeftButtonMode {
case none
case back
case close
}
enum UIViewControllerPresentationMode {
case push
case modal
}
| 35.706573 | 118 | 0.660509 |
67e94f038318c84b19ad3f53108319414a71ea2b | 6,200 | //
// LocationViewController.swift
// HermesAlarmProject
//
// Created by Feng-iMac on 4/15/18.
// Copyright © 2018 LongGames. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
import Foundation
class LocationViewController: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate {
var locationManager:CLLocationManager!
@IBOutlet weak var locIndicator: UILabel!
var coordinateB: String!
var bPoint = MKPointAnnotation()
var userLocation:CLLocation!
var strSrcLoc: String!
var sourceLocation: String!
var saved: DarwinBoolean = false
@IBOutlet weak var destinationSearch: UISearchBar!
@IBAction func goBack(_ sender: Any) {
// _ = navigationController?.popViewController(animated: true)
self.dismiss(animated:true)
}
@IBAction func goBackAndSave(_ sender: Any) {
if (sourceLocation == nil){
//pop up box error
// create the alert
let alert = UIAlertController(title: "Error", message: "Location cannot be empty", preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
saved = false
}else{
//send over variables
// create the alert
let alert = UIAlertController(title: "Success!", message: "Source Location set as: \(strSrcLoc)", preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
//alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: {
sleep(2)
self.dismiss(animated:true, completion: {
LabelEditViewController.GlobalVariable.srcName = self.strSrcLoc
LabelEditViewController.GlobalVariable.srcCoord = self.sourceLocation
self.dismiss(animated: true)
})
})
saved = true
//(() -> Void)?
/*
self.dismiss(animated: true, completion: {
self.dismiss(animated:true)
})
*/
// self.dismiss(animated:true)
}
}
override func viewDidAppear(_ animated: Bool) {
print("View Appeared")
if ((saved).boolValue){
self.dismiss(animated:true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("View Loaded")
destinationSearch.delegate = self
destinationSearch.text = LabelEditViewController.GlobalVariable.srcName
if ((strSrcLoc) != ""){
self.locIndicator.backgroundColor = UIColor.green
self.locIndicator.textColor = UIColor.yellow
self.locIndicator.text = "Valid"
destinationSearch.text = strSrcLoc
}else{
locIndicator.backgroundColor = UIColor.red
locIndicator.textColor = UIColor.green
locIndicator.text = "Invalid"
}
}
override func viewWillAppear(_ animated: Bool) {
print("View Will Appear")
view.backgroundColor = UIColor(white: 1, alpha: 0.9)
}
//search for destination coordinates
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.becomeFirstResponder()
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(searchBar.text!) { (placemarks:[CLPlacemark]?, error:Error?) in
if error == nil {
let placemarks = placemarks?.first
//let ano = MKPointAnnotation()
let ano = self.bPoint
//Change the text that the user inputted to a better formatted one
var corrText = ""
if (placemarks?.name != nil){
corrText += "\((placemarks?.name)!), "
}
if (placemarks?.subThoroughfare != nil){
corrText += "\((placemarks?.subThoroughfare)!), "
}
if (placemarks?.thoroughfare != nil){
corrText += "\((placemarks?.thoroughfare)!), "
}
if (placemarks?.locality != nil){
corrText += "\((placemarks?.locality)!), "
}
if (placemarks?.administrativeArea != nil){
corrText += "\((placemarks?.administrativeArea)!), "
}
if (placemarks?.country != nil){
corrText += "\((placemarks?.country)!), "
}
if (placemarks?.postalCode != nil){
corrText += "\((placemarks?.postalCode)!), "
}
let trunc = String(corrText.characters.dropLast(2))
searchBar.text = trunc
//get coordinates
ano.coordinate = (placemarks?.location?.coordinate)!
self.coordinateB = String(ano.coordinate.latitude) + "," + String(ano.coordinate.longitude)
self.strSrcLoc = trunc
self.sourceLocation = self.coordinateB
self.locIndicator.backgroundColor = UIColor.green
self.locIndicator.textColor = UIColor.black
self.locIndicator.text = "Valid"
}
else {
print (error?.localizedDescription ?? "error")
self.locIndicator.backgroundColor = UIColor.red
self.locIndicator.textColor = UIColor.green
self.locIndicator.text = "Invalid"
}
}
}
}
| 33.513514 | 155 | 0.532258 |
696092cba6f506a43a61dde4f9a590324429a7e9 | 2,261 | // swift-tools-version:5.5
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2022 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "async-http-client-examples",
platforms: [
.macOS(.v10_15),
.iOS(.v13),
.tvOS(.v13),
.watchOS(.v6),
],
products: [
.executable(name: "GetHTML", targets: ["GetHTML"]),
.executable(name: "GetJSON", targets: ["GetJSON"]),
.executable(name: "StreamingByteCounter", targets: ["StreamingByteCounter"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.38.0"),
// in real-world projects this would be
// .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0")
.package(name: "async-http-client", path: "../"),
],
targets: [
// MARK: - Examples
.executableTarget(
name: "GetHTML",
dependencies: [
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "NIOCore", package: "swift-nio"),
], path: "GetHTML"
),
.executableTarget(
name: "GetJSON",
dependencies: [
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOFoundationCompat", package: "swift-nio"),
], path: "GetJSON"
),
.executableTarget(
name: "StreamingByteCounter",
dependencies: [
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "NIOCore", package: "swift-nio"),
], path: "StreamingByteCounter"
),
]
)
| 34.784615 | 96 | 0.530739 |
67101258218a647857a7bd12d5de641583fdec50 | 1,555 |
import SwiftUI
import CoreML
struct ContentView: View {
let images = ["cat", "person", "berries",
"car", "orange", "spider"]
@State private var currentIndex: Int = 0
let model: MobileNetV2 = {
do {
let config = MLModelConfiguration()
return try MobileNetV2(configuration: config)
} catch {
print(error)
fatalError("Couldn't create MobileNetV2")
}
}()
private func classifyImage() {
//let currentImage = images[currentIndex]
}
var body: some View {
VStack {
Text("Image Classifier")
.padding()
Image(images[currentIndex])
.resizable()
.aspectRatio(contentMode: .fit)
Button("Next Image >") {
if self.currentIndex < self.images.count - 1 {
self.currentIndex = self.currentIndex + 1
}
else {
self.currentIndex = 0
}
}.padding()
Button("Classify") {
classifyImage()
}
}
.font(.system(size: 60))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22.214286 | 62 | 0.415434 |
ac280c51c9c6eed515c24c3e1cd002bcbe213f1e | 1,263 | import Foundation
class RuuviDaemonWorker: NSObject {
var thread: Thread!
private var block: (() -> Void)!
@objc internal func runBlock() {
autoreleasepool {
block()
}
}
internal func start(_ block: @escaping () -> Void) {
self.block = block
let threadName = String(describing: self)
.components(separatedBy: .punctuationCharacters)[1]
thread = Thread { [weak self] in
while self != nil && !self!.thread.isCancelled {
RunLoop.current.run(
mode: RunLoop.Mode.default,
before: Date.distantFuture)
}
Thread.exit()
}
thread.name = "\(threadName)-\(UUID().uuidString)"
thread.start()
perform(#selector(runBlock),
on: thread,
with: nil,
waitUntilDone: false,
modes: [RunLoop.Mode.default.rawValue])
}
public func stopWork() {
perform(#selector(stopThread),
on: thread,
with: nil,
waitUntilDone: false,
modes: [RunLoop.Mode.default.rawValue])
}
@objc func stopThread() {
Thread.exit()
}
}
| 25.26 | 63 | 0.509105 |
16fd8658e800e40716b87ad71a234160895f268d | 754 | import XCTest
import RPTMultiSelection
class Tests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.604775 |
fb4557e8b9b43d2e74eb65fa0b074e59a184f1d2 | 114,588 | // @generated
// This file was automatically generated and should not be edited.
import Apollo
import Foundation
public final class GetCharactersQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetCharacters($page: Int) {
characters(page: $page) {
__typename
info {
__typename
pages
count
}
results {
__typename
...CharacterSmall
}
}
}
"""
public let operationName: String = "GetCharacters"
public let operationIdentifier: String? = "2638e39e2809244d03049d31a2a9a139fdf9fc72dbec67bd084260126e9c3c99"
public var queryDocument: String { return operationDefinition.appending("\n" + CharacterSmall.fragmentDefinition) }
public var page: Int?
public init(page: Int? = nil) {
self.page = page
}
public var variables: GraphQLMap? {
return ["page": page]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("characters", arguments: ["page": GraphQLVariable("page")], type: .object(Character.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(characters: Character? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "characters": characters.flatMap { (value: Character) -> ResultMap in value.resultMap }])
}
/// Get the list of all characters
public var characters: Character? {
get {
return (resultMap["characters"] as? ResultMap).flatMap { Character(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "characters")
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Characters"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Characters", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("pages", type: .scalar(Int.self)),
GraphQLField("count", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(pages: Int? = nil, count: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "pages": pages, "count": count])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The amount of pages.
public var pages: Int? {
get {
return resultMap["pages"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "pages")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
GraphQLField("episode", type: .list(.object(Episode.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil, episode: [Episode?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image, "episode": episode.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
/// Episodes in which this character appeared.
public var episode: [Episode?]? {
get {
return (resultMap["episode"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Episode?] in value.map { (value: ResultMap?) -> Episode? in value.flatMap { (value: ResultMap) -> Episode in Episode(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, forKey: "episode")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var characterSmall: CharacterSmall {
get {
return CharacterSmall(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
}
}
}
}
public final class GetCharacterQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetCharacter($id: ID!) {
character(id: $id) {
__typename
...CharacterFull
}
}
"""
public let operationName: String = "GetCharacter"
public let operationIdentifier: String? = "8115a5c0478fe3260388181ca5fdc3a1287796eb8046731ba14cca133c816420"
public var queryDocument: String { return operationDefinition.appending("\n" + CharacterFull.fragmentDefinition) }
public var id: GraphQLID
public init(id: GraphQLID) {
self.id = id
}
public var variables: GraphQLMap? {
return ["id": id]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("character", arguments: ["id": GraphQLVariable("id")], type: .object(Character.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(character: Character? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "character": character.flatMap { (value: Character) -> ResultMap in value.resultMap }])
}
/// Get a specific character by ID
public var character: Character? {
get {
return (resultMap["character"] as? ResultMap).flatMap { Character(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "character")
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
GraphQLField("status", type: .scalar(String.self)),
GraphQLField("species", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("gender", type: .scalar(String.self)),
GraphQLField("episode", type: .list(.object(Episode.selections))),
GraphQLField("location", type: .object(Location.selections)),
GraphQLField("origin", type: .object(Origin.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil, status: String? = nil, species: String? = nil, type: String? = nil, gender: String? = nil, episode: [Episode?]? = nil, location: Location? = nil, origin: Origin? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image, "status": status, "species": species, "type": type, "gender": gender, "episode": episode.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, "location": location.flatMap { (value: Location) -> ResultMap in value.resultMap }, "origin": origin.flatMap { (value: Origin) -> ResultMap in value.resultMap }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
/// The status of the character ('Alive', 'Dead' or 'unknown').
public var status: String? {
get {
return resultMap["status"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "status")
}
}
/// The species of the character.
public var species: String? {
get {
return resultMap["species"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "species")
}
}
/// The type or subspecies of the character.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The gender of the character ('Female', 'Male', 'Genderless' or 'unknown').
public var gender: String? {
get {
return resultMap["gender"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "gender")
}
}
/// Episodes in which this character appeared.
public var episode: [Episode?]? {
get {
return (resultMap["episode"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Episode?] in value.map { (value: ResultMap?) -> Episode? in value.flatMap { (value: ResultMap) -> Episode in Episode(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, forKey: "episode")
}
}
/// The character's last known location
public var location: Location? {
get {
return (resultMap["location"] as? ResultMap).flatMap { Location(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "location")
}
}
/// The character's origin location
public var origin: Origin? {
get {
return (resultMap["origin"] as? ResultMap).flatMap { Origin(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "origin")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var characterFull: CharacterFull {
get {
return CharacterFull(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, airDate: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "air_date": airDate])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
}
public struct Location: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
public struct Origin: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
}
}
}
public final class GetEpisodesQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetEpisodes($page: Int) {
episodes(page: $page) {
__typename
info {
__typename
count
pages
}
results {
__typename
...EpisodeDetail
}
}
}
"""
public let operationName: String = "GetEpisodes"
public let operationIdentifier: String? = "d8dc6cda60db1bb486b681d92a9d854e1f6350c7cc73e4fdc86dc7f57619c788"
public var queryDocument: String { return operationDefinition.appending("\n" + EpisodeDetail.fragmentDefinition) }
public var page: Int?
public init(page: Int? = nil) {
self.page = page
}
public var variables: GraphQLMap? {
return ["page": page]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("episodes", arguments: ["page": GraphQLVariable("page")], type: .object(Episode.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(episodes: Episode? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "episodes": episodes.flatMap { (value: Episode) -> ResultMap in value.resultMap }])
}
/// Get the list of all episodes
public var episodes: Episode? {
get {
return (resultMap["episodes"] as? ResultMap).flatMap { Episode(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "episodes")
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episodes"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episodes", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("count", type: .scalar(Int.self)),
GraphQLField("pages", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(count: Int? = nil, pages: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "count": count, "pages": pages])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
/// The amount of pages.
public var pages: Int? {
get {
return resultMap["pages"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "pages")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("created", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
GraphQLField("episode", type: .scalar(String.self)),
GraphQLField("characters", type: .list(.object(Character.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, created: String? = nil, airDate: String? = nil, episode: String? = nil, characters: [Character?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "created": created, "air_date": airDate, "episode": episode, "characters": characters.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Time at which the episode was created in the database.
public var created: String? {
get {
return resultMap["created"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "created")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
/// The code of the episode.
public var episode: String? {
get {
return resultMap["episode"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "episode")
}
}
/// List of characters who have been seen in the episode.
public var characters: [Character?]? {
get {
return (resultMap["characters"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Character?] in value.map { (value: ResultMap?) -> Character? in value.flatMap { (value: ResultMap) -> Character in Character(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }, forKey: "characters")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var episodeDetail: EpisodeDetail {
get {
return EpisodeDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
}
}
public final class GetEpisodeQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetEpisode($id: ID!) {
episode(id: $id) {
__typename
...EpisodeDetail
}
}
"""
public let operationName: String = "GetEpisode"
public let operationIdentifier: String? = "75005e8d842c61423597c65cb3e95d85d20aded325d99a10dc0e1abc94d92d76"
public var queryDocument: String { return operationDefinition.appending("\n" + EpisodeDetail.fragmentDefinition) }
public var id: GraphQLID
public init(id: GraphQLID) {
self.id = id
}
public var variables: GraphQLMap? {
return ["id": id]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("episode", arguments: ["id": GraphQLVariable("id")], type: .object(Episode.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(episode: Episode? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "episode": episode.flatMap { (value: Episode) -> ResultMap in value.resultMap }])
}
/// Get a specific episode by ID
public var episode: Episode? {
get {
return (resultMap["episode"] as? ResultMap).flatMap { Episode(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "episode")
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("created", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
GraphQLField("episode", type: .scalar(String.self)),
GraphQLField("characters", type: .list(.object(Character.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, created: String? = nil, airDate: String? = nil, episode: String? = nil, characters: [Character?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "created": created, "air_date": airDate, "episode": episode, "characters": characters.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Time at which the episode was created in the database.
public var created: String? {
get {
return resultMap["created"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "created")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
/// The code of the episode.
public var episode: String? {
get {
return resultMap["episode"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "episode")
}
}
/// List of characters who have been seen in the episode.
public var characters: [Character?]? {
get {
return (resultMap["characters"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Character?] in value.map { (value: ResultMap?) -> Character? in value.flatMap { (value: ResultMap) -> Character in Character(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }, forKey: "characters")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var episodeDetail: EpisodeDetail {
get {
return EpisodeDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
}
public final class GetLocationsQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetLocations($page: Int) {
locations(page: $page) {
__typename
info {
__typename
count
pages
}
results {
__typename
...LocationDetail
}
}
}
"""
public let operationName: String = "GetLocations"
public let operationIdentifier: String? = "bf026c3686b572b369a4d872270fba48814a8d2ab7cb385c49fdbb2b3301f1d1"
public var queryDocument: String { return operationDefinition.appending("\n" + LocationDetail.fragmentDefinition) }
public var page: Int?
public init(page: Int? = nil) {
self.page = page
}
public var variables: GraphQLMap? {
return ["page": page]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("locations", arguments: ["page": GraphQLVariable("page")], type: .object(Location.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(locations: Location? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "locations": locations.flatMap { (value: Location) -> ResultMap in value.resultMap }])
}
/// Get the list of all locations
public var locations: Location? {
get {
return (resultMap["locations"] as? ResultMap).flatMap { Location(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "locations")
}
}
public struct Location: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Locations"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Locations", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("count", type: .scalar(Int.self)),
GraphQLField("pages", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(count: Int? = nil, pages: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "count": count, "pages": pages])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
/// The amount of pages.
public var pages: Int? {
get {
return resultMap["pages"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "pages")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("dimension", type: .scalar(String.self)),
GraphQLField("residents", type: .list(.object(Resident.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, type: String? = nil, dimension: String? = nil, residents: [Resident?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name, "type": type, "dimension": dimension, "residents": residents.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The type of the location.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The dimension in which the location is located.
public var dimension: String? {
get {
return resultMap["dimension"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "dimension")
}
}
/// List of characters who have been last seen in the location.
public var residents: [Resident?]? {
get {
return (resultMap["residents"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Resident?] in value.map { (value: ResultMap?) -> Resident? in value.flatMap { (value: ResultMap) -> Resident in Resident(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }, forKey: "residents")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var locationDetail: LocationDetail {
get {
return LocationDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Resident: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
}
}
public final class GetLocationQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetLocation($id: ID!) {
location(id: $id) {
__typename
...LocationDetail
}
}
"""
public let operationName: String = "GetLocation"
public let operationIdentifier: String? = "685aeff3a140a7c5828baceb8b920f4692b17944d8f645494adb5099f40366d7"
public var queryDocument: String { return operationDefinition.appending("\n" + LocationDetail.fragmentDefinition) }
public var id: GraphQLID
public init(id: GraphQLID) {
self.id = id
}
public var variables: GraphQLMap? {
return ["id": id]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("location", arguments: ["id": GraphQLVariable("id")], type: .object(Location.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(location: Location? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "location": location.flatMap { (value: Location) -> ResultMap in value.resultMap }])
}
/// Get a specific locations by ID
public var location: Location? {
get {
return (resultMap["location"] as? ResultMap).flatMap { Location(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "location")
}
}
public struct Location: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("dimension", type: .scalar(String.self)),
GraphQLField("residents", type: .list(.object(Resident.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, type: String? = nil, dimension: String? = nil, residents: [Resident?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name, "type": type, "dimension": dimension, "residents": residents.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The type of the location.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The dimension in which the location is located.
public var dimension: String? {
get {
return resultMap["dimension"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "dimension")
}
}
/// List of characters who have been last seen in the location.
public var residents: [Resident?]? {
get {
return (resultMap["residents"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Resident?] in value.map { (value: ResultMap?) -> Resident? in value.flatMap { (value: ResultMap) -> Resident in Resident(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }, forKey: "residents")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var locationDetail: LocationDetail {
get {
return LocationDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Resident: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
}
public final class GetSearchQuery: GraphQLQuery {
/// The raw GraphQL definition of this operation.
public let operationDefinition: String =
"""
query GetSearch($name: String!) {
characters(page: 1, filter: {name: $name}) {
__typename
info {
__typename
count
}
results {
__typename
...CharacterSmall
}
}
locations(page: 1, filter: {name: $name}) {
__typename
info {
__typename
count
}
results {
__typename
...LocationDetail
}
}
episodes(page: 1, filter: {name: $name}) {
__typename
info {
__typename
count
}
results {
__typename
...EpisodeDetail
}
}
}
"""
public let operationName: String = "GetSearch"
public let operationIdentifier: String? = "c6016673c2e6ac38869749d9a4790551b4a90d4f88548201bb7ffa9f5c46de58"
public var queryDocument: String { return operationDefinition.appending("\n" + CharacterSmall.fragmentDefinition).appending("\n" + LocationDetail.fragmentDefinition).appending("\n" + EpisodeDetail.fragmentDefinition) }
public var name: String
public init(name: String) {
self.name = name
}
public var variables: GraphQLMap? {
return ["name": name]
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Query"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("characters", arguments: ["page": 1, "filter": ["name": GraphQLVariable("name")]], type: .object(Character.selections)),
GraphQLField("locations", arguments: ["page": 1, "filter": ["name": GraphQLVariable("name")]], type: .object(Location.selections)),
GraphQLField("episodes", arguments: ["page": 1, "filter": ["name": GraphQLVariable("name")]], type: .object(Episode.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(characters: Character? = nil, locations: Location? = nil, episodes: Episode? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "characters": characters.flatMap { (value: Character) -> ResultMap in value.resultMap }, "locations": locations.flatMap { (value: Location) -> ResultMap in value.resultMap }, "episodes": episodes.flatMap { (value: Episode) -> ResultMap in value.resultMap }])
}
/// Get the list of all characters
public var characters: Character? {
get {
return (resultMap["characters"] as? ResultMap).flatMap { Character(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "characters")
}
}
/// Get the list of all locations
public var locations: Location? {
get {
return (resultMap["locations"] as? ResultMap).flatMap { Location(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "locations")
}
}
/// Get the list of all episodes
public var episodes: Episode? {
get {
return (resultMap["episodes"] as? ResultMap).flatMap { Episode(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "episodes")
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Characters"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Characters", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("count", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(count: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "count": count])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
GraphQLField("episode", type: .list(.object(Episode.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil, episode: [Episode?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image, "episode": episode.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
/// Episodes in which this character appeared.
public var episode: [Episode?]? {
get {
return (resultMap["episode"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Episode?] in value.map { (value: ResultMap?) -> Episode? in value.flatMap { (value: ResultMap) -> Episode in Episode(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, forKey: "episode")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var characterSmall: CharacterSmall {
get {
return CharacterSmall(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
}
}
public struct Location: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Locations"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Locations", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("count", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(count: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "count": count])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("dimension", type: .scalar(String.self)),
GraphQLField("residents", type: .list(.object(Resident.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, type: String? = nil, dimension: String? = nil, residents: [Resident?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name, "type": type, "dimension": dimension, "residents": residents.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The type of the location.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The dimension in which the location is located.
public var dimension: String? {
get {
return resultMap["dimension"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "dimension")
}
}
/// List of characters who have been last seen in the location.
public var residents: [Resident?]? {
get {
return (resultMap["residents"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Resident?] in value.map { (value: ResultMap?) -> Resident? in value.flatMap { (value: ResultMap) -> Resident in Resident(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }, forKey: "residents")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var locationDetail: LocationDetail {
get {
return LocationDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Resident: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episodes"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("info", type: .object(Info.selections)),
GraphQLField("results", type: .list(.object(Result.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(info: Info? = nil, results: [Result?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episodes", "info": info.flatMap { (value: Info) -> ResultMap in value.resultMap }, "results": results.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
public var info: Info? {
get {
return (resultMap["info"] as? ResultMap).flatMap { Info(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "info")
}
}
public var results: [Result?]? {
get {
return (resultMap["results"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Result?] in value.map { (value: ResultMap?) -> Result? in value.flatMap { (value: ResultMap) -> Result in Result(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Result?]) -> [ResultMap?] in value.map { (value: Result?) -> ResultMap? in value.flatMap { (value: Result) -> ResultMap in value.resultMap } } }, forKey: "results")
}
}
public struct Info: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Info"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("count", type: .scalar(Int.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(count: Int? = nil) {
self.init(unsafeResultMap: ["__typename": "Info", "count": count])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The length of the response.
public var count: Int? {
get {
return resultMap["count"] as? Int
}
set {
resultMap.updateValue(newValue, forKey: "count")
}
}
}
public struct Result: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("created", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
GraphQLField("episode", type: .scalar(String.self)),
GraphQLField("characters", type: .list(.object(Character.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, created: String? = nil, airDate: String? = nil, episode: String? = nil, characters: [Character?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "created": created, "air_date": airDate, "episode": episode, "characters": characters.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Time at which the episode was created in the database.
public var created: String? {
get {
return resultMap["created"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "created")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
/// The code of the episode.
public var episode: String? {
get {
return resultMap["episode"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "episode")
}
}
/// List of characters who have been seen in the episode.
public var characters: [Character?]? {
get {
return (resultMap["characters"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Character?] in value.map { (value: ResultMap?) -> Character? in value.flatMap { (value: ResultMap) -> Character in Character(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }, forKey: "characters")
}
}
public var fragments: Fragments {
get {
return Fragments(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
public struct Fragments {
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public var episodeDetail: EpisodeDetail {
get {
return EpisodeDetail(unsafeResultMap: resultMap)
}
set {
resultMap += newValue.resultMap
}
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
}
}
}
public struct CharacterFull: GraphQLFragment {
/// The raw GraphQL definition of this fragment.
public static let fragmentDefinition: String =
"""
fragment CharacterFull on Character {
__typename
id
name
image
status
species
type
gender
episode {
__typename
id
name
air_date
}
location {
__typename
id
name
}
origin {
__typename
id
name
}
}
"""
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
GraphQLField("status", type: .scalar(String.self)),
GraphQLField("species", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("gender", type: .scalar(String.self)),
GraphQLField("episode", type: .list(.object(Episode.selections))),
GraphQLField("location", type: .object(Location.selections)),
GraphQLField("origin", type: .object(Origin.selections)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil, status: String? = nil, species: String? = nil, type: String? = nil, gender: String? = nil, episode: [Episode?]? = nil, location: Location? = nil, origin: Origin? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image, "status": status, "species": species, "type": type, "gender": gender, "episode": episode.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, "location": location.flatMap { (value: Location) -> ResultMap in value.resultMap }, "origin": origin.flatMap { (value: Origin) -> ResultMap in value.resultMap }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
/// The status of the character ('Alive', 'Dead' or 'unknown').
public var status: String? {
get {
return resultMap["status"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "status")
}
}
/// The species of the character.
public var species: String? {
get {
return resultMap["species"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "species")
}
}
/// The type or subspecies of the character.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The gender of the character ('Female', 'Male', 'Genderless' or 'unknown').
public var gender: String? {
get {
return resultMap["gender"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "gender")
}
}
/// Episodes in which this character appeared.
public var episode: [Episode?]? {
get {
return (resultMap["episode"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Episode?] in value.map { (value: ResultMap?) -> Episode? in value.flatMap { (value: ResultMap) -> Episode in Episode(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, forKey: "episode")
}
}
/// The character's last known location
public var location: Location? {
get {
return (resultMap["location"] as? ResultMap).flatMap { Location(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "location")
}
}
/// The character's origin location
public var origin: Origin? {
get {
return (resultMap["origin"] as? ResultMap).flatMap { Origin(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "origin")
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, airDate: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "air_date": airDate])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
}
public struct Location: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
public struct Origin: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
}
public struct CharacterSmall: GraphQLFragment {
/// The raw GraphQL definition of this fragment.
public static let fragmentDefinition: String =
"""
fragment CharacterSmall on Character {
__typename
id
name
image
episode {
__typename
id
name
}
}
"""
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
GraphQLField("episode", type: .list(.object(Episode.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil, episode: [Episode?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image, "episode": episode.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
/// Episodes in which this character appeared.
public var episode: [Episode?]? {
get {
return (resultMap["episode"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Episode?] in value.map { (value: ResultMap?) -> Episode? in value.flatMap { (value: ResultMap) -> Episode in Episode(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Episode?]) -> [ResultMap?] in value.map { (value: Episode?) -> ResultMap? in value.flatMap { (value: Episode) -> ResultMap in value.resultMap } } }, forKey: "episode")
}
}
public struct Episode: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
}
}
public struct LocationDetail: GraphQLFragment {
/// The raw GraphQL definition of this fragment.
public static let fragmentDefinition: String =
"""
fragment LocationDetail on Location {
__typename
id
name
type
dimension
residents {
__typename
id
name
image
}
}
"""
public static let possibleTypes: [String] = ["Location"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("type", type: .scalar(String.self)),
GraphQLField("dimension", type: .scalar(String.self)),
GraphQLField("residents", type: .list(.object(Resident.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, type: String? = nil, dimension: String? = nil, residents: [Resident?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Location", "id": id, "name": name, "type": type, "dimension": dimension, "residents": residents.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the location.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the location.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// The type of the location.
public var type: String? {
get {
return resultMap["type"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "type")
}
}
/// The dimension in which the location is located.
public var dimension: String? {
get {
return resultMap["dimension"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "dimension")
}
}
/// List of characters who have been last seen in the location.
public var residents: [Resident?]? {
get {
return (resultMap["residents"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Resident?] in value.map { (value: ResultMap?) -> Resident? in value.flatMap { (value: ResultMap) -> Resident in Resident(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Resident?]) -> [ResultMap?] in value.map { (value: Resident?) -> ResultMap? in value.flatMap { (value: Resident) -> ResultMap in value.resultMap } } }, forKey: "residents")
}
}
public struct Resident: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
public struct EpisodeDetail: GraphQLFragment {
/// The raw GraphQL definition of this fragment.
public static let fragmentDefinition: String =
"""
fragment EpisodeDetail on Episode {
__typename
id
name
created
air_date
episode
characters {
__typename
id
name
image
}
}
"""
public static let possibleTypes: [String] = ["Episode"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("created", type: .scalar(String.self)),
GraphQLField("air_date", type: .scalar(String.self)),
GraphQLField("episode", type: .scalar(String.self)),
GraphQLField("characters", type: .list(.object(Character.selections))),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, created: String? = nil, airDate: String? = nil, episode: String? = nil, characters: [Character?]? = nil) {
self.init(unsafeResultMap: ["__typename": "Episode", "id": id, "name": name, "created": created, "air_date": airDate, "episode": episode, "characters": characters.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the episode.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the episode.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Time at which the episode was created in the database.
public var created: String? {
get {
return resultMap["created"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "created")
}
}
/// The air date of the episode.
public var airDate: String? {
get {
return resultMap["air_date"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "air_date")
}
}
/// The code of the episode.
public var episode: String? {
get {
return resultMap["episode"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "episode")
}
}
/// List of characters who have been seen in the episode.
public var characters: [Character?]? {
get {
return (resultMap["characters"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Character?] in value.map { (value: ResultMap?) -> Character? in value.flatMap { (value: ResultMap) -> Character in Character(unsafeResultMap: value) } } }
}
set {
resultMap.updateValue(newValue.flatMap { (value: [Character?]) -> [ResultMap?] in value.map { (value: Character?) -> ResultMap? in value.flatMap { (value: Character) -> ResultMap in value.resultMap } } }, forKey: "characters")
}
}
public struct Character: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Character"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("id", type: .scalar(GraphQLID.self)),
GraphQLField("name", type: .scalar(String.self)),
GraphQLField("image", type: .scalar(String.self)),
]
}
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(id: GraphQLID? = nil, name: String? = nil, image: String? = nil) {
self.init(unsafeResultMap: ["__typename": "Character", "id": id, "name": name, "image": image])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The id of the character.
public var id: GraphQLID? {
get {
return resultMap["id"] as? GraphQLID
}
set {
resultMap.updateValue(newValue, forKey: "id")
}
}
/// The name of the character.
public var name: String? {
get {
return resultMap["name"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "name")
}
}
/// Link to the character's image.
/// All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars.
public var image: String? {
get {
return resultMap["image"] as? String
}
set {
resultMap.updateValue(newValue, forKey: "image")
}
}
}
}
| 31.909774 | 522 | 0.569859 |
e694d36d4f639e9f35909adf3c7cd399d0ece303 | 8,148 | //
// AreaPicker.swift
// ZYTool
//
// Created by Iann on 2021/12/1.
//
import Foundation
import SnapKit
import UIKit
public enum AreaPickerSource:Int {
case province
case city
case county
case town
}
public struct AreaItem {
let source:AreaPickerDataSource
let index:Int
}
public protocol AreaPickerDataSource {
func numberOfSections(_ areaPicker:AreaPicker) -> Int
func numberOfRowsAtSection(_ areaPicker:AreaPicker,section:Int) -> Int
func titleOfIndexPath(_ areaPicker:AreaPicker,indexPath:IndexPath) -> String
}
public protocol AreaPickerDelegate {
func didSelected(_ areaPicker:AreaPicker,indexPath:IndexPath)
}
public class AreaPicker: UIView {
private var views = [String:AreaContentView]()
private var titles:[String] = [String]() {
didSet {
titleView.titles = titles
}
}
private var selectedIndexs = [String:Int]()
private var _count:Int = 0 {
didSet {
collectionView.reloadData()
}
}
public var count:Int {
return _count
}
private var numbers:Int = 1
convenience init() {
self.init(frame: .zero)
setup()
}
public func reloadData() {
_count = dataSource?.numberOfSections(self) ?? 0
titleView.max = _count
}
func setup() {
addSubview(titleView)
titleView.setDidSelected { [weak self] (row, title) in
guard let self = self else {return}
self.collectionView.scrollToItem(at: IndexPath(row: row, section: 0), at: .centeredHorizontally, animated: true)
}
addSubview(collectionView)
}
func insert(_ title:String,at index:Int) {
titles.insert(title, at: index)
let count = titles.count + 1
numbers = count < _count ? count : _count
collectionView.reloadData()
titleView.currentNumber = numbers
titleView.selectedIndex = titles.count < (_count - 1) ? titles.count : (_count - 1)
}
func replace(_ title:String,at index:Int) {
if title.isEmpty {
return
}
debugPrint("title",title)
if index < titles.count {
if titles[index] == title {
titles.remove(at: index)
insert(title, at: index)
return
}
titles.removeLast()
}
if index >= titles.count {
insert(title, at: index)
} else {
replace(title, at: index)
}
}
// func setBlock(_ target:AreaContentView,section:Int) {
// target.page = section
//
// target.setNumberOfRows {[weak self] page in
// debugPrint("setNumberOfRows",page)
// guard let self = self,let dataSourse = self.dataSource else { return 0}
// let count = dataSourse.numberOfRowsAtSection(self, section: page)
// return count
// }
//
// target.setTitleOfRow { [weak self] (page,row) in
// guard let self = self,let dataSourse = self.dataSource else { return ""}
// debugPrint("setTitleOfRow",page)
// return dataSourse.titleOfIndexPath(self, indexPath: IndexPath(item: row, section: page))
// }
//
// target.setDidSelected {[weak self] (page,row,title) in
// guard let self = self else { return}
// let newIndexPath = IndexPath(item: row, section: page)
// self.replace(title, at: section)
//
// if let delegate = self.delegate {
// delegate.didSelected(self, indexPath: newIndexPath)
// }
// }
// target.tableView.reloadData()
// }
lazy var titleView: AreaTitleView = {
$0.backgroundColor = .white
return $0
}(AreaTitleView())
public override func layoutSubviews() {
super.layoutSubviews()
titleView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 40)
collectionView.frame = CGRect(x: 0, y: 40, width: bounds.width, height: bounds.height - 40)
}
public var dataSource:AreaPickerDataSource? {
didSet {
reloadData()
}
}
public var delegate:AreaPickerDelegate?
public var selectedIndex:Int = 0
lazy var flowLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 200, height: 200)
return layout
}()
lazy var collectionView: UICollectionView = {
let view = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
view.backgroundColor = .clear
view.dataSource = self
view.delegate = self
view.register(AreaContentCell.self, forCellWithReuseIdentifier: "AreaContentCell")
view.isPagingEnabled = true
return view
}()
lazy var scrollView: UIScrollView = {
$0.isPagingEnabled = true
$0.delegate = self
return $0
}(UIScrollView())
}
extension AreaPicker: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AreaContentCell", for: indexPath)
if let cell = cell as? AreaContentCell {
cell.index = indexPath.row
cell.selectedIndex = selectedIndexs["\(indexPath.row)"] ?? -1
cell.setNumberOfRows { [weak self] section in
guard let self = self,let dataSourse = self.dataSource else { return 0}
let count = dataSourse.numberOfRowsAtSection(self, section: section)
return count
}
cell.setTitleOfRow { [weak self] (section,row) in
guard let self = self,let dataSourse = self.dataSource else { return ""}
return dataSourse.titleOfIndexPath(self, indexPath: IndexPath(item: row, section: section))
}
cell.setDidSelected {[weak self] (section,row,title) in
guard let self = self else { return}
let newIndexPath = IndexPath(item: row, section: section)
self.replace(title, at: section)
if self.titles.count < self.selectedIndexs.count {
for i in self.titles.count..<self.selectedIndexs.count {
self.selectedIndexs["\(i)"] = -1
}
}
self.selectedIndexs["\(section)"] = row
if let delegate = self.delegate {
delegate.didSelected(self, indexPath: newIndexPath)
}
collectionView.reloadData()
}
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? AreaContentCell {
cell.tableView.reloadData()
}
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
debugPrint(indexPath)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numbers
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.bounds.width
let offSet = scrollView.contentOffset.x
let index = Int(offSet / width)
titleView.selectedIndex = index
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = bounds.size
return CGSize(width: size.width, height: size.height - 40)
}
}
| 33.393443 | 167 | 0.605056 |
e43986102fe3be4af1df1fd3afb38b07558b333f | 2,532 | //
// RSDateComponentsTransform.swift
// ResearchSuiteApplicationFramework
//
// Created by James Kizer on 11/24/17.
//
// Copyright Curiosity Health Company. All rights reserved.
//
import UIKit
import Gloss
///this should be able to take a list of things that evaluate to date components and merge them
open class RSDateComponentsTransform: RSValueTransformer {
public static func supportsType(type: String) -> Bool {
return type == "dateComponents"
}
public static func generateValue(jsonObject: JSON, state: RSState, context: [String : AnyObject]) -> ValueConvertible? {
//we have a list of values that should evaluate to either date or date components
guard let objectsToMerge: [JSON] = "merge" <~~ jsonObject else {
return nil
}
let calendar = Calendar(identifier: .gregorian)
let finalDateComponentsOpt: DateComponents? = objectsToMerge.reduce(nil) { (acc, json) -> DateComponents? in
guard let componentsStringArray: [String] = "components" <~~ json else {
return acc
}
let components = Set(componentsStringArray.compactMap { calendar.component(fromComponentString: $0) })
//this isn't going to evaluate directly into a date, we need to use valuemanager to handle this
if let dateJSON: JSON = "date" <~~ json,
let dateConvertible = RSValueManager.processValue(jsonObject: dateJSON, state: state, context: context),
let date = dateConvertible.evaluate() as? Date {
return calendar.dateComponents(components, mergeFrom: date, mergeInto: acc ?? DateComponents())
}
else if let dateComponentsJSON: JSON = "dateComponents" <~~ json,
let dateComponentsConvertible = RSValueManager.processValue(jsonObject: dateComponentsJSON, state: state, context: context),
let dateComponents = dateComponentsConvertible.evaluate() as? DateComponents {
return calendar.dateComponents(components, mergeFrom: dateComponents, mergeInto: acc ?? DateComponents())
}
else {
return acc
}
}
if let finalDateComponents = finalDateComponentsOpt {
return RSValueConvertible(value: finalDateComponents as NSDateComponents)
}
else {
return nil
}
}
}
| 38.363636 | 140 | 0.623618 |
4611973510df1e9637f3db453be6b68c4bd709ce | 3,570 | enum CustomRequestInfos {
case resetESCCap(cardId: String, privateKey: String?)
case getCongrats(data: Data?, congratsModel: CustomParametersModel)
case createPayment(privateKey: String?, publicKey: String, data: Data?, header: [String: String]?)
}
extension CustomRequestInfos: RequestInfos {
var endpoint: String {
switch self {
case .resetESCCap(let cardId, _): return "px_mobile/v1/esc_cap/\(cardId)"
case .getCongrats: return "v1/px_mobile/congrats"
case .createPayment: return "v1/px_mobile/payments"
}
}
var method: HTTPMethodType {
switch self {
case .resetESCCap: return .delete
case .getCongrats: return .get
case .createPayment: return .post
}
}
var shouldSetEnvironment: Bool {
switch self {
case .resetESCCap: return true
case .createPayment, .getCongrats: return false
}
}
var parameters: [String: Any]? {
switch self {
case .resetESCCap: return nil
case .getCongrats(_, let parameters): return organizeParameters(parameters: parameters)
case .createPayment(_, let publicKey, _, _):
return [
"public_key": publicKey,
"api_version": "2.0"
]
}
}
var headers: [String: String]? {
switch self {
case .resetESCCap, .getCongrats: return nil
case .createPayment(_, _, _, let header): return header
}
}
var body: Data? {
switch self {
case .resetESCCap: return nil
case .getCongrats(let data, _): return data
case .createPayment(_, _, let data, _): return data
}
}
var accessToken: String? {
switch self {
case .resetESCCap(_, let privateKey): return privateKey
case .getCongrats(_, let parameters): return parameters.privateKey
case .createPayment(let privateKey, _, _, _): return privateKey
}
}
}
extension CustomRequestInfos {
func organizeParameters(parameters: CustomParametersModel) -> [String: Any] {
var filteredParameters: [String: Any] = [:]
if parameters.publicKey != "" {
filteredParameters.updateValue(parameters.publicKey, forKey: "public_key")
}
if parameters.paymentMethodIds != "" {
filteredParameters.updateValue(parameters.paymentMethodIds, forKey: "payment_methods_ids")
}
if parameters.paymentId != "" {
filteredParameters.updateValue(parameters.paymentId, forKey: "payment_ids")
}
if let prefId = parameters.prefId {
filteredParameters.updateValue(prefId, forKey: "pref_id")
}
if let campaignId = parameters.campaignId {
filteredParameters.updateValue(campaignId, forKey: "campaign_id")
}
if let flowName = parameters.flowName {
filteredParameters.updateValue(flowName, forKey: "flow_name")
}
if let merchantOrderId = parameters.merchantOrderId {
filteredParameters.updateValue(merchantOrderId, forKey: "merchant_order_id")
}
if let paymentTypeId = parameters.paymentTypeId {
filteredParameters.updateValue(paymentTypeId, forKey: "payment_type_id ")
}
filteredParameters.updateValue("2.0", forKey: "api_version")
filteredParameters.updateValue(parameters.ifpe, forKey: "ifpe")
filteredParameters.updateValue("MP", forKey: "platform")
return filteredParameters
}
}
| 32.454545 | 102 | 0.628852 |
f70067bba5056c2960d95f11e7e7b9bf8b8dd96d | 13,571 | //
// HSReplayAPI.swift
// HSTracker
//
// Created by Benjamin Michotte on 12/08/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import OAuthSwift
import PromiseKit
enum HSReplayError: Error {
case missingAccount
case authorizationTokenNotSet
case collectionUploadMissingURL
case genericError(message: String)
}
enum ClaimBlizzardAccountResponse {
case success
case error
case tokenAlreadyClaimed
}
class HSReplayAPI {
static let apiKey = "f1c6965c-f5ee-43cb-ab42-768f23dd35e8"
static let oAuthClientKey = "pk_live_IB0TiMMT8qrwIJ4G6eVHYaAi"//"pk_test_AUThiV1Ex9nKCbHSFchv7ybX"
static let oAuthClientSecret = "sk_live_20180308078UceCXo8qmoG72ExZxeqOW"//"sk_test_20180308Z5qWO7yiYpqi8qAmQY0PDzcJ"
private static let defaultHeaders = ["Accept": "application/json", "Content-Type": "application/json"]
static var accountData: AccountData?
static let tokenRenewalHandler: OAuthSwift.TokenRenewedHandler = { result in
switch result {
case .success(let credential):
Settings.hsReplayOAuthToken = credential.oauthToken
Settings.hsReplayOAuthRefreshToken = credential.oauthRefreshToken
case .failure(let error):
logger.error("Failed to renew token: \(error)")
}
}
static let oauthswift = {
return OAuth2Swift(
consumerKey: oAuthClientKey,
consumerSecret: oAuthClientSecret,
authorizeUrl: HSReplay.oAuthAuthorizeUrl,
accessTokenUrl: HSReplay.oAuthTokenUrl,
responseType: "code"
)
}()
static func oAuthAuthorize(handle: @escaping () -> Void) {
_ = oauthswift.authorize(
withCallbackURL: URL(string: "hstracker://oauth-callback/hsreplay")!,
scope: "fullaccess",
state: "HSREPLAY",
completionHandler: { result in
switch result {
case .success(let (credential, _, _)):
logger.info("HSReplay: OAuth succeeded")
Settings.hsReplayOAuthToken = credential.oauthToken
Settings.hsReplayOAuthRefreshToken = credential.oauthRefreshToken
handle()
case .failure(let error):
// TODO: Better error handling
logger.info("HSReplay: OAuth failed \(error)")
}
}
)
}
static func getUploadToken(handle: @escaping (String) -> Void) {
if let token = Settings.hsReplayUploadToken {
handle(token)
return
}
let http = Http(url: "\(HSReplay.tokensUrl)/")
http.json(method: .post,
parameters: ["api_token": apiKey],
headers: ["X-Api-Key": apiKey]) { json in
if let json = json as? [String: Any],
let key = json["key"] as? String {
logger.info("HSReplay : Obtained new upload-token")
Settings.hsReplayUploadToken = key
handle(key)
} else {
logger.error("Failed to obtain upload token")
handle("failed-token")
}
}
}
static func claimBattleTag(account_hi: Int, account_lo: Int, battleTag: String) -> Promise<ClaimBlizzardAccountResponse> {
return Promise<ClaimBlizzardAccountResponse> { seal in
oauthswift.startAuthorizedRequest("\(HSReplay.claimBattleTagUrl)/\(account_hi)/\(account_lo)/", method: .POST,
parameters: ["battletag": battleTag], headers: defaultHeaders,
onTokenRenewal: tokenRenewalHandler,
completionHandler: { result in
switch result {
case .success:
seal.fulfill(.success)
case .failure(let error):
logger.error(error)
if error.description.contains("account_already_claimed") {
seal.fulfill(.tokenAlreadyClaimed)
} else {
seal.fulfill(.error)
}
}
}
)
}
}
static func claimAccount() {
guard let token = Settings.hsReplayUploadToken else {
logger.error("Authorization token not set yet")
return
}
logger.info("Getting claim url...")
let http = Http(url: HSReplay.claimAccountUrl)
http.json(method: .post,
headers: [
"X-Api-Key": apiKey,
"Authorization": "Token \(token)"]) { json in
if let json = json as? [String: Any],
let url = json["url"] as? String {
logger.info("Opening browser to claim account...")
let url = URL(string: "\(HSReplay.baseUrl)\(url)")
NSWorkspace.shared.open(url!)
} else {
}
}
}
static func updateAccountStatus(handle: @escaping (Bool) -> Void) {
guard let token = Settings.hsReplayUploadToken else {
logger.error("Authorization token not set yet")
handle(false)
return
}
logger.info("Checking account status...")
let http = Http(url: "\(HSReplay.tokensUrl)/\(token)/")
http.json(method: .get,
headers: [
"X-Api-Key": apiKey,
"Authorization": "Token \(token)"
]) { json in
if let json = json as? [String: Any],
let user = json["user"] as? [String: Any] {
if let username = user["username"] as? String {
Settings.hsReplayUsername = username
}
Settings.hsReplayId = user["id"] as? Int ?? 0
logger.info("id=\(String(describing: Settings.hsReplayId)), Username=\(String(describing: Settings.hsReplayUsername))")
handle(true)
} else {
handle(false)
}
}
}
private static func getUploadCollectionToken() -> Promise<String> {
return Promise<String> { seal in
guard let accountId = MirrorHelper.getAccountId() else {
seal.reject(HSReplayError.missingAccount)
return
}
oauthswift.startAuthorizedRequest("\(HSReplay.collectionTokensUrl)", method: .GET, parameters: ["account_hi": accountId.hi, "account_lo": accountId.lo], headers: defaultHeaders, onTokenRenewal: tokenRenewalHandler,
completionHandler: { result in
switch result {
case .success(let response):
do {
guard let json = try response.jsonObject() as? [String: Any], let token = json["url"] as? String else {
logger.error("HSReplay: Unexpected JSON \(String(describing: response.string))")
seal.reject(HSReplayError.collectionUploadMissingURL)
return
}
logger.info("HSReplay: obtained new collection upload json: \(json)")
seal.fulfill(token)
} catch {
seal.reject(HSReplayError.missingAccount)
}
case .failure(let error):
logger.error(error)
seal.reject(HSReplayError.authorizationTokenNotSet)
}
})
}
}
private static func uploadCollectionInternal(collectionData: UploadCollectionData, url: String, seal: Resolver<CollectionUploadResult>) {
let upload = Http(url: url)
let enc = JSONEncoder()
if let data = try? enc.encode(collectionData) {
upload.uploadPromise(method: .put, headers: [ "Content-Type": "application/json" ], data: data).done { data in
if data != nil {
seal.fulfill(.successful)
}
}.catch { error in
seal.fulfill(.failed(error: error.localizedDescription))
}
} else {
seal.fulfill(.failed(error: "JSON convertion failed"))
}
}
static func uploadCollection(collectionData: UploadCollectionData) -> Promise<CollectionUploadResult> {
return Promise<CollectionUploadResult> { seal in
guard let accountId = MirrorHelper.getAccountId() else {
seal.reject(HSReplayError.missingAccount)
return
}
let hi = accountId.hi.intValue
let lo = accountId.lo.intValue
if !(accountData?.blizzard_accounts.any({ x in x.account_hi == hi && x.account_lo == lo }) ?? false) {
if let battleTag = MirrorHelper.getBattleTag() {
HSReplayAPI.claimBattleTag(account_hi: hi, account_lo: lo, battleTag: battleTag).done { result in
switch result {
case .success:
logger.info("Successfully claimed battletag \(battleTag)")
getAccount().done { result in
switch result {
case .success(account: let data):
self.accountData = data
case .failed:
logger.debug("Failed to update account data")
}
}.catch { error in
seal.reject(error)
}
getUploadCollectionToken().done { url in
uploadCollectionInternal(collectionData: collectionData, url: url, seal: seal)
}.catch { error in
seal.reject(error)
}
case .tokenAlreadyClaimed:
let message = "Your blizzard account (\(battleTag), \(hi)-\(lo)) is already attached to another HSReplay.net Account. You are currently logged in as \(accountData?.username ?? ""). Please contact us at [email protected] if this is not correct."
logger.error(message)
seal.fulfill(.failed(error: message))
case .error:
let message = "Could not attach your Blizzard account (\(battleTag), \(hi)-\(lo)) to HSReplay.net Account (\(accountData?.username ?? "")). Please try again later or contact us at [email protected] if this persists."
seal.fulfill(.failed(error: message))
}
}.catch { error in
logger.error(error)
seal.reject(HSReplayError.genericError(message: error.localizedDescription))
}
} else {
seal.reject(HSReplayError.missingAccount)
}
} else {
getUploadCollectionToken().done { url in
uploadCollectionInternal(collectionData: collectionData, url: url, seal: seal)
}.catch { error in
logger.error(error)
seal.reject(HSReplayError.genericError(message: error.localizedDescription))
}
}
}
}
private static func parseAccountData(data: Data) -> AccountData? {
let decoder = JSONDecoder()
do {
let ad = try decoder.decode(AccountData.self, from: data)
return ad
} catch let error {
logger.error("Failed to parse account response: \(error)")
return nil
}
}
static func getAccount() -> Promise<GetAccountResult> {
return Promise<GetAccountResult> { seal in
oauthswift.startAuthorizedRequest("\(HSReplay.accountUrl)", method: .GET, parameters: [:], headers: defaultHeaders, onTokenRenewal: tokenRenewalHandler, completionHandler: { result in
switch result {
case .success(let response):
if let ad = parseAccountData(data: response.data) {
accountData = ad
seal.fulfill(.success(account: ad))
} else {
accountData = nil
seal.fulfill(.failed)
}
case .failure(let error):
accountData = nil
logger.error(error)
seal.fulfill(.failed)
}
})
}
}
}
| 44.788779 | 275 | 0.502174 |
0aa7dcb9b32cb0a91410a5d0fe8218e5a49811c6 | 1,812 | // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import MaterialComponents.MaterialFlexibleHeader
import MaterialComponents.MaterialFlexibleHeader_ColorThemer
class FlexibleHeaderColorThemerTests: XCTestCase {
func testColorThemerChangesTheBackgroundColor() {
// Given
let colorScheme = MDCSemanticColorScheme()
let flexibleHeaderView = MDCFlexibleHeaderView()
colorScheme.primaryColor = .red
flexibleHeaderView.backgroundColor = .white
// When
MDCFlexibleHeaderColorThemer.applySemanticColorScheme(colorScheme, to: flexibleHeaderView)
// Then
XCTAssertEqual(flexibleHeaderView.backgroundColor, colorScheme.primaryColor)
}
func testSurfaceVariantColorThemerChangesTheBackgroundColor() {
// Given
let colorScheme = MDCSemanticColorScheme()
let flexibleHeaderView = MDCFlexibleHeaderView()
colorScheme.surfaceColor = .red
flexibleHeaderView.backgroundColor = .white
// When
MDCFlexibleHeaderColorThemer.applySurfaceVariant(withColorScheme: colorScheme,
to: flexibleHeaderView)
// Then
XCTAssertEqual(flexibleHeaderView.backgroundColor, colorScheme.surfaceColor)
}
}
| 36.24 | 94 | 0.759382 |
225b83732b22fda1b0d9b27993e436426f9dc733 | 5,888 | //
// LeaveThreadCallbacks.swift
// FanapPodChatSDK
//
// Created by Mahyar Zhiani on 3/18/1398 AP.
// Copyright © 1398 Mahyar Zhiani. All rights reserved.
//
import Foundation
import SwiftyJSON
import SwiftyBeaver
import FanapPodAsyncSDK
extension Chat {
/// LeaveThread Response comes from server
///
/// - Outputs:
/// - it doesn't have direct output,
/// - but on the situation where the response is valid,
/// - it will call the "onResultCallback" callback to leaveThread function (by using "leaveThreadCallbackToUser")
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
func responseOfLeaveThread(withMessage message: ChatMessage) {
log.verbose("Message of type 'LEAVE_THREAD' recieved", context: "Chat")
let returnData = CreateReturnData(hasError: false,
errorMessage: "",
errorCode: 0,
result: message.content?.convertToJSON() ?? [:],
resultAsArray: nil,
resultAsString: nil,
contentCount: message.contentCount,
subjectId: message.subjectId)
let leaveThreadModel = ThreadResponse(messageContent: message.content?.convertToJSON() ?? [:],
hasError: false,
errorMessage: "",
errorCode: 0)
let tLeaveEM = ThreadEventModel(type: ThreadEventTypes.THREAD_LEAVE_PARTICIPANT,
participants: leaveThreadModel.thread?.participants,
threads: nil,
threadId: message.subjectId,
senderId: nil,
unreadCount: message.content?.convertToJSON()["unreadCount"].int,
pinMessage: nil)
delegate?.threadEvents(model: tLeaveEM)
let tLastActivityEM = ThreadEventModel(type: ThreadEventTypes.THREAD_LAST_ACTIVITY_TIME,
participants: nil,
threads: nil,
threadId: message.subjectId,
senderId: nil,
unreadCount: message.content?.convertToJSON()["unreadCount"].int,
pinMessage: nil)
delegate?.threadEvents(model: tLastActivityEM)
if enableCache {
if let threadJSON = message.content?.convertToJSON() {
let conversation = Conversation(messageContent: threadJSON)
if let _ = conversation.title {
var participantIds = [Int]()
for participant in conversation.participants ?? [] {
let myParticipant = Participant(messageContent: participant.formatToJSON(), threadId: message.subjectId)
participantIds.append(myParticipant.id!)
}
Chat.cacheDB.deleteParticipant(inThread: message.subjectId!, withParticipantIds: participantIds)
} else {
Chat.cacheDB.deleteThreads(withThreadIds: [conversation.id!])
}
}
}
if Chat.map[message.uniqueId] != nil {
let callback: CallbackProtocol = Chat.map[message.uniqueId]!
callback.onResultCallback(uID: message.uniqueId,
response: returnData,
success: { (successJSON) in
self.leaveThreadCallbackToUser?(successJSON)
}) { _ in }
Chat.map.removeValue(forKey: message.uniqueId)
} else if (Chat.spamMap[message.uniqueId] != nil) {
let callback: CallbackProtocol = Chat.spamMap[message.uniqueId]!.first!
callback.onResultCallback(uID: message.uniqueId,
response: returnData,
success: { (successJSON) in
self.spamPvThreadCallbackToUser?(successJSON)
}) { _ in }
Chat.spamMap[message.uniqueId]?.removeFirst()
if (Chat.spamMap[message.uniqueId]!.count < 1) {
Chat.spamMap.removeValue(forKey: message.uniqueId)
}
}
}
@available(*,deprecated , message:"Removed in 0.10.5.0 version")
public class LeaveThreadCallbacks: CallbackProtocol {
func onResultCallback(uID: String,
response: CreateReturnData,
success: @escaping callbackTypeAlias,
failure: @escaping callbackTypeAlias) {
log.verbose("LeaveThreadCallbacks", context: "Chat")
if let content = response.result {
let leaveThreadModel = ThreadResponse(messageContent: content,
hasError: response.hasError,
errorMessage: response.errorMessage,
errorCode: response.errorCode)
success(leaveThreadModel)
}
}
}
}
| 49.898305 | 128 | 0.476393 |
e83fcce1a0ffa90e73c8e8bc2972783c4108e651 | 19,665 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Transfer {
/// Lists the details for all the accesses you have on your server.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listAccessesPaginator<Result>(
_ input: ListAccessesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListAccessesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listAccesses,
inputKey: \ListAccessesRequest.nextToken,
outputKey: \ListAccessesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listAccessesPaginator(
_ input: ListAccessesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListAccessesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listAccesses,
inputKey: \ListAccessesRequest.nextToken,
outputKey: \ListAccessesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists all executions for the specified workflow.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listExecutionsPaginator<Result>(
_ input: ListExecutionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListExecutionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listExecutions,
inputKey: \ListExecutionsRequest.nextToken,
outputKey: \ListExecutionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listExecutionsPaginator(
_ input: ListExecutionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListExecutionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listExecutions,
inputKey: \ListExecutionsRequest.nextToken,
outputKey: \ListExecutionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the security policies that are attached to your file transfer protocol-enabled servers.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listSecurityPoliciesPaginator<Result>(
_ input: ListSecurityPoliciesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListSecurityPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listSecurityPolicies,
inputKey: \ListSecurityPoliciesRequest.nextToken,
outputKey: \ListSecurityPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listSecurityPoliciesPaginator(
_ input: ListSecurityPoliciesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListSecurityPoliciesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listSecurityPolicies,
inputKey: \ListSecurityPoliciesRequest.nextToken,
outputKey: \ListSecurityPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the file transfer protocol-enabled servers that are associated with your Amazon Web Services account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listServersPaginator<Result>(
_ input: ListServersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListServersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listServers,
inputKey: \ListServersRequest.nextToken,
outputKey: \ListServersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listServersPaginator(
_ input: ListServersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListServersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listServers,
inputKey: \ListServersRequest.nextToken,
outputKey: \ListServersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists all of the tags associated with the Amazon Resource Name (ARN) that you specify. The resource can be a user, server, or role.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTagsForResourcePaginator<Result>(
_ input: ListTagsForResourceRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTagsForResource,
inputKey: \ListTagsForResourceRequest.nextToken,
outputKey: \ListTagsForResourceResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTagsForResourcePaginator(
_ input: ListTagsForResourceRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTagsForResource,
inputKey: \ListTagsForResourceRequest.nextToken,
outputKey: \ListTagsForResourceResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the users for a file transfer protocol-enabled server that you specify by passing the ServerId parameter.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listUsersPaginator<Result>(
_ input: ListUsersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListUsersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listUsers,
inputKey: \ListUsersRequest.nextToken,
outputKey: \ListUsersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listUsersPaginator(
_ input: ListUsersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListUsersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listUsers,
inputKey: \ListUsersRequest.nextToken,
outputKey: \ListUsersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists all of your workflows.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listWorkflowsPaginator<Result>(
_ input: ListWorkflowsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListWorkflowsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listWorkflows,
inputKey: \ListWorkflowsRequest.nextToken,
outputKey: \ListWorkflowsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listWorkflowsPaginator(
_ input: ListWorkflowsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListWorkflowsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listWorkflows,
inputKey: \ListWorkflowsRequest.nextToken,
outputKey: \ListWorkflowsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension Transfer.ListAccessesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListAccessesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
serverId: self.serverId
)
}
}
extension Transfer.ListExecutionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListExecutionsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
workflowId: self.workflowId
)
}
}
extension Transfer.ListSecurityPoliciesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListSecurityPoliciesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Transfer.ListServersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListServersRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Transfer.ListTagsForResourceRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListTagsForResourceRequest {
return .init(
arn: self.arn,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Transfer.ListUsersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListUsersRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
serverId: self.serverId
)
}
}
extension Transfer.ListWorkflowsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Transfer.ListWorkflowsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| 42.657267 | 168 | 0.642766 |
67c3273b8491c02304033f5e5f661ae81c4acf33 | 225 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import SwiftUI
@main
struct OrtBasicUsageApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 16.071429 | 60 | 0.68 |
d6498295643954b654a37c8a4424d841dd9906f7 | 501 | //
// ViewController.swift
// SunnyFPS
//
// Created by jiazhaoyang on 16/2/15.
// Copyright © 2016年 gitpark. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.269231 | 80 | 0.668663 |
f4712ffcb11fb3651212df00f8ee3e003fe6255c | 4,136 | //
// MovieListViewControllerViewModel.swift
// MoviePlayerDemo
//
// Created by Malti Maurya on 08/01/21.
// Copyright © 2021 Malti Maurya. All rights reserved.
//
import Foundation
import Alamofire
import CoreData
protocol MovieListViewControllerViewModelProtocol {
var alertMessage: Dynamic<AlertMessage> { get set }
var response: Dynamic<MoviesResponse?> { get set }
func serviceRequest(apiName : EndPointType)
func failTest()
}
class MovieListViewControllerViewModel: NSObject, MovieListViewControllerViewModelProtocol {
// MARK: - Vars & Lets
var alertMessage: Dynamic<AlertMessage> = Dynamic(AlertMessage(title: "", body: ""))
var response: Dynamic<MoviesResponse?> = Dynamic(nil)
private let apiManager = Apimanager(sessionManager: SessionManager(), retrier: APIManagerRetrier())
let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
var context:NSManagedObjectContext!
// MARK: - Public methods
func serviceRequest(apiName : EndPointType) {
self.apiManager.call(type: apiName){(res: Result<MoviesResponse?>) in
switch res
{
case .success(let response):
self.response.value = response
self.openDatabse(movieObj: response!)
break
case .failure(let message):
self.alertMessage.value = message as! AlertMessage
break
}
}
}
func failTest() {
self.apiManager.call(type: RequestItemsType.fail) { (res:Result<[String : Any]>) in
switch res {
case .success(let response):
print(response)
break
case .failure(let message):
print(message.localizedDescription)
self.alertMessage.value = message as! AlertMessage
break
}
}
}
// MARK: Methods to Open, Store and Fetch data
func openDatabse(movieObj:MoviesResponse)
{
context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "MovieList", in: context)
let movieList = NSManagedObject(entity: entity!, insertInto: context)
for index in 0 ..< movieObj.results.count
{
let movie = movieObj.results[index]
saveData(MovieDBObj:movieList, movieData: movie)
}
}
func saveData(MovieDBObj:NSManagedObject,movieData : Movie )
{
MovieDBObj.setValue(movieData.id, forKey: "id")
MovieDBObj.setValue(movieData.adult, forKey: "adult")
MovieDBObj.setValue(movieData.backdropPath, forKey: "backdrop_path")
MovieDBObj.setValue(movieData.overview, forKey: "overview")
MovieDBObj.setValue(movieData.posterPath, forKey: "poster_path")
MovieDBObj.setValue(movieData.title, forKey: "title")
MovieDBObj.setValue(movieData.voteAverage, forKey: "vote_average")
MovieDBObj.setValue(movieData.voteCount, forKey: "vote_count")
print("Storing Data..")
do {
try context.save()
} catch {
print("Storing data Failed")
}
fetchData()
}
func fetchData()
{
print("Fetching Data..")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MovieList")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let title = data.value(forKey: "title") as! String
let overview = data.value(forKey: "overview") as! String
print("Movie Name is : "+title+" and overview is : "+overview)
}
} catch {
print("Fetching data Failed")
}
}
// MARK: - Init
override init() {
super.init()
}
}
| 31.815385 | 103 | 0.589217 |
21aacde4cf4e6c7d9d0f48e0d7a6555165775f95 | 2,761 | //
// SceneDelegate.swift
// GuessTheFlag
//
// Created by Nikolay Volosatov on 10/13/19.
// Copyright © 2019 BX23. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.476923 | 147 | 0.706266 |
50dbeecce8b9f945743df3b1bd6bd80cca26c4a5 | 2,160 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
extension SFSymbol {
public static var homepod: Homepod { .init(name: "homepod") }
open class Homepod: SFSymbol {
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var _2: SFSymbol { ext(.start + ".2") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var _2Fill: SFSymbol { ext(.start + ".2".fill) }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var andAppletv: SFSymbol { ext(.start + ".and.appletv") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var andAppletvFill: SFSymbol { ext(.start + ".and.appletv".fill) }
@available(iOS 14.5, macOS 11.3, tvOS 14.5, watchOS 7.4, *)
open var andHomepodmini: SFSymbol { ext(.start + ".and.homepodmini") }
@available(iOS 14.5, macOS 11.3, tvOS 14.5, watchOS 7.4, *)
open var andHomepodminiFill: SFSymbol { ext(.start + ".and.homepodmini".fill) }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var fill: SFSymbol { ext(.start.fill) }
}
} | 48 | 81 | 0.711574 |
1675804157f9ed2f5013d386763ed3eaa7aa1977 | 948 | //
// Model.swift
// tmdb
//
// Created by Sunil Targe on 2021/9/25.
//
import Foundation
// response model
struct Response: Codable {
var page: Int
var results: [Movie]
var total_pages: Int
var total_results: Int
}
// movie model
struct Movie: Codable {
let title: String
let original_title: String
let id: Int
let overview: String
let release_date: String
let original_language: String
let popularity: Double
let vote_count: Double
let vote_average: Double
// optional
let poster_path: String?
let backdrop_path: String?
let genres: [Genre]?
let runtime: Double?
let tagline: String?
let homepage: String?
let status: String?
let production_countries: [Country]?
}
// genre model
struct Genre: Codable {
let id: Int
let name: String
}
// production country model
struct Country: Codable {
let iso_3166_1: String
let name: String
}
| 17.555556 | 40 | 0.664557 |
dd9e4131d2a98e919e8752f287f28b6b90f9296a | 1,009 | //
// EngineFuelRate.swift
// OBD II wifi
//
// Created by Lucas Bicca on 11/11/17.
// Copyright © 2017 MacBook Pro. All rights reserved.
//
import Foundation
open class EngineFuelRateUtil {
open class func formatResult(result: String) throws -> String {
if (ResultUtil.hasNoData(result: result) || ResultUtil.isUnableToConnect(result: result)) {
return "-"
}
let stringArray = result.components(separatedBy: " ")
if (stringArray.count < 4) {
throw CommandError.indexError
}
let firstByte = stringArray[2]
let secondByte = stringArray[3]
guard let firstDecimal = UInt(firstByte, radix: 16), firstByte.count > 0 else {
return "-"
}
guard let secondDecimal = UInt(secondByte, radix: 16), secondByte.count > 0 else {
return "-"
}
let calculation = ((256 * firstDecimal) + secondDecimal) / 20
return "\(calculation) L/h"
}
}
| 29.676471 | 99 | 0.591675 |
e0036e72485885a491de5ffba66b8df5826dd93f | 7,732 | //
// ScanViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-12-12.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
import AVFoundation
typealias ScanCompletion = (PaymentRequest?) -> Void
typealias KeyScanCompletion = (String) -> Void
class ScanViewController : UIViewController, Trackable {
static func presentCameraUnavailableAlert(fromRoot: UIViewController) {
let alertController = UIAlertController(title: S.Send.cameraUnavailableTitle, message: S.Send.cameraUnavailableMessage, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: S.Button.settings, style: .`default`, handler: { _ in
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}))
fromRoot.present(alertController, animated: true, completion: nil)
}
static var isCameraAllowed: Bool {
return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) != .denied
}
let completion: ScanCompletion?
let scanKeyCompletion: KeyScanCompletion?
let isValidURI: (String) -> Bool
fileprivate let guide = CameraGuideView()
fileprivate let session = AVCaptureSession()
private let toolbar = UIView()
private let close = UIButton.close
private let flash = UIButton.icon(image: #imageLiteral(resourceName: "Flash"), accessibilityLabel: S.Scanner.flashButtonLabel)
fileprivate var currentUri = ""
init(completion: @escaping ScanCompletion, isValidURI: @escaping (String) -> Bool) {
self.completion = completion
self.scanKeyCompletion = nil
self.isValidURI = isValidURI
super.init(nibName: nil, bundle: nil)
}
init(scanKeyCompletion: @escaping KeyScanCompletion, isValidURI: @escaping (String) -> Bool) {
self.scanKeyCompletion = scanKeyCompletion
self.completion = nil
self.isValidURI = isValidURI
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
view.backgroundColor = .black
toolbar.backgroundColor = .black
flash.tintColor = .white
close.tintColor = .gradientStart
view.addSubview(toolbar)
toolbar.addSubview(close)
toolbar.addSubview(flash)
view.addSubview(guide)
toolbar.constrainBottomCorners(sidePadding: 0, bottomPadding: 0)
toolbar.constrain([
toolbar.constraint(.height, constant: 70.0) ])
close.constrain([
close.constraint(.leading, toView: toolbar),
close.constraint(.top, toView: toolbar, constant: 3.0),
close.constraint(.bottom, toView: toolbar, constant: -3.0),
close.constraint(.width, constant: 64.0) ])
flash.constrain([
flash.constraint(.trailing, toView: toolbar),
flash.constraint(.top, toView: toolbar, constant: 3.0),
flash.constraint(.bottom, toView: toolbar, constant: -3.0),
flash.constraint(.width, constant: 64.0) ])
guide.constrain([
guide.constraint(.leading, toView: view, constant: C.padding[6]),
guide.constraint(.trailing, toView: view, constant: -C.padding[6]),
guide.constraint(.centerY, toView: view),
NSLayoutConstraint(item: guide, attribute: .width, relatedBy: .equal, toItem: guide, attribute: .height, multiplier: 1.0, constant: 0.0) ])
guide.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
close.tap = { [weak self] in
self?.saveEvent("scan.dismiss")
self?.dismiss(animated: true, completion: {
self?.completion?(nil)
})
}
addCameraPreview()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.spring(0.8, animations: {
self.guide.transform = .identity
}, completion: { _ in })
}
private func addCameraPreview() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
guard let input = try? AVCaptureDeviceInput(device: device) else { return }
session.addInput(input)
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, at: 0)
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: .main)
session.addOutput(output)
if output.availableMetadataObjectTypes.contains(where: { objectType in
return objectType == AVMetadataObject.ObjectType.qr
}) {
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
} else {
print("no qr code support")
}
DispatchQueue(label: "qrscanner").async {
self.session.startRunning()
}
if device.hasTorch {
flash.tap = { [weak self] in
do {
try device.lockForConfiguration()
device.torchMode = device.torchMode == .on ? .off : .on
device.unlockForConfiguration()
if device.torchMode == .on {
self?.saveEvent("scan.torchOn")
} else {
self?.saveEvent("scan.torchOn")
}
} catch let error {
print("Camera Torch error: \(error)")
}
}
}
}
override var prefersStatusBarHidden: Bool {
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ScanViewController : AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if let data = metadataObjects as? [AVMetadataMachineReadableCodeObject] {
if data.count == 0 {
guide.state = .normal
} else {
data.forEach {
guard let uri = $0.stringValue else { return }
if completion != nil {
handleURI(uri)
} else if scanKeyCompletion != nil {
handleKey(uri)
}
}
}
}
}
func handleURI(_ uri: String) {
if self.currentUri != uri {
self.currentUri = uri
if let paymentRequest = PaymentRequest(string: uri) {
saveEvent("scan.bitcoinUri")
guide.state = .positive
//Add a small delay so the green guide will be seen
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
self.dismiss(animated: true, completion: {
self.completion?(paymentRequest)
})
})
} else {
guide.state = .negative
}
}
}
func handleKey(_ address: String) {
if isValidURI(address) {
saveEvent("scan.privateKey")
guide.state = .positive
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
self.dismiss(animated: true, completion: {
self.scanKeyCompletion?(address)
})
})
} else {
guide.state = .negative
}
}
}
| 36.995215 | 152 | 0.595577 |
e673a0aa774609b4664ba2f13027e8b724bc1de3 | 763 | import UIKit
import XCTest
import MensamaticSMS
class Tests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.433333 | 111 | 0.606815 |
09c49ccb0ec0ceb5d025564c162db1533184b054 | 1,148 | //
// AppError.swift
// Unit 3 assessment
//
// Created by Pursuit on 12/19/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import Foundation
enum AppError: Error, CustomStringConvertible {
case badURL(String) // associated value
case noResponse
case networkClientError(Error) // no internet connection
case noData
case decodingError(Error)
case encodingError(Error)
case badStatusCode(Int) // 404, 500
case badMimeType(String) // image/jpg
var description: String {
switch self {
case .decodingError(let error):
return "\(error)"
case .badStatusCode(let code):
return "Bad status code of \(code) returned from web api"
case .encodingError(let error):
return "encoding error: \(error)"
case .networkClientError(let error):
return "network error: \(error)"
case .badURL(let url):
return "\(url) is a bad url"
case .noData:
return "no data returned from web api"
case .noResponse:
return "no response returned from web api"
case .badMimeType(let mimeType):
return "Verify your mime type found a \(mimeType) mime type"
}
}
}
| 27.333333 | 66 | 0.675087 |
11ed892e70733e5bb2479562beb221e24743df49 | 1,094 | //
// CategoryCollectionViewCell.swift
// 020g
//
// Created by Юрий Истомин on 01/10/2018.
// Copyright © 2018 Юрий Истомин. All rights reserved.
//
import UIKit
class CategoryCollectionViewCell: UICollectionViewCell {
let catalogCollectionView = CatalogCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
override init(frame: CGRect) {
super.init(frame: frame)
addCatalogCollectionView()
setCataloCollectionViewConstraints()
}
private func addCatalogCollectionView() {
addSubview(catalogCollectionView)
}
private func setCataloCollectionViewConstraints() {
catalogCollectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
catalogCollectionView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
catalogCollectionView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
catalogCollectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 29.567568 | 117 | 0.763254 |
187b5e235d9e1c08c33276b8bfe6dde396696837 | 723 | //
// SignupPresenterTests.swift
// unit-testTests
//
// Created by Ted on 2021/04/19.
//
import XCTest
@testable import unit_test
class SignupPresenterTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testSignupPresenter_WhenInformationProvided_WillValidateEachProperty() {
// Arrange
let signupFormModel = SignupFormModel()
// Act
// Assert
}
}
| 22.59375 | 111 | 0.661134 |
33b4bafff6d0d9a7b02971284bced9615c295f0c | 11,742 | //
// ViewController.swift
// TAPKit-Example
//
// Created by Shahar Biran on 08/04/2018.
// Copyright © 2018 Shahar Biran. All rights reserved.
//
import UIKit
import TAPKit
class ViewController: UIViewController {
@IBOutlet weak var mouse: UIImageView!
private var devCount = 0
private var imuCount = 0;
override func viewDidLoad() {
super.viewDidLoad()
// Any class that wish to get taps related callbacks, must add itself as a delegate:
TAPKit.sharedKit.addDelegate(self)
// You can enable/disable logs for specific events, or all events
// TAPKitLogEvent.error, TAPKitLogEvent.fatal, TAPKitLogEvent.info, TAPKitLogEvent.warning
// For example, to enable only errors logs:
// TAPKit.log.enable(event: .error)
TAPKit.log.disable(event: .warning)
TAPKit.log.enableAllEvents()
// start should be called typically in the main screen, after the delegate was being set earlier.
TAPKit.sharedKit.start()
// At any point of your app, you may get the connected taps:
// result is a dictionary format of [identifier:name]
// let taps = TAPKit.sharedKit.getConnectedTaps()
// Tap Input mode:
// ---------------
// TAPInputMode.controller()
// allows receiving the "tapped" and "moused" funcs callback in TAPKitDelegate with the fingers combination without any post-processing.
//
// TAPInputMode.text()
// "tapped" and "moused" funcs in TAPKitDelegate will not be called, the TAP device will be acted as a plain bluetooth keyboard.
//
// TAPInputMode.controllerWithMouseHID() -
// Same as controller mode but allows the user to use the mouse also as a regular mouse input.
// Starting iOS 13, Apple added Assitive Touch feature. (Can be toggled within accessibility settings on iPhone).
// This adds a cursor to the screen that can be navigated using TAP device.
//
// TAPInputMode.rawSensor(sensitivity: TAPRawSensorSensitivity(deviceAccelerometer: Int, imuGyro: Int, imuAccelerometer: Int))
// Sends sensor (Gyro and Accelerometers) data . callback function: rawSensorDataReceived. read the readme.md for more information about this mode.
//
// If you wish for a TAP device to enter text as part of your app, you'll need to set the mode to TAPInputMode.text(), and when you want to receive tap combination data,
// you'll need to set the mode to TAPInputMode.controller()
// Setting text mode:
// TAPKit.sharedKit.setTAPInputMode(TAPInputMode.text(), forIdentifiers: [tapidentifiers])
// tapidentifiers : array of identifiers of tap devices to set the mode to text. if nil - all taps devices connected to the iOS device will be set to text.
// Same for settings the mode to controller:
// TAPKit.sharedKit.setTAPInputMode(TAPInputMode.controller(), forIdentifiers: [tapIdentifiers])
// When [tapIdentifiers] is null or missing - the mode will be applied to ALL connected TAPs.
//
// Setting the default TAPInputMode for new TAPs that will be connected. (can be applied to current connected TAPs):
// TAPKit.sharedKit.setDefaultTAPInputMode(TAPInputMode..., immediate: true/false)
// "immediate" - When true, this mode will be applied to all currently connected TAPs.
// Air Gestures
// ------------
// TAP v2.0 devices adds Air Gestures features.
// These Air Gestures will be triggered in:
// func tapAirGestured(identifier: String, gesture: TAPAirGesture)
// Please refer to the enum TAPAirGesture to see the available gestures.
// Works in "controller" and "controllerWithMouseHID" modes.
// Another related callback event is:
// func tapChangedAirGesturesState(identifier: String, isInAirGesturesState: Bool)
// This event will be triggered when the TAP entering or leaving Air Gesture State.
// Send Haptic/Vibration to TAP devices.
// To make the TAP vibrate, to your specified array of durations, call:
// TAPKit.sharedKit.vibrate(durations: [hapticDuration, pauseDuration, hapticDuration, pauseDuration, ...], forIdentifiers: [tapIdentifiers])
// durations: An array of durations in the format of haptic, pause, haptic, pause ... You can specify up to 18 elements in this array. The rest will be ignored.
// Each array element is defined in milliseconds.
// When [tapIdentifiers] is null or missing - the mode will be applied to ALL connected TAPs.
// Example:
// TAPKit.sharedKit.vibrate(durations: [500,100,500])
// Will send two 500 milliseconds haptics with a 100 milliseconds pause in the middle.
}
override func viewWillDisappear(_ animated: Bool) {
TAPKit.sharedKit.removeDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : TAPKitDelegate {
func centralBluetoothState(poweredOn: Bool) {
// Do something if the bluetooth state is on or off.
}
func tapped(identifier: String, combination: UInt8) {
// Called when a user tap, only when the TAP device is in controller mode.
print("TAP \(identifier) tapped combination: \(combination)")
// Combination is a 8-bit unsigned number, between 1 and 31.
// It's binary form represents the fingers that are tapped.
// The LSB is thumb finger, the MSB (bit number 5) is the pinky finger.
// For example: if combination equls 3 - it's binary form is 00101,
// Which means that the thumb and the middle fingers are tapped.
// For your convenience, you can convert the binary format into fingers boolean array, while:
// fingers[0] indicates if the thumb is being tapped.
// fingers[1] indicates if the index finger is being tapped.
// fingers[2] indicates if the middle finger is being tapped.
// fingers[3] indicates if the ring finger is being tapped.
// fingers[4] indicates if the pinky finger is being tapped.
let fingers = TAPCombination.toFingers(combination)
// For printing :
var fingersString = ""
for i in 0..<fingers.count {
if fingers[i] {
fingersString.append(TAPCombination.fingerName(i) + " ")
}
}
print("---combination fingers : \(fingersString)")
}
func tapDisconnected(withIdentifier identifier: String) {
// TAP device disconnected
print("TAP \(identifier) disconnected.")
}
func tapConnected(withIdentifier identifier: String, name: String) {
// TAP device connected
// We recomend that you'll keep track of the taps' identifier, if you're developing a multiplayer game and you need to keep track of all the players,
// As multiple taps can be connected to the same iOS device.
print("TAP \(identifier), \(name) connected!")
}
func tapFailedToConnect(withIdentifier identifier: String, name: String) {
// TAP device failed to connect
print("TAP \(identifier), \(name) failed to connect!")
}
func moused(identifier: String, velocityX: Int16, velocityY: Int16, isMouse: Bool) {
// Added isMouse parameter:
// A boolean that determines if the TAP is really using the mouse (true) or is it a dummy mouse movement (false)
// Getting an event for when the Tap is using the mouse, called only when the Tap is in controller mode.
// Since iOS doesn't support mouse - You can implement it in your app using the parameters of this function.
// velocityX : get the amount of movement for X-axis.
// velocityY : get the amount of movement for Y-axis.
// Important:
// You may want to multiply/divide velocityX and velocityY by a constant number to your liking, in order to enhance the mouse movement to match your expectation in your app.
// So, basically, by multiplying/dividing the velocityX and velocityY by a constant you can implement a "mouse sensitivity" feature that will be used in your app.
// For example: if you have an object responding to mouse object, like written below, then muliplying the velocityX and velocityY by 2 will make the object move
// twice as fast.
// Example: Moving the mouse image :
if (isMouse) {
let newPoint = CGPoint(x: self.mouse.frame.origin.x + CGFloat(velocityX), y: self.mouse.frame.origin.y + CGFloat(velocityY))
var dx : CGFloat = 0
var dy : CGFloat = 0
if self.view.frame.contains(CGPoint(x: 0, y: newPoint.y)) {
dy = CGFloat(velocityY)
}
if self.view.frame.contains(CGPoint(x: newPoint.x, y: 0)) {
dx = CGFloat(velocityX)
}
mouse.frame = mouse.frame.offsetBy(dx: dx, dy: dy)
}
}
func rawSensorDataReceived(identifier: String, data: RawSensorData) {
//RawSensorData Object has a timestamp, type and an array points(x,y,z).
if (data.type == .Device) {
// Fingers accelerometer.
// Each point in array represents the accelerometer value of a finger (thumb, index, middle, ring, pinky).
if let thumb = data.getPoint(for: RawSensorData.iDEV_THUMB) {
print("Thumb accelerometer value: (\(thumb.x),\(thumb.y),\(thumb.z))")
}
// Etc... use indexes: RawSensorData.iDEV_THUMB, RawSensorData.iDEV_INDEX, RawSensorData.iDEV_MIDDLE, RawSensorData.iDEV_RING, RawSensorData.iDEV_PINKY
} else if (data.type == .IMU) {
// Refers to an additional accelerometer on the Thumb sensor and a Gyro (placed on the thumb unit as well).
if let gyro = data.getPoint(for: RawSensorData.iIMU_GYRO) {
print("IMU Gyro value: (\(gyro.x),\(gyro.y),\(gyro.z)")
}
// Etc... use indexes: RawSensorData.iIMU_GYRO, RawSensorData.iIMU_ACCELEROMETER
}
// -------------------------------------------------
// -- Please refer readme.md for more information --
// -------------------------------------------------
}
func tapAirGestured(identifier: String, gesture: TAPAirGesture) {
switch (gesture) {
case .OneFingerDown : print("Air Gestured: One Finger Down")
case .OneFingerLeft : print("Air Gestured: One Finger Left")
case .OneFingerUp : print("Air Gestured: One Finger Up")
case .OnefingerRight : print("Air Gestured: One Finger Right")
case .TwoFingersDown : print("Air Gestured: Two Fingers Down")
case .TwoFingersLeft : print("Air Gestured: Two Fingers Left")
case .TwoFingersUp : print("Air Gestured: Two Fingers Up")
case .TwoFingersRight : print("Air Gestured: Two Fingers Right")
case .IndexToThumbTouch : print("Air Gestured: Index finger tapping the Thumb")
case .MiddleToThumbTouch : print("Air Gestured: Middle finger tapping the Thumb")
}
}
func tapChangedAirGesturesState(identifier: String, isInAirGesturesState: Bool) {
print("Tap is in Air Gesture State: \(isInAirGesturesState)")
}
}
| 51.955752 | 183 | 0.638733 |
1d847aa049e8394dc3baff76b51d0f2f8b75a25c | 277 | //
// UserLocationConstants.swift
// MapBasics
//
// Created by Tim Ng on 1/15/19.
// Copyright © 2019 timothyng. All rights reserved.
//
import Foundation
struct UserLocationConstants {
static let Latitude: Double = 0.0
static let Longitude: Double = 0.0
}
| 17.3125 | 52 | 0.68231 |
7504b31321754ba35999a7ed5b871586d15a446f | 1,714 | //
// ScrollTransition.swift
// TPGHorizontalMenu
//
// Created by David Livadaru on 06/03/2017.
// Copyright © 2017 3Pillar Global. All rights reserved.
//
import Foundation
public class ScrollTransition: NSObject {
public enum Direction {
case left, right
}
/// The type of transition.
///
/// - scroll: sent while scrolling is performed.
/// - selection: sent when user selected an index.
public enum Kind {
case scroll, selection
}
/// Start index for transition.
public let fromIndex: Int
/// End index for transition.
public let toIndex: Int
/// Progress of the transition
public let progress: CGFloat
/// The kind of transition
public let kind: Kind
/// Direction of progress.
public var direction: Direction {
return (toIndex > fromIndex) ? .right : .left
}
public static let invalidIndex = Int.min
override public var debugDescription: String {
return "ScrollTransition: { fromIndex: \(fromIndex), toIndex: \(toIndex), progress: \(progress) }"
}
public init(fromIndex: Int = ScrollTransition.invalidIndex, toIndex: Int, progress: CGFloat = 0.0,
kind: Kind = .scroll) {
self.fromIndex = fromIndex
self.toIndex = toIndex
self.progress = progress
self.kind = kind
}
// MARK: Equatable
public override func isEqual(_ object: Any?) -> Bool {
guard let transition = object as? ScrollTransition else { return false }
guard self !== transition else { return true }
return self.fromIndex == transition.fromIndex && self.toIndex == transition.toIndex
}
}
| 28.098361 | 106 | 0.627771 |
6198d0de068a3276591563fb121a8d42bd2432f1 | 968 | // Copyright © 2017-2021 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import WalletCore
import XCTest
class XDCNetworkTests: XCTestCase {
// TODO: Check and finalize implementation
func testAddress() {
// TODO: Check and finalize implementation
let key = PrivateKey(data: Data(hexString: "__PRIVATE_KEY_DATA__")!)!
let pubkey = key.getPublicKeyEd25519()
let address = AnyAddress(publicKey: pubkey, coin: .xdcnetwork)
let addressFromString = AnyAddress(string: "__ADDRESS_DATA__", coin: .xdcnetwork)!
XCTAssertEqual(pubkey.data.hexString, "__EXPECTED_PUBKEY_DATA__")
XCTAssertEqual(address.description, addressFromString.description)
}
func testSign() {
// TODO: Create implementation
}
}
| 33.37931 | 90 | 0.713843 |
ef19511e44f69f9c3901321501419ff02ee1876f | 847 | //
// GetGroupsInCommon.swift
// tl2swift
//
// Generated automatically. Any changes will be lost!
// Based on TDLib 1.8.0-fa8feefe
// https://github.com/tdlib/td/tree/fa8feefe
//
import Foundation
/// Returns a list of common group chats with a given user. Chats are sorted by their type and creation date
public struct GetGroupsInCommon: Codable, Equatable {
/// The maximum number of chats to be returned; up to 100
public let limit: Int?
/// Chat identifier starting from which to return chats; use 0 for the first request
public let offsetChatId: Int64?
/// User identifier
public let userId: Int64?
public init(
limit: Int?,
offsetChatId: Int64?,
userId: Int64?
) {
self.limit = limit
self.offsetChatId = offsetChatId
self.userId = userId
}
}
| 22.891892 | 108 | 0.663518 |
21495b08596a6a50dff1fc379a4470036a0970d7 | 1,174 | //
// URLRequest+curlCommand.swift
// Figo
//
// Created by Christian König on 29.01.17.
// Copyright © 2017 figo GmbH. All rights reserved.
//
import Foundation
extension URLRequest {
var curlCommand: String {
var command = "curl -k"
if let method = self.httpMethod {
if method == "PUT" || method == "DELETE" {
command.append(" -X \(method)")
}
if method == "POST" || method == "PUT" || method == "DELETE" {
if let httpBody = self.httpBody {
var body = String(data: httpBody, encoding: .utf8)
body = body?.replacingOccurrences(of: "\"", with: "\\\"")
if let body = body {
command.append(" -d \"\(body)\"")
}
}
}
}
self.allHTTPHeaderFields?.forEach { (key: String, value: String) in
command.append(" -H \"\(key): \(value)\"")
}
command.append(" --compressed")
command.append(" \"\(self.url!.absoluteString)\"")
command.append(" | python -mjson.tool")
return command
}
}
| 30.102564 | 77 | 0.484668 |
e0e26f9c6c31bcb3fa83414d283416f0ab81a676 | 405 | //
// FileInfoCollection.swift
// Neon-Ios
//
// Created by Temp on 29/08/19.
// Copyright © 2019 Girnar. All rights reserved.
//
import Foundation
class FileInfoCollection {
static let sharedInstance = FileInfoCollection()
var fileInfo = [FileInfo]()
var imageTagArray = [ImageTagModel]()
var imageLocalPathSaved = NSCache<NSString, UIImage>()
private init(){}
}
| 19.285714 | 58 | 0.666667 |
bbb630d6ba6e19cbf92e26933c6a84beac8af52b | 718 | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import XCTest
class test_nodep: XCTestCase {
func testCompare() {
XCTAssertNotEqual(1, 2, "Pass")
}
}
| 29.916667 | 76 | 0.727019 |
72c0a3f780118cc2cf040cad6aaa2ed78e202555 | 2,218 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 BeagleSchema
final class ScreenController: UIViewController {
private let screen: Screen
private unowned let beagleController: BeagleScreenViewController
var layoutManager: LayoutManager?
init(
screen: Screen,
beagleController: BeagleScreenViewController
) {
self.screen = screen
self.beagleController = beagleController
super.init(nibName: nil, bundle: nil)
extendedLayoutIncludesOpaqueBars = true
layoutManager = LayoutManager(viewController: self, safeArea: screen.safeArea)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
public override func loadView() {
view = screen.toView(renderer: beagleController.renderer)
beagleController.configBindings()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layoutManager?.applyLayout()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let event = screen.screenAnalyticsEvent {
beagleController.dependencies.analytics?.trackEventOnScreenAppeared(event)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let event = screen.screenAnalyticsEvent {
beagleController.dependencies.analytics?.trackEventOnScreenDisappeared(event)
}
}
}
| 31.685714 | 89 | 0.68936 |
e224bc97b19bf87fc77d0d46b9cfbd3238e52fe7 | 1,407 | import UIKit
class MenuTableCell: UITableViewCell {
var label: UILabel!
var channelName: String {
get {
return label?.text ?? String()
}
set(name) {
label.text = name
}
}
var selectedBackgroundColor: UIColor {
return UIColor(red:0.969, green:0.902, blue:0.894, alpha:1)
}
var labelHighlightedTextColor: UIColor {
return UIColor(red:0.22, green:0.024, blue:0.016, alpha:1)
}
var labelTextColor: UIColor {
return UIColor(red:0.973, green:0.557, blue:0.502, alpha:1)
}
override func awakeFromNib() {
label = viewWithTag(200) as? UILabel
label.highlightedTextColor = labelHighlightedTextColor
label.textColor = labelTextColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if (selected) {
contentView.backgroundColor = selectedBackgroundColor
} else {
contentView.backgroundColor = nil
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if (highlighted) {
contentView.backgroundColor = selectedBackgroundColor
} else {
contentView.backgroundColor = nil
}
}
}
| 27.588235 | 71 | 0.602701 |
1812591974dda262e93f7dbd0a989ebedaf9a24b | 1,102 | import Foundation
public struct BinarySingletonIterator<B: BinarySliceRepresentable>: IteratorProtocol {
public typealias Element = BinarySingleton<B>
private var reader: BinaryReader
public init(_ binary: Binary) {
reader = binary.reader
}
public init(_ view: BinaryView) {
reader = view.reader
}
public mutating func next() -> Element? {
guard reader.hasNext(as: B.self) else { return nil }
return reader.next()
}
}
public struct BinarySliceIterator<B: BinarySliceRepresentable>: IteratorProtocol {
public typealias Element = BinarySlice<B>
private let stride: Int
private var reader: BinaryReader
public init(_ binary: Binary, count: Int) {
reader = binary.reader
stride = count
}
public init(_ view: BinaryView, count: Int) {
reader = view.reader
stride = count
}
public mutating func next() -> Element? {
guard reader.hasNext(stride, as: B.self) else { return nil }
return reader.next(stride)
}
}
| 24.488889 | 86 | 0.627042 |
ffd671f8b54598f97e0d61a752194aba2adfb537 | 718 | //
// CrossHelper.swift
// Qin
//
// Created by teenloong on 2022/2/10.
// Copyright © 2022 com.teenloong. All rights reserved.
//
import Foundation
#if canImport(AppKit)
import AppKit
public typealias CrossColor = NSColor
public typealias CrossImage = NSImage
public typealias CrossView = NSView
public typealias CrossViewRepresent = NSViewRepresent
public typealias CrossViewControllerRepresent = NSViewControllerRepresent
#endif
#if canImport(UIKit)
import UIKit
public typealias CrossColor = UIColor
public typealias CrossImage = UIImage
public typealias CrossView = UIView
public typealias CrossViewRepresent = UIViewRepresent
public typealias CrossViewControllerRepresent = UIViewControllerRepresent
#endif
| 27.615385 | 73 | 0.821727 |
292af83e8f8f4ce03f75b153db3c37a53dcf9541 | 962 | //
// PhotoLibrary.swift
// Pods-PrivacyHelper_Example
//
// Created by 张先生 on 2021/8/18.
//
import Foundation
import Photos
extension PrivacyHelper {
@objc open class func photoLibrary(_ authorized: @escaping () -> Void, unauthorized: @escaping () -> Void) {
let authorizationStatus = PHPhotoLibrary.authorizationStatus()
switch authorizationStatus {
case .notDetermined:
// 用户未做出选择, 开始申请相册权限
PHPhotoLibrary.requestAuthorization { (status) in
DispatchQueue.main.async {
if status == .authorized {
// 授权
authorized()
} else {
// 未授权
unauthorized()
}
}
}
case .authorized:
// 已授权
authorized()
default:
// 未授权
unauthorized()
}
}
}
| 26 | 112 | 0.481289 |
508f0a0ed2ea9540dd16682623e48e73ea29ce9d | 4,797 | //
// ProductDetailViewModal.swift
// nth Rewards
//
// Created by akshay on 11/12/19.
// Copyright © 2019 Deepak Tomar. All rights reserved.
//
import UIKit
protocol ProductDetailViewModalDelegate {
func onDidClick(atIndex : Int)
}
class ProductDetailViewModal: NSObject {
var showAlert : ((_ alertStr : String? , _ service : Services) ->())?
public var bindingProductDetailViewModel : ((_ data : Any , _ serviceType : Services) ->())?
public var updateCart : ((_ data : Any , _ serviceType : Services) ->())?
let productDetailArray = ["Description"]
let productDetailImageArray = ["offer_detail"]
var delegate : ProductDetailViewModalDelegate?
public func callCartDetailService(){
self.populateData(service: .cartDetail, params: [String : Any]())
}
public func callAddToCartService(withDic : [String:Any]){
self.populateData(service: .addtocart, params: withDic)
}
private func populateData(service:Services , params : [String:Any]){
NetworkManager.sharedInstance.callApiService(serviceType: service, parameters: params, successClosure: {(dictData, ResponseStatus) in
switch ResponseStatus {
case .fail:
self.showAlert?(dictData as? String , service)
break
case .sucess:
if service == .products{
self.handleProductDetailResponse(responseDict: dictData as! [String : Any])
}else if service == .addtocart {
self.handleAddToCartResponse(responseDict: dictData as! [String : Any])
}else if service == .cartDetail{
self.handleCartDetailResponse(responseDict: dictData as! [String : Any])
}
break
}
})
}
func handleProductDetailResponse(responseDict : [String : Any]){
do {
//Get JSON object from retrieved data string
let jsonData = try JSONSerialization.data(withJSONObject: responseDict)
let objDecoder = JSONDecoder()
let objUserInfo = try objDecoder.decode(OfferDetailModal.self, from: jsonData)
self.bindingProductDetailViewModel?(objUserInfo, .offers_detail)
}catch(let error){
print("JSON Parsing Error >> \(error)")
}
}
func handleCartDetailResponse(responseDict : [String : Any]){
do {
//Get JSON object from retrieved data string
let jsonData = try JSONSerialization.data(withJSONObject: responseDict)
let objDecoder = JSONDecoder()
let cartModalObj = try objDecoder.decode(AddToCardModal.self, from: jsonData)
self.updateCart?(cartModalObj,.cartDetail)
}
catch(let error){
print("JSON Parsing Error >> \(error)")
}
}
func handleAddToCartResponse(responseDict : [String : Any]){
do {
//Get JSON object from retrieved data string
let jsonData = try JSONSerialization.data(withJSONObject: responseDict)
let objDecoder = JSONDecoder()
let objUserInfo = try objDecoder.decode(AddToCardModal.self, from: jsonData)
self.bindingProductDetailViewModel?(objUserInfo,.addtocart)
}
catch(let error){
print("JSON Parsing Error >> \(error)")
}
}
}
extension ProductDetailViewModal : UITableViewDelegate , UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.productDetailArray.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OfferDetailTableViewCell", for: indexPath as IndexPath) as! OfferDetailTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.nameLabel.text = self.productDetailArray[indexPath.row]
cell.imgView.image = UIImage(named: productDetailImageArray[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
Utility.printLog(messge: "\(indexPath.row)")
delegate?.onDidClick(atIndex: indexPath.row)
}
}
| 33.082759 | 150 | 0.599541 |
28b63062b78a11b17abd37f912b613b26b1ea40c | 1,629 | //
// ResponseCodable.swift
//
//
// Created by BJ Miller on 7/9/20.
//
import Foundation
public protocol ResponseCodable: RequestEncodable & ResponseDecodable {}
public protocol RequestEncodable: Encodable {}
public protocol ResponseDecodable: Decodable {
/// sampleJSON used to supply json to decode into a sampleInstance()
static var sampleJSON: String { get }
/// decoder used to decode an instance of self from Data
static var decoder: JSONDecoder { get }
/// defaultValue used to provide a default value from a REST response if there was a failure parsing the response into self.
/// For instance, the server may return `{}`, but what you need is `{ "result": [] }`.
/// ResponseDecodable extension default implementation returns `nil`, as not many types may need to implement this.
static var defaultValue: Self? { get }
}
public extension ResponseDecodable {
static var sampleData: Data { sampleJSON.data(using: .utf8)! }
static var decoder: JSONDecoder { .defaultDecoder }
static func sampleInstance() -> Self? {
do {
let obj = try decoder.decode(Self.self, from: sampleData)
return obj
} catch {
print("Failed to parse sampleInstance for type: \(String(describing: Self.self))")
print("Error: \(error.localizedDescription)")
return nil
}
}
static var defaultValue: Self? { nil }
static func decode(from data: Data) -> Self? {
try? Self.decoder.decode(Self.self, from: data)
}
}
public extension RequestEncodable {
var encoder: JSONEncoder { .defaultEncoder }
func asData() -> Data? {
try? encoder.encode(self)
}
}
| 27.610169 | 126 | 0.696746 |
7207daf323151319e053b4091e08b49f27adabc3 | 1,170 | //
// BaseContract.swift
// SampleGit
//
// Created by Eda Nilay DAĞDEMİR on 18.01.2021.
// Copyright © 2021 Eda Nilay DAĞDEMİR. All rights reserved.
//
import UIKit
protocol IBaseView: class {
func showProgressHUD()
func hideProgressHUD()
func showErrorDialog(with message: String)
}
extension UIViewController: IBaseView {
func showProgressHUD() {
LoadingManager.shared.showLoadingProgress()
}
func hideProgressHUD() {
LoadingManager.shared.hideLoadingProgress()
}
func showErrorDialog(with message: String) {
let alert = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func getSpinnerView() -> UIView {
LoadingManager.shared.getSpinnerView()
}
}
protocol IBasePresenter: class {
func viewDidLoad()
}
protocol IBaseInteractorToPresenter: class {
func wsErrorOccurred(with message: String)
}
protocol IBaseAdapter: class {
func itemCount() -> Int
}
| 23.877551 | 120 | 0.703419 |
61f1dc88a4d1d4bb8e4da1ebebfec1184bcf2f02 | 779 | //
// SceneDelegate.swift
// Waveform
//
// Created by Damian Carrillo on 7/5/19.
// Copyright © 2019 Damian Carrillo. All rights reserved.
//
import UIKit
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard let windowScene = (scene as? UIWindowScene) else {
return
}
let navigationController = UINavigationController(
rootViewController: ViewController()
)
window = UIWindow(windowScene: windowScene)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
}
}
| 22.911765 | 64 | 0.661104 |
e92362843dc9a94bbcaa06338351ce191c1719b2 | 1,540 | //
// EligibilityRequestPurpose.swift
// Asclepius
// Module: R4
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
A code specifying the types of information being requested.
URL: http://hl7.org/fhir/eligibilityrequest-purpose
ValueSet: http://hl7.org/fhir/ValueSet/eligibilityrequest-purpose
*/
public enum EligibilityRequestPurpose: String, AsclepiusPrimitiveType {
/// The prior authorization requirements for the listed, or discovered if specified, converages for the categories
/// of service and/or specifed biling codes are requested.
case authRequirements = "auth-requirements"
/// The plan benefits and optionally benefits consumed for the listed, or discovered if specified, converages are
/// requested.
case benefits
/// The insurer is requested to report on any coverages which they are aware of in addition to any specifed.
case discovery
/// A check that the specified coverages are in-force is requested.
case validation
}
| 37.560976 | 116 | 0.746753 |
f84b591b4ef26e35997ac2ee8e85a3cb24c1fd4d | 8,985 | //
// Scheduler.swift
// Flow
//
// Created by Måns Bernhardt on 2015-09-30.
// Copyright © 2015 iZettle. All rights reserved.
//
import Foundation
/// Encapsulates how to asynchronously and synchronously scheduler work and allows comparing if two instances are representing the same scheduler.
public final class Scheduler {
private let identifyingObject: AnyObject
private let _async: (@escaping () -> Void) -> Void
private let _sync: (() -> Void) -> Void
/// Creates an instance that will use `async` for asynchrouns scheduling and `sync` for synchrouns scheduling.
/// - Parameter identifyingObject: Used to identify if two scheduler are the same using `===`.
public init(identifyingObject: AnyObject, async: @escaping (@escaping () -> Void) -> Void, sync: @escaping (() -> Void) -> Void) {
self.identifyingObject = identifyingObject
_async = async
_sync = sync
}
}
public extension Scheduler {
/// Asynchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
func async(execute work: @escaping () -> Void) {
guard !isImmediate else {
return work()
}
_async {
let state = threadState
assert(state.scheduler == nil)
state.scheduler = self
work()
state.scheduler = nil
}
}
/// Synchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
func sync<T>(execute work: () -> T) -> T {
guard !isImmediate else {
return work()
}
let state = threadState
state.syncScheduler = self
var result: T!
_sync {
result = work()
}
state.syncScheduler = nil
return result
}
/// Returns true if `async()` and `sync()` will execute work immediately and hence not be scheduled.
var isImmediate: Bool {
if (self == .main && Thread.isMainThread) || self == .none { return true }
let state = threadState
return self == state.scheduler || self == state.syncScheduler
}
/// Returns true if `self` is currently execute work
var isExecuting: Bool {
let state = threadState
return self == state.scheduler || (Thread.isMainThread && self == .main) || self == state.syncScheduler
}
/// Synchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
/// - Throws: If `work` throws.
func sync<T>(execute work: () throws -> T) throws -> T {
return try sync {
Result { try work() }
}.getValue()
}
/// Will asynchronously schedule `work` on `self` after `delay` seconds
func async(after delay: TimeInterval, execute work: @escaping () -> ()) {
return DispatchQueue.concurrentBackground.asyncAfter(deadline: DispatchTime.now() + delay) {
self.async(execute: work)
}
}
/// Will perform `work` in the context of `self` so that any scheduling on `self` while executing `work` will be called immediately.
/// This can be useful when working with APIs where you provide a queue
/// for the callback to be called on and you want remaining execution on the
/// same queue to be schedule immediately:
///
/// NotificationCenter.default.addObserver(forName: ..., queue: myQueue) { _ in
/// myScheduler.perform {
/// // Schedule e.g. signals or futures using `myScheduler`
/// }
/// }
func perform<T>(work: () throws -> T) rethrows -> T {
let state = threadState
state.syncScheduler = self
defer { state.syncScheduler = nil }
return try work()
}
}
public extension Scheduler {
/// The scheduler we are currently being scheduled on.
/// If we are currently not being scheduled, `.main` will be returned if we are on the main thread or `.background` if not.
static var current: Scheduler {
let state = threadState
return state.syncScheduler ?? state.scheduler ?? (Thread.isMainThread ? .main : .background)
}
/// A Scheduler that won't schedule any work and hence just call work() immediatly
static let none = Scheduler(identifyingObject: 0 as AnyObject, async: { _ in fatalError() }, sync: { _ in fatalError() })
/// A Scheduler that will schedule work on `DispatchQueue.main``
static let main = Scheduler(queue: .main)
/// A Scheduler that will schedule work on a serial background queue
static let background = Scheduler(label: "flow.background.serial")
/// A Scheduler that will schedule work on a concurrent background queue
static let concurrentBackground = Scheduler(label: "flow.background.concurrent", attributes: .concurrent)
}
public extension Scheduler {
/// Create a new instance that will schedule its work on the provided `queue`
convenience init(queue: DispatchQueue) {
self.init(identifyingObject: queue, async: { queue.async(execute: $0) }, sync: queue.sync)
}
/// Create a new instance that will schedule its work on a `DispatchQueue` created with the provided parameters: `label`, `qos`, `attributes`, `autoreleaseFrequency` and `target`.
convenience init(label: String, qos: DispatchQoS = .default, attributes: DispatchQueue.Attributes = [], autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil) {
self.init(queue: DispatchQueue(label: label, qos: qos, attributes: attributes, autoreleaseFrequency: autoreleaseFrequency, target: target))
}
}
extension Scheduler: Equatable {
public static func == (lhs: Scheduler, rhs: Scheduler) -> Bool {
return lhs.identifyingObject === rhs.identifyingObject
}
}
#if canImport(CoreData)
import CoreData
public extension NSManagedObjectContext {
var scheduler: Scheduler {
return concurrencyType == .mainQueueConcurrencyType ? .main : Scheduler(identifyingObject: self, async: perform, sync: performAndWait)
}
}
#endif
/// Used for scheduling delays and might be overridend in unit test with simulatated delays
func disposableAsync(after delay: TimeInterval, execute work: @escaping () -> ()) -> Disposable {
return _disposableAsync(delay, work)
}
private var _disposableAsync: (_ delay: TimeInterval, _ work: @escaping () -> ()) -> Disposable = Scheduler.concurrentBackground.disposableAsync
/// Useful for overriding `disposableAsync` in unit test with simulatated delays
func overrideDisposableAsync(by disposableAsync: @escaping (_ delay: TimeInterval, _ work: @escaping () -> ()) -> Disposable) -> Disposable {
let prev = _disposableAsync
_disposableAsync = disposableAsync
return Disposer {
_disposableAsync = prev
}
}
extension Scheduler {
/// Will asynchronously schedule `work` on `self` after `delay` seconds
/// - Returns: A disposable for cancelation
/// - Note: There is no guarantee that `work` will not be called after disposing the returned `Disposable`
func disposableAsync(after delay: TimeInterval, execute work: @escaping () -> ()) -> Disposable {
precondition(delay >= 0)
let state = StateAndCallback(state: Optional(work))
async(after: delay) { [weak state] in
guard let state = state else { return }
state.lock()
let work = state.val
state.val = nil
state.unlock()
// We can not hold a lock while calling out (risk of deadlock if callout calls dispose), hence dispose might be called just after releasing a lock but before calling out. This means there is guarantee `work` would be called after a dispose.
work?()
}
return Disposer { state.protectedVal = nil }
}
}
extension DispatchQueue {
static let concurrentBackground = DispatchQueue(label: "flow.background.concurrent", attributes: .concurrent)
static let serialBackground = DispatchQueue(label: "flow.background.serial")
}
final class ThreadState {
var scheduler: Scheduler?
var syncScheduler: Scheduler?
init() {}
}
var threadState: ThreadState {
guard !Thread.isMainThread else { return mainThreadState }
if let state = pthread_getspecific(threadStateKey) {
return Unmanaged<ThreadState>.fromOpaque(state).takeUnretainedValue()
}
let state = ThreadState()
pthread_setspecific(threadStateKey, Unmanaged.passRetained(state).toOpaque())
return state
}
private let mainThreadState = ThreadState()
private var _threadStateKey: pthread_key_t = 0
private var threadStateKey: pthread_key_t = {
let cleanup: @convention(c) (UnsafeMutableRawPointer) -> Void = { state in
Unmanaged<ThreadState>.fromOpaque(state).release()
}
pthread_key_create(&_threadStateKey, cleanup)
return _threadStateKey
}()
| 40.29148 | 252 | 0.670785 |
ddc34c4fb3809190ccead14ba1314c7c118242ee | 40,474 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import Foundation
import func POSIX.exit
/// Errors which may be encountered when running argument parser.
public enum ArgumentParserError: Swift.Error {
/// An unknown option is encountered.
case unknownOption(String)
/// The value of an argument is invalid.
case invalidValue(argument: String, error: ArgumentConversionError)
/// Expected a value from the option.
case expectedValue(option: String)
/// An unexpected positional argument encountered.
case unexpectedArgument(String)
/// Expected these positional arguments but not found.
case expectedArguments(ArgumentParser, [String])
}
extension ArgumentParserError: CustomStringConvertible {
public var description: String {
switch self {
case .unknownOption(let option):
return "unknown option \(option); use --help to list available options"
case .invalidValue(let argument, let error):
return "\(error) for argument \(argument); use --help to print usage"
case .expectedValue(let option):
return "option \(option) requires a value; provide a value using '\(option) <value>' or '\(option)=<value>'"
case .unexpectedArgument(let argument):
return "unexpected argument \(argument); use --help to list available arguments"
case .expectedArguments(_, let arguments):
return "expected arguments: \(arguments.joined(separator: ", "))"
}
}
}
/// Conversion errors that can be returned from `ArgumentKind`'s failable
/// initializer.
public enum ArgumentConversionError: Swift.Error {
/// The value is unknown.
case unknown(value: String)
/// The value could not be converted to the target type.
case typeMismatch(value: String, expectedType: Any.Type)
/// Custom reason for conversion failure.
case custom(String)
}
extension ArgumentConversionError: CustomStringConvertible {
public var description: String {
switch self {
case .unknown(let value):
return "unknown value '\(value)'"
case .typeMismatch(let value, let expectedType):
return "'\(value)' is not convertible to \(expectedType)"
case .custom(let reason):
return reason
}
}
}
extension ArgumentConversionError: Equatable {
public static func ==(lhs: ArgumentConversionError, rhs: ArgumentConversionError) -> Bool {
switch (lhs, rhs) {
case (.unknown(let lhsValue), .unknown(let rhsValue)):
return lhsValue == rhsValue
case (.unknown, _):
return false
case (.typeMismatch(let lhsValue, let lhsType), .typeMismatch(let rhsValue, let rhsType)):
return lhsValue == rhsValue && lhsType == rhsType
case (.typeMismatch, _):
return false
case (.custom(let lhsReason), .custom(let rhsReason)):
return lhsReason == rhsReason
case (.custom, _):
return false
}
}
}
/// Different shells for which we can generate shell scripts.
public enum Shell: String, StringEnumArgument {
case bash
case zsh
public static var completion: ShellCompletion = .values([
(bash.rawValue, "generate completion script for Bourne-again shell"),
(zsh.rawValue, "generate completion script for Z shell"),
])
}
/// Various shell completions modes supplied by ArgumentKind.
public enum ShellCompletion {
/// Offers no completions at all; e.g. for a string identifier.
case none
/// No specific completions, will offer tool's completions.
case unspecified
/// Offers filename completions.
case filename
/// Custom function for generating completions. Must be provided in the script's scope.
case function(String)
/// Offers completions from predefined list. A description can be provided which is shown in some shells, like zsh.
case values([(value: String, description: String)])
}
/// A protocol representing the possible types of arguments.
///
/// Conforming to this protocol will qualify the type to act as
/// positional and option arguments in the argument parser.
public protocol ArgumentKind {
/// Throwable convertion initializer.
init(argument: String) throws
/// Type of shell completion to provide for this argument.
static var completion: ShellCompletion { get }
}
// MARK: - ArgumentKind conformance for common types
extension String: ArgumentKind {
public init(argument: String) throws {
self = argument
}
public static let completion: ShellCompletion = .none
}
extension Int: ArgumentKind {
public init(argument: String) throws {
guard let int = Int(argument) else {
throw ArgumentConversionError.typeMismatch(value: argument, expectedType: Int.self)
}
self = int
}
public static let completion: ShellCompletion = .none
}
extension Bool: ArgumentKind {
public init(argument: String) throws {
switch argument {
case "true":
self = true
case "false":
self = false
default:
throw ArgumentConversionError.unknown(value: argument)
}
}
public static var completion: ShellCompletion = .unspecified
}
/// A protocol which implements ArgumentKind for string initializable enums.
///
/// Conforming to this protocol will automatically make an enum with is
/// String initializable conform to ArgumentKind.
public protocol StringEnumArgument: ArgumentKind {
init?(rawValue: String)
}
extension StringEnumArgument {
public init(argument: String) throws {
guard let value = Self.init(rawValue: argument) else {
throw ArgumentConversionError.unknown(value: argument)
}
self = value
}
}
/// An argument representing a path (file / directory).
///
/// The path is resolved in the current working directory.
public struct PathArgument: ArgumentKind {
public let path: AbsolutePath
public init(argument: String) throws {
// FIXME: This should check for invalid paths.
if let cwd = localFileSystem.currentWorkingDirectory {
path = AbsolutePath(argument, relativeTo: cwd)
} else {
path = try AbsolutePath(validating: argument)
}
}
public static var completion: ShellCompletion = .filename
}
/// An enum representing the strategy to parse argument values.
public enum ArrayParsingStrategy {
/// Will parse only the next argument and append all values together: `-Xcc -Lfoo -Xcc -Lbar`.
case oneByOne
/// Will parse all values up to the next option argument: `--files file1 file2 --verbosity 1`.
case upToNextOption
/// Will parse all remaining arguments, usually for executable commands: `swift run exe --option 1`.
case remaining
/// Function that parses the current arguments iterator based on the strategy
/// and returns the parsed values.
func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
var values: [ArgumentKind] = []
switch self {
case .oneByOne:
guard let nextArgument = parser.next() else {
throw ArgumentParserError.expectedValue(option: parser.currentArgument)
}
try values.append(kind.init(argument: nextArgument))
case .upToNextOption:
/// Iterate over arguments until the end or an optional argument
while let nextArgument = parser.peek(), isPositional(argument: nextArgument) {
/// We need to call next to consume the argument. The peek above did not.
_ = parser.next()
try values.append(kind.init(argument: nextArgument))
}
case .remaining:
while let nextArgument = parser.next() {
try values.append(kind.init(argument: nextArgument))
}
}
return values
}
}
/// A protocol representing positional or options argument.
protocol ArgumentProtocol: Hashable {
// FIXME: This should be constrained to ArgumentKind but Array can't conform
// to it: `extension of type 'Array' with constraints cannot have an
// inheritance clause`.
//
/// The argument kind of this argument for eg String, Bool etc.
associatedtype ArgumentKindTy
/// Name of the argument which will be parsed by the parser.
var name: String { get }
/// Short name of the argument, this is usually used in options arguments
/// for a short names for e.g: `--help` -> `-h`.
var shortName: String? { get }
/// The parsing strategy to adopt when parsing values.
var strategy: ArrayParsingStrategy { get }
/// Defines is the argument is optional
var isOptional: Bool { get }
/// The usage text associated with this argument. Used to generate complete help string.
var usage: String? { get }
/// The shell completions to offer as values for this argument.
var completion: ShellCompletion { get }
// FIXME: Because `ArgumentKindTy`` can't conform to `ArgumentKind`, this
// function has to be provided a kind (which will be different from
// ArgumentKindTy for arrays). Once the generics feature exists we can
// improve this API.
//
/// Parses and returns the argument values from the parser.
func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind]
}
extension ArgumentProtocol {
// MARK: - Conformance for Hashable
public func hash(into hasher: inout Hasher) {
return hasher.combine(name)
}
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
return lhs.name == rhs.name && lhs.usage == rhs.usage
}
}
/// Returns true if the given argument does not starts with '-' i.e. it is
/// a positional argument, otherwise it is an options argument.
fileprivate func isPositional(argument: String) -> Bool {
return !argument.hasPrefix("-")
}
/// A class representing option arguments. These are optional arguments which may
/// or may not be provided in the command line. They are always prefixed by their
/// name. For e.g. --verbosity true.
public final class OptionArgument<Kind>: ArgumentProtocol {
typealias ArgumentKindTy = Kind
let name: String
let shortName: String?
// Option arguments are always optional.
var isOptional: Bool { return true }
let strategy: ArrayParsingStrategy
let usage: String?
let completion: ShellCompletion
init(name: String, shortName: String?, strategy: ArrayParsingStrategy, usage: String?, completion: ShellCompletion) {
precondition(!isPositional(argument: name))
self.name = name
self.shortName = shortName
self.strategy = strategy
self.usage = usage
self.completion = completion
}
func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
do {
return try _parse(kind, with: &parser)
} catch let conversionError as ArgumentConversionError {
throw ArgumentParserError.invalidValue(argument: name, error: conversionError)
}
}
func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
// When we have an associated value, we ignore the strategy and only
// parse that value.
if let associatedArgument = parser.associatedArgumentValue {
return try [kind.init(argument: associatedArgument)]
}
// As a special case, Bool options don't consume arguments.
if kind == Bool.self && strategy == .oneByOne {
return [true]
}
let values = try strategy.parse(kind, with: &parser)
guard !values.isEmpty else {
throw ArgumentParserError.expectedValue(option: name)
}
return values
}
}
/// A class representing positional arguments. These arguments must be present
/// and in the same order as they are added in the parser.
public final class PositionalArgument<Kind>: ArgumentProtocol {
typealias ArgumentKindTy = Kind
let name: String
// Postional arguments don't need short names.
var shortName: String? { return nil }
let strategy: ArrayParsingStrategy
let isOptional: Bool
let usage: String?
let completion: ShellCompletion
init(name: String, strategy: ArrayParsingStrategy, optional: Bool, usage: String?, completion: ShellCompletion) {
precondition(isPositional(argument: name))
self.name = name
self.strategy = strategy
self.isOptional = optional
self.usage = usage
self.completion = completion
}
func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
do {
return try _parse(kind, with: &parser)
} catch let conversionError as ArgumentConversionError {
throw ArgumentParserError.invalidValue(argument: name, error: conversionError)
}
}
func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
let value = try kind.init(argument: parser.currentArgument)
var values = [value]
switch strategy {
case .oneByOne:
// We shouldn't apply the strategy with `.oneByOne` because we
// already have one, the parsed `parser.currentArgument`.
break
case .upToNextOption, .remaining:
try values.append(contentsOf: strategy.parse(kind, with: &parser))
}
return values
}
}
/// A type-erased argument.
///
/// Note: Only used for argument parsing purpose.
final class AnyArgument: ArgumentProtocol, CustomStringConvertible {
typealias ArgumentKindTy = Any
let name: String
let shortName: String?
let strategy: ArrayParsingStrategy
let isOptional: Bool
let usage: String?
let completion: ShellCompletion
/// The argument kind this holds, used while initializing that argument.
let kind: ArgumentKind.Type
/// True if the argument kind is of array type.
let isArray: Bool
/// A type-erased wrapper around the argument's `parse` function.
private let parseClosure: (ArgumentKind.Type, inout ArgumentParserProtocol) throws -> [ArgumentKind]
init<T: ArgumentProtocol>(_ argument: T) {
self.kind = T.ArgumentKindTy.self as! ArgumentKind.Type
self.name = argument.name
self.shortName = argument.shortName
self.strategy = argument.strategy
self.isOptional = argument.isOptional
self.usage = argument.usage
self.completion = argument.completion
self.parseClosure = argument.parse(_:with:)
isArray = false
}
/// Initializer for array arguments.
init<T: ArgumentProtocol>(_ argument: T) where T.ArgumentKindTy: Sequence {
self.kind = T.ArgumentKindTy.Element.self as! ArgumentKind.Type
self.name = argument.name
self.shortName = argument.shortName
self.strategy = argument.strategy
self.isOptional = argument.isOptional
self.usage = argument.usage
self.completion = argument.completion
self.parseClosure = argument.parse(_:with:)
isArray = true
}
var description: String {
return "Argument(\(name))"
}
func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
return try self.parseClosure(kind, &parser)
}
func parse(with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] {
return try self.parseClosure(self.kind, &parser)
}
}
// FIXME: We probably don't need this protocol anymore and should convert this to a class.
//
/// Argument parser protocol passed in initializers of ArgumentKind to manipulate
/// parser as needed by the argument.
public protocol ArgumentParserProtocol {
/// The current argument being parsed.
var currentArgument: String { get }
/// The associated value in a `--foo=bar` style argument.
var associatedArgumentValue: String? { get }
/// Provides (consumes) and returns the next argument. Returns `nil` if there are not arguments left.
mutating func next() -> String?
/// Peek at the next argument without consuming it.
func peek() -> String?
}
/// Argument parser struct responsible to parse the provided array of arguments
/// and return the parsed result.
public final class ArgumentParser {
/// A class representing result of the parsed arguments.
public class Result: CustomStringConvertible {
/// Internal representation of arguments mapped to their values.
private var results = [String: Any]()
/// Result of the parent parent parser, if any.
private var parentResult: Result?
/// Reference to the parser this result belongs to.
private let parser: ArgumentParser
/// The subparser command chosen.
fileprivate var subparser: String?
/// Create a result with a parser and parent result.
init(parser: ArgumentParser, parent: Result?) {
self.parser = parser
self.parentResult = parent
}
/// Adds a result.
///
/// - Parameters:
/// - values: The associated values of the argument.
/// - argument: The argument for which this result is being added.
/// - Note:
/// While it may seem more fragile to use an array as input in the
/// case of single-value arguments, this design choice allows major
/// simplifications in the parsing code.
fileprivate func add(_ values: [ArgumentKind], for argument: AnyArgument) throws {
if argument.isArray {
var array = results[argument.name] as? [ArgumentKind] ?? []
array.append(contentsOf: values)
results[argument.name] = array
} else {
// We expect only one value for non-array arguments.
guard let value = values.spm_only else {
assertionFailure()
return
}
results[argument.name] = value
}
}
/// Get an option argument's value from the results.
///
/// Since the options are optional, their result may or may not be present.
public func get<T>(_ argument: OptionArgument<T>) -> T? {
return (results[argument.name] as? T) ?? parentResult?.get(argument)
}
/// Array variant for option argument's get(_:).
public func get<T>(_ argument: OptionArgument<[T]>) -> [T]? {
return (results[argument.name] as? [T]) ?? parentResult?.get(argument)
}
/// Get a positional argument's value.
public func get<T>(_ argument: PositionalArgument<T>) -> T? {
return results[argument.name] as? T
}
/// Array variant for positional argument's get(_:).
public func get<T>(_ argument: PositionalArgument<[T]>) -> [T]? {
return results[argument.name] as? [T]
}
/// Get an argument's value using its name.
/// - throws: An ArgumentParserError.invalidValue error if the parsed argument does not match the expected type.
public func get<T>(_ name: String) throws -> T? {
guard let value = results[name] else {
// if we have a parent and this is an option argument, look in the parent result
if let parentResult = parentResult, name.hasPrefix("-") {
return try parentResult.get(name)
} else {
return nil
}
}
guard let typedValue = value as? T else {
throw ArgumentParserError.invalidValue(argument: name, error: .typeMismatch(value: String(describing: value), expectedType: T.self))
}
return typedValue
}
/// Get the subparser which was chosen for the given parser.
public func subparser(_ parser: ArgumentParser) -> String? {
if parser === self.parser {
return subparser
}
return parentResult?.subparser(parser)
}
public var description: String {
var description = "ArgParseResult(\(results))"
if let parent = parentResult {
description += " -> " + parent.description
}
return description
}
}
/// The mapping of subparsers to their subcommand.
private(set) var subparsers: [String: ArgumentParser] = [:]
/// List of arguments added to this parser.
private(set) var optionArguments: [AnyArgument] = []
private(set) var positionalArguments: [AnyArgument] = []
// If provided, will be substituted instead of arg0 in usage text.
let commandName: String?
/// Usage string of this parser.
let usage: String
/// Overview text of this parser.
let overview: String
/// See more text of this parser.
let seeAlso: String?
/// If this parser is a subparser.
private let isSubparser: Bool
/// Boolean specifying if the parser can accept further positional
/// arguments (false if it already has a positional argument with
/// `isOptional` set to `true` or strategy set to `.remaining`).
private var canAcceptPositionalArguments: Bool = true
/// Create an argument parser.
///
/// - Parameters:
/// - commandName: If provided, this will be substitued in "usage" line of the generated usage text.
/// Otherwise, first command line argument will be used.
/// - usage: The "usage" line of the generated usage text.
/// - overview: The "overview" line of the generated usage text.
/// - seeAlso: The "see also" line of generated usage text.
public init(commandName: String? = nil, usage: String, overview: String, seeAlso: String? = nil) {
self.isSubparser = false
self.commandName = commandName
self.usage = usage
self.overview = overview
self.seeAlso = seeAlso
}
/// Create a subparser with its help text.
private init(subparser overview: String) {
self.isSubparser = true
self.commandName = nil
self.usage = ""
self.overview = overview
self.seeAlso = nil
}
/// Adds an option to the parser.
public func add<T: ArgumentKind>(
option: String,
shortName: String? = nil,
kind: T.Type,
usage: String? = nil,
completion: ShellCompletion? = nil
) -> OptionArgument<T> {
assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice")
let argument = OptionArgument<T>(name: option, shortName: shortName, strategy: .oneByOne, usage: usage, completion: completion ?? T.completion)
optionArguments.append(AnyArgument(argument))
return argument
}
/// Adds an array argument type.
public func add<T: ArgumentKind>(
option: String,
shortName: String? = nil,
kind: [T].Type,
strategy: ArrayParsingStrategy = .upToNextOption,
usage: String? = nil,
completion: ShellCompletion? = nil
) -> OptionArgument<[T]> {
assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice")
let argument = OptionArgument<[T]>(name: option, shortName: shortName, strategy: strategy, usage: usage, completion: completion ?? T.completion)
optionArguments.append(AnyArgument(argument))
return argument
}
/// Adds an argument to the parser.
///
/// Note: Only one positional argument is allowed if optional setting is enabled.
public func add<T: ArgumentKind>(
positional: String,
kind: T.Type,
optional: Bool = false,
usage: String? = nil,
completion: ShellCompletion? = nil
) -> PositionalArgument<T> {
precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers")
precondition(canAcceptPositionalArguments, "Can not accept more positional arguments")
if optional {
canAcceptPositionalArguments = false
}
let argument = PositionalArgument<T>(name: positional, strategy: .oneByOne, optional: optional, usage: usage, completion: completion ?? T.completion)
positionalArguments.append(AnyArgument(argument))
return argument
}
/// Adds an argument to the parser.
///
/// Note: Only one multiple-value positional argument is allowed.
public func add<T: ArgumentKind>(
positional: String,
kind: [T].Type,
optional: Bool = false,
strategy: ArrayParsingStrategy = .upToNextOption,
usage: String? = nil,
completion: ShellCompletion? = nil
) -> PositionalArgument<[T]> {
precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers")
precondition(canAcceptPositionalArguments, "Can not accept more positional arguments")
if optional || strategy == .remaining {
canAcceptPositionalArguments = false
}
let argument = PositionalArgument<[T]>(name: positional, strategy: strategy, optional: optional, usage: usage, completion: completion ?? T.completion)
positionalArguments.append(AnyArgument(argument))
return argument
}
/// Add a parser with a subcommand name and its corresponding overview.
@discardableResult
public func add(subparser command: String, overview: String) -> ArgumentParser {
precondition(positionalArguments.isEmpty, "Subparsers are not supported with positional arguments")
let parser = ArgumentParser(subparser: overview)
subparsers[command] = parser
return parser
}
// MARK: - Parsing
/// A wrapper struct to pass to the ArgumentKind initializers.
struct Parser: ArgumentParserProtocol {
let currentArgument: String
private(set) var associatedArgumentValue: String?
/// The iterator used to iterate arguments.
fileprivate var argumentsIterator: IndexingIterator<[String]>
init(associatedArgumentValue: String?, argumentsIterator: IndexingIterator<[String]>, currentArgument: String) {
self.associatedArgumentValue = associatedArgumentValue
self.argumentsIterator = argumentsIterator
self.currentArgument = currentArgument
}
mutating func next() -> String? {
return argumentsIterator.next()
}
func peek() -> String? {
var iteratorCopy = argumentsIterator
let nextArgument = iteratorCopy.next()
return nextArgument
}
}
/// Parses the provided array and return the result.
public func parse(_ arguments: [String] = []) throws -> Result {
return try parse(arguments, parent: nil)
}
private func parse(_ arguments: [String] = [], parent: Result?) throws -> Result {
let result = Result(parser: self, parent: parent)
// Create options map to quickly look up the arguments.
let optionsTuple = optionArguments.flatMap({ option -> [(String, AnyArgument)] in
var result = [(option.name, option)]
// Add the short names too, if we have them.
if let shortName = option.shortName {
result += [(shortName, option)]
}
return result
})
let optionsMap = Dictionary(items: optionsTuple)
// Create iterators.
var positionalArgumentIterator = positionalArguments.makeIterator()
var argumentsIterator = arguments.makeIterator()
while let argumentString = argumentsIterator.next() {
let argument: AnyArgument
let parser: Parser
// If argument is help then just print usage and exit.
if argumentString == "-h" || argumentString == "-help" || argumentString == "--help" {
printUsage(on: stdoutStream)
exit(0)
} else if isPositional(argument: argumentString) {
/// If this parser has subparsers, we allow only one positional argument which is the subparser command.
if !subparsers.isEmpty {
// Make sure this argument has a subparser.
guard let subparser = subparsers[argumentString] else {
throw ArgumentParserError.expectedArguments(self, Array(subparsers.keys))
}
// Save which subparser was chosen.
result.subparser = argumentString
// Parse reset of the arguments with the subparser.
return try subparser.parse(Array(argumentsIterator), parent: result)
}
// Get the next positional argument we are expecting.
guard let positionalArgument = positionalArgumentIterator.next() else {
throw ArgumentParserError.unexpectedArgument(argumentString)
}
argument = positionalArgument
parser = Parser(
associatedArgumentValue: nil,
argumentsIterator: argumentsIterator,
currentArgument: argumentString)
} else {
let (argumentString, value) = argumentString.spm_split(around: "=")
// Get the corresponding option for the option argument.
guard let optionArgument = optionsMap[argumentString] else {
throw ArgumentParserError.unknownOption(argumentString)
}
argument = optionArgument
parser = Parser(
associatedArgumentValue: value,
argumentsIterator: argumentsIterator,
currentArgument: argumentString)
}
// Update results.
var parserProtocol = parser as ArgumentParserProtocol
let values = try argument.parse(with: &parserProtocol)
try result.add(values, for: argument)
// Restore the argument iterator state.
argumentsIterator = (parserProtocol as! Parser).argumentsIterator
}
// Report if there are any non-optional positional arguments left which were not present in the arguments.
let leftOverArguments = Array(positionalArgumentIterator)
if leftOverArguments.contains(where: { !$0.isOptional }) {
throw ArgumentParserError.expectedArguments(self, leftOverArguments.map({ $0.name }))
}
return result
}
/// Prints usage text for this parser on the provided stream.
public func printUsage(on stream: OutputByteStream) {
/// Space settings.
let maxWidthDefault = 24
let padding = 2
let maxWidth: Int
// Determine the max width based on argument length or choose the
// default width if max width is longer than the default width.
if let maxArgument = (positionalArguments + optionArguments).map({
[$0.name, $0.shortName].compactMap({ $0 }).joined(separator: ", ").count
}).max(), maxArgument < maxWidthDefault {
maxWidth = maxArgument + padding + 1
} else {
maxWidth = maxWidthDefault
}
/// Prints an argument on a stream if it has usage.
func print(formatted argument: String, usage: String, on stream: OutputByteStream) {
// Start with a new line and add some padding.
stream <<< "\n" <<< Format.asRepeating(string: " ", count: padding)
let count = argument.count
// If the argument is longer than the max width, print the usage
// on a new line. Otherwise, print the usage on the same line.
if count >= maxWidth - padding {
stream <<< argument <<< "\n"
// Align full width because usage is to be printed on a new line.
stream <<< Format.asRepeating(string: " ", count: maxWidth + padding)
} else {
stream <<< argument
// Align to the remaining empty space on the line.
stream <<< Format.asRepeating(string: " ", count: maxWidth - count)
}
stream <<< usage
}
stream <<< "OVERVIEW: " <<< overview
// We only print command usage for top level parsers.
if !isSubparser {
stream <<< "\n\n"
// Get the binary name from command line arguments.
let defaultCommandName = CommandLine.arguments[0].components(separatedBy: "/").last!
stream <<< "USAGE: " <<< (commandName ?? defaultCommandName) <<< " " <<< usage
}
if optionArguments.count > 0 {
stream <<< "\n\n"
stream <<< "OPTIONS:"
for argument in optionArguments.lazy.sorted(by: { $0.name < $1.name }) {
guard let usage = argument.usage else { continue }
// Create name with its shortname, if available.
let name = [argument.name, argument.shortName].compactMap({ $0 }).joined(separator: ", ")
print(formatted: name, usage: usage, on: stream)
}
// Print help option, if this is a top level command.
if !isSubparser {
print(formatted: "--help", usage: "Display available options", on: stream)
}
}
if subparsers.keys.count > 0 {
stream <<< "\n\n"
stream <<< "SUBCOMMANDS:"
for (command, parser) in subparsers.sorted(by: { $0.key < $1.key }) {
// Special case for hidden subcommands.
guard !parser.overview.isEmpty else { continue }
print(formatted: command, usage: parser.overview, on: stream)
}
}
if positionalArguments.count > 0 {
stream <<< "\n\n"
stream <<< "POSITIONAL ARGUMENTS:"
for argument in positionalArguments {
guard let usage = argument.usage else { continue }
print(formatted: argument.name, usage: usage, on: stream)
}
}
if let seeAlso = seeAlso {
stream <<< "\n\n"
stream <<< "SEE ALSO: \(seeAlso)"
}
stream <<< "\n"
stream.flush()
}
}
/// A class to bind ArgumentParser's arguments to an option structure.
public final class ArgumentBinder<Options> {
/// The signature of body closure.
private typealias BodyClosure = (inout Options, ArgumentParser.Result) throws -> Void
/// This array holds the closures which should be executed to fill the options structure.
private var bodies = [BodyClosure]()
/// Create a binder.
public init() {
}
/// Bind an option argument.
public func bind<T>(
option: OptionArgument<T>,
to body: @escaping (inout Options, T) throws -> Void
) {
addBody {
guard let result = $1.get(option) else { return }
try body(&$0, result)
}
}
/// Bind an array option argument.
public func bindArray<T>(
option: OptionArgument<[T]>,
to body: @escaping (inout Options, [T]) throws -> Void
) {
addBody {
guard let result = $1.get(option) else { return }
try body(&$0, result)
}
}
/// Bind a positional argument.
public func bind<T>(
positional: PositionalArgument<T>,
to body: @escaping (inout Options, T) throws -> Void
) {
addBody {
// All the positional argument will always be present.
guard let result = $1.get(positional) else { return }
try body(&$0, result)
}
}
/// Bind an array positional argument.
public func bindArray<T>(
positional: PositionalArgument<[T]>,
to body: @escaping (inout Options, [T]) throws -> Void
) {
addBody {
// All the positional argument will always be present.
guard let result = $1.get(positional) else { return }
try body(&$0, result)
}
}
/// Bind two positional arguments.
public func bindPositional<T, U>(
_ first: PositionalArgument<T>,
_ second: PositionalArgument<U>,
to body: @escaping (inout Options, T, U) throws -> Void
) {
addBody {
// All the positional arguments will always be present.
guard let first = $1.get(first) else { return }
guard let second = $1.get(second) else { return }
try body(&$0, first, second)
}
}
/// Bind three positional arguments.
public func bindPositional<T, U, V>(
_ first: PositionalArgument<T>,
_ second: PositionalArgument<U>,
_ third: PositionalArgument<V>,
to body: @escaping (inout Options, T, U, V) throws -> Void
) {
addBody {
// All the positional arguments will always be present.
guard let first = $1.get(first) else { return }
guard let second = $1.get(second) else { return }
guard let third = $1.get(third) else { return }
try body(&$0, first, second, third)
}
}
/// Bind two options.
public func bind<T, U>(
_ first: OptionArgument<T>,
_ second: OptionArgument<U>,
to body: @escaping (inout Options, T?, U?) throws -> Void
) {
addBody {
try body(&$0, $1.get(first), $1.get(second))
}
}
/// Bind three options.
public func bind<T, U, V>(
_ first: OptionArgument<T>,
_ second: OptionArgument<U>,
_ third: OptionArgument<V>,
to body: @escaping (inout Options, T?, U?, V?) throws -> Void
) {
addBody {
try body(&$0, $1.get(first), $1.get(second), $1.get(third))
}
}
/// Bind two array options.
public func bindArray<T, U>(
_ first: OptionArgument<[T]>,
_ second: OptionArgument<[U]>,
to body: @escaping (inout Options, [T], [U]) throws -> Void
) {
addBody {
try body(&$0, $1.get(first) ?? [], $1.get(second) ?? [])
}
}
/// Add three array option and call the final closure with their values.
public func bindArray<T, U, V>(
_ first: OptionArgument<[T]>,
_ second: OptionArgument<[U]>,
_ third: OptionArgument<[V]>,
to body: @escaping (inout Options, [T], [U], [V]) throws -> Void
) {
addBody {
try body(&$0, $1.get(first) ?? [], $1.get(second) ?? [], $1.get(third) ?? [])
}
}
/// Bind a subparser.
public func bind(
parser: ArgumentParser,
to body: @escaping (inout Options, String) throws -> Void
) {
addBody {
guard let result = $1.subparser(parser) else { return }
try body(&$0, result)
}
}
/// Appends a closure to bodies array.
private func addBody(_ body: @escaping BodyClosure) {
bodies.append(body)
}
/// Fill the result into the options structure,
/// throwing if one of the user-provided binder function throws.
public func fill(parseResult result: ArgumentParser.Result, into options: inout Options) throws {
try bodies.forEach { try $0(&options, result) }
}
/// Fill the result into the options structure.
@available(*, deprecated, renamed: "fill(parseResult:into:)")
public func fill(_ result: ArgumentParser.Result, into options: inout Options) {
try! fill(parseResult: result, into: &options)
}
}
| 36.561879 | 158 | 0.622918 |
e9d9f22df090ff19c9157b2a60ec898d1d4d7f66 | 219 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var a{if true as[Void{}struct d<T where h:T{var:N
| 36.5 | 87 | 0.757991 |
edd5b6eb3e900f07cea238788f683937cb71f1f8 | 5,319 | //
// ICloudStoreObserver.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
#if os(iOS) || os(OSX)
// MARK: - ICloudStoreObserver
/**
Implement the `ICloudStoreObserver` protocol to observe ubiquitous storage notifications from the specified iCloud store.
Note that `ICloudStoreObserver` methods are only called when all the following conditions are true:
- the observer is registered to the `ICloudStore` via the `ICloudStore.addObserver(_:)` method
- the `ICloudStore` was added to a `DataStack`
- the `ICloudStore` and the `DataStack` are still persisted in memory
*/
public protocol ICloudStoreObserver: class {
/**
Notifies that the initial ubiquitous store import will complete
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that the initial ubiquitous store import completed
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account will be added to the coordinator
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillAddAccount(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account was added to the coordinator
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidAddAccount(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account will be removed from the coordinator
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillRemoveAccount(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that an iCloud account was removed from the coordinator
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidRemoveAccount(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that iCloud contents will be deleted
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreWillRemoveContent(storage storage: ICloudStore, dataStack: DataStack)
/**
Notifies that iCloud contents were deleted
- parameter storage: the `ICloudStore` instance being observed
- parameter dataStack: the `DataStack` that manages the peristent store
*/
func iCloudStoreDidRemoveContent(storage storage: ICloudStore, dataStack: DataStack)
}
public extension ICloudStoreObserver {
public func iCloudStoreWillFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidFinishUbiquitousStoreInitialImport(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillAddAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidAddAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveAccount(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreWillRemoveContent(storage storage: ICloudStore, dataStack: DataStack) {}
public func iCloudStoreDidRemoveContent(storage storage: ICloudStore, dataStack: DataStack) {}
}
#endif
| 41.88189 | 122 | 0.743185 |
d6981f4781ef57874e4c71718ab57360956397dc | 475 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class C
class A:C
struct S<T where g:a{
class B<d{class a
func B{
let s=((a{
| 31.666667 | 79 | 0.741053 |
ed72b7bfcaa6796c045331daf30b2f4bd9c55bc9 | 1,594 | import XCTest
@testable import OSCKit
final class OSCKitTests: XCTestCase {
func testArguments() {
let message = OSCMessage(with: "/osc/kit", arguments: [1,
3.142,
"hello world!",
Data(count: 2),
OSCArgument.oscTrue,
OSCArgument.oscFalse,
OSCArgument.oscNil,
OSCArgument.oscImpulse])
XCTAssertEqual(message.arguments.count, 8)
XCTAssertEqual(message.argumentTypes.count, 8)
XCTAssertEqual(message.typeTagString, ",ifsbTFNI")
XCTAssertEqual(message.argumentTypes[0], OSCArgument.oscInt)
XCTAssertEqual(message.argumentTypes[1], OSCArgument.oscFloat)
XCTAssertEqual(message.argumentTypes[2], OSCArgument.oscString)
XCTAssertEqual(message.argumentTypes[3], OSCArgument.oscBlob)
XCTAssertEqual(message.argumentTypes[4], OSCArgument.oscTrue)
XCTAssertEqual(message.argumentTypes[5], OSCArgument.oscFalse)
XCTAssertEqual(message.argumentTypes[6], OSCArgument.oscNil)
XCTAssertEqual(message.argumentTypes[7], OSCArgument.oscImpulse)
}
static var allTests = [
("testArguments", testArguments),
]
}
| 44.277778 | 87 | 0.507528 |
f8447ae94ea2edb54bd53cd963a5bac150715c4d | 16,004 | //
// CircularSlider.swift
// CircularSliderExample
//
// Created by Matteo Tagliafico on 02/09/16.
// Copyright © 2016 Matteo Tagliafico. All rights reserved.
//
import Foundation
import UIKit
@objc public protocol CircularSliderDelegate: NSObjectProtocol {
@objc optional func circularSlider(_ circularSlider: CircularSlider, valueForValue value: Float) -> Float
@objc optional func circularSlider(_ circularSlider: CircularSlider, didBeginEditing textfield: UITextField)
@objc optional func circularSlider(_ circularSlider: CircularSlider, didEndEditing textfield: UITextField)
// optional func circularSlider(circularSlider: CircularSlider, attributeTextForValue value: Float) -> NSAttributedString
}
@IBDesignable
open class CircularSlider: UIView {
// MARK: - outlets
@IBOutlet fileprivate weak var iconImageView: UIImageView!
@IBOutlet fileprivate weak var iconCenterY: NSLayoutConstraint!
@IBOutlet fileprivate weak var centeredView: UIView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var textfield: UITextField! {
didSet {
addDoneButtonOnKeyboard()
}
}
@IBOutlet fileprivate weak var divisaLabel: UILabel!
// MARK: - properties
open weak var delegate: CircularSliderDelegate?
fileprivate var containerView: UIView!
fileprivate var nibName = "CircularSlider"
fileprivate var backgroundCircleLayer = CAShapeLayer()
fileprivate var progressCircleLayer = CAShapeLayer()
fileprivate var knobLayer = CAShapeLayer()
fileprivate var backingValue: Float = 0
fileprivate var backingKnobAngle: CGFloat = 0
fileprivate var rotationGesture: RotationGestureRecognizer?
fileprivate var backingFractionDigits: NSInteger = 2
fileprivate let maxFractionDigits: NSInteger = 4
fileprivate var startAngle: CGFloat {
return -(CGFloat.pi / 2) + radiansOffset
}
fileprivate var endAngle: CGFloat {
return 3 * (CGFloat.pi / 2) - radiansOffset
}
fileprivate var angleRange: CGFloat {
return endAngle - startAngle
}
fileprivate var valueRange: Float {
return maximumValue - minimumValue
}
fileprivate var arcCenter: CGPoint {
return CGPoint(x: frame.width / 2, y: frame.height / 2)
}
fileprivate var arcRadius: CGFloat {
return min(frame.width,frame.height) / 2 - lineWidth / 2
}
fileprivate var normalizedValue: Float {
return (value - minimumValue) / (maximumValue - minimumValue)
}
fileprivate var knobAngle: CGFloat {
return CGFloat(normalizedValue) * angleRange + startAngle
}
fileprivate var knobMidAngle: CGFloat {
return (2 * CGFloat.pi + startAngle - endAngle) / 2 + endAngle
}
fileprivate var knobRotationTransform: CATransform3D {
return CATransform3DMakeRotation(knobAngle, 0.0, 0.0, 1)
}
fileprivate var intFont = UIFont.systemFont(ofSize: 42)
fileprivate var decimalFont = UIFont.systemFont(ofSize: 42)
fileprivate var divisaFont = UIFont.systemFont(ofSize: 26)
@IBInspectable
open var title: String = "Title" {
didSet {
titleLabel.text = title
}
}
@IBInspectable
open var radiansOffset: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
open var icon: UIImage? = UIImage() {
didSet {
configureIcon()
}
}
@IBInspectable
open var divisa: String = "" {
didSet {
appearanceDivisa()
}
}
@IBInspectable
open var value: Float {
get {
return backingValue
}
set {
backingValue = min(maximumValue, max(minimumValue, newValue))
}
}
@IBInspectable
open var minimumValue: Float = 0
@IBInspectable
open var maximumValue: Float = 500
@IBInspectable
open var lineWidth: CGFloat = 5 {
didSet {
appearanceBackgroundLayer()
appearanceProgressLayer()
}
}
@IBInspectable
open var bgColor: UIColor = UIColor.lightGray {
didSet {
appearanceBackgroundLayer()
}
}
@IBInspectable
open var pgNormalColor: UIColor = UIColor.darkGray {
didSet {
appearanceProgressLayer()
}
}
@IBInspectable
open var pgHighlightedColor: UIColor = UIColor.green {
didSet {
appearanceProgressLayer()
}
}
@IBInspectable
open var knobRadius: CGFloat = 20 {
didSet {
appearanceKnobLayer()
}
}
@IBInspectable
open var highlighted: Bool = true {
didSet {
appearanceProgressLayer()
appearanceKnobLayer()
}
}
@IBInspectable
open var hideLabels: Bool = false {
didSet {
setLabelsHidden(self.hideLabels)
}
}
@IBInspectable
open var fractionDigits: NSInteger {
get {
return backingFractionDigits
}
set {
backingFractionDigits = min(maxFractionDigits, max(0, newValue))
}
}
@IBInspectable
open var customDecimalSeparator: String? = nil {
didSet {
if let c = self.customDecimalSeparator, c.count > 1 {
self.customDecimalSeparator = nil
}
}
}
// MARK: - init
public override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
configure()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
configure()
}
fileprivate func xibSetup() {
containerView = loadViewFromNib()
containerView.frame = bounds
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(containerView)
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
// MARK: - drawing methods
override open func draw(_ rect: CGRect) {
print("drawRect")
backgroundCircleLayer.bounds = bounds
progressCircleLayer.bounds = bounds
knobLayer.bounds = bounds
backgroundCircleLayer.position = arcCenter
progressCircleLayer.position = arcCenter
knobLayer.position = arcCenter
rotationGesture?.arcRadius = arcRadius
backgroundCircleLayer.path = getCirclePath()
progressCircleLayer.path = getCirclePath()
knobLayer.path = getKnobPath()
appearanceIconImageView()
setValue(value, animated: false)
}
fileprivate func getCirclePath() -> CGPath {
return UIBezierPath(arcCenter: arcCenter,
radius: arcRadius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true).cgPath
}
fileprivate func getKnobPath() -> CGPath {
return UIBezierPath(roundedRect:
CGRect(x: arcCenter.x + arcRadius - knobRadius / 2, y: arcCenter.y - knobRadius / 2, width: knobRadius, height: knobRadius),
cornerRadius: knobRadius / 2).cgPath
}
// MARK: - configure
fileprivate func configure() {
clipsToBounds = false
configureBackgroundLayer()
configureProgressLayer()
configureKnobLayer()
configureGesture()
configureFont()
}
fileprivate func configureIcon() {
iconImageView.image = icon
appearanceIconImageView()
}
fileprivate func configureBackgroundLayer() {
backgroundCircleLayer.frame = bounds
layer.addSublayer(backgroundCircleLayer)
appearanceBackgroundLayer()
}
fileprivate func configureProgressLayer() {
progressCircleLayer.frame = bounds
progressCircleLayer.strokeEnd = 0
layer.addSublayer(progressCircleLayer)
appearanceProgressLayer()
}
fileprivate func configureKnobLayer() {
knobLayer.frame = bounds
knobLayer.position = arcCenter
layer.addSublayer(knobLayer)
appearanceKnobLayer()
}
fileprivate func configureGesture() {
rotationGesture = RotationGestureRecognizer(target: self, action: #selector(handleRotationGesture(_:)), arcRadius: arcRadius, knobRadius: knobRadius)
addGestureRecognizer(rotationGesture!)
}
fileprivate func configureFont() {
if #available(iOS 8.2, *) {
intFont = UIFont.systemFont(ofSize: 42, weight: .regular)
decimalFont = UIFont.systemFont(ofSize: 42, weight: .thin)
divisaFont = UIFont.systemFont(ofSize: 26, weight: .thin)
}
}
// MARK: - appearance
fileprivate func appearanceIconImageView() {
iconCenterY.constant = arcRadius
}
fileprivate func appearanceBackgroundLayer() {
backgroundCircleLayer.lineWidth = lineWidth
backgroundCircleLayer.fillColor = UIColor.clear.cgColor
backgroundCircleLayer.strokeColor = bgColor.cgColor
backgroundCircleLayer.lineCap = .round
}
fileprivate func appearanceProgressLayer() {
progressCircleLayer.lineWidth = lineWidth
progressCircleLayer.fillColor = UIColor.clear.cgColor
progressCircleLayer.strokeColor = highlighted ? pgHighlightedColor.cgColor : pgNormalColor.cgColor
progressCircleLayer.lineCap = .round
}
fileprivate func appearanceKnobLayer() {
knobLayer.lineWidth = 2
knobLayer.fillColor = highlighted ? pgHighlightedColor.cgColor : pgNormalColor.cgColor
knobLayer.strokeColor = UIColor.white.cgColor
}
fileprivate func appearanceDivisa() {
divisaLabel.text = divisa
divisaLabel.font = divisaFont
}
// MARK: - update
open func setValue(_ value: Float, animated: Bool) {
self.value = delegate?.circularSlider?(self, valueForValue: value) ?? value
updateLabels()
setStrokeEnd(animated: animated)
setKnobRotation(animated: animated)
}
fileprivate func setStrokeEnd(animated: Bool) {
CATransaction.begin()
CATransaction.setDisableActions(true)
let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeAnimation.duration = animated ? 0.66 : 0
strokeAnimation.repeatCount = 1
strokeAnimation.fromValue = progressCircleLayer.strokeEnd
strokeAnimation.toValue = CGFloat(normalizedValue)
strokeAnimation.isRemovedOnCompletion = false
strokeAnimation.fillMode = .removed
strokeAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
progressCircleLayer.add(strokeAnimation, forKey: "strokeAnimation")
progressCircleLayer.strokeEnd = CGFloat(normalizedValue)
CATransaction.commit()
}
fileprivate func setKnobRotation(animated: Bool) {
CATransaction.begin()
CATransaction.setDisableActions(true)
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.duration = animated ? 0.66 : 0
animation.values = [backingKnobAngle, knobAngle]
knobLayer.add(animation, forKey: "knobRotationAnimation")
knobLayer.transform = knobRotationTransform
CATransaction.commit()
backingKnobAngle = knobAngle
}
fileprivate func setLabelsHidden(_ isHidden: Bool) {
centeredView.isHidden = isHidden
}
fileprivate func updateLabels() {
updateValueLabel()
}
fileprivate func updateValueLabel() {
textfield.attributedText = value.formatWithFractionDigits(fractionDigits, customDecimalSeparator: customDecimalSeparator).sliderAttributeString(intFont: intFont, decimalFont: decimalFont, customDecimalSeparator: customDecimalSeparator )
}
// MARK: - gesture handler
@objc fileprivate func handleRotationGesture(_ sender: AnyObject) {
guard let gesture = sender as? RotationGestureRecognizer else { return }
if gesture.state == .began {
cancelAnimation()
}
var rotationAngle = gesture.rotation
if rotationAngle > knobMidAngle {
rotationAngle -= 2 * CGFloat.pi
} else if rotationAngle < (knobMidAngle - 2 * CGFloat.pi) {
rotationAngle += 2 * CGFloat.pi
}
rotationAngle = min(endAngle, max(startAngle, rotationAngle))
guard abs(Double(rotationAngle - knobAngle)) < (Double.pi / 2) else { return }
let valueForAngle = Float(rotationAngle - startAngle) / Float(angleRange) * valueRange + minimumValue
setValue(valueForAngle, animated: false)
}
func cancelAnimation() {
progressCircleLayer.removeAllAnimations()
knobLayer.removeAllAnimations()
}
// MARK:- methods
open override func becomeFirstResponder() -> Bool {
return textfield.becomeFirstResponder()
}
open override func resignFirstResponder() -> Bool {
return textfield.resignFirstResponder()
}
fileprivate func addDoneButtonOnKeyboard() {
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(resignFirstResponder))
doneToolbar.barStyle = UIBarStyle.default
doneToolbar.items = [flexSpace, doneButton]
doneToolbar.sizeToFit()
textfield.inputAccessoryView = doneToolbar
}
}
// MARK: - UITextFieldDelegate
extension CircularSlider: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.circularSlider?(self, didBeginEditing: textfield)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.circularSlider?(self, didEndEditing: textfield)
layoutIfNeeded()
setValue(textfield.text!.toFloat(), animated: true)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if newString.count > 0 {
let fmt = NumberFormatter()
let scanner: Scanner = Scanner(string:newString.replacingOccurrences(of: customDecimalSeparator ?? fmt.decimalSeparator, with: "."))
let isNumeric = scanner.scanDecimal(nil) && scanner.isAtEnd
if isNumeric {
var decimalFound = false
var charactersAfterDecimal = 0
for ch in newString.reversed() {
if ch == fmt.decimalSeparator.first {
decimalFound = true
break
}
charactersAfterDecimal += 1
}
if decimalFound && charactersAfterDecimal > fractionDigits {
return false
}
else {
return true
}
}
else {
return false
}
}
else {
return true
}
}
}
| 32.728016 | 244 | 0.628343 |
e29eee444a7e8e82e1850e10c6e50326b9fe5e13 | 1,850 | //
// User.swift
// DNSwiftProject
//
// Created by mainone on 16/12/26.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
class User: NSObject {
// 登录状态
class var isLoginStatus: Bool {
get {
return UserDefaults.standard.bool(forKey: "isloginstatus")
}
set (isLogin) {
UserDefaults.standard.set(isLogin, forKey: "isloginstatus")
UserDefaults.standard.synchronize()
}
}
// 用户ID
class var userID: String {
get {
if let userId = UserDefaults.standard.object(forKey: "userid") as? String {
return userId.length > 0 ? userId : "-1"
} else {
return "-1"
}
}
set (userId) {
UserDefaults.standard.set(userId, forKey: "userid")
UserDefaults.standard.synchronize()
}
}
// 昵称
class var userNickName: String {
get {
if let nickName = UserDefaults.standard.object(forKey: "user_nickname") as? String {
return nickName.length > 0 ? nickName : "未知"
} else {
return "未知"
}
}
set(nickName) {
UserDefaults.standard.set(nickName, forKey: "user_nickname")
UserDefaults.standard.synchronize()
}
}
// 绑定邮箱
class var userEmail: String {
get {
if let userEmail = UserDefaults.standard.object(forKey: "user_email") as? String {
return userEmail.length > 0 ? userEmail : "[email protected]"
} else {
return "[email protected]"
}
}
set(userEmail) {
UserDefaults.standard.set(userEmail, forKey: "user_email")
UserDefaults.standard.synchronize()
}
}
}
| 26.811594 | 96 | 0.524324 |
918e31ca7f5e8849b4f793f67f905e87b34c4935 | 4,602 | //
// AppDelegate.swift
// Login
//
// Created by Geoffrey Vedernikoff on 12/3/16.
// Copyright © 2016 Geoffrey Vedernikoff. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Login")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.957447 | 285 | 0.687744 |
64473eb1e037bb778f10d3b2605b13985b7e793c | 2,579 | //
// DataManager.swift
// SimpleDataKit
//
// Created by Harley.xk on 2017/4/8.
// Copyright (c) 2017 Harley. All rights reserved.
//
//
import CoreData
open class DataManager {
open static var shared: DataManager {
return sharedDataManager
}
// MARK: - CoreData
open private(set) var context: NSManagedObjectContext!
public typealias ContextSetupResult = (Error?) -> Void
open func setupContext(with momdName: String = "Data", completion: ContextSetupResult? = nil) {
if #available(iOS 10.0, *) {
let container = NSPersistentContainer(name: momdName)
container.loadPersistentStores { (_, error) in
self.context = container.viewContext
DispatchQueue.main.async {
completion?(error)
}
}
} else {
var errorInfo: Error?
if let model = NSManagedObjectModel.mergedModel(from: nil) {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
do {
let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)[0] as NSString
let storeURL = URL(fileURLWithPath: path.appendingPathComponent(momdName + ".momd"))
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
} catch {
errorInfo = error
}
self.context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
self.context.persistentStoreCoordinator = coordinator
} else {
errorInfo = NSError(domain: "SimpleDataKit", code: -1, userInfo: ["message":"model not found"])
}
DispatchQueue.main.async {
completion?(errorInfo)
}
}
}
@discardableResult open func save() -> Bool {
do {
try context.save()
return true
} catch {
#if DEBUG
print("SimpleDataKit: Model saving failed: \(error.localizedDescription)")
#endif
// context.rollback()
return false
}
}
open func performChangeAndSave(closure: @escaping () -> Void) {
context.perform {
closure()
self.save()
}
}
// MARK: - Private
private static let sharedDataManager = DataManager()
private init() {}
}
| 33.493506 | 134 | 0.569988 |
1d2ed932feb4b0d32ed093f0fbf001a2812eab2f | 889 | // VolumeSlider.swift
// Copyright (c) 2020, zhiayang
// Licensed under the Apache License Version 2.0.
import Cocoa
import SwiftUI
import Foundation
struct VolumeSlider : NSViewRepresentable
{
@Binding var value: Int
func makeNSView(context: Context) -> NSSlider
{
let slider = NSSlider(value: Double(self.value), minValue: 0, maxValue: 100,
target: context.coordinator,
action: #selector(Coordinator.valueChanged(_:)))
return slider
}
func updateNSView(_ view: NSSlider, context: Context)
{
view.doubleValue = Double(self.value)
}
func makeCoordinator() -> Coordinator
{
return Coordinator(value: $value)
}
final class Coordinator : NSObject
{
var value: Binding<Int>
init(value: Binding<Int>)
{
self.value = value
}
@objc func valueChanged(_ sender: NSSlider)
{
self.value.wrappedValue = Int(sender.doubleValue)
}
}
}
| 18.914894 | 78 | 0.703037 |
388cefa5a2b8e80bf7b143628edf44c4b2160a65 | 759 | import XCTest
import CoreBluetoothExtension
class Tests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 26.172414 | 111 | 0.607378 |
dbfebe5e1e82db80c6b4ac2cdefc12086bd58be6 | 3,124 | //
//
// HTTPAdaptor.swift
// NavCogMiraikan
//
/*******************************************************************************
* Copyright (c) 2021 © Miraikan - The National Museum of Emerging Science and Innovation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
import Foundation
enum HttpMethod : String {
case GET
case POST
case PUT
case DELETE
}
/**
Instantiate it for HTTP requests
*/
class HTTPAdaptor {
/**
HTTP Request
- Parameters:
- host: The server host
- endpoint:The URL for specific action
- params: The parameters in URL
- headers: The request headers
- body: The data content to be posted
- success: The action after successful request
- fail: The action after request failure
*/
public func http(host: String = Host.miraikan.address,
endpoint: String,
params: [URLQueryItem]? = nil,
method: HttpMethod = .GET,
headers: [String: String]? = nil,
body: Data? = nil,
success: ((Data)->())?,
fail: (()->())? = nil) {
var url = URLComponents(string: "\(host)\(endpoint)")!
var req = URLRequest(url: url.url!)
if let items = params {
url.queryItems = items
}
req.httpMethod = method.rawValue
if let b = body {
req.httpBody = b
}
if let h = headers {
req.allHTTPHeaderFields = h
}
URLSession.shared.dataTask(with: req) { (data, res, err) in
if let _err = err,
let _f = fail {
print(_err.localizedDescription)
DispatchQueue.main.async { _f() }
}
if let _data = data,
let _f = success {
DispatchQueue.main.async { _f(_data) }
}
}.resume()
}
}
| 33.591398 | 91 | 0.56306 |
4b46ea30d621d7fe4ebaca58a8cd358492827616 | 7,110 | //
// MSAlert.swift
// Created by Maor Shams on 11/11/2017.
// Copyright © 2017 Maor Shams. All rights reserved.
//
import UIKit
import AVFoundation
class MSAlert: UIAlertController {
class MSAlertAction : UIAlertAction{
var type : MSAlert.MSActionType?
convenience init(actionTitle: String,
style: UIAlertActionStyle,
image : UIImage? = nil,
actionType : MSAlert.MSActionType? = nil,
handler: @escaping ((UIAlertAction) -> Void) ){
self.init(title: actionTitle, style: style, handler: handler)
self.setValue(image, forKey: "image")
self.type = actionType
}
}
enum MSActionType {
case cancel
case ok
case yes
case no
var title : String{
switch self {
case .cancel : return "Cancel"
case .ok : return "Ok"
case .yes : return "Yes"
case .no : return "No"
}
}
/// Add your images here
var image : UIImage?{
switch self {
default : return #imageLiteral(resourceName: "icons8-ok")
}
}
}
override var preferredStyle: UIAlertControllerStyle {
return .alert
}
init() {
super.init(nibName: nil, bundle: nil)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
convenience init(viewController : UIViewController,
sourceView : UIView? ,
arrowDirections : UIPopoverArrowDirection = [.any],
title: String? = nil,
message: String? = nil) {
self.init()
initialize(viewController: viewController,sourceView: sourceView, title: title, message: message)
}
// Configuration for alert
private func initialize(viewController : UIViewController? = nil,
sourceView : UIView? = nil,
arrowDirections : UIPopoverArrowDirection = [.any],
title: String? = nil,
message: String? = nil) {
if let title = title {
self.title = title
}
if let message = message {
self.message = message
}
let rootVC = UIApplication.shared.keyWindow?.rootViewController
currentvViewController = (viewController == nil) ? rootVC : viewController
self.sourceView = sourceView
self.popoverPresentationController?.permittedArrowDirections = arrowDirections
}
fileprivate var currentvViewController : UIViewController?
fileprivate var handler : ((MSAlert.MSActionType?) -> Void)?
private var sourceView : UIView?
private var player: AVAudioPlayer?
/// Add new custom alert action.
/// - parameters:
/// - title: The title of the action
/// - isDestructive: (_optional_) - The style of the alert action, by default the value is false.
/// - image: (_optional_) - The image of the alert action, by default nil (no image)
/// - handler: (_optional_) - Completion for the alert action.
func add(title : String,
isDestructive : Bool = false,
image : UIImage? = nil,
handler : (()->Void)? = nil) -> MSAlert{
let customButtonAction = MSAlertAction(actionTitle: title, style: self.isDestructive(isDestructive) , image: image) { _ in
handler?()
}
return self.add(action: customButtonAction)
}
/// Add new alert action to the action sheet.
/// - parameters:
/// - type: - The type of the alert action
/// - title: (_optional_) - The title of the alert action, by default the values from MSActionsSheet.ActionType
/// - style: (_optional_) - The style of the alert action, by default the value is .default. If the type of the action sheet is .cancel, and the style is nil, the style will set as .cancel
/// - image: (_optional_) - The image of the alert action, by default nil (no image)
/// - defaultImage: (_optional_) - The default image based on the type from MSActionsSheet.ActionType
func add(_ type : MSActionType,
title : String? = nil,
style : UIAlertActionStyle? = nil,
image : UIImage? = nil,
defaultImage : Bool = false) -> MSAlert{
let newTitle : String = (title == nil) ? type.title : title!
let newImage : UIImage? = defaultImage == true ? type.image : image
let newStyle : UIAlertActionStyle = (type == .cancel && style == nil) ? .cancel : style == nil ? .default : style!
let action = MSAlertAction(actionTitle: newTitle,
style: newStyle,
image: newImage,
actionType: type,
handler: alertAction)
return self.add(action: action)
}
/// Set color for the alert
/// - parameters:
/// - color: The tint color of the alert
func setTint(color : UIColor) -> MSAlert{
self.view.tintColor = color
return self
}
/// Set sound that will play with the alert
func setSound(from resourceURL : URL) -> MSAlert{
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try? AVAudioSession.sharedInstance().setActive(true)
player = try? AVAudioPlayer(contentsOf: resourceURL)
return self
}
/// Presents the ActionSheet on the view controller.
/// (Make sure this is the last method called!)
/// - parameters:
/// - completion: (_optional ActionType) The selected alert action.
func show(completion: ((MSAlert.MSActionType?) -> Void)? = nil){
self.handler = completion
if UIDevice.current.userInterfaceIdiom == .pad, let source = sourceView{
self.popoverPresentationController?.sourceView = source
self.popoverPresentationController?.sourceRect = source.bounds
}
if let player = player {
player.play()
}
currentvViewController?.present(self, animated: true, completion: nil)
}
private func alertAction(_ action : UIAlertAction){
guard let action = action as? MSAlertAction else {
return
}
self.handler?(action.type)
}
private func add(action: MSAlertAction) -> MSAlert{
self.addAction(action)
return self
}
private func isDestructive(_ destructive : Bool) -> UIAlertActionStyle {
return destructive ? .destructive : .default
}
}
| 34.182692 | 194 | 0.557243 |
eb60b280810ac83c9d95bf3aa1ed8be8aa3a9bc1 | 2,557 | //
// SidebarOutlineView.swift
// MarkDownEditor
//
// Created by Koji Murata on 2018/02/16.
// Copyright © 2018年 Koji Murata. All rights reserved.
//
import Cocoa
final class SidebarOutlineView: NSOutlineView {
private var defaultNoteMenu: NSMenu!
private var deletedNoteMenu: NSMenu!
private var trashMenu: NSMenu!
private var backgroundMenu: NSMenu!
private(set) var indexesForMenu: IndexSet?
private(set) var parentNodeForMenu: NodeModel?
func setMenus(defaultNoteMenu: NSMenu, deletedNoteMenu: NSMenu, trashMenu: NSMenu, backgroundMenu: NSMenu) {
self.defaultNoteMenu = defaultNoteMenu
self.deletedNoteMenu = deletedNoteMenu
self.trashMenu = trashMenu
self.backgroundMenu = backgroundMenu
}
override func menu(for event: NSEvent) -> NSMenu? {
indexesForMenu = nil
parentNodeForMenu = nil
let location = convert(event.locationInWindow, from: nil)
let clickedRow = row(at: location)
if let node = item(atRow: clickedRow) as? NodeModel {
parentNodeForMenu = node.isDirectory ? node : node.parent
if selectedRowIndexes.contains(clickedRow) {
indexesForMenu = selectedRowIndexes
} else {
indexesForMenu = IndexSet(integer: clickedRow)
}
if node.isTrash {
menu = trashMenu
} else if node.isDeleted {
menu = deletedNoteMenu
} else {
menu = defaultNoteMenu
}
} else {
menu = backgroundMenu
}
if let indexesForMenu = indexesForMenu, menu == defaultNoteMenu {
let nodes = indexesForMenu.compactMap { self.item(atRow: $0) as? NodeModel }
let isGroupable = nodes.count == indexesForMenu.count && nodes.hasSameParent
let newDirectoryFromSelectionItem = defaultNoteMenu.items.first { $0.identifier == NSUserInterfaceItemIdentifier("newDirectoryFromSelection") }
newDirectoryFromSelectionItem?.isEnabled = isGroupable
}
return super.menu(for: event)
}
private var isPreparedReloadData = false
// outlineviewはreloaddataの時にitemを参照してしまうため、realmの削除済みデータを参照してクラッシュする
func prepareReloadData() -> Bool {
if isPreparedReloadData { return false }
defer { isPreparedReloadData = true }
guard let rootItemCount = dataSource?.outlineView?(self, numberOfChildrenOfItem: nil) else { return false }
let indexSet = IndexSet(0..<rootItemCount)
removeItems(at: indexSet, inParent: nil, withAnimation: [])
return true
}
override func reloadData() {
isPreparedReloadData = false
super.reloadData()
}
}
| 31.9625 | 149 | 0.70395 |
90d4041008c498635ffeece0cbacab68bfca39ba | 349 | //
// Request.swift
// Patterns
//
// Created by 杨晴贺 on 2017/3/26.
// Copyright © 2017年 Silence. All rights reserved.
//
import Foundation
// 请求
struct Request {
enum RequestType: String {
case leave = "请假"
case salary = "加薪"
}
var requestType: RequestType
var requestContent: String
var number: Int
}
| 15.863636 | 51 | 0.613181 |
e9f8eae08a88741ce980b9c8db8380271d291896 | 377 | //
// AddCollectionViewCell.swift
// Collection View in a Table View Cell
//
// Created by Yauheni Yarotski on 6/18/16.
// Copyright © 2016 Ash Furrow. All rights reserved.
//
import UIKit
class AddCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addImage: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var followers: UILabel!
}
| 23.5625 | 53 | 0.729443 |
76e5220a4400aa522715df93d4dc8f8c1132e4c3 | 1,869 | //
// SceneDelegate.swift
// GitIt
//
// Created by Loay Ashraf on 18/10/2021.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
@available(iOS 13.0, *)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
}
@available(iOS 13.0, *)
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
@available(iOS 13.0, *)
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
@available(iOS 13.0, *)
func sceneWillResignActive(_ scene: UIScene) {
try? DataManager.standard.saveData()
}
@available(iOS 13.0, *)
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
@available(iOS 13.0, *)
func sceneWillEnterBackground(_ scene: UIScene) {
try? DataManager.standard.saveData()
}
@available(iOS 13.0, *)
func sceneDidEnterBackground(_ scene: UIScene) {
try? DataManager.standard.saveData()
}
}
| 32.789474 | 140 | 0.678973 |
1441c0f3a4cafb27bf58a3cd54396e2dbdf9229b | 2,868 | //
// Format.swift
// Covid-19 Status
//
// Created by Marcin Gajda on 24/03/2020.
// Copyright © 2020 Marcin Gajda. All rights reserved.
//
import Cocoa
import Foundation
func menuBarTextFormatter(label: String) -> NSMutableAttributedString {
let text = NSMutableAttributedString()
text.append(NSAttributedString(
string: label,
attributes: [
.font: NSFont.menuBarFont(ofSize: 12),
.baselineOffset: -1.5
]
))
return text
}
enum StatsFormatMethod: String {
case short
case long
}
class StatsFormatter {
var stats: RegionStats
var method: StatsFormatMethod
init(stats: RegionStats, method: StatsFormatMethod) {
self.stats = stats
self.method = method
}
func formatStatistic(value: Int) -> String {
if method == .long {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.groupingSeparator = " "
return numberFormatter.string(from: NSNumber(value: value)) ?? "??"
} else {
return Double(value).shortStringRepresentation
}
}
func getUniqueId() -> String {
return "\(stats.country) \(stats.cases) \(stats.deaths) \(stats.recovered)"
}
func getRegionStatus() -> NSMutableAttributedString {
let value1 = formatStatistic(value: stats.cases)
let value2 = formatStatistic(value: stats.deaths)
let value3 = formatStatistic(value: stats.recovered)
return menuBarTextFormatter(label: "😷 \(value1) 💀 \(value2) ❤️ \(value3)")
}
func getRegionDelta() -> String {
let value1 = formatStatistic(value: stats.todayCases ?? 0)
let value2 = formatStatistic(value: stats.todayDeaths ?? 0)
return String(format: NSLocalizedString("Today: +%@ confirmed +%@ deaths", comment: ""), value1, value2)
}
func getTooltip() -> String {
let countryName = NSLocalizedString(stats.country, comment: "")
return String(
format: NSLocalizedString("COVID-19 (%@)\nConfirmed | Deaths | Recured", comment: ""),
countryName
)
}
}
extension Double {
var shortStringRepresentation: String {
if self.isNaN {
return "NaN"
}
if self.isInfinite {
return "\(self < 0.0 ? "-" : "+")Infinity"
}
if self == 0 {
return "0"
}
let units = ["", "k", "M", "B"]
var value = self
var unitIndex = 0
while unitIndex < units.count - 1 {
if abs(value) < 1000.0 {
break
}
unitIndex += 1
value /= 1000.0
}
return "\(String(format: "%0.*g", Int(log10(abs(value))) + 2, value))\(units[unitIndex])"
}
}
| 26.803738 | 112 | 0.580195 |
71419adcbbe09205ab4cead4aa304cca7a2fcf19 | 51,377 | import Foundation
import UIKit
import Display
import SwiftSignalKit
import Postbox
import TelegramCore
import SyncCore
import TelegramPresentationData
import ItemListUI
import PresentationDataUtils
import TextFormat
import OverlayStatusController
import AccountContext
import AlertUI
import PresentationDataUtils
import PasswordSetupUI
import Markdown
private final class TwoStepVerificationUnlockSettingsControllerArguments {
let updatePasswordText: (String) -> Void
let checkPassword: () -> Void
let openForgotPassword: () -> Void
let openSetupPassword: () -> Void
let openDisablePassword: () -> Void
let openSetupEmail: () -> Void
let openResetPendingEmail: () -> Void
let updateEmailCode: (String) -> Void
let openConfirmEmail: () -> Void
init(updatePasswordText: @escaping (String) -> Void, checkPassword: @escaping () -> Void, openForgotPassword: @escaping () -> Void, openSetupPassword: @escaping () -> Void, openDisablePassword: @escaping () -> Void, openSetupEmail: @escaping () -> Void, openResetPendingEmail: @escaping () -> Void, updateEmailCode: @escaping (String) -> Void, openConfirmEmail: @escaping () -> Void) {
self.updatePasswordText = updatePasswordText
self.checkPassword = checkPassword
self.openForgotPassword = openForgotPassword
self.openSetupPassword = openSetupPassword
self.openDisablePassword = openDisablePassword
self.openSetupEmail = openSetupEmail
self.openResetPendingEmail = openResetPendingEmail
self.updateEmailCode = updateEmailCode
self.openConfirmEmail = openConfirmEmail
}
}
private enum TwoStepVerificationUnlockSettingsSection: Int32 {
case password
case email
}
private enum TwoStepVerificationUnlockSettingsEntryTag: ItemListItemTag {
case password
func isEqual(to other: ItemListItemTag) -> Bool {
if let other = other as? TwoStepVerificationUnlockSettingsEntryTag {
switch self {
case .password:
if case .password = other {
return true
} else {
return false
}
}
} else {
return false
}
}
}
private enum TwoStepVerificationUnlockSettingsEntry: ItemListNodeEntry {
case passwordEntry(PresentationTheme, PresentationStrings, String, String)
case passwordEntryInfo(PresentationTheme, String)
case passwordSetup(PresentationTheme, String)
case passwordSetupInfo(PresentationTheme, String)
case changePassword(PresentationTheme, String)
case turnPasswordOff(PresentationTheme, String)
case setupRecoveryEmail(PresentationTheme, String)
case passwordInfo(PresentationTheme, String)
case pendingEmailConfirmInfo(PresentationTheme, String)
case pendingEmailConfirmCode(PresentationTheme, PresentationStrings, String, String)
case pendingEmailInfo(PresentationTheme, String)
case pendingEmailOpenConfirm(PresentationTheme, String)
var section: ItemListSectionId {
switch self {
case .pendingEmailConfirmInfo, .pendingEmailConfirmCode, .pendingEmailInfo, .pendingEmailOpenConfirm:
return TwoStepVerificationUnlockSettingsSection.email.rawValue
default:
return TwoStepVerificationUnlockSettingsSection.password.rawValue
}
}
var stableId: Int32 {
switch self {
case .passwordEntry:
return 0
case .passwordEntryInfo:
return 1
case .passwordSetup:
return 2
case .passwordSetupInfo:
return 3
case .changePassword:
return 4
case .turnPasswordOff:
return 5
case .setupRecoveryEmail:
return 6
case .passwordInfo:
return 7
case .pendingEmailConfirmInfo:
return 8
case .pendingEmailConfirmCode:
return 9
case .pendingEmailInfo:
return 10
case .pendingEmailOpenConfirm:
return 11
}
}
static func <(lhs: TwoStepVerificationUnlockSettingsEntry, rhs: TwoStepVerificationUnlockSettingsEntry) -> Bool {
return lhs.stableId < rhs.stableId
}
func item(presentationData: ItemListPresentationData, arguments: Any) -> ListViewItem {
let arguments = arguments as! TwoStepVerificationUnlockSettingsControllerArguments
switch self {
case let .passwordEntry(theme, strings, text, value):
return ItemListSingleLineInputItem(presentationData: presentationData, title: NSAttributedString(string: text, textColor: theme.list.itemPrimaryTextColor), text: value, placeholder: "", type: .password, spacing: 10.0, tag: TwoStepVerificationUnlockSettingsEntryTag.password, sectionId: self.section, textUpdated: { updatedText in
arguments.updatePasswordText(updatedText)
}, action: {
arguments.checkPassword()
})
case let .passwordEntryInfo(theme, text):
return ItemListTextItem(presentationData: presentationData, text: .markdown(text), sectionId: self.section, linkAction: { action in
switch action {
case .tap:
arguments.openForgotPassword()
}
})
case let .passwordSetup(theme, text):
return ItemListActionItem(presentationData: presentationData, title: text, kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: {
arguments.openSetupPassword()
})
case let .passwordSetupInfo(theme, text):
return ItemListTextItem(presentationData: presentationData, text: .markdown(text), sectionId: self.section)
case let .changePassword(theme, text):
return ItemListActionItem(presentationData: presentationData, title: text, kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: {
arguments.openSetupPassword()
})
case let .turnPasswordOff(theme, text):
return ItemListActionItem(presentationData: presentationData, title: text, kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: {
arguments.openDisablePassword()
})
case let .setupRecoveryEmail(theme, text):
return ItemListActionItem(presentationData: presentationData, title: text, kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: {
arguments.openSetupEmail()
})
case let .passwordInfo(theme, text):
return ItemListTextItem(presentationData: presentationData, text: .plain(text), sectionId: self.section)
case let .pendingEmailConfirmInfo(theme, text):
return ItemListTextItem(presentationData: presentationData, text: .plain(text), sectionId: self.section)
case let .pendingEmailConfirmCode(theme, strings, title, text):
return ItemListSingleLineInputItem(presentationData: presentationData, title: NSAttributedString(string: ""), text: text, placeholder: title, type: .number, sectionId: self.section, textUpdated: { value in
arguments.updateEmailCode(value)
}, action: {})
case let .pendingEmailInfo(theme, text):
return ItemListTextItem(presentationData: presentationData, text: .markdown(text), sectionId: self.section, linkAction: { action in
switch action {
case .tap:
arguments.openResetPendingEmail()
}
})
case let .pendingEmailOpenConfirm(theme, text):
return ItemListActionItem(presentationData: presentationData, title: text, kind: .generic, alignment: .natural, sectionId: self.section, style: .blocks, action: {
arguments.openConfirmEmail()
})
}
}
}
private struct TwoStepVerificationUnlockSettingsControllerState: Equatable {
var passwordText: String = ""
var checking: Bool = false
var emailCode: String = ""
}
private func twoStepVerificationUnlockSettingsControllerEntries(presentationData: PresentationData, state: TwoStepVerificationUnlockSettingsControllerState, data: TwoStepVerificationUnlockSettingsControllerData) -> [TwoStepVerificationUnlockSettingsEntry] {
var entries: [TwoStepVerificationUnlockSettingsEntry] = []
switch data {
case let .access(configuration):
if let configuration = configuration {
switch configuration {
case let .notSet(pendingEmail):
if let pendingEmail = pendingEmail {
entries.append(.pendingEmailConfirmInfo(presentationData.theme, presentationData.strings.TwoStepAuth_SetupPendingEmail(pendingEmail.email.pattern).0))
entries.append(.pendingEmailConfirmCode(presentationData.theme, presentationData.strings, presentationData.strings.TwoStepAuth_RecoveryCode, state.emailCode))
entries.append(.pendingEmailInfo(presentationData.theme, "[" + presentationData.strings.TwoStepAuth_ConfirmationAbort + "]()"))
/*entries.append(.pendingEmailInfo(presentationData.theme, presentationData.strings.TwoStepAuth_ConfirmationText + "\n\n\(pendingEmailAndValue.pendingEmail.pattern)\n\n[" + presentationData.strings.TwoStepAuth_ConfirmationAbort + "]()"))*/
} else {
entries.append(.passwordSetup(presentationData.theme, presentationData.strings.TwoStepAuth_SetPassword))
entries.append(.passwordSetupInfo(presentationData.theme, presentationData.strings.TwoStepAuth_SetPasswordHelp))
}
case let .set(hint, _, _):
entries.append(.passwordEntry(presentationData.theme, presentationData.strings, presentationData.strings.TwoStepAuth_EnterPasswordPassword, state.passwordText))
if hint.isEmpty {
entries.append(.passwordEntryInfo(presentationData.theme, presentationData.strings.TwoStepAuth_EnterPasswordHelp + "\n\n[" + presentationData.strings.TwoStepAuth_EnterPasswordForgot + "](forgot)"))
} else {
entries.append(.passwordEntryInfo(presentationData.theme, presentationData.strings.TwoStepAuth_EnterPasswordHint(escapedPlaintextForMarkdown(hint)).0 + "\n\n" + presentationData.strings.TwoStepAuth_EnterPasswordHelp + "\n\n[" + presentationData.strings.TwoStepAuth_EnterPasswordForgot + "](forgot)"))
}
}
}
case let .manage(_, emailSet, pendingEmail, _):
entries.append(.changePassword(presentationData.theme, presentationData.strings.TwoStepAuth_ChangePassword))
entries.append(.turnPasswordOff(presentationData.theme, presentationData.strings.TwoStepAuth_RemovePassword))
entries.append(.setupRecoveryEmail(presentationData.theme, emailSet ? presentationData.strings.TwoStepAuth_ChangeEmail : presentationData.strings.TwoStepAuth_SetupEmail))
if let _ = pendingEmail {
entries.append(.pendingEmailConfirmInfo(presentationData.theme, presentationData.strings.TwoStepAuth_EmailSent))
entries.append(.pendingEmailOpenConfirm(presentationData.theme, presentationData.strings.TwoStepAuth_EnterEmailCode))
} else {
entries.append(.passwordInfo(presentationData.theme, presentationData.strings.TwoStepAuth_GenericHelp))
}
}
return entries
}
enum TwoStepVerificationUnlockSettingsControllerMode {
case access(intro: Bool, data: Signal<TwoStepVerificationUnlockSettingsControllerData, NoError>?)
case manage(password: String, email: String, pendingEmail: TwoStepVerificationPendingEmail?, hasSecureValues: Bool)
}
struct TwoStepVerificationPendingEmailState: Equatable {
let password: String?
let email: TwoStepVerificationPendingEmail
}
enum TwoStepVerificationAccessConfiguration: Equatable {
case notSet(pendingEmail: TwoStepVerificationPendingEmailState?)
case set(hint: String, hasRecoveryEmail: Bool, hasSecureValues: Bool)
init(configuration: TwoStepVerificationConfiguration, password: String?) {
switch configuration {
case let .notSet(pendingEmail):
self = .notSet(pendingEmail: pendingEmail.flatMap({ TwoStepVerificationPendingEmailState(password: password, email: $0) }))
case let .set(hint, hasRecoveryEmail, _, hasSecureValues):
self = .set(hint: hint, hasRecoveryEmail: hasRecoveryEmail, hasSecureValues: hasSecureValues)
}
}
}
enum TwoStepVerificationUnlockSettingsControllerData: Equatable {
case access(configuration: TwoStepVerificationAccessConfiguration?)
case manage(password: String, emailSet: Bool, pendingEmail: TwoStepVerificationPendingEmail?, hasSecureValues: Bool)
}
func twoStepVerificationUnlockSettingsController(context: AccountContext, mode: TwoStepVerificationUnlockSettingsControllerMode, openSetupPasswordImmediately: Bool = false) -> ViewController {
let initialState = TwoStepVerificationUnlockSettingsControllerState()
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((TwoStepVerificationUnlockSettingsControllerState) -> TwoStepVerificationUnlockSettingsControllerState) -> Void = { f in
statePromise.set(stateValue.modify { f($0) })
}
var replaceControllerImpl: ((ViewController, Bool) -> Void)?
var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)?
var dismissImpl: (() -> Void)?
let actionsDisposable = DisposableSet()
let checkDisposable = MetaDisposable()
actionsDisposable.add(checkDisposable)
let setupDisposable = MetaDisposable()
actionsDisposable.add(setupDisposable)
let setupResultDisposable = MetaDisposable()
actionsDisposable.add(setupResultDisposable)
let dataPromise = Promise<TwoStepVerificationUnlockSettingsControllerData>()
let remoteDataPromise = Promise<TwoStepVerificationUnlockSettingsControllerData>()
switch mode {
case let .access(_, data):
if let data = data {
dataPromise.set(data)
} else {
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: nil))
|> then(remoteDataPromise.get()))
remoteDataPromise.set(twoStepVerificationConfiguration(account: context.account)
|> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: nil)) })
}
case let .manage(password, email, pendingEmail, hasSecureValues):
dataPromise.set(.single(.manage(password: password, emailSet: !email.isEmpty, pendingEmail: pendingEmail, hasSecureValues: hasSecureValues)))
}
let checkEmailConfirmation: () -> Void = {
let _ = (dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
var pendingEmailData: TwoStepVerificationPendingEmailState?
switch data {
case let .access(configuration):
guard let configuration = configuration else {
return
}
switch configuration {
case let .notSet(pendingEmail):
pendingEmailData = pendingEmail
case .set:
break
}
case let .manage(password, _, pendingEmail, _):
if let pendingEmail = pendingEmail {
pendingEmailData = TwoStepVerificationPendingEmailState(password: password, email: pendingEmail)
}
}
if let pendingEmail = pendingEmailData {
var code: String?
updateState { state in
var state = state
if !state.checking {
code = state.emailCode
state.checking = true
}
return state
}
if let code = code {
setupDisposable.set((confirmTwoStepRecoveryEmail(network: context.account.network, code: code)
|> deliverOnMainQueue).start(error: { error in
updateState { state in
var state = state
state.checking = false
return state
}
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
let text: String
switch error {
case .invalidEmail:
text = presentationData.strings.TwoStepAuth_EmailInvalid
case .invalidCode:
text = presentationData.strings.Login_InvalidCodeError
case .expired:
text = presentationData.strings.TwoStepAuth_EmailCodeExpired
let _ = (dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case .access:
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: .notSet(pendingEmail: nil))))
case let .manage(manage):
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.manage(password: manage.password, emailSet: false, pendingEmail: nil, hasSecureValues: manage.hasSecureValues)))
}
updateState { state in
var state = state
state.checking = false
state.emailCode = ""
return state
}
})
case .flood:
text = presentationData.strings.TwoStepAuth_FloodError
case .generic:
text = presentationData.strings.Login_UnknownError
}
presentControllerImpl?(textAlertController(context: context, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), nil)
}, completed: {
let _ = (dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case .access:
if let password = pendingEmail.password {
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.manage(password: password, emailSet: true, pendingEmail: nil, hasSecureValues: false)))
} else {
dataPromise.set(.single(.access(configuration: nil))
|> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: pendingEmail.password)) }))
}
case let .manage(manage):
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.manage(password: manage.password, emailSet: true, pendingEmail: nil, hasSecureValues: manage.hasSecureValues)))
}
updateState { state in
var state = state
state.checking = false
state.emailCode = ""
return state
}
})
}))
}
}
})
}
let arguments = TwoStepVerificationUnlockSettingsControllerArguments(updatePasswordText: { updatedText in
updateState { state in
var state = state
state.passwordText = updatedText
return state
}
}, checkPassword: {
var wasChecking = false
var password: String?
updateState { state in
var state = state
wasChecking = state.checking
password = state.passwordText
state.checking = true
return state
}
if let password = password, !password.isEmpty, !wasChecking {
checkDisposable.set((requestTwoStepVerifiationSettings(network: context.account.network, password: password)
|> mapToSignal { settings -> Signal<(TwoStepVerificationSettings, TwoStepVerificationPendingEmail?), AuthorizationPasswordVerificationError> in
return twoStepVerificationConfiguration(account: context.account)
|> mapError { _ -> AuthorizationPasswordVerificationError in
return .generic
}
|> map { configuration in
var pendingEmail: TwoStepVerificationPendingEmail?
if case let .set(configuration) = configuration {
pendingEmail = configuration.pendingEmail
}
return (settings, pendingEmail)
}
}
|> deliverOnMainQueue).start(next: { settings, pendingEmail in
updateState { state in
var state = state
state.checking = false
return state
}
replaceControllerImpl?(twoStepVerificationUnlockSettingsController(context: context, mode: .manage(password: password, email: settings.email, pendingEmail: pendingEmail, hasSecureValues: settings.secureSecret != nil)), true)
}, error: { error in
updateState { state in
var state = state
state.checking = false
return state
}
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
let text: String
switch error {
case .limitExceeded:
text = presentationData.strings.LoginPassword_FloodError
case .invalidPassword:
text = presentationData.strings.LoginPassword_InvalidPasswordError
case .generic:
text = presentationData.strings.Login_UnknownError
}
presentControllerImpl?(textAlertController(context: context, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}))
}
}, openForgotPassword: {
setupDisposable.set((dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case let .access(configuration):
if let configuration = configuration {
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
switch configuration {
case let .set(_, hasRecoveryEmail, _):
if hasRecoveryEmail {
updateState { state in
var state = state
state.checking = true
return state
}
setupResultDisposable.set((requestTwoStepVerificationPasswordRecoveryCode(network: context.account.network)
|> deliverOnMainQueue).start(next: { emailPattern in
updateState { state in
var state = state
state.checking = false
return state
}
var completionImpl: (() -> Void)?
let controller = resetPasswordController(context: context, emailPattern: emailPattern, completion: {
completionImpl?()
})
completionImpl = { [weak controller] in
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: .notSet(pendingEmail: nil))))
controller?.view.endEditing(true)
controller?.dismiss()
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(presentationData.strings.TwoStepAuth_DisableSuccess, false)), nil)
}
presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}, error: { _ in
updateState { state in
var state = state
state.checking = false
return state
}
presentControllerImpl?(textAlertController(context: context, title: nil, text: presentationData.strings.Login_UnknownError, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}))
} else {
presentControllerImpl?(textAlertController(context: context, title: nil, text: presentationData.strings.TwoStepAuth_RecoveryUnavailable, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}
case .notSet:
break
}
}
case .manage:
break
}
}))
}, openSetupPassword: {
setupDisposable.set((dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case let .access(configuration):
if let configuration = configuration {
switch configuration {
case .notSet:
let controller = SetupTwoStepVerificationController(context: context, initialState: .createPassword, stateUpdated: { update, shouldDismiss, controller in
switch update {
case .noPassword:
dataPromise.set(.single(.access(configuration: .notSet(pendingEmail: nil))))
case let .awaitingEmailConfirmation(password, pattern, codeLength):
dataPromise.set(.single(.access(configuration: .notSet(pendingEmail: TwoStepVerificationPendingEmailState(password: password, email: TwoStepVerificationPendingEmail(pattern: pattern, codeLength: codeLength))))))
case let .passwordSet(password, hasRecoveryEmail, hasSecureValues):
if let password = password {
dataPromise.set(.single(.manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues)))
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(presentationData.strings.TwoStepAuth_EnabledSuccess, false)), nil)
} else {
dataPromise.set(.single(.access(configuration: nil))
|> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: password)) }))
}
}
if shouldDismiss {
controller.dismiss()
}
})
presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet, completion: {
if case let .access(intro, _) = mode, intro {
let controller = twoStepVerificationUnlockSettingsController(context: context, mode: .access(intro: false, data: dataPromise.get()))
replaceControllerImpl?(controller, false)
}
}))
case .set:
break
}
}
case let .manage(password, hasRecovery, pendingEmail, hasSecureValues):
let controller = SetupTwoStepVerificationController(context: context, initialState: .updatePassword(current: password, hasRecoveryEmail: hasRecovery, hasSecureValues: hasSecureValues), stateUpdated: { update, shouldDismiss, controller in
switch update {
case .noPassword:
dataPromise.set(.single(.access(configuration: .notSet(pendingEmail: nil))))
case .awaitingEmailConfirmation:
assertionFailure()
break
case let .passwordSet(password, hasRecoveryEmail, hasSecureValues):
if let password = password {
dataPromise.set(.single(.manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues)))
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(presentationData.strings.TwoStepAuth_PasswordChangeSuccess, false)), nil)
} else {
dataPromise.set(.single(.access(configuration: nil))
|> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: password)) }))
}
}
if shouldDismiss {
controller.dismiss()
}
})
presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}
}))
}, openDisablePassword: {
setupDisposable.set((dataPromise.get() |> take(1) |> deliverOnMainQueue).start(next: { data in
switch data {
case let .manage(_, _, _, hasSecureValues):
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
var text = presentationData.strings.TwoStepAuth_PasswordRemoveConfirmation
if hasSecureValues {
text = presentationData.strings.TwoStepAuth_PasswordRemovePassportConfirmation
}
presentControllerImpl?(textAlertController(context: context, title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.TwoStepAuth_Disable, action: {
var disablePassword = false
updateState { state in
var state = state
if state.checking {
return state
} else {
disablePassword = true
state.checking = true
return state
}
}
if disablePassword {
setupDisposable.set((dataPromise.get()
|> take(1)
|> mapError { _ -> UpdateTwoStepVerificationPasswordError in return .generic }
|> mapToSignal { data -> Signal<Void, UpdateTwoStepVerificationPasswordError> in
switch data {
case .access:
return .complete()
case let .manage(password, _, _, _):
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(presentationData.strings.TwoStepAuth_DisableSuccess, false)), nil)
return updateTwoStepVerificationPassword(network: context.account.network, currentPassword: password, updatedPassword: .none)
|> mapToSignal { _ -> Signal<Void, UpdateTwoStepVerificationPasswordError> in
return .complete()
}
}
}
|> deliverOnMainQueue).start(error: { _ in
updateState { state in
var state = state
state.checking = false
return state
}
}, completed: {
updateState { state in
var state = state
state.checking = false
return state
}
//dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: .notSet(pendingEmail: nil))))
dismissImpl?()
}))
}
})]), ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
default:
break
}
}))
}, openSetupEmail: {
setupDisposable.set((dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case .access:
break
case let .manage(password, emailSet, _, hasSecureValues):
//let controller = TwoFactorDataInputScreen(context: context, mode: .updateEmailAddress(password: password))
let controller = SetupTwoStepVerificationController(context: context, initialState: .addEmail(hadRecoveryEmail: emailSet, hasSecureValues: hasSecureValues, password: password), stateUpdated: { update, shouldDismiss, controller in
switch update {
case .noPassword:
assertionFailure()
break
case let .awaitingEmailConfirmation(password, pattern, codeLength):
let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: emailSet, pendingEmail: TwoStepVerificationPendingEmail(pattern: pattern, codeLength: codeLength), hasSecureValues: hasSecureValues)
dataPromise.set(.single(data))
case let .passwordSet(password, hasRecoveryEmail, hasSecureValues):
if let password = password {
let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues)
dataPromise.set(.single(data))
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(emailSet ? presentationData.strings.TwoStepAuth_EmailChangeSuccess : presentationData.strings.TwoStepAuth_EmailAddSuccess, false)), nil)
} else {
dataPromise.set(.single(.access(configuration: nil))
|> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: password)) }))
}
}
if shouldDismiss {
controller.dismiss()
}
})
presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}
}))
}, openResetPendingEmail: {
updateState { state in
var state = state
state.checking = true
return state
}
setupDisposable.set((updateTwoStepVerificationPassword(network: context.account.network, currentPassword: nil, updatedPassword: .none)
|> deliverOnMainQueue).start(next: { _ in
updateState { state in
var state = state
state.checking = false
return state
}
dataPromise.set(.single(TwoStepVerificationUnlockSettingsControllerData.access(configuration: .notSet(pendingEmail: nil))))
}, error: { _ in
updateState { state in
var state = state
state.checking = false
return state
}
}))
}, updateEmailCode: { value in
var previousValue: String?
updateState { state in
var state = state
previousValue = state.emailCode
state.emailCode = value
return state
}
let _ = (dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case let .access(configuration):
if let configuration = configuration {
switch configuration {
case let .notSet(pendingEmail):
if let pendingEmail = pendingEmail, let codeLength = pendingEmail.email.codeLength {
if let previousValue = previousValue, previousValue.count != codeLength && value.count == codeLength {
checkEmailConfirmation()
}
}
case .set:
break
}
}
case .manage:
break
}
})
}, openConfirmEmail: {
let _ = (dataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
switch data {
case .access:
break
case let .manage(password, emailSet, pendingEmail, hasSecureValues):
guard let pendingEmail = pendingEmail else {
return
}
let controller = SetupTwoStepVerificationController(context: context, initialState: .confirmEmail(password: password, hasSecureValues: hasSecureValues, pattern: pendingEmail.pattern, codeLength: pendingEmail.codeLength), stateUpdated: { update, shouldDismiss, controller in
switch update {
case .noPassword:
assertionFailure()
break
case let .awaitingEmailConfirmation(password, pattern, codeLength):
let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: emailSet, pendingEmail: TwoStepVerificationPendingEmail(pattern: pattern, codeLength: codeLength), hasSecureValues: hasSecureValues)
dataPromise.set(.single(data))
case let .passwordSet(password, hasRecoveryEmail, hasSecureValues):
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
presentControllerImpl?(OverlayStatusController(theme: presentationData.theme, type: .genericSuccess(emailSet ? presentationData.strings.TwoStepAuth_EmailChangeSuccess : presentationData.strings.TwoStepAuth_EmailAddSuccess, false)), nil)
if let password = password {
let data: TwoStepVerificationUnlockSettingsControllerData = .manage(password: password, emailSet: hasRecoveryEmail, pendingEmail: nil, hasSecureValues: hasSecureValues)
dataPromise.set(.single(data))
} else {
dataPromise.set(.single(.access(configuration: nil))
|> then(twoStepVerificationConfiguration(account: context.account) |> map { TwoStepVerificationUnlockSettingsControllerData.access(configuration: TwoStepVerificationAccessConfiguration(configuration: $0, password: password)) }))
}
}
if shouldDismiss {
controller.dismiss()
}
})
presentControllerImpl?(controller, ViewControllerPresentationArguments(presentationAnimation: .modalSheet))
}
})
})
var initialFocusImpl: (() -> Void)?
var didAppear = false
let signal = combineLatest(context.sharedContext.presentationData, statePromise.get(), dataPromise.get() |> deliverOnMainQueue) |> deliverOnMainQueue
|> map { presentationData, state, data -> (ItemListControllerState, (ItemListNodeState, Any)) in
var rightNavigationButton: ItemListNavigationButton?
var emptyStateItem: ItemListControllerEmptyStateItem?
let title: String
switch data {
case let .access(configuration):
title = presentationData.strings.TwoStepAuth_Title
if let configuration = configuration {
if state.checking {
rightNavigationButton = ItemListNavigationButton(content: .none, style: .activity, enabled: true, action: {})
} else {
switch configuration {
case let .notSet(pendingEmail):
if let _ = pendingEmail {
rightNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Next), style: .bold, enabled: !state.emailCode.isEmpty, action: {
checkEmailConfirmation()
})
}
case .set:
rightNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Next), style: .bold, enabled: true, action: {
arguments.checkPassword()
})
}
}
} else {
emptyStateItem = ItemListLoadingIndicatorEmptyStateItem(theme: presentationData.theme)
}
case let .manage(manage):
title = presentationData.strings.PrivacySettings_TwoStepAuth
if state.checking {
rightNavigationButton = ItemListNavigationButton(content: .none, style: .activity, enabled: true, action: {})
} else {
if let _ = manage.pendingEmail {
rightNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Common_Next), style: .bold, enabled: !state.emailCode.isEmpty, action: {
checkEmailConfirmation()
})
}
}
}
let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(title), leftNavigationButton: nil, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false)
let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: twoStepVerificationUnlockSettingsControllerEntries(presentationData: presentationData, state: state, data: data), style: .blocks, focusItemTag: didAppear ? TwoStepVerificationUnlockSettingsEntryTag.password : nil, emptyStateItem: emptyStateItem, animateChanges: false)
return (controllerState, (listState, arguments))
}
|> afterDisposed {
actionsDisposable.dispose()
}
let controller = ItemListController(context: context, state: signal)
replaceControllerImpl = { [weak controller] c, animated in
(controller?.navigationController as? NavigationController)?.replaceTopController(c, animated: animated)
}
presentControllerImpl = { [weak controller] c, p in
if let controller = controller {
controller.present(c, in: .window(.root), with: p)
}
}
dismissImpl = { [weak controller] in
controller?.dismiss()
}
initialFocusImpl = { [weak controller] in
guard let controller = controller, controller.didAppearOnce else {
return
}
var resultItemNode: ItemListSingleLineInputItemNode?
let _ = controller.frameForItemNode({ itemNode in
if let itemNode = itemNode as? ItemListSingleLineInputItemNode, let tag = itemNode.tag, tag.isEqual(to: TwoStepVerificationUnlockSettingsEntryTag.password) {
resultItemNode = itemNode
return true
}
return false
})
if let resultItemNode = resultItemNode {
resultItemNode.focus()
}
}
controller.didAppear = { firstTime in
if !firstTime {
return
}
didAppear = true
initialFocusImpl?()
if openSetupPasswordImmediately {
arguments.openSetupPassword()
}
}
if case let .access(intro, _) = mode, intro {
actionsDisposable.add((remoteDataPromise.get()
|> take(1)
|> deliverOnMainQueue).start(next: { data in
if case let .access(configuration) = data, let config = configuration, case let .notSet(pendingEmail) = config, pendingEmail == nil {
let controller = PrivacyIntroController(context: context, mode: .twoStepVerification, arguments: PrivacyIntroControllerPresentationArguments(fadeIn: true), proceedAction: {
arguments.openSetupPassword()
})
replaceControllerImpl?(controller, false)
replaceControllerImpl = { [weak controller] c, animated in
(controller?.navigationController as? NavigationController)?.replaceTopController(c, animated: animated)
}
presentControllerImpl = { [weak controller] c, p in
if let controller = controller {
controller.present(c, in: .window(.root), with: p)
}
}
}
}))
}
return controller
}
| 58.184598 | 389 | 0.565175 |
f71fcdf43ea41ea98e54c4197ba2b51b4c7e09c1 | 3,142 | //
// AppDelegate.swift
// Twitter
//
// Created by David Kuchar on 5/18/15.
// Copyright (c) 2015 David Kuchar. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: userDidLogoutNotification, object: nil)
if User.currentUser != nil {
// Go to the logged in screen
println("Current user detected \(User.currentUser?.name)")
var nc = storyboard.instantiateViewControllerWithIdentifier("NavigationController") as! UINavigationController
window?.rootViewController = nc
}
return true
}
func userDidLogout() {
var vc = storyboard.instantiateInitialViewController() as! UIViewController
window?.rootViewController = vc
}
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:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
TwitterClient.sharedInstance().openURL(url)
return true
}
}
| 44.885714 | 285 | 0.709739 |
ffad66d4c8b1158eb23a97df888023679ed74ace | 7,061 | //
// BroadcastPreviewView.swift
// Broadcasting
//
// Created by Uldis Zingis on 10/06/2021.
//
import SwiftUI
import AmazonIVSBroadcast
struct BroadcastView: View {
@Environment(\.verticalSizeClass) var verticalSizeClass: UserInterfaceSizeClass?
@ObservedObject private var viewModel: BroadcastViewModel
@StateObject private var timeManager = ElapsedTimeAndDataManager()
@State var isDebugInfoPresent: Bool = false
@State var isControlButtonsPresent: Bool = true
init(viewModel: BroadcastViewModel) {
self.viewModel = viewModel
}
var body: some View {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
viewModel.previewView
.edgesIgnoringSafeArea(.all)
.blur(radius: viewModel.cameraIsOn ? 0 : 24)
.onTapGesture {
withAnimation() {
isControlButtonsPresent.toggle()
}
}
.onChange(of: viewModel.configurations.activeVideoConfiguration) { _ in
viewModel.deviceOrientationChanged(toLandscape: verticalSizeClass == .compact)
}
.onChange(of: verticalSizeClass) { vSizeClass in
viewModel.deviceOrientationChanged(toLandscape: vSizeClass == .compact)
}
if !viewModel.cameraIsOn {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
.opacity(0.5)
VStack(spacing: 10) {
Image(systemName: "video.slash.fill")
.foregroundColor(.white)
.font(.system(size: 38))
Text("Camera Off")
.foregroundColor(.white)
.font(Constants.fAppBoldExtraLarge)
}
}
}
if viewModel.isScreenSharingActive {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
VStack {
InformationBlock(
icon: "iphone.badge.play",
iconSize: 50,
iconColor: Constants.yellow,
withIconFrame: false,
title: "Screen sharing active",
description: "The camera is disabled while you are sharing your screen. Stop sharing to enable it again.",
height: 50
)
SimpleButton(title: "Stop sharing", height: 40, maxWidth: 200) {
viewModel.broadcastPicker.toggleView()
}
.padding(.top, 15)
}
.padding()
}
}
if verticalSizeClass == .compact {
// Landscape
HStack {
StatusBar(viewModel: viewModel, timeManager: timeManager)
.edgesIgnoringSafeArea(.all)
Spacer()
if isControlButtonsPresent {
ControlButtonsSlider(viewModel: viewModel,
isControlButtonsPresent: $isControlButtonsPresent,
isDebugInfoPresent: $isDebugInfoPresent)
.frame(minHeight: 100)
.transition(.move(edge: .trailing))
}
}
.sheet(isPresented: $viewModel.settingsOpen, content: {
SettingsView(viewModel: viewModel)
})
} else {
// Portrait
VStack {
StatusBar(viewModel: viewModel, timeManager: timeManager)
Spacer()
if isControlButtonsPresent {
ControlButtonsSlider(viewModel: viewModel,
isControlButtonsPresent: $isControlButtonsPresent,
isDebugInfoPresent: $isDebugInfoPresent)
.frame(minHeight: 100)
.transition(.move(edge: .bottom))
}
}
.sheet(isPresented: $viewModel.settingsOpen, content: {
SettingsView(viewModel: viewModel)
})
.edgesIgnoringSafeArea(.top)
}
if viewModel.developerMode && isDebugInfoPresent {
DebugInfo(viewModel: viewModel, isPresent: $isDebugInfoPresent)
.padding(.top, verticalSizeClass == .compact ? 0 : 90)
.padding(.bottom, verticalSizeClass == .compact ? 0 : 190)
.frame(maxWidth: verticalSizeClass == .compact ? 200 : .infinity,
maxHeight: verticalSizeClass == .compact ? 100 : .infinity)
}
if viewModel.isReconnectViewVisible {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
.opacity(0.7)
VStack(spacing: 10) {
Text("Reconnecting...")
.foregroundColor(.white)
.font(Constants.fAppBoldExtraLarge)
Text("The connection to the server was lost. The app will automatically try to reconnect.")
.multilineTextAlignment(.center)
.foregroundColor(.white)
.font(Constants.fAppRegular)
SimpleButton(title: "Don't reconnect", height: 37, font: Constants.fAppBold, backgroundColor: Constants.red) {
viewModel.cancelAutoReconnect()
}
.frame(width: 155)
.padding(.top, 40)
SimpleButton(title: "Hide this notice", height: 37) {
viewModel.isReconnectViewVisible = false
}
.frame(width: 155)
.padding(.top, 8)
}
}
}
}
.onAppear {
viewModel.observeUserDefaultChanges()
viewModel.initializeBroadcastSession()
}
.onReceive(NotificationCenter.default.publisher(for: AVAudioSession.interruptionNotification)) { notification in
viewModel.audioSessionInterrupted(notification)
}
.onChange(of: viewModel.sessionIsRunning, perform: { _ in
if viewModel.sessionIsRunning {
timeManager.start()
} else {
timeManager.stop()
}
})
}
}
| 40.348571 | 134 | 0.469763 |
878ba9b0c1a3a1f9e2b08d939745ff9006be8bb3 | 70 | import PackageDescription
let package = Package(
name: "libcapn"
)
| 11.666667 | 25 | 0.742857 |
79ffbbfedfbf2d2f2fe8ae8884e529d534f1ce8d | 2,768 | // --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// 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
/// an individual value in a ConditionalSchema
class ConditionalValue: Codable, LanguageShortcut {
/// per-language information for this value
public var language: Languages
/// the actual value
// TODO: Resolve issue with enum
let target: String // StringOrNumberOrBoolean
/// the source value
// TODO: Resolve issue with enum
let source: String // StringOrNumberOrBoolean
/// Additional metadata extensions dictionary
let extensions: [String: AnyCodable]?
enum CodingKeys: String, CodingKey {
case language, target, source, extensions
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
language = try container.decode(Languages.self, forKey: .language)
target = try container.decode(String.self, forKey: .target)
source = try container.decode(String.self, forKey: .source)
extensions = try? container.decode([String: AnyCodable].self, forKey: .extensions)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(language, forKey: .language)
try container.encode(target, forKey: .target)
try container.encode(source, forKey: .source)
if extensions != nil { try container.encode(extensions, forKey: .extensions) }
}
}
| 42.584615 | 90 | 0.682442 |
bf0dbac6b70b160b85b4703017472e29a7fe17ab | 1,320 | //
// File.swift
//
//
// Created by Stefan Urbanek on 02/04/2022.
//
import Foundation
extension Node {
var _traitHood: NeighbourhoodOfOne {
NeighbourhoodOfOne(self, selector:LinkSelector("trait"))
}
/// Get node trait, if it is associated with it.
///
public var trait: Trait? {
if let node = _traitHood.node {
return Trait(node)
}
else {
return nil
}
}
/// Set node trait.
///
/// This method connects the node with the trait. The optional ``attributes``
/// are added to the newly created link.
///
public func setTrait(_ trait: Trait, attributes: AttributeDictionary=[:]) {
_traitHood.set(trait.representedNode, attributes: attributes)
}
/// Removes node trait.
///
public func removeTrait() {
_traitHood.remove()
}
/// Get a named neighbourhood for the node.
///
public func neighbourhood(_ name: String) -> LabelledNeighbourhood? {
guard let trait = self.trait else {
return nil
}
guard let hoodTraitNode = trait.neighbourhoods[name] else {
return nil
}
let hoodTrait = NeighbourhoodTrait(hoodTraitNode)
return hoodTrait.neighbourhood(in: self)
}
}
| 23.571429 | 81 | 0.584091 |
295e8d7b1785a37fd54501d8ddc45a9ea952af7d | 23,581 | import Foundation
import TSCBasic
import TuistCore
import TuistGraph
import TuistSupport
import XcodeProj
public struct GroupFileElement: Hashable {
var path: AbsolutePath
var group: ProjectGroup
var isReference: Bool
init(path: AbsolutePath, group: ProjectGroup, isReference: Bool = false) {
self.path = path
self.group = group
self.isReference = isReference
}
}
// swiftlint:disable:next type_body_length
class ProjectFileElements {
// MARK: - Static
// swiftlint:disable:next force_try
static let localizedRegex = try! NSRegularExpression(
pattern: "(.+\\.lproj)/.+",
options: []
)
private static let localizedGroupExtensions = [
"storyboard",
"strings",
"xib",
"intentdefinition",
]
// MARK: - Attributes
var elements: [AbsolutePath: PBXFileElement] = [:]
var products: [String: PBXFileReference] = [:]
var sdks: [AbsolutePath: PBXFileReference] = [:]
var knownRegions: Set<String> = Set([])
// MARK: - Init
init(_ elements: [AbsolutePath: PBXFileElement] = [:]) {
self.elements = elements
}
func generateProjectFiles(
project: Project,
graphTraverser: GraphTraversing,
groups: ProjectGroups,
pbxproj: PBXProj
) throws {
var files = Set<GroupFileElement>()
try project.targets.forEach { target in
try files.formUnion(targetFiles(target: target))
}
let projectFileElements = projectFiles(project: project)
files.formUnion(projectFileElements)
let sortedFiles = files.sorted { one, two -> Bool in
one.path < two.path
}
/// Files
try generate(
files: sortedFiles,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: project.sourceRootPath
)
// Products
let directProducts = project.targets.map {
GraphDependencyReference.product(target: $0.name, productName: $0.productNameWithExtension)
}
// Dependencies
let dependencies = try graphTraverser.allProjectDependencies(path: project.path).sorted()
try generate(
dependencyReferences: Set(directProducts + dependencies),
groups: groups,
pbxproj: pbxproj,
sourceRootPath: project.sourceRootPath,
filesGroup: project.filesGroup
)
}
func projectFiles(project: Project) -> Set<GroupFileElement> {
var fileElements = Set<GroupFileElement>()
/// Config files
let configFiles = project.settings.configurations.values.compactMap { $0?.xcconfig }
fileElements.formUnion(configFiles.map {
GroupFileElement(path: $0, group: project.filesGroup)
})
// Additional files
fileElements.formUnion(project.additionalFiles.map {
GroupFileElement(
path: $0.path,
group: project.filesGroup,
isReference: $0.isReference
)
})
// Add the .storekit files if needed. StoreKit files must be added to the
// project/workspace so that the scheme can correctly reference them.
// In case the configuration already contains such file, we should avoid adding it twice
let storekitFiles = project.schemes.compactMap { scheme -> GroupFileElement? in
guard let path = scheme.runAction?.options.storeKitConfigurationPath else { return nil }
return GroupFileElement(path: path, group: project.filesGroup)
}
fileElements.formUnion(storekitFiles)
// Add the .gpx files if needed. GPS Exchange files must be added to the
// project/workspace so that the scheme can correctly reference them.
// In case the configuration already contains such file, we should avoid adding it twice
let gpxFiles = project.schemes.compactMap { scheme -> GroupFileElement? in
guard case let .gpxFile(path) = scheme.runAction?.options.simulatedLocation else {
return nil
}
return GroupFileElement(path: path, group: project.filesGroup)
}
fileElements.formUnion(gpxFiles)
return fileElements
}
func targetFiles(target: Target) throws -> Set<GroupFileElement> {
var files = Set<AbsolutePath>()
files.formUnion(target.sources.map(\.path))
files.formUnion(target.playgrounds)
files.formUnion(target.coreDataModels.map(\.path))
files.formUnion(target.coreDataModels.flatMap(\.versions))
if let headers = target.headers {
files.formUnion(headers.public)
files.formUnion(headers.private)
files.formUnion(headers.project)
}
// Support files
if let infoPlist = target.infoPlist, let path = infoPlist.path {
files.insert(path)
}
if let entitlements = target.entitlements {
files.insert(entitlements)
}
// Config files
target.settings?.configurations.xcconfigs().forEach { configFilePath in
files.insert(configFilePath)
}
// Additional files
files.formUnion(target.additionalFiles.map(\.path))
// Elements
var elements = Set<GroupFileElement>()
elements.formUnion(files.map { GroupFileElement(path: $0, group: target.filesGroup) })
elements.formUnion(target.resources.map {
GroupFileElement(
path: $0.path,
group: target.filesGroup,
isReference: $0.isReference
)
})
target.copyFiles.forEach {
elements.formUnion($0.files.map {
GroupFileElement(
path: $0.path,
group: target.filesGroup,
isReference: $0.isReference
)
})
}
return elements
}
func generate(
files: [GroupFileElement],
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath
) throws {
try files.forEach {
try generate(fileElement: $0, groups: groups, pbxproj: pbxproj, sourceRootPath: sourceRootPath)
}
}
func generate(
dependencyReferences: Set<GraphDependencyReference>,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath,
filesGroup: ProjectGroup
) throws {
let sortedDependencies = dependencyReferences.sorted()
func generatePrecompiled(_ path: AbsolutePath) throws {
let fileElement = GroupFileElement(path: path, group: filesGroup)
try generate(
fileElement: fileElement,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath
)
}
try sortedDependencies.forEach { dependency in
switch dependency {
case let .xcframework(path, _, _, _):
try generatePrecompiled(path)
case let .framework(path, _, _, _, _, _, _, _):
try generatePrecompiled(path)
case let .library(path, _, _, _):
try generatePrecompiled(path)
case let .bundle(path):
try generatePrecompiled(path)
case let .sdk(sdkNodePath, _, _):
generateSDKFileElement(
sdkNodePath: sdkNodePath,
toGroup: groups.frameworks,
pbxproj: pbxproj
)
case let .product(target: target, productName: productName, _):
generateProduct(
targetName: target,
productName: productName,
groups: groups,
pbxproj: pbxproj
)
}
}
}
private func generateProduct(
targetName: String,
productName: String,
groups: ProjectGroups,
pbxproj: PBXProj
) {
guard products[targetName] == nil else { return }
let fileType = RelativePath(productName).extension.flatMap { Xcode.filetype(extension: $0) }
let fileReference = PBXFileReference(
sourceTree: .buildProductsDir,
explicitFileType: fileType,
path: productName,
includeInIndex: false
)
pbxproj.add(object: fileReference)
groups.products.children.append(fileReference)
products[targetName] = fileReference
}
func generate(
fileElement: GroupFileElement,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath
) throws {
// The file already exists
if elements[fileElement.path] != nil { return }
let fileElementRelativeToSourceRoot = fileElement.path.relative(to: sourceRootPath)
let closestRelativeRelativePath = closestRelativeElementPath(pathRelativeToSourceRoot: fileElementRelativeToSourceRoot)
let closestRelativeAbsolutePath = sourceRootPath.appending(closestRelativeRelativePath)
// Add the first relative element.
let group: PBXGroup
switch fileElement.group {
case let .group(name: groupName):
group = try groups.projectGroup(named: groupName)
}
guard let firstElement = addElement(
relativePath: closestRelativeRelativePath,
isLeaf: closestRelativeRelativePath == fileElementRelativeToSourceRoot,
from: sourceRootPath,
toGroup: group,
pbxproj: pbxproj
)
else {
return
}
// If it matches the file that we are adding or it's not a group we can exit.
if (closestRelativeAbsolutePath == fileElement.path) || !(firstElement.element is PBXGroup) {
return
}
var lastGroup: PBXGroup! = firstElement.element as? PBXGroup
var lastPath: AbsolutePath = firstElement.path
let components = fileElement.path.relative(to: lastPath).components
for component in components.enumerated() {
if lastGroup == nil { return }
guard let element = addElement(
relativePath: RelativePath(component.element),
isLeaf: component.offset == components.count - 1,
from: lastPath,
toGroup: lastGroup!,
pbxproj: pbxproj
)
else {
return
}
lastGroup = element.element as? PBXGroup
lastPath = element.path
}
}
// MARK: - Internal
@discardableResult func addElement(
relativePath: RelativePath,
isLeaf: Bool,
from: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj
) -> (element: PBXFileElement, path: AbsolutePath)? {
let absolutePath = from.appending(relativePath)
if elements[absolutePath] != nil {
return (element: elements[absolutePath]!, path: from.appending(relativePath))
}
// If the path is ../../xx we specify the name
// to prevent Xcode from using that as a name.
var name: String?
let components = relativePath.components
if components.count != 1 {
name = components.last!
}
// Add the file element
if isLocalized(path: absolutePath) {
// Localized container (e.g. /path/to/en.lproj) we don't add it directly
// an element will get added once the next path component is evaluated
//
// note: assumption here is a path to a nested resource is always provided
return (element: toGroup, path: absolutePath)
} else if isLocalized(path: from) {
// Localized file (e.g. /path/to/en.lproj/foo.png)
addLocalizedFile(
localizedFile: absolutePath,
toGroup: toGroup,
pbxproj: pbxproj
)
return nil
} else if isVersionGroup(path: absolutePath) {
return addVersionGroupElement(
from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj
)
} else if !isLeaf {
return addGroupElement(
from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj
)
} else {
addFileElement(
from: from,
fileAbsolutePath: absolutePath,
fileRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj
)
return nil
}
}
func addLocalizedFile(
localizedFile: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj
) {
// e.g.
// from: resources/en.lproj/
// localizedFile: resources/en.lproj/App.strings
let fileName = localizedFile.basename // e.g. App.strings
let localizedContainer = localizedFile.parentDirectory // e.g. resources/en.lproj
let variantGroupPath = localizedContainer
.parentDirectory
.appending(component: fileName) // e.g. resources/App.strings
let variantGroup: PBXVariantGroup
if let existingVariantGroup = self.variantGroup(containing: localizedFile) {
variantGroup = existingVariantGroup.group
// For variant groups formed by Interface Builder files (.xib or .storyboard) and corresponding .strings
// files, name and path of the group must have the extension of the Interface Builder file. Since the order
// in which such groups are formed is not deterministic, we must change the name and path here as necessary.
if ["xib", "storyboard"].contains(localizedFile.extension), !variantGroup.nameOrPath.hasSuffix(fileName) {
variantGroup.name = fileName
elements[existingVariantGroup.path] = nil
elements[variantGroupPath] = variantGroup
}
} else {
variantGroup = addVariantGroup(
variantGroupPath: variantGroupPath,
localizedName: fileName,
toGroup: toGroup,
pbxproj: pbxproj
)
}
// Localized element
addLocalizedFileElement(
localizedFile: localizedFile,
variantGroup: variantGroup,
localizedContainer: localizedContainer,
pbxproj: pbxproj
)
}
private func addVariantGroup(
variantGroupPath: AbsolutePath,
localizedName: String,
toGroup: PBXGroup,
pbxproj: PBXProj
) -> PBXVariantGroup {
let variantGroup = PBXVariantGroup(children: [], sourceTree: .group, name: localizedName)
pbxproj.add(object: variantGroup)
toGroup.children.append(variantGroup)
elements[variantGroupPath] = variantGroup
return variantGroup
}
private func addLocalizedFileElement(
localizedFile: AbsolutePath,
variantGroup: PBXVariantGroup,
localizedContainer: AbsolutePath,
pbxproj: PBXProj
) {
let localizedFilePath = localizedFile.relative(to: localizedContainer.parentDirectory)
let lastKnownFileType = localizedFile.extension.flatMap { Xcode.filetype(extension: $0) }
let language = localizedContainer.basenameWithoutExt
let localizedFileReference = PBXFileReference(
sourceTree: .group,
name: language,
lastKnownFileType: lastKnownFileType,
path: localizedFilePath.pathString
)
pbxproj.add(object: localizedFileReference)
variantGroup.children.append(localizedFileReference)
knownRegions.insert(language)
}
func addVersionGroupElement(
from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj
) -> (element: PBXFileElement, path: AbsolutePath) {
let group = XCVersionGroup(
currentVersion: nil,
path: folderRelativePath.pathString,
name: name,
sourceTree: .group,
versionGroupType: versionGroupType(for: folderRelativePath)
)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addGroupElement(
from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj
) -> (element: PBXFileElement, path: AbsolutePath) {
let group = PBXGroup(children: [], sourceTree: .group, name: name, path: folderRelativePath.pathString)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addFileElement(
from _: AbsolutePath,
fileAbsolutePath: AbsolutePath,
fileRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj
) {
let lastKnownFileType = fileAbsolutePath.extension.flatMap { Xcode.filetype(extension: $0) }
let xcLanguageSpecificationIdentifier = lastKnownFileType == "file.playground" ? "xcode.lang.swift" : nil
let file = PBXFileReference(
sourceTree: .group,
name: name,
lastKnownFileType: lastKnownFileType,
path: fileRelativePath.pathString,
xcLanguageSpecificationIdentifier: xcLanguageSpecificationIdentifier
)
pbxproj.add(object: file)
toGroup.children.append(file)
elements[fileAbsolutePath] = file
}
private func generateSDKFileElement(
sdkNodePath: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj
) {
guard sdks[sdkNodePath] == nil else {
return
}
addSDKElement(sdkNodePath: sdkNodePath, toGroup: toGroup, pbxproj: pbxproj)
}
private func addSDKElement(
sdkNodePath: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj
) {
let sdkPath = sdkNodePath.relative(to: AbsolutePath("/")) // SDK paths are relative
let lastKnownFileType = sdkPath.extension.flatMap { Xcode.filetype(extension: $0) }
let file = PBXFileReference(
sourceTree: .developerDir,
name: sdkPath.basename,
lastKnownFileType: lastKnownFileType,
path: sdkPath.pathString
)
pbxproj.add(object: file)
toGroup.children.append(file)
sdks[sdkNodePath] = file
}
func group(path: AbsolutePath) -> PBXGroup? {
elements[path] as? PBXGroup
}
func product(target name: String) -> PBXFileReference? {
products[name]
}
func sdk(path: AbsolutePath) -> PBXFileReference? {
sdks[path]
}
func file(path: AbsolutePath) -> PBXFileReference? {
elements[path] as? PBXFileReference
}
func isLocalized(path: AbsolutePath) -> Bool {
path.extension == "lproj"
}
func isVersionGroup(path: AbsolutePath) -> Bool {
path.extension == "xcdatamodeld"
}
/// Normalizes a path. Some paths have no direct representation in Xcode,
/// like localizable files. This method normalizes those and returns a project
/// representable path.
///
/// - Example:
/// /test/es.lproj/Main.storyboard ~> /test/es.lproj
func normalize(_ path: AbsolutePath) -> AbsolutePath {
let pathString = path.pathString
let range = NSRange(location: 0, length: pathString.count)
if let localizedMatch = ProjectFileElements.localizedRegex.firstMatch(
in: pathString,
options: [],
range: range
) {
let lprojPath = (pathString as NSString).substring(with: localizedMatch.range(at: 1))
return AbsolutePath(lprojPath)
} else {
return path
}
}
/// Returns the relative path of the closest relative element to the source root path.
/// If source root path is /a/b/c/project/ and file path is /a/d/myfile.swift
/// this method will return ../../../d/
func closestRelativeElementPath(pathRelativeToSourceRoot: RelativePath) -> RelativePath {
let relativePathComponents = pathRelativeToSourceRoot.components
let firstElementComponents = relativePathComponents.reduce(into: [String]()) { components, component in
let isLastRelative = components.last == ".." || components.last == "."
if components.last != nil, !isLastRelative { return }
components.append(component)
}
if firstElementComponents.isEmpty, !relativePathComponents.isEmpty {
return RelativePath(relativePathComponents.first!)
} else {
return RelativePath(firstElementComponents.joined(separator: "/"))
}
}
func variantGroup(containing localizedFile: AbsolutePath) -> (group: PBXVariantGroup, path: AbsolutePath)? {
let variantGroupBasePath = localizedFile.parentDirectory.parentDirectory
// Variant groups used to localize Interface Builder or Intent Definition files (.xib, .storyboard or .intentdefition)
// can contain files of these, respectively, and corresponding .strings files. However, the groups' names must always
// use the extension of the main file, i.e. either .xib or .storyboard. Since the order in which such
// groups are formed is not deterministic, we must check for existing groups having the same name as the
// localized file and any of these extensions.
if let fileExtension = localizedFile.extension,
Self.localizedGroupExtensions.contains(fileExtension)
{
for groupExtension in Self.localizedGroupExtensions {
let variantGroupPath = variantGroupBasePath.appending(
component: "\(localizedFile.basenameWithoutExt).\(groupExtension)"
)
if let variantGroup = elements[variantGroupPath] as? PBXVariantGroup {
return (variantGroup, variantGroupPath)
}
}
}
let variantGroupPath = variantGroupBasePath.appending(component: localizedFile.basename)
guard let variantGroup = elements[variantGroupPath] as? PBXVariantGroup else {
return nil
}
return (variantGroup, variantGroupPath)
}
private func versionGroupType(for filePath: RelativePath) -> String? {
switch filePath.extension {
case "xcdatamodeld":
return "wrapper.xcdatamodel"
case let fileExtension?:
return Xcode.filetype(extension: fileExtension)
default:
return nil
}
}
}
| 35.837386 | 127 | 0.609686 |
9c1e39d1cda7342df0a77584ce7d4b92d58a60d0 | 2,478 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
import NIO
/**
The Amazon API Gateway Management API allows you to directly manage runtime aspects of your deployed APIs. To use it, you must explicitly set the SDK's endpoint to point to the endpoint of your deployed API. The endpoint will be of the form https://{api-id}.execute-api.{region}.amazonaws.com/{stage}, or will be the endpoint corresponding to your API's custom domain and base path, if applicable.
*/
public struct ApiGatewayManagementApi {
public let client: AWSClient
public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, sessionToken: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil, middlewares: [AWSServiceMiddleware] = [], eventLoopGroupProvider: AWSClient.EventLoopGroupProvider = .useAWSClientShared) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
service: "execute-api",
serviceProtocol: ServiceProtocol(type: .restjson, version: ServiceProtocol.Version(major: 1, minor: 1)),
apiVersion: "2018-11-29",
endpoint: endpoint,
middlewares: middlewares,
possibleErrorTypes: [ApiGatewayManagementApiErrorType.self],
eventLoopGroupProvider: eventLoopGroupProvider
)
}
/// Delete the connection with the provided id.
@discardableResult public func deleteConnection(_ input: DeleteConnectionRequest) -> Future<Void> {
return client.send(operation: "DeleteConnection", path: "/@connections/{connectionId}", httpMethod: "DELETE", input: input)
}
/// Get information about the connection with the provided id.
public func getConnection(_ input: GetConnectionRequest) -> Future<GetConnectionResponse> {
return client.send(operation: "GetConnection", path: "/@connections/{connectionId}", httpMethod: "GET", input: input)
}
/// Sends the provided data to the specified connection.
@discardableResult public func postToConnection(_ input: PostToConnectionRequest) -> Future<Void> {
return client.send(operation: "PostToConnection", path: "/@connections/{connectionId}", httpMethod: "POST", input: input)
}
}
| 55.066667 | 397 | 0.716303 |
203e51542e41a2628fbb3f71f52dfe35ac297535 | 4,167 | //
// HotListCell.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/4/23.
// Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved.
//
import UIKit
import SDWebImage
import ReactiveCocoa
import ReactiveSwift
import Result
class HotListCell: UICollectionViewCell {
private var nickNameLabel: UILabel! ///昵称
private var hierarchyImgView: UIImageView! ///等级
private var categoryLabel: UILabel! ///家族
private var liveMarkImgView: UIImageView! ///直播标签
private var numberLabel: UILabel! ///观看人数
private var backgroundImgView: UIImageView! ///封面(可以用Button backgroundimage)
private var actionBtn: LinkButton! ///响应点击的按钮(可以直接使用backgroundImagView的点击手势)
var actionSignal: Signal<LinkButton, NoError> {
return actionBtn.reactive.controlEvents(.touchUpInside)
}
public func setupCell(nickName: String?, starLevel: Int?, category: String?, liveMark: UIImage?, number: Int?, backgroundImagURLString: String?, roomLink: String) {
backgroundImgView = UIImageView()
backgroundImgView.isUserInteractionEnabled = true ///使用imageView一定注意将用户交互设为true
backgroundImgView.sd_setImage(with: URL(string: backgroundImagURLString!), placeholderImage: #imageLiteral(resourceName: "no_follow_250x247"))
self.contentView.addSubview(backgroundImgView)
backgroundImgView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.size.equalToSuperview()
}
///其他控件都放到这里
let infoContainerView = UIView()
infoContainerView.backgroundColor = UIColor.clear
self.backgroundImgView.addSubview(infoContainerView)
infoContainerView.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.bottom.equalTo(-5)
make.height.equalTo(self.contentView).dividedBy(5)///高度等于cell的1/4
}
nickNameLabel = UILabel()
nickNameLabel.text = nickName
nickNameLabel.textColor = UIColor.white
infoContainerView.addSubview(nickNameLabel)
nickNameLabel.snp.makeConstraints { (make) in
make.left.top.right.equalToSuperview()
make.height.equalTo(infoContainerView).dividedBy(2)
}
hierarchyImgView = UIImageView()
hierarchyImgView.image = UIImage(named: "girl_star" + String(describing: starLevel!) + "_40x19")
infoContainerView.addSubview(hierarchyImgView)
hierarchyImgView.snp.makeConstraints { (make) in
make.left.bottom.equalToSuperview()
make.top.equalTo(nickNameLabel.snp.bottom)
make.width.equalTo(infoContainerView).dividedBy(5)
}
numberLabel = UILabel()
numberLabel.textAlignment = .right
numberLabel.text = String(describing: number!) + "人"
numberLabel.textColor = UIColor.white
infoContainerView.addSubview(numberLabel)
numberLabel.snp.makeConstraints { (make) in
make.left.equalTo(hierarchyImgView.snp.right)
make.top.bottom.equalTo(hierarchyImgView)
make.right.equalTo(infoContainerView)
}
categoryLabel = UILabel()
categoryLabel.text = category
categoryLabel.textColor = UIColor.white
self.backgroundImgView.addSubview(categoryLabel)
categoryLabel.snp.makeConstraints { (make) in
make.topMargin.leftMargin.equalTo(10)
make.size.equalTo(CGSize(width: 50, height: 20))
}
liveMarkImgView = UIImageView()
liveMarkImgView.image = liveMark
self.backgroundImgView.addSubview(liveMarkImgView)
liveMarkImgView.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.right.equalTo(-10)
make.size.equalTo(CGSize(width: 40, height: 20))
}
actionBtn = LinkButton(type: .custom)
actionBtn.link = roomLink
self.backgroundImgView.addSubview(actionBtn)
actionBtn.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.size.equalToSuperview()
}
}
}
| 40.456311 | 168 | 0.668107 |
8a97bb8eb1a2fbc6d40145754f00af9c38134a46 | 5,042 | import RxSwift
class TransactionsPresenter {
private let interactor: ITransactionsInteractor
private let router: ITransactionsRouter
private let factory: ITransactionViewItemFactory
private let loader: TransactionsLoader
private let dataSource: TransactionsMetadataDataSource
weak var view: ITransactionsView?
init(interactor: ITransactionsInteractor, router: ITransactionsRouter, factory: ITransactionViewItemFactory, loader: TransactionsLoader, dataSource: TransactionsMetadataDataSource) {
self.interactor = interactor
self.router = router
self.factory = factory
self.loader = loader
self.dataSource = dataSource
}
}
extension TransactionsPresenter: ITransactionLoaderDelegate {
func fetchRecords(fetchDataList: [FetchData]) {
interactor.fetchRecords(fetchDataList: fetchDataList)
}
func didChangeData() {
// print("Reload View")
view?.reload()
}
func reload(with diff: [IndexChange]) {
view?.reload(with: diff)
}
}
extension TransactionsPresenter: ITransactionsViewDelegate {
func viewDidLoad() {
interactor.initialFetch()
}
func onFilterSelect(coin: Coin?) {
let coins = coin.map { [$0] } ?? []
interactor.set(selectedCoins: coins)
}
var itemsCount: Int {
return loader.itemsCount
}
func item(forIndex index: Int) -> TransactionViewItem {
let item = loader.item(forIndex: index)
let lastBlockHeight = dataSource.lastBlockHeight(coin: item.coin)
let threshold = dataSource.threshold(coin: item.coin)
let rate = dataSource.rate(coin: item.coin, timestamp: item.record.timestamp)
return factory.viewItem(fromItem: loader.item(forIndex: index), lastBlockHeight: lastBlockHeight, threshold: threshold, rate: rate)
}
func onBottomReached() {
DispatchQueue.main.async {
// print("On Bottom Reached")
self.loader.loadNext()
}
}
func onTransactionItemClick(index: Int) {
router.openTransactionInfo(viewItem: item(forIndex: index))
}
}
extension TransactionsPresenter: ITransactionsInteractorDelegate {
func onUpdate(selectedCoins: [Coin]) {
// print("Selected Coin Codes Updated: \(selectedCoins)")
loader.set(coins: selectedCoins)
loader.loadNext(initial: true)
}
func onUpdate(coinsData: [(Coin, Int, Int?)]) {
var coins = [Coin]()
for (coin, threshold, lastBlockHeight) in coinsData {
coins.append(coin)
dataSource.set(threshold: threshold, coin: coin)
if let lastBlockHeight = lastBlockHeight {
dataSource.set(lastBlockHeight: lastBlockHeight, coin: coin)
}
}
interactor.fetchLastBlockHeights()
if coins.count < 2 {
view?.show(filters: [])
} else {
view?.show(filters: [nil] + coins)
}
loader.set(coins: coins)
loader.loadNext(initial: true)
}
func onUpdateBaseCurrency() {
// print("Base Currency Updated")
dataSource.clearRates()
view?.reload()
fetchRates(recordsData: loader.allRecordsData)
}
func onUpdate(lastBlockHeight: Int, coin: Coin) {
// print("Last Block Height Updated: \(coin) - \(lastBlockHeight)")
let oldLastBlockHeight = dataSource.lastBlockHeight(coin: coin)
dataSource.set(lastBlockHeight: lastBlockHeight, coin: coin)
if let threshold = dataSource.threshold(coin: coin), let oldLastBlockHeight = oldLastBlockHeight {
let indexes = loader.itemIndexesForPending(coin: coin, blockHeight: oldLastBlockHeight - threshold)
if !indexes.isEmpty {
view?.reload(indexes: indexes)
}
} else {
view?.reload()
}
}
func didUpdate(records: [TransactionRecord], coin: Coin) {
loader.didUpdate(records: records, coin: coin)
fetchRates(recordsData: [coin: records])
}
func didFetch(rateValue: Decimal, coin: Coin, currency: Currency, timestamp: Double) {
dataSource.set(rate: CurrencyValue(currency: currency, value: rateValue), coin: coin, timestamp: timestamp)
let indexes = loader.itemIndexes(coin: coin, timestamp: timestamp)
if !indexes.isEmpty {
view?.reload(indexes: indexes)
}
}
func didFetch(recordsData: [Coin: [TransactionRecord]]) {
// print("Did Fetch Records: \(records.map { key, value -> String in "\(key) - \(value.count)" })")
fetchRates(recordsData: recordsData)
loader.didFetch(recordsData: recordsData)
}
private func fetchRates(recordsData: [Coin: [TransactionRecord]]) {
var timestampsData = [Coin: [Double]]()
for (coin, records) in recordsData {
timestampsData[coin] = records.map { $0.timestamp }
}
interactor.fetchRates(timestampsData: timestampsData)
}
}
| 29.48538 | 186 | 0.645775 |
1476b73df7e219ee9c74da3748dd4b3ab7ab72e2 | 5,952 | // Copyright 2016 Razeware Inc. (see LICENSE.txt for details)
import Foundation
/*:
## Basic Control Flow
### Question 1
What’s wrong with the following code?
let firstName = "Matt"
if firstName == "Matt" {
let lastName = "Galloway"
} else if firstName == "Ray" {
let lastName = "Wenderlich"
}
let fullName = firstName + " " + lastName
*/
// `lastName` is not visible to the scope when setting `fullName`.
// A correct solution:
let firstName = "Matt"
var lastName = ""
if firstName == "Matt" {
lastName = "Galloway"
} else if firstName == "Ray" {
lastName = "Wenderlich"
}
let fullName = firstName + " " + lastName
/*:
### Question 2
In each of the following statements, what is the value of the Boolean `answer` constant?
*/
let answer4 = true && true
// true
let answer5 = false || false
// false
let answer6 = (true && 1 != 2) || (4 > 3 && 100 < 1)
// true
let answer7 = ((10 / 2) > 3) && ((10 % 2) == 0)
// true
/*:
### Question 3
Suppose the squares on a chessboard are numbered left to right, top to bottom, with 0 being the top-left square and 63 being the bottom-right square. Rows are numbered top to bottom, 0 to 7. Columns are numbered left to right, 0 to 7. Given a current position on the chessboard, expressed as a row and column number, calculate the next position on the chessboard, again expressed as a row and column number. The ordering is determined by the numbering from 0 to 63. The position after 63 is again 0.
*/
let row = 7
let column = 7
var nextRow = row
var nextColumn = column + 1
if nextColumn > 7 {
nextColumn = 0
nextRow += 1
}
if nextRow > 7 {
nextRow = 0
}
print("The position after (\(row), \(column)) is (\(nextRow), \(nextColumn))")
/*:
### Question 4
Given the coefficients a, b and c, calculate the solutions to a quadratic equation with these coefficients. Take into account the different number of solutions (0, 1 or 2). If you need a math refresher, this Wikipedia article on the quadratic equation will help [https://en.wikipedia.org/wiki/Quadratic_formula](https://en.wikipedia.org/wiki/Quadratic_formula).
*/
let a = 1.0
let b = -5.0
let c = 6.0
let d = b * b - 4 * a * c
if d > 0 {
let x1 = (-b + sqrt(d)) / (2 * a)
let x2 = (-b - sqrt(d)) / (2 * a)
print("The solutions are \(x1) and \(x2)")
} else if d == 0 {
let x = -b / (2 * a)
print("Both solutions are \(x)")
} else {
print("This equation has no solutions")
}
/*:
### Question 5
Given a month (represented with a `String` in all lowercase) and the current year (represented with an `Int`), calculate the number of days in the month. Remember that because of leap years, "february" has 29 days when the year is a multiple of 4 but not a multiple of 100. February also has 29 days when the year is a multiple of 400.
*/
let month = "february"
let year = 2016
if month == "january" || month == "march" || month == "may" || month == "july" || month == "august" || month == "october" || month == "december" {
print("This month has 31 days")
} else if month == "april" || month == "june" || month == "september" || month == "november" {
print("This month has 30 days")
} else if month == "february" && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
print("This month has 29 days")
} else if month == "february" {
print("This month has 28 days")
} else {
print("This is not a valid month")
}
/*:
### Question 6
Given a number, determine if this number is a power of 2. (Hint: you can use `log2(number)` to find the base 2 logarithm of `number`. `log2(number)` will return a whole number if `number` is a power of two. You can also solve the problem using a loop and no logarithm.)
*/
let number = 1024.0
/*:
Solution using logarithms:
*/
let log = log2(number)
if log == Double(Int(log)) {
print("\(number) is a power of 2")
} else {
print("\(number) is not a power of 2")
}
/*:
Solution without using logarithms:
*/
var dividend = number
while dividend.truncatingRemainder(dividingBy: 2) == 0 {
dividend /= 2
}
if dividend == 1 {
print("\(number) is a power of 2")
} else {
print("\(number) is not a power of 2")
}
/*:
### Question 7
Print a table of the first 10 powers of 2.
*/
var exponent = 0
var power = 1
while exponent <= 10 {
print("\(exponent)\t\(power)")
exponent += 1
power *= 2
}
/*:
### Question 8
Given a number n, calculate the n-th Fibonacci number. (Recall Fibonacci is 1, 1, 2, 3, 5, 8, 13, ... Start with 1 and 1 and add these values together to get the next value. The next value is the sum of the previous two. So the next value in this case is 8+13 = 21.)
*/
let goal = 10 // the value of n
var current = 1
var previous = 1
var done = 2
while done < goal {
let next = current + previous
previous = current
current = next
done += 1
}
print("Fibonacci number \(goal) is \(current)")
/*:
### Question 9
Given a number n, calculate the factorial of n. (Example: 4 factorial is equal to 1 * 2 * 3 * 4.)
*/
let n = 5
var accumulator = 1
done = 1
while done < n {
done += 1
accumulator *= done
}
print("\(n)! is \(accumulator)")
/*:
### Question 10
Given a number between 2 and 12, calculate the odds of rolling this number using two six-sided dice. Compute it by exhaustively looping through all of the combinations and counting the fraction of outcomes that give you that value. Don't use a formula.
*/
let targetValue = 7
var combinationsFound = 0
var valueOnFirstDice = 1
while valueOnFirstDice <= 6 {
var valueOnSecondDice = 1
while valueOnSecondDice <= 6 {
if valueOnFirstDice + valueOnSecondDice == targetValue {
combinationsFound += 1
}
valueOnSecondDice += 1
}
valueOnFirstDice += 1
}
let percentage = Int(Double(combinationsFound) / 36 * 100)
print("The odds of rolling a \(targetValue) are \(combinationsFound) in 36 or \(percentage)%")
| 29.909548 | 500 | 0.648185 |
2fab6377331334789d1343c84468813d54a5d435 | 262 | //
// Int32Message.swift
//
// Created by wesgoodhoofd on 2018-09-19.
//
import UIKit
import ObjectMapper
public class Int32Message: RBSMessage {
public var data: Int32 = 0
public override func mapping(map: Map) {
data <- map["data"]
}
}
| 14.555556 | 44 | 0.652672 |
defcf6453015433701bebb46d055be6f492545ed | 164 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(XYPlotForSwiftTests.allTests),
]
}
#endif
| 16.4 | 47 | 0.682927 |
ddcba2bafd62aaa66ab6dbf437aff352147d0b55 | 8,569 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// WSCompression.swift
//
// Created by Joseph Ross on 7/16/14.
// Copyright © 2017 Joseph Ross & Vluxe. 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.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Compression implementation is implemented in conformance with RFC 7692 Compression Extensions
// for WebSocket: https://tools.ietf.org/html/rfc7692
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
public class WSCompression: CompressionHandler {
let headerWSExtensionName = "Sec-WebSocket-Extensions"
var decompressor: Decompressor?
var compressor: Compressor?
var decompressorTakeOver = false
var compressorTakeOver = false
public init() {
}
public func load(headers: [String: String]) {
guard let extensionHeader = headers[headerWSExtensionName] else { return }
decompressorTakeOver = false
compressorTakeOver = false
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
decompressor = Decompressor(windowBits: val)
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressor = Compressor(windowBits: val)
}
} else if part == "client_no_context_takeover" {
compressorTakeOver = true
} else if part == "server_no_context_takeover" {
decompressorTakeOver = true
}
}
}
public func decompress(data: Data, isFinal: Bool) -> Data? {
guard let decompressor = decompressor else { return nil }
do {
let decompressedData = try decompressor.decompress(data, finish: isFinal)
if decompressorTakeOver {
try decompressor.reset()
}
return decompressedData
} catch {
//do nothing with the error for now
}
return nil
}
public func compress(data: Data) -> Data? {
guard let compressor = compressor else { return nil }
do {
let compressedData = try compressor.compress(data)
if compressorTakeOver {
try compressor.reset()
}
return compressedData
} catch {
//do nothing with the error for now
}
return nil
}
}
class Decompressor {
// private var strm = z_stream()
private var buffer = [UInt8](repeating: 0, count: 0x2000)
private var inflateInitialized = false
private let windowBits: Int
init?(windowBits: Int) {
self.windowBits = windowBits
guard initInflate() else { return nil }
}
private func initInflate() -> Bool {
// if Z_OK == inflateInit2_(&strm, -CInt(windowBits),
// ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))
// {
// inflateInitialized = true
// return true
// }
return false
}
func reset() throws {
teardownInflate()
guard initInflate() else { throw WSError(type: .compressionError, message: "Error for decompressor on reset", code: 0) }
}
func decompress(_ data: Data, finish: Bool) throws -> Data {
return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Data in
return try decompress(bytes: bytes, count: data.count, finish: finish)
}
}
func decompress(bytes: UnsafePointer<UInt8>, count: Int, finish: Bool) throws -> Data {
var decompressed = Data()
try decompress(bytes: bytes, count: count, out: &decompressed)
if finish {
let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF]
try decompress(bytes: tail, count: tail.count, out: &decompressed)
}
return decompressed
}
private func decompress(bytes: UnsafePointer<UInt8>, count: Int, out: inout Data) throws {
// var res: CInt = 0
// strm.next_in = UnsafeMutablePointer<UInt8>(mutating: bytes)
// strm.avail_in = CUnsignedInt(count)
//
// repeat {
// buffer.withUnsafeMutableBytes { (bufferPtr) in
// strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress
// strm.avail_out = CUnsignedInt(bufferPtr.count)
//
// res = inflate(&strm, 0)
// }
//
// let byteCount = buffer.count - Int(strm.avail_out)
// out.append(buffer, count: byteCount)
// } while res == Z_OK && strm.avail_out == 0
//
// guard (res == Z_OK && strm.avail_out > 0)
// || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)
// else {
// throw WSError(type: .compressionError, message: "Error on decompressing", code: 0)
// }
}
private func teardownInflate() {
// if inflateInitialized, Z_OK == inflateEnd(&strm) {
// inflateInitialized = false
// }
}
deinit {
teardownInflate()
}
}
class Compressor {
// private var strm = z_stream()
private var buffer = [UInt8](repeating: 0, count: 0x2000)
private var deflateInitialized = false
private let windowBits: Int
init?(windowBits: Int) {
self.windowBits = windowBits
guard initDeflate() else { return nil }
}
private func initDeflate() -> Bool {
// if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
// -CInt(windowBits), 8, Z_DEFAULT_STRATEGY,
// ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))
// {
// deflateInitialized = true
// return true
// }
return false
}
func reset() throws {
teardownDeflate()
guard initDeflate() else { throw WSError(type: .compressionError, message: "Error for compressor on reset", code: 0) }
}
func compress(_ data: Data) throws -> Data {
var compressed = Data()
// var res: CInt = 0
// data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
// strm.next_in = UnsafeMutablePointer<UInt8>(mutating: ptr)
// strm.avail_in = CUnsignedInt(data.count)
//
// repeat {
// buffer.withUnsafeMutableBytes { (bufferPtr) in
// strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress
// strm.avail_out = CUnsignedInt(bufferPtr.count)
//
// res = deflate(&strm, Z_SYNC_FLUSH)
// }
//
// let byteCount = buffer.count - Int(strm.avail_out)
// compressed.append(buffer, count: byteCount)
// }
// while res == Z_OK && strm.avail_out == 0
//
// }
//
// guard res == Z_OK && strm.avail_out > 0
// || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)
// else {
// throw WSError(type: .compressionError, message: "Error on compressing", code: 0)
// }
//
// compressed.removeLast(4)
return compressed
}
private func teardownDeflate() {
// if deflateInitialized, Z_OK == deflateEnd(&strm) {
// deflateInitialized = false
// }
}
deinit {
teardownDeflate()
}
}
| 34.692308 | 128 | 0.555141 |
9b354e86d60d414c741fffdaa405364fa8447701 | 2,414 | //
// AuthView.swift
// Music
//
// Created by Shotaro Hirano on 2021/08/24.
//
import SwiftUI
import WebKit
struct AuthView: UIViewRepresentable {
var loadStatusChanged: ((Bool, Error?) -> Void)? = nil
typealias UIViewType = WKWebView
func makeUIView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = context.coordinator
if let url = AuthManager.shared.signInURL {
webView.load(URLRequest(url: url))
}
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if let url = uiView.url {
uiView.load(URLRequest(url: url))
}
}
func onLoadStatusChanged(perform: ((Bool, Error?) -> Void)?) -> some View {
var copy = self
copy.loadStatusChanged = perform
return copy
}
func makeCoordinator() -> AuthView.Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, WKNavigationDelegate {
let parent: AuthView
init(_ parent: AuthView) {
self.parent = parent
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
parent.loadStatusChanged?(true, nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
parent.loadStatusChanged?(false, nil)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
parent.loadStatusChanged?(false, error)
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
guard let url = webView.url else { return }
guard let code = URLComponents(string: url.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value else { return }
webView.isHidden = true
AuthManager.shared.exchangeCodeForToken(code: code)
}
}
}
struct AuthView_Previews: PreviewProvider {
static var previews: some View {
AuthView()
}
}
| 30.948718 | 142 | 0.613919 |
8a51b2ccc547cbed2da594aadc978110bb7263ff | 995 | //
// LogFileViewController.swift
// RSSISniffer
//
// Created by Robert Huston on 7/4/20.
// Copyright © 2020 Pinpoint Dynamics. All rights reserved.
//
import UIKit
class LogFileViewController: UIViewController {
@IBOutlet weak var logTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
loadLogFile()
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
@IBAction func doClear(_ sender: Any) {
LogFileManager.clear(fileName: Constants.Files.DeviceSurveillance)
loadLogFile()
}
@IBAction func doCopy(_ sender: Any) {
UIPasteboard.general.string = LogFileManager.read(fileName: Constants.Files.DeviceSurveillance)
}
func loadLogFile() {
logTextView.text = LogFileManager.read(fileName: Constants.Files.DeviceSurveillance)
}
}
| 23.690476 | 103 | 0.688442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.