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
|
---|---|---|---|---|---|
c100790bb16cd7c16f7223e426b3c067825218a5 | 1,047 | // Copyright 2020 Carton contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import OpenCombine
import TSCBasic
import TSCUtility
final class Watcher {
private let subject = PassthroughSubject<[AbsolutePath], Never>()
private var fsWatch: FSWatch!
let publisher: AnyPublisher<[AbsolutePath], Never>
init(_ paths: [AbsolutePath]) throws {
publisher = subject.eraseToAnyPublisher()
fsWatch = FSWatch(paths: paths, latency: 0.1) { [weak self] in
self?.subject.send($0)
}
try fsWatch.start()
}
}
| 31.727273 | 75 | 0.730659 |
50d01698508db96ea9579b298e36f84351b02e95 | 6,238 | //
// APIDemoView.swift
// SwiftyBase
//
// Created by MacMini-2 on 05/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
import SwiftyBase
class APIDemoView: BaseView,UITableViewDataSource, UITableViewDelegate {
// MARK: - Attributes -
var listTableView : UITableView!
var countrylist : AllContry!
// MARK: - Lifecycle -
override init(frame: CGRect) {
super.init(frame:frame)
self.loadViewControls()
self.setViewlayout()
self.getListServerRequest()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
deinit{
listTableView = nil
}
// MARK: - Layout -
override func loadViewControls(){
super.loadViewControls()
listTableView = UITableView(frame: CGRect.zero, style: .plain)
listTableView.translatesAutoresizingMaskIntoConstraints = false
//must required for self.getDictionaryOfVariableBindings funcation Used
listTableView.layer.setValue("listTableView", forKey: ControlConstant.name)
listTableView.register(UITableViewCell.self, forCellReuseIdentifier: CellIdentifire.defaultCell)
listTableView.backgroundColor = UIColor.clear
listTableView.separatorStyle = .singleLine
listTableView.separatorColor = AppColor.buttonSecondaryBG.value
listTableView.clipsToBounds = true
listTableView.tableHeaderView = UIView(frame: CGRect.zero)
listTableView.tableFooterView = UIView(frame: CGRect.zero)
listTableView.rowHeight = UITableView.automaticDimension
self.addSubview(listTableView)
listTableView.delegate = self
listTableView.dataSource = self
}
override func setViewlayout(){
super.setViewlayout()
baseLayout.viewDictionary = self.getDictionaryOfVariableBindings(superView: self, viewDic: NSDictionary()) as? [String : AnyObject]
let controlTopBottomPadding : CGFloat = ControlConstant.verticalPadding
let controlLeftRightPadding : CGFloat = ControlConstant.horizontalPadding
baseLayout.metrics = ["controlTopBottomPadding" : controlTopBottomPadding,
"controlLeftRightPadding" : controlLeftRightPadding
]
baseLayout.control_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|[listTableView]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: baseLayout.viewDictionary)
baseLayout.control_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|[listTableView]|", options:[.alignAllLeading , .alignAllTrailing], metrics: nil, views: baseLayout.viewDictionary)
self.addConstraints(baseLayout.control_H)
self.addConstraints(baseLayout.control_V)
self.layoutSubviews()
}
// MARK: - Public Interface -
// MARK: - User Interaction -
// MARK: - Internal Helpers -
// MARK: - Server Request -
func getListServerRequest(){
self.isShowEmptyView(true,message: "API Call Running...")
APIManager.shared.getRequest(URL: API.countries, Parameter: NSDictionary(), completionHandler:{(result) in
switch result{
case .Success(let object, _):
self.isShowEmptyView(false,message: "API Call Running...")
AppUtility.executeTaskInMainQueueWithCompletion {
self.hideToastActivity()
BaseProgressHUD.shared.hide()
}
self.makeToast(message: "Success")
let jsonData = (object as! String).parseJSONString
self.countrylist = AllContry.init(fromDictionary: jsonData as! [String : Any])
AppUtility.executeTaskInMainQueueWithCompletion {
self.listTableView.reloadWithAnimation()
}
break
case .Error(let error):
AppUtility.executeTaskInMainQueueWithCompletion {
self.hideToastActivity()
BaseProgressHUD.shared.hide()
}
print(error ?? "")
break
case .Internet(let isOn):
print("Internet is \(isOn)")
self.handleNetworkCheck(isAvailable: isOn, viewController: self, showLoaddingView: true)
break
}
})
}
// MARK: - UITableView DataSource Methods -
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if self.countrylist != nil{
return self.countrylist.result.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifire.defaultCell) as UITableViewCell?
if(cell == nil){
cell = UITableViewCell(style: .subtitle, reuseIdentifier: CellIdentifire.defaultCell)
}
let result : Result = self.countrylist.result[indexPath.row]
cell?.textLabel?.text = result.name
return cell!
}
// MARK: - UITableView Delegate Methods -
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
}
}
| 31.989744 | 205 | 0.604681 |
621172c53d21ae461f2ad45abda8c1f6b51d504b | 2,308 | //
// SceneDelegate.swift
// CustomReorderableTableView
//
// Created by hanwe lee on 2020/11/23.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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).
}
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.
}
}
| 43.54717 | 147 | 0.714905 |
bbac9532cb3a58620f09af5d767fc98357badbe2 | 2,729 | //
// ViewController.swift
// TypedNotificationExample
//
// Copyright (c) 2019 Rocket Insights, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import TypedNotification
import UIKit
class ViewController: UITableViewController {
private var token: NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
token = NotificationCenter.default.addObserver(for: TestNotification.self, queue: .main) { [weak self] notification in
switch notification {
case .eventA:
self?.showMessage("Received eventA")
case .eventB:
self?.showMessage("Received eventB")
case .eventC:
self?.showMessage("Received eventC")
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
DispatchQueue.global(qos: .background).async {
switch indexPath.row {
case 0:
NotificationCenter.default.post(TestNotification.eventA, from: self)
case 1:
NotificationCenter.default.post(TestNotification.eventB, from: self)
case 2:
NotificationCenter.default.post(TestNotification.eventC, from: self)
default:
break
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
private func showMessage(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true)
}
}
| 36.878378 | 126 | 0.671675 |
2284b641a013ef356ab2e35e549f58a43edfdcb5 | 1,659 | //
// AppDelegate.swift
// EarthQuake
//
// Created by Rahul Dubey on 3/8/21.
//
import UIKit
import CorePackage
@main
class EQAppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NetworkMonitor.shared.startMonitoring()
return true
}
// MARK: UISceneSession Lifecycle
@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
@available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func applicationDidEnterBackground(_ application: UIApplication) {
NetworkMonitor.shared.stopMonitoring()
}
func applicationWillResignActive(_ application: UIApplication) {
NetworkMonitor.shared.stopMonitoring()
}
}
| 36.866667 | 179 | 0.73478 |
e49c95e31b0185e3d0059cc12fede71211382446 | 3,365 | //
// EditCheckersThemeView.swift
// GradientGames
//
// Created by Sam McBroom on 3/3/22.
//
import SwiftUI
struct EditCheckersThemeView: View {
@EnvironmentObject private var navigation: Navigation
@State var theme: CheckersTheme
@State private var symbol: String
@State private var squareLight: Color
@State private var squareDark: Color
@State private var pieceLight: Color
@State private var pieceDark: Color
@State private var showShare = false
init(_ theme: CheckersTheme) {
symbol = theme.symbol!
squareLight = Color(theme.squareLight)
squareDark = Color(theme.squareDark)
pieceLight = Color(theme.pieceLight)
pieceDark = Color(theme.pieceDark)
self.theme = theme
}
private func themeURL() -> URL {
let pieceLightShortHex = String(UIColor(pieceLight).hex, radix: 16)
let pieceLightHex = String(repeating: "0", count: 6 - pieceLightShortHex.count) + pieceLightShortHex
let pieceDarkShortHex = String(UIColor(pieceDark).hex, radix: 16)
let pieceDarkHex = String(repeating: "0", count: 6 - pieceDarkShortHex.count) + pieceDarkShortHex
let squareLightShortHex = String(UIColor(squareLight).hex, radix: 16)
let squareLightHex = String(repeating: "0", count: 6 - squareLightShortHex.count) + squareLightShortHex
let squareDarkShortHex = String(UIColor(squareDark).hex, radix: 16)
let squareDarkHex = String(repeating: "0", count: 6 - squareDarkShortHex.count) + squareDarkShortHex
var components = URLComponents()
components.scheme = "https"
components.host = "www.sammcb.com"
components.path = ThemeLink.checkers.rawValue
components.queryItems = [
URLQueryItem(name: "symbol", value: symbol),
URLQueryItem(name: "pieceLight", value: pieceLightHex),
URLQueryItem(name: "pieceDark", value: pieceDarkHex),
URLQueryItem(name: "squareLight", value: squareLightHex),
URLQueryItem(name: "squareDark", value: squareDarkHex)
]
guard let url = components.url else {
return URL(string: "https://www.sammcb.com")!
}
return url
}
var body: some View {
Form {
Section("Symbol") {
TextField("Symbol", text: $symbol)
.onChange(of: symbol) { _ in
theme.symbol = symbol
Store.shared.save()
}
}
Section("Colors") {
ColorPicker("Light squares", selection: $squareLight, supportsOpacity: false)
.onChange(of: squareLight) { _ in
theme.squareLightRaw = UIColor(squareLight).hex
Store.shared.save()
}
ColorPicker("Dark squares", selection: $squareDark, supportsOpacity: false)
.onChange(of: squareDark) { _ in
theme.squareDarkRaw = UIColor(squareDark).hex
Store.shared.save()
}
ColorPicker("Light pieces", selection: $pieceLight, supportsOpacity: false)
.onChange(of: pieceLight) { _ in
theme.pieceLightRaw = UIColor(pieceLight).hex
Store.shared.save()
}
ColorPicker("Dark pieces", selection: $pieceDark, supportsOpacity: false)
.onChange(of: pieceDark) { _ in
theme.pieceDarkRaw = UIColor(pieceDark).hex
Store.shared.save()
}
}
}
.toolbar {
Button {
showShare = true
} label: {
Label("Share", systemImage: "square.and.arrow.up")
}
}
.onChange(of: navigation.editing) { _ in
showShare = false
}
.sheet(isPresented: $showShare) {
ShareSheet(activityItems: [themeURL()])
}
.navigationTitle(symbol)
}
}
| 31.448598 | 105 | 0.699257 |
f5f3ff07165c827b1f97ccafa8d535a13c6ab622 | 3,451 | //
// AddStoryViewModel.swift
// StoryMap
//
// Created by Dory on 21/10/2021.
//
import Foundation
class AddStoryViewModel: AddStoryViewModelType {
let titlePlaceholder: String = LocalizationKit.addStory.titlePlaceholder
let confirmTitle: String = LocalizationKit.addStory.confirmButtonTitle
var location: Location
var title: String? = "title"
var titleError: String {
get {
title?.isEmpty ?? true ? LocalizationKit.addStory.titleError : " "
}
}
var addPhotoTitle: String {
get {
image == nil ? LocalizationKit.addStory.addPhotoButtonTitle : LocalizationKit.addStory.replacePhotoButtonTitle
}
}
var confirmButtonEnabled: Bool {
get {
!(title?.isEmpty ?? true) && image != nil
}
}
var image: Data?
var onShowAlert: ((AlertConfig) -> Void)?
var onShowImagePicker: ((PhotoInputType) -> Void)?
var onConfirm: ((Story) -> Void)?
var onClose: (() -> Void)?
private let realmDataProvider = RealmDataProvider.shared
init(location: Location) {
self.location = location
}
func showPhotoAlert() {
let alert = AlertConfig(
title: LocalizationKit.addStory.addPhotoDialogueTitle,
message: nil,
style: .actionSheet,
actions: [
AlertAction(
title: LocalizationKit.addStory.addPhotoCaptureAction,
style: .default,
handler: { [weak self] in
self?.onShowImagePicker?(.camera)
}
),
AlertAction(
title: LocalizationKit.addStory.addPhotoChooseAction,
style: .default,
handler: { [weak self] in
self?.onShowImagePicker?(.photoLibrary)
}
),
AlertAction(
title: LocalizationKit.general.cancel,
style: .cancel,
handler: nil
)
]
)
onShowAlert?(alert)
}
func showAreYouSureAlert() {
let alert = AlertConfig(
title: LocalizationKit.addStory.closeDialogueTitle,
message: LocalizationKit.addStory.closeDialogueMessage,
style: .actionSheet,
actions: [
AlertAction(
title: LocalizationKit.general.close,
style: .destructive,
handler: { [weak self] in
self?.onClose?()
}
),
AlertAction(
title: LocalizationKit.general.cancel,
style: .cancel,
handler: nil
)
]
)
onShowAlert?(alert)
}
func capturePhoto() {
onShowImagePicker?(.camera)
}
func confirm() {
guard let title = title, let image = image else {
return
}
let story = Story(
title: title,
image: image,
location: location.randomize()
)
realmDataProvider?.write(object: story)
onConfirm?(story)
}
func close() {
showAreYouSureAlert()
}
}
| 26.960938 | 122 | 0.497247 |
117d05c0fe97bfe6d478dcf608409c738a34ec63 | 856 | import Foundation
import MatomoTracker
extension MatomoTracker {
static let shared: MatomoTracker = {
let queue = UserDefaultsQueue(UserDefaults.standard, autoSave: true)
let dispatcher = URLSessionDispatcher(baseURL: URL(string: "https://demo2.matomo.org/piwik.php")!)
let matomoTracker = MatomoTracker(siteId: "23", queue: queue, dispatcher: dispatcher)
matomoTracker.logger = DefaultLogger(minLevel: .info)
matomoTracker.migrateFromFourPointFourSharedInstance()
return matomoTracker
}()
private func migrateFromFourPointFourSharedInstance() {
guard !UserDefaults.standard.bool(forKey: "migratedFromFourPointFourSharedInstance") else { return }
copyFromOldSharedInstance()
UserDefaults.standard.set(true, forKey: "migratedFromFourPointFourSharedInstance")
}
}
| 42.8 | 108 | 0.734813 |
e0914dac8eac3d649bf2b7777f53c5388ade685b | 2,289 | //
// SceneDelegate.swift
// Xcode12.5
//
// Created by thirata on 2021/05/23.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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).
}
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.
}
}
| 43.188679 | 147 | 0.712538 |
148b5e8aaddb4957a0852f7934309ba0bd2fd810 | 1,097 | //
// ListEventsCharacteristic.swift
// CoreLock
//
// Created by Alsey Coleman Miller on 8/31/19.
//
import Foundation
import Bluetooth
/// List events request
public struct ListEventsCharacteristic: TLVCharacteristic, Codable, Equatable {
public static let uuid = BluetoothUUID(rawValue: "98433693-D5BB-44A4-A929-63B453C3A8C4")!
public static let service: GATTProfileService.Type = LockService.self
public static let properties: Bluetooth.BitMaskOptionSet<GATT.Characteristic.Property> = [.write]
/// Identifier of key making request.
public let identifier: UUID
/// HMAC of key and nonce, and HMAC message
public let authentication: Authentication
/// Fetch limit for events to view.
public let fetchRequest: LockEvent.FetchRequest?
public init(identifier: UUID,
authentication: Authentication,
fetchRequest: LockEvent.FetchRequest? = nil) {
self.identifier = identifier
self.authentication = authentication
self.fetchRequest = fetchRequest
}
}
| 28.868421 | 101 | 0.690975 |
f88c2e6e2dd89769e93aebb8713f81c98d53b76b | 377 | //
// ViewController.swift
// FastComponent
//
// Created by Rdxer on 07/18/2017.
// Copyright (c) 2017 Rdxer. All rights reserved.
//
import UIKit
import FastComponent
import XXLogger
import Material
import SwiftyJSON
import Eureka
import Async
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 13.464286 | 50 | 0.697613 |
f9ff2fc98c3c22c44971d33532fd3fbfa1445d10 | 1,420 | //
// AuthorsViewController.swift
// BookShelf
//
// Created by Chuck Perdue on 8/3/19.
// Copyright © 2019 SycloneFX, LLC. All rights reserved.
//
import UIKit
class AuthorsViewController: UIViewController {
// Outlets
@IBOutlet var tableView: UITableView!
// Variables
var authors = [Author]()
override func viewDidLoad() {
super.viewDidLoad()
//authors = DataService.instance.authors
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
authors = DataService.instance.authors
tableView.reloadData()
}
// Actions
}
extension AuthorsViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return authors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AuthorCell", for: indexPath)
let author = authors[indexPath.row]
cell.textLabel?.text = author.name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
DataService.instance.authorIndex = indexPath.row
performSegue(withIdentifier: "AuthorSegue", sender: self)
}
}
| 24.067797 | 98 | 0.711972 |
623d0c064bb38f7b6c34b458a5bab14b8fa56176 | 5,359 | //
// HitsConnector.swift
// InstantSearchCore
//
// Created by Vladislav Fitc on 29/11/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
import Foundation
/// Component that manages and displays a list of search results
///
/// [Documentation](https://www.algolia.com/doc/api-reference/widgets/hits/ios/)
public class HitsConnector<Hit: Codable> {
/// Searcher that handles your searches
public let searcher: Searcher
/// Logic applied to the hits
public let interactor: HitsInteractor<Hit>
/// FilterState that holds your filters
public let filterState: FilterState?
/// Connection between hits interactor and filter state
public let filterStateConnection: Connection?
/// Connection between hits interactor and searcher
public let searcherConnection: Connection
/// Connections between interactor and controllers
public var controllerConnections: [Connection]
internal init<S: Searcher>(searcher: S,
interactor: HitsInteractor<Hit>,
filterState: FilterState? = .none,
connectSearcher: (S) -> Connection) {
self.searcher = searcher
self.filterState = filterState
self.interactor = interactor
self.filterStateConnection = filterState.flatMap(interactor.connectFilterState)
self.searcherConnection = connectSearcher(searcher)
self.controllerConnections = []
}
internal convenience init<S: Searcher, Controller: HitsController>(searcher: S,
interactor: HitsInteractor<Hit>,
filterState: FilterState? = .none,
connectSearcher: (S) -> Connection,
controller: Controller,
externalReload: Bool = false) where Controller.DataSource == HitsInteractor<Hit> {
self.init(searcher: searcher,
interactor: interactor,
filterState: filterState,
connectSearcher: connectSearcher)
connectController(controller, externalReload: externalReload)
}
}
extension HitsConnector: Connection {
public func connect() {
filterStateConnection?.connect()
searcherConnection.connect()
controllerConnections.forEach { $0.connect() }
}
public func disconnect() {
filterStateConnection?.disconnect()
searcherConnection.disconnect()
controllerConnections.forEach { $0.disconnect() }
}
}
// MARK: - Convenient initializers
public extension HitsConnector {
/**
- Parameters:
- searcher: Searcher that handles your searches.
- interactor: External hits interactor
- filterState: FilterState that holds your filters
*/
convenience init(searcher: HitsSearcher,
interactor: HitsInteractor<Hit> = .init(),
filterState: FilterState? = .none) {
self.init(searcher: searcher,
interactor: interactor,
filterState: filterState,
connectSearcher: interactor.connectSearcher)
Telemetry.shared.traceConnector(type: .hits,
parameters: [
filterState == nil ? .none : .filterStateParameter
])
}
/**
- Parameters:
- appID: ID of your application.
- apiKey: Your application API Key. Be sure to use your Search-only API key.
- indexName: Name of the index to search
- infiniteScrolling: Whether or not infinite scrolling is enabled.
- showItemsOnEmptyQuery: If false, no results are displayed when the user hasn’t entered any query text.
- filterState: FilterState that holds your filters
*/
convenience init(appID: ApplicationID,
apiKey: APIKey,
indexName: IndexName,
infiniteScrolling: InfiniteScrolling = Constants.Defaults.infiniteScrolling,
showItemsOnEmptyQuery: Bool = Constants.Defaults.showItemsOnEmptyQuery,
filterState: FilterState? = .none) {
let searcher = HitsSearcher(appID: appID,
apiKey: apiKey,
indexName: indexName)
let interactor = HitsInteractor<Hit>(infiniteScrolling: infiniteScrolling, showItemsOnEmptyQuery: showItemsOnEmptyQuery)
self.init(searcher: searcher,
interactor: interactor,
filterState: filterState,
connectSearcher: interactor.connectSearcher)
Telemetry.shared.traceConnector(type: .hits,
parameters: [
.appID,
.apiKey,
.indexName,
infiniteScrolling == Constants.Defaults.infiniteScrolling ? .none : .infiniteScrolling,
showItemsOnEmptyQuery == Constants.Defaults.showItemsOnEmptyQuery ? .none : .showItemsOnEmptyQuery,
filterState == nil ? .none : .filterStateParameter
])
}
}
| 39.696296 | 151 | 0.590035 |
e4671f25140003e3ea75dd56f0ce421e380bb759 | 1,071 | /**
* Umbra
* Copyright (c) Luca Meghnagi 2021
* MIT license, see LICENSE file for details
*/
import UIKit
public extension UIView {
struct Shadow {
public var color = UIColor.black
public var opacity = Float(0)
public var offset = CGSize.zero
public var radius = CGFloat(0)
public var path: CGPath? = nil
}
var shadow: Shadow {
get {
Shadow(
color: layer.shadowColor.flatMap(UIColor.init) ?? .black,
opacity: layer.shadowOpacity,
offset: layer.shadowOffset,
radius: layer.shadowRadius,
path: layer.shadowPath
)
}
set {
layer.shadowColor = newValue.color.cgColor
layer.shadowOpacity = newValue.opacity
layer.shadowOffset = newValue.offset
layer.shadowRadius = newValue.radius
layer.shadowPath = newValue.path
}
}
static let none = UIView.Shadow()
}
| 23.8 | 73 | 0.533147 |
3356a8490708e23b337ebd6bc1dc1e84b18f977e | 9,196 | import FlutterMacOS
import Foundation
import AVFoundation
public class FlutterTtsPlugin: NSObject, FlutterPlugin, AVSpeechSynthesizerDelegate {
final var iosAudioCategoryKey = "iosAudioCategoryKey"
final var iosAudioCategoryOptionsKey = "iosAudioCategoryOptionsKey"
let synthesizer = AVSpeechSynthesizer()
var language: String = AVSpeechSynthesisVoice.currentLanguageCode()
var rate: Float = AVSpeechUtteranceDefaultSpeechRate
var languages = Set<String>()
var volume: Float = 1.0
var pitch: Float = 1.0
var voice: AVSpeechSynthesisVoice?
var channel = FlutterMethodChannel()
init(channel: FlutterMethodChannel) {
super.init()
self.channel = channel
synthesizer.delegate = self
setLanguages()
}
private func setLanguages() {
for voice in AVSpeechSynthesisVoice.speechVoices(){
self.languages.insert(voice.language)
}
}
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_tts", binaryMessenger: registrar.messenger)
let instance = FlutterTtsPlugin(channel: channel)
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "speak":
let text: String = call.arguments as! String
self.speak(text: text, result: result)
break
case "synthesizeToFile":
guard let args = call.arguments as? [String: Any] else {
result("iOS could not recognize flutter arguments in method: (sendParams)")
return
}
let text = args["text"] as! String
let fileName = args["fileName"] as! String
self.synthesizeToFile(text: text, fileName: fileName, result: result)
break
case "pause":
self.pause(result: result)
break
case "setLanguage":
let language: String = call.arguments as! String
self.setLanguage(language: language, result: result)
break
case "setSpeechRate":
let rate: Double = call.arguments as! Double
self.setRate(rate: Float(rate))
result(1)
break
case "setVolume":
let volume: Double = call.arguments as! Double
self.setVolume(volume: Float(volume), result: result)
break
case "setPitch":
let pitch: Double = call.arguments as! Double
self.setPitch(pitch: Float(pitch), result: result)
break
case "stop":
self.stop()
result(1)
break
case "getLanguages":
self.getLanguages(result: result)
break
case "getSpeechRateValidRange":
self.getSpeechRateValidRange(result: result)
break
case "isLanguageAvailable":
let language: String = call.arguments as! String
self.isLanguageAvailable(language: language, result: result)
break
case "getVoices":
self.getVoices(result: result)
break
case "setVoice":
let voiceName = call.arguments as! String
self.setVoice(voiceName: voiceName, result: result)
break
default:
result(FlutterMethodNotImplemented)
}
}
private func speak(text: String, result: FlutterResult) {
if (self.synthesizer.isPaused) {
if (self.synthesizer.continueSpeaking()) {
result(1)
} else {
result(0)
}
} else {
let utterance = AVSpeechUtterance(string: text)
if self.voice != nil {
utterance.voice = self.voice!
} else {
utterance.voice = AVSpeechSynthesisVoice(language: self.language)
}
utterance.rate = self.rate
utterance.volume = self.volume
utterance.pitchMultiplier = self.pitch
self.synthesizer.speak(utterance)
result(1)
}
}
private func synthesizeToFile(text: String, fileName: String, result: FlutterResult) {
var output: AVAudioFile?
var failed = false
let utterance = AVSpeechUtterance(string: text)
if #available(iOS 13.0, *) {
self.synthesizer.write(utterance) { (buffer: AVAudioBuffer) in
guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
NSLog("unknow buffer type: \(buffer)")
failed = true
return
}
print(pcmBuffer.format)
if pcmBuffer.frameLength == 0 {
// finished
} else {
// append buffer to file
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(fileName)
NSLog("Saving utterance to file: \(fileURL.absoluteString)")
if output == nil {
do {
output = try AVAudioFile(
forWriting: fileURL,
settings: pcmBuffer.format.settings,
commonFormat: .pcmFormatInt16,
interleaved: false)
} catch {
NSLog(error.localizedDescription)
failed = true
return
}
}
try! output!.write(from: pcmBuffer)
}
}
} else {
result("Unsupported iOS version")
}
if failed {
result(0)
}
result(1)
}
private func pause(result: FlutterResult) {
if (self.synthesizer.pauseSpeaking(at: AVSpeechBoundary.word)) {
result(1)
} else {
result(0)
}
}
private func setLanguage(language: String, result: FlutterResult) {
if !(self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) {
result(0)
} else {
self.language = language
self.voice = nil
result(1)
}
}
private func setRate(rate: Float) {
self.rate = rate
}
private func setVolume(volume: Float, result: FlutterResult) {
if (volume >= 0.0 && volume <= 1.0) {
self.volume = volume
result(1)
} else {
result(0)
}
}
private func setPitch(pitch: Float, result: FlutterResult) {
if (volume >= 0.5 && volume <= 2.0) {
self.pitch = pitch
result(1)
} else {
result(0)
}
}
private func stop() {
self.synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
}
private func getLanguages(result: FlutterResult) {
result(Array(self.languages))
}
private func getSpeechRateValidRange(result: FlutterResult) {
let validSpeechRateRange: [String:String] = [
"min": String(AVSpeechUtteranceMinimumSpeechRate),
"normal": String(AVSpeechUtteranceDefaultSpeechRate),
"max": String(AVSpeechUtteranceMaximumSpeechRate),
"platform": "ios"
]
result(validSpeechRateRange)
}
private func isLanguageAvailable(language: String, result: FlutterResult) {
var isAvailable: Bool = false
if (self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) {
isAvailable = true
}
result(isAvailable);
}
private func getVoices(result: FlutterResult) {
if #available(iOS 9.0, *) {
let voices = NSMutableArray()
for voice in AVSpeechSynthesisVoice.speechVoices() {
voices.add(voice.name)
}
result(voices)
} else {
// Since voice selection is not supported below iOS 9, make voice getter and setter
// have the same bahavior as language selection.
getLanguages(result: result)
}
}
private func setVoice(voiceName: String, result: FlutterResult) {
if #available(iOS 9.0, *) {
if let voice = AVSpeechSynthesisVoice.speechVoices().first(where: { $0.name == voiceName }) {
self.voice = voice
self.language = voice.language
result(1)
return
}
result(0)
} else {
setLanguage(language: voiceName, result: result)
}
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
self.channel.invokeMethod("speak.onComplete", arguments: nil)
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
self.channel.invokeMethod("speak.onStart", arguments: nil)
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
self.channel.invokeMethod("speak.onPause", arguments: nil)
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
self.channel.invokeMethod("speak.onContinue", arguments: nil)
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
self.channel.invokeMethod("speak.onCancel", arguments: nil)
}
public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let nsWord = utterance.speechString as NSString
let data: [String:String] = [
"text": utterance.speechString,
"start": String(characterRange.location),
"end": String(characterRange.location + characterRange.length),
"word": nsWord.substring(with: characterRange)
]
self.channel.invokeMethod("speak.onProgress", arguments: data)
}
}
| 31.385666 | 153 | 0.656481 |
f7228e53adc76c9bcf673b43d97e4d0e872874fc | 285 | //
// ArrayExtension.swift
// PrincessGuide
//
// Created by zzk on 2018/7/8.
// Copyright © 2018 zzk. All rights reserved.
//
import Foundation
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
| 15.833333 | 51 | 0.607018 |
e4d8e84c5aa98ebf5ce7f2024316fda605bde5a6 | 7,098 | //
// HomeContentView.swift
// RodrigoSantos-Portfolio
//
// Created by Rodrigo Santos on 28/05/20.
// Copyright © 2020 Rodrigo Santos. All rights reserved.
//
import SwiftUI
// MARK: - Home View
struct HomeContentView: View {
@ObservedObject var sot: HomeSourceOfTruth
@State var time = Timer.publish(every: 0.1, on: .current, in: .tracking).autoconnect()
@State var show = false
var body: some View {
ZStack(alignment: .top, content: {
ScrollView(.vertical, showsIndicators: false, content: {
VStack {
GeometryReader { g in
Image ("poster")
.resizable()
.offset(y: g.frame(in: .global).minY > 0 ?
-g.frame(in: .global).minY : 0)
.frame(height: g.frame(in: .global).minY > 0 ? UIScreen.main.bounds.height / 2.2 +
g.frame(in: .global).minY :
UIScreen.main.bounds.height / 2.2)
.onReceive(self.time) { (_) in
let y = g.frame(in: .global).minY
if -y > (UIScreen.main.bounds.height / 2.2) - 50 {
withAnimation(){
self.show = true
}
}else{
withAnimation(){
self.show = false
}
}
}
}
.frame(height: UIScreen.main.bounds.height / 2.2)
VStack {
HStack {
Text("New Game We Love")
.font(.title)
.fontWeight(.bold)
Spacer()
Button(action: {}) {
Text("See All")
.fontWeight(.bold)
}
}
VStack (spacing: 20) {
ForEach(data) { item in
CardView(data: item)
}
}
.padding(.top)
}
.padding()
Spacer()
}
})
if (self.show) {
TopView()
}
})
.edgesIgnoringSafeArea(.all)
}
}
// MARK: - Card View
struct CardView: View {
var data: Card
var body: some View {
HStack(alignment: .top, spacing: 20) {
Image(self.data.image)
VStack(alignment: .leading, spacing: 6) {
Text(self.data.title)
.fontWeight(.bold)
Text(self.data.title)
.font(.caption)
.foregroundColor(.gray)
HStack(spacing: 12) {
Button(action: {}) {
Text("Get")
.padding(.vertical, 10)
.padding(.horizontal, 25)
.background(Color.primary.opacity(0.06))
.clipShape(Capsule())
}
Text("In-App\n Purchases")
.font(.caption)
.foregroundColor(.gray)
}
}
Spacer(minLength: 0)
}
}
}
// MARK: - Top View
struct TopView: View {
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .top) {
Image("apple")
.renderingMode(.template)
.resizable()
.frame(width: 25, height: 30)
.foregroundColor(.primary)
Text("Arcade")
.font(.title)
.fontWeight(.bold)
}
Text("One mounth free, then $4.99/month")
.font(.caption)
.foregroundColor(.gray)
}
Spacer(minLength: 0)
NavigationLink(destination: MapContentView()) {
Text("Try it free")
.foregroundColor(.white)
.padding(.vertical, 10)
.padding(.horizontal, 25)
.background(Color.blue)
.clipShape(Capsule())
}
}
.padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top == 0 ? 15 : (UIApplication.shared.windows.first?.safeAreaInsets.top)! + 5)
.padding(.horizontal)
.padding(.bottom)
.background(BlurBG())
}
}
// MARK: - Blur Background
struct BlurBG : UIViewRepresentable {
func makeUIView(context: Context) -> UIVisualEffectView {
// for dark mode adoption...
let view = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial))
return view
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
}
}
#if DEBUG
struct HomeContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
HomeContentView(sot: HomeSourceOfTruth())
.previewDevice(PreviewDevice(rawValue: "iPhone 8"))
.previewDisplayName("iPhone 8")
HomeContentView(sot: HomeSourceOfTruth())
.previewDevice(PreviewDevice(rawValue: "iPhone XS Max"))
.previewDisplayName("iPhone XS Max")
}
}
}
#endif
// MARK: - Data local
var data = [
Card(id: 0, image: "g1", title: "Zombie Gunship Survival", subTitle: "Tour the apocalypse"),
Card(id: 1, image: "g2", title: "Portal", subTitle: "Travel through dimensions"),
Card(id: 2, image: "g3", title: "Wave Form", subTitle: "Fun enagaging wave game"),
Card(id: 3, image: "g4", title: "Temple Run", subTitle: "Run for your life"),
Card(id: 4, image: "g5", title: "World of Warcrat", subTitle: "Be whoever you want"),
Card(id: 5, image: "g6", title: "Alto’s Adventure", subTitle: "A snowboarding odyssey"),
Card(id: 6, image: "g7", title: "Space Frog", subTitle: "Jump and have fun"),
Card(id: 7, image: "g8", title: "Dinosaur Mario", subTitle: "Keep running")
]
| 33.013953 | 152 | 0.409411 |
e40abda2d432599cf94df87d01b31c18332f4b4e | 1,353 | //
// RawDataRoutes.swift
// HubKit
//
// Created by Loïc GRIFFIE on 25/09/2018.
// Copyright © 2018 Loïc GRIFFIE. All rights reserved.
//
import Alamofire
import HubkitModel
import Foundation
extension RawData {
/// Create a new session raw data
@discardableResult
public static func create(in session: HubkitModel.Session,
_ device: Device,
_ file: MultiPart,
progress: @escaping (Double) -> Void,
completion: @escaping (Result<Self, AFError>) -> Void) -> DataRequest? {
let parameters: Parameters = [
"session": session.id,
"device": device.id
]
return Hubkit.shared.upload(action: "raw_datas",
parameters: parameters,
files: [file],
progress: progress,
completion: completion)
}
/// Get the raw data for the given identifier
@discardableResult
public static func get(with identifier: String,
completion: @escaping (Result<Self, AFError>) -> Void) -> DataRequest? {
Hubkit.shared.get(action: "raw_datas/\(identifier)", completion: completion)
}
}
| 33.825 | 102 | 0.524021 |
e22eebd0522bbc7c95ca4c4b4520dc98c0446a78 | 1,083 | //
// GMDirection.swift
// GridMapKit
//
// Created by Calle Englund on 2016-12-07.
// Copyright © 2016 Calle Englund. All rights reserved.
//
import Foundation
import GameplayKit
public enum GMDirection {
case east
case northEast
case north
case northWest
case west
case southWest
case south
case southEast
public func point(relativeTo point: vector_int2) -> vector_int2 {
switch self {
case .east:
return vector_int2(point.x + 1, point.y)
case .northEast:
return vector_int2(point.x + 1, point.y + 1)
case .north:
return vector_int2(point.x, point.y + 1)
case .northWest:
return vector_int2(point.x - 1, point.y + 1)
case .west:
return vector_int2(point.x - 1, point.y)
case .southWest:
return vector_int2(point.x - 1, point.y - 1)
case .south:
return vector_int2(point.x, point.y - 1)
case .southEast:
return vector_int2(point.x + 1, point.y - 1)
}
}
}
| 25.186047 | 69 | 0.582641 |
69949fb73230157426c652a09a97f2a4da404f55 | 5,932 | //
// Event Filter System Common Tests.swift
// MIDIKit • https://github.com/orchetect/MIDIKit
//
#if !os(watchOS)
import XCTest
import MIDIKit
class MIDIEventFilter_SystemCommon_Tests: XCTestCase {
func testMetadata() {
// isSystemCommon
let events = kEvents.SysCommon.oneOfEachEventType
events.forEach {
XCTAssertFalse($0.isChannelVoice)
XCTAssertTrue($0.isSystemCommon)
XCTAssertFalse($0.isSystemExclusive)
XCTAssertFalse($0.isSystemRealTime)
}
// isSystemCommon(ofType:)
XCTAssertTrue(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofType: .tuneRequest)
)
XCTAssertFalse(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofType: .songPositionPointer)
)
// isSystemCommon(ofTypes:)
XCTAssertTrue(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofTypes: [.tuneRequest])
)
XCTAssertTrue(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofTypes: [.tuneRequest, .songSelect])
)
XCTAssertFalse(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofTypes: [.songSelect])
)
XCTAssertFalse(
MIDI.Event.tuneRequest(group: 0)
.isSystemCommon(ofTypes: [])
)
}
// MARK: - only
func testFilter_SysCommon_only() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .only)
let expectedEvents = kEvents.SysCommon.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
func testFilter_SysCommon_onlyType() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .onlyType(.tuneRequest))
let expectedEvents = [kEvents.SysCommon.tuneRequest]
XCTAssertEqual(filteredEvents, expectedEvents)
}
func testFilter_SysCommon_onlyTypes() {
let events = kEvents.oneOfEachEventType
var filteredEvents: [MIDI.Event]
var expectedEvents: [MIDI.Event]
filteredEvents = events.filter(sysCommon: .onlyTypes([.tuneRequest]))
expectedEvents = [kEvents.SysCommon.tuneRequest]
XCTAssertEqual(filteredEvents, expectedEvents)
filteredEvents = events.filter(sysCommon: .onlyTypes([.tuneRequest, .songSelect]))
expectedEvents = [kEvents.SysCommon.songSelect, kEvents.SysCommon.tuneRequest]
XCTAssertEqual(filteredEvents, expectedEvents)
filteredEvents = events.filter(sysCommon: .onlyTypes([]))
expectedEvents = []
XCTAssertEqual(filteredEvents, expectedEvents)
}
// MARK: - keep
func testFilter_SysCommon_keepType() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .keepType(.tuneRequest))
let expectedEvents =
kEvents.ChanVoice.oneOfEachEventType
+ [
kEvents.SysCommon.tuneRequest
]
+ kEvents.SysEx.oneOfEachEventType
+ kEvents.SysRealTime.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
func testFilter_SysCommon_keepTypes() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .keepTypes([.tuneRequest, .songSelect]))
let expectedEvents =
kEvents.ChanVoice.oneOfEachEventType
+ [
kEvents.SysCommon.songSelect,
kEvents.SysCommon.tuneRequest
]
+ kEvents.SysEx.oneOfEachEventType
+ kEvents.SysRealTime.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
// MARK: - drop
func testFilter_SysCommon_drop() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .drop)
let expectedEvents =
kEvents.ChanVoice.oneOfEachEventType
+ []
+ kEvents.SysEx.oneOfEachEventType
+ kEvents.SysRealTime.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
func testFilter_SysCommon_dropType() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .dropType(.tuneRequest))
let expectedEvents =
kEvents.ChanVoice.oneOfEachEventType
+ [
kEvents.SysCommon.timecodeQuarterFrame,
kEvents.SysCommon.songPositionPointer,
kEvents.SysCommon.songSelect,
kEvents.SysCommon.unofficialBusSelect
]
+ kEvents.SysEx.oneOfEachEventType
+ kEvents.SysRealTime.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
func testFilter_SysCommon_dropTypes() {
let events = kEvents.oneOfEachEventType
let filteredEvents = events.filter(sysCommon: .dropTypes([.tuneRequest, .songSelect]))
let expectedEvents =
kEvents.ChanVoice.oneOfEachEventType
+ [
kEvents.SysCommon.timecodeQuarterFrame,
kEvents.SysCommon.songPositionPointer,
kEvents.SysCommon.unofficialBusSelect
]
+ kEvents.SysEx.oneOfEachEventType
+ kEvents.SysRealTime.oneOfEachEventType
XCTAssertEqual(filteredEvents, expectedEvents)
}
}
#endif
| 28.247619 | 94 | 0.5971 |
ac75e374c85efb0424e55ee371c60825b80aedda | 346 | //
// ViewModel.swift
// WSLoggerExample
//
// Created by Ricardo Pereira on 15/10/2016.
// Copyright © 2016 Whitesmith. All rights reserved.
//
import Foundation
struct ViewModel: Loggable {
func configure() {
log("Bind model data with views")
}
static func create() {
log("Create a new view model")
}
}
| 15.727273 | 53 | 0.627168 |
62b3ff1bdb05a1ebdcc567d09cb4c972005aea15 | 1,856 | //
// ParagraphStyle+Codables.swift
// ExampleApp
//
// Created by Rajdeep Kwatra on 15/1/20.
// Copyright © 2020 Rajdeep Kwatra. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
protocol Encoding {
var key: String { get }
var value: JSON? { get }
}
extension NSParagraphStyle: Encoding {
var key: String { return "style" }
var value: JSON? {
let attributes: JSON = [
"alignment": alignment.rawValue,
"firstLineHeadIndent": firstLineHeadIndent,
"linespacing": lineSpacing,
"paragraphSpacing": paragraphSpacing
]
return attributes
}
}
extension UIFont: InlineEncoding {
var key: String { return "font" }
var value: InlineValueType {
let attributes: JSON = [
"name": fontName,
"family": familyName,
"size": fontDescriptor.pointSize,
"isBold": fontDescriptor.symbolicTraits.contains(.traitBold),
"isItalics": fontDescriptor.symbolicTraits.contains(.traitItalic),
"isMonospace": fontDescriptor.symbolicTraits.contains(.traitMonoSpace),
"textStyle": fontDescriptor.object(forKey: .textStyle) as? String ?? "UICTFontTextStyleBody"
]
return .json(value: attributes)
}
}
| 31.457627 | 104 | 0.662177 |
18b3e1bebbc041f96ee4afab38b8d42efb899b8a | 277 | import Foundation
#if os(Linux)
import FoundationNetworking
#endif
public struct AppPreviewSetsResponse: Codable {
public var data: [AppPreviewSet]
public var included: [AppPreview]
public var links: PagedDocumentLinks
public var meta: PagingInformation?
}
| 18.466667 | 47 | 0.765343 |
e5c8741deb233c9afe7c2741ab45a9de2847bddc | 1,384 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `SwitchCharacteristicCell` displays Boolean characteristics.
*/
import UIKit
import HomeKit
/**
A `CharacteristicCell` subclass that contains a single switch.
Used for Boolean characteristics.
*/
class SwitchCharacteristicCell: CharacteristicCell {
// MARK: Properties
@IBOutlet weak var valueSwitch: UISwitch!
override var characteristic: HMCharacteristic! {
didSet {
valueSwitch.alpha = enabled ? 1.0 : CharacteristicCell.DisabledAlpha
valueSwitch.isUserInteractionEnabled = enabled
}
}
/// If notify is false, sets the switch to the value.
override func setValue(_ newValue: CellValueType?, notify: Bool) {
super.setValue(newValue, notify: notify)
if !notify {
if let boolValue = newValue as? Bool {
valueSwitch.setOn(boolValue, animated: true)
}
}
}
/**
Responds to the switch updating and sets the
value to the switch's value.
- parameter valueSwitch: The switch that updated.
*/
@IBAction func didChangeSwitchValue(_ valueSwitch: UISwitch) {
setValue(valueSwitch.isOn as NSNumber?, notify: true)
}
}
| 27.68 | 80 | 0.640173 |
4bd024ae5fed9a4c23de07cb1ded0ccc690b42af | 684 | import Vapor
import HTTP
let drop = Droplet()
// Workaround for Heroku TLS connections: https://github.com/vapor/vapor/issues/699
drop.client = FoundationClient.self
drop.get { req in
return try drop.view.make("welcome", [
"message": drop.localization[req.lang, "welcome", "title"]
])
}
drop.get("books") { request in
guard let query = request.data["query"]?.string else {
throw Abort.badRequest
}
return try drop.client.get("\(drop.config["google-books", "api-base-url"]!.string!)/volumes", query: [
"q": query,
"key": drop.config["google-books", "api-key"]!.string!
])
}
drop.resource("posts", PostController())
drop.run()
| 24.428571 | 106 | 0.649123 |
222da270bce4bea7cdf17620e7e2f9a1b61bee3f | 3,953 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Combine
//---
public
struct FeatureStatus
{
public
enum StatusIndicator: String, Equatable, Codable
{
case ok = "🟢"
case busy = "🟠"
case failure = "🔴"
case missing = "⚠️"
}
//---
public
let title: String
public
let subtitle: String
public
let state: SomeStateBase?
public
let indicator: StatusIndicator
public
init(missing feature: SomeFeatureBase.Type)
{
self.title = feature.displayName
self.subtitle = "<missing>"
self.state = nil
self.indicator = .missing
}
public
init(with state: SomeStateBase)
{
self.title = type(of: state).feature.displayName
self.subtitle = .init(describing: type(of: state).self)
self.state = state
switch state
{
case is FailureIndicator:
self.indicator = .failure
case is BusyIndicator:
self.indicator = .busy
default:
self.indicator = .ok
}
}
}
// MARK: - Access log - Processed - get features status (dashboard)
public
extension Publisher where Output == StorageDispatcher.ProcessedAccessEventReport, Failure == Never
{
var statusReport: AnyPublisher<[FeatureStatus], Failure>
{
self
.filter {
!$0.mutations.isEmpty
}
.map {
$0.storage
.allValues
.compactMap {
$0 as? SomeStateBase
}
.map(
FeatureStatus.init
)
}
.eraseToAnyPublisher()
}
}
public
extension Publisher where Output == [FeatureStatus], Failure == Never
{
func matched(
with features: [SomeFeatureBase.Type]
) -> AnyPublisher<Output, Failure> {
self
.map { existingStatuses in
features
.map { feature in
existingStatuses
.first(where: {
if
let state = $0.state
{
return type(of: state).feature.name == feature.name
}
else
{
return false
}
})
?? .init(missing: feature)
}
}
.eraseToAnyPublisher()
}
}
| 27.451389 | 98 | 0.522388 |
265a96192042df752f1a58fbe5559779233bc138 | 762 | import UIKit
import XCTest
import PKCAlertView
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.4 | 111 | 0.606299 |
1ed87e0d6eed57939c5bfa3e1c22ec28402b994e | 1,901 | //
// MVDownloaderError.swift
// MVDownloader
//
// Created by Manase Michael on 30/06/2019.
//
import Foundation
public enum MVDownloaderError: Error {
/// Loader has been completely deallocated
case InvalidImageData
/// The server response was invalid or corrupted
case MalformedResponse
/// Loader has been completely deallocated
case LoaderDeallocated
/// The response data returned from the server is invalid or corrupted
case InvalidResponseData
/// The request was internally cancelled by the system
case RequestCancelledBySYS
/// The request was explicitly cancelled by the user
case RequestCancelledByUser
/// Generic error
case Generic(_ error: Error)
/// Image caching error
case ImageCacheFailed(_ image: MVImage, _ identifier: NSURL)
}
extension MVDownloaderError: LocalizedError {
public var errorDescription: String? {
switch self {
case .LoaderDeallocated:
return "Loader has been completely deallocated"
case .RequestCancelledByUser:
return "The request was explicitly cancelled by the user"
case .RequestCancelledBySYS:
return "The request was internally cancelled by the system"
case .MalformedResponse:
return "The server response was invalid or corrupted"
case .InvalidResponseData:
return "The response data returned from the server is invalid or corrupted"
case .InvalidImageData:
return "The image data response was corrupted or invalid"
case .ImageCacheFailed(let mvimage, let identifier):
return "An error occured while trying to cache \(mvimage) of type with an identifier \(identifier)"
case .Generic(let error):
return "An error occured: \(error.localizedDescription)"
}
}
}
| 30.66129 | 111 | 0.676486 |
380a88378d131debb681bd00ef4beb48d6fe0fa9 | 751 | import XCTest
import AttributedText
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.896552 | 111 | 0.603196 |
71b8427ddf1e14add241ffbf271b51b27597bc1e | 409 | public struct Complexf {
public var r: Float
public var i: Float
init(_ r: Float, _ i: Float) {
self.r = r
self.i = i
}
public func conj() -> Complexf {
return Complexf(r, -i)
}
}
public func +(lhs: Complexf, rhs: Complexf) -> Complexf {
return Complexf(lhs.r + rhs.r, lhs.i + rhs.i)
}
public func -(lhs: Complexf, rhs: Complexf) -> Complexf {
return Complexf(lhs.r - rhs.r, lhs.i - rhs.i)
} | 19.47619 | 57 | 0.630807 |
79748daf83c4b1658b84e3dfd11a087fde755730 | 3,469 | //
// StringTest.swift
// DemoTestTests
//
// Created by Tien Nhat Vu on 4/11/18.
//
import XCTest
import TVNExtensions
class StringTest: XCTestCase {
let s = "asdfqwer"
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 testIndex() {
XCTAssertEqual(String(s[s.index(fromStart: 3)]), "f")
XCTAssertEqual(String(s[s.index(fromStart: -2)]), "a")
XCTAssertEqual(String(s[s.index(fromStart: 30)]), "r")
XCTAssertEqual(String(s[s.index(fromEnd: 3)]), "w")
XCTAssertEqual(String(s[s.index(fromEnd: -2)]), "r")
XCTAssertEqual(String(s[s.index(fromEnd: 30)]), "a")
}
func testSubscript() {
XCTAssertEqual(s[2...4], "dfq")
XCTAssertEqual(s[2..<4], "df")
XCTAssertEqual(s[...4], "asdfq")
XCTAssertEqual(s[4...], "qwer")
}
func testReplace() {
XCTAssertEqual(s.replace(in: 2...4, with: "111"), "as111wer")
XCTAssertEqual(s.replace(in: 2..<5, with: "111"), "as111wer")
}
func testFirstCharUppercase() {
XCTAssertEqual(s.firstCharacterUppercase(), "Asdfqwer")
XCTAssertEqual("a".firstCharacterUppercase(), "A")
XCTAssertEqual("".firstCharacterUppercase(), "")
}
func testIsValidEmail() {
XCTAssertFalse(s.isValidEmail())
XCTAssertFalse("[email protected]".isValidEmail())
XCTAssertTrue("[email protected]".isValidEmail())
XCTAssertTrue("[email protected]".isValidEmail())
XCTAssertTrue("[email protected]".isValidEmail())
}
func testIsValidURL() {
XCTAssertFalse(s.isValidURL())
XCTAssertFalse("google. com".isValidURL())
XCTAssertFalse("www. google.com".isValidURL())
XCTAssertTrue("google.com".isValidURL())
XCTAssertTrue("www.googl.com".isValidURL())
XCTAssertTrue("http://www.google.com".isValidURL())
XCTAssertTrue("https://google.com/asdf?zz=ss".isValidURL())
}
func testFormatDecimal() {
XCTAssertEqual(s.formatDecimalString(numbersAfterDecimal: 2), "0.00")
let n = "523456"
XCTAssertEqual(n.formatDecimalString(numbersAfterDecimal: 1), "52345.6")
XCTAssertEqual(n.formatDecimalString(numbersAfterDecimal: 2), "5234.56")
XCTAssertEqual(n.formatDecimalString(numbersAfterDecimal: 8), "0.00523456")
let n1 = "5.23456"
XCTAssertEqual(n1.formatDecimalString(numbersAfterDecimal: 1), "52345.6")
}
func testCurrencySymbol() {
XCTAssertEqual("USD".toCurrencySymbol(), "$")
XCTAssertEqual("EUR".toCurrencySymbol(), "€")
XCTAssertEqual("VND".toCurrencySymbol(), "₫")
XCTAssertEqual("AUD".toCurrencySymbol(), "$")
XCTAssertEqual("XBT".toCurrencySymbol(), "XBT")
}
func testCurrencyFormatter() {
XCTAssertEqual("5.2345".toCurrencyFormatter(currencyCode: "USD"), "$5.23")
// XCTAssertEqual("5.2345".toCurrencyFormatter(currencyCode: "XBT"), "XBT5.23") // in iOS 13 it become "XBT 5.23"
XCTAssertEqual("5.2345".toCurrencyFormatter(currencyCode: "AUD"), "A$5.23")
XCTAssertEqual(s.toCurrencyFormatter(currencyCode: "USD"), s)
}
}
| 35.762887 | 120 | 0.620352 |
21ce182896831af8458bdb08a42b05e8136c0a56 | 9,400 | //
// AKPhaseDistortionOscillatorBank.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
/// Phase Distortion Oscillator Bank
///
open class AKPhaseDistortionOscillatorBank: AKPolyphonicNode, AKComponent {
public typealias AKAudioUnitType = AKPhaseDistortionOscillatorBankAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(instrument: "phdb")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var waveform: AKTable?
fileprivate var phaseDistortionParameter: AUParameter?
fileprivate var attackDurationParameter: AUParameter?
fileprivate var decayDurationParameter: AUParameter?
fileprivate var sustainLevelParameter: AUParameter?
fileprivate var releaseDurationParameter: AUParameter?
fileprivate var pitchBendParameter: AUParameter?
fileprivate var vibratoDepthParameter: AUParameter?
fileprivate var vibratoRateParameter: AUParameter?
/// Ramp Duration represents the speed at which parameters are allowed to change
@objc open dynamic var rampDuration: Double = AKSettings.rampDuration {
willSet {
internalAU?.rampDuration = newValue
}
}
/// Duty cycle width (range -1 - 1).
@objc open dynamic var phaseDistortion: Double = 0.0 {
willSet {
guard phaseDistortion != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
phaseDistortionParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.phaseDistortion = Float(newValue)
}
}
}
/// Attack duration in seconds
@objc open dynamic var attackDuration: Double = 0.1 {
willSet {
guard attackDuration != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
attackDurationParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.attackDuration = Float(newValue)
}
}
}
/// Decay duration in seconds
@objc open dynamic var decayDuration: Double = 0.1 {
willSet {
guard decayDuration != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
decayDurationParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.decayDuration = Float(newValue)
}
}
}
/// Sustain Level
@objc open dynamic var sustainLevel: Double = 1.0 {
willSet {
guard sustainLevel != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
sustainLevelParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.sustainLevel = Float(newValue)
}
}
}
/// Release duration in seconds
@objc open dynamic var releaseDuration: Double = 0.1 {
willSet {
guard releaseDuration != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
releaseDurationParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.releaseDuration = Float(newValue)
}
}
}
/// Pitch Bend as number of semitones
@objc open dynamic var pitchBend: Double = 0 {
willSet {
guard pitchBend != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
pitchBendParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.pitchBend = Float(newValue)
}
}
}
/// Vibrato Depth in semitones
@objc open dynamic var vibratoDepth: Double = 0 {
willSet {
guard vibratoDepth != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
vibratoDepthParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.vibratoDepth = Float(newValue)
}
}
}
/// Vibrato Rate in Hz
@objc open dynamic var vibratoRate: Double = 0 {
willSet {
guard vibratoRate != newValue else { return }
if internalAU?.isSetUp == true {
if let existingToken = token {
vibratoRateParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.vibratoRate = Float(newValue)
}
}
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(waveform: AKTable(.sine))
}
/// Initialize this oscillator node
///
/// - Parameters:
/// - waveform: The waveform of oscillation
/// - phaseDistortion: Phase distortion amount (range -1 - 1).
/// - attackDuration: Attack duration in seconds
/// - decayDuration: Decay duration in seconds
/// - sustainLevel: Sustain Level
/// - releaseDuration: Release duration in seconds
/// - pitchBend: Change of pitch in semitones
/// - vibratoDepth: Vibrato size in semitones
/// - vibratoRate: Frequency of vibrato in Hz
///
@objc public init(
waveform: AKTable,
phaseDistortion: Double = 0.0,
attackDuration: Double = 0.1,
decayDuration: Double = 0.1,
sustainLevel: Double = 1.0,
releaseDuration: Double = 0.1,
pitchBend: Double = 0,
vibratoDepth: Double = 0,
vibratoRate: Double = 0) {
self.waveform = waveform
self.phaseDistortion = phaseDistortion
self.attackDuration = attackDuration
self.decayDuration = decayDuration
self.sustainLevel = sustainLevel
self.releaseDuration = releaseDuration
self.pitchBend = pitchBend
self.vibratoDepth = vibratoDepth
self.vibratoRate = vibratoRate
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioUnit = avAudioUnit
self?.avAudioNode = avAudioUnit
self?.midiInstrument = avAudioUnit as? AVAudioUnitMIDIInstrument
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
self?.internalAU?.setupWaveform(Int32(waveform.count))
for (i, sample) in waveform.enumerated() {
self?.internalAU?.setWaveformValue(sample, at: UInt32(i))
}
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
phaseDistortionParameter = tree["phaseDistortion"]
attackDurationParameter = tree["attackDuration"]
decayDurationParameter = tree["decayDuration"]
sustainLevelParameter = tree["sustainLevel"]
releaseDurationParameter = tree["releaseDuration"]
pitchBendParameter = tree["pitchBend"]
vibratoDepthParameter = tree["vibratoDepth"]
vibratoRateParameter = tree["vibratoRate"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.phaseDistortion = Float(phaseDistortion)
internalAU?.attackDuration = Float(attackDuration)
internalAU?.decayDuration = Float(decayDuration)
internalAU?.sustainLevel = Float(sustainLevel)
internalAU?.releaseDuration = Float(releaseDuration)
internalAU?.pitchBend = Float(pitchBend)
internalAU?.vibratoDepth = Float(vibratoDepth)
internalAU?.vibratoRate = Float(vibratoRate)
}
// MARK: - AKPolyphonic
// Function to start, play, or activate the node at frequency
open override func play(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
frequency: Double,
channel: MIDIChannel = 0) {
internalAU?.startNote(noteNumber, velocity: velocity, frequency: Float(frequency))
}
/// Function to stop or bypass the node, both are equivalent
open override func stop(noteNumber: MIDINoteNumber) {
internalAU?.stopNote(noteNumber)
}
}
| 35.877863 | 98 | 0.602553 |
d9bd3ebe9aa12946b6583c8bc51ad4040d121c80 | 2,851 | //
// PlatformBaseSectionController.swift
// magic
//
// Created by SteveLin on 2017/6/19.
// Copyright © 2017年 SteveLin. All rights reserved.
//
import UIKit
import IGListKit
class PlatformBaseSectionController: IGListSectionController, IGListSectionType {
override init() {
super.init()
supplementaryViewSource = self
}
var data: SectionContent?
func numberOfItems() -> Int {
return data?.list.count ?? 0
}
func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext?.containerSize.width ?? 0, height: 90)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let nibCell = collectionContext!.dequeueReusableCell(withNibName: "PlatBaseInfoCell", bundle: nil, for: self, at: index) as! PlatBaseInfoCell
nibCell.info = data?.list[index] as? PlatBaseInfo
nibCell.infoView.rightButtonCall = { [weak self] uri in
if let vc = UIStoryboard(name: "PlatSelectGuide", bundle: nil).instantiateInitialViewController() {
self?.viewController?.present(vc, animated: true, completion: nil)
}
}
return nibCell
}
func didUpdate(to object: Any) {
data = object as? SectionContent
}
func didSelectItem(at index: Int) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.white
vc.title = "平台详情"
viewController?.navigationController?.pushViewController(vc, animated: true)
deLog("didSelectItem")
}
}
extension PlatformBaseSectionController: IGListSupplementaryViewSource {
func supportedElementKinds() -> [String] {
return [UICollectionElementKindSectionHeader]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
for: self,
nibName: "BoldTitleHeader",
bundle: nil,
at: index) as! BoldTitleHeader
view.leftLabel.text = data?.title
view.rightButton.setTitle(data?.rightEntry, for: .normal)
return view
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
var h: CGFloat = 0.01
if let data = data {
if data.isShowHeader {
h = 40
}
}
return CGSize(width: collectionContext!.containerSize.width, height: h)
}
}
| 31.32967 | 149 | 0.581901 |
ff9fe548b1780b16df27363cc61da544d68dcf74 | 2,470 | //
// AppDelegate.swift
// PersonalMusic
//
// Created by Mekor on 2018/2/11.
// Copyright © 2018年 Citynight. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let nav = UINavigationController(rootViewController:
MusicListViewController())
nav.navigationBar.prefersLargeTitles = true
nav.navigationBar.backgroundColor = UIColor.clear
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = nav
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 44.107143 | 285 | 0.739676 |
11c95388b62db93bc8076ca9d69ac18ea0545bee | 4,398 | //===----------------------------------------------------------------------===//
//
// 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.
@_exported import SotoCore
/// Service object for interacting with AWS PersonalizeEvents service.
///
/// Amazon Personalize can consume real-time user event data, such as stream or click data, and use it for model training either alone or combined with historical data. For more information see Recording Events.
public struct PersonalizeEvents: AWSService {
// MARK: Member variables
/// Client used for communication with AWS
public let client: AWSClient
/// Service configuration
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the PersonalizeEvents client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "personalize-events",
signingName: "personalize",
serviceProtocol: .restjson,
apiVersion: "2018-03-22",
endpoint: endpoint,
errorType: PersonalizeEventsErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Records user interaction event data. For more information see Recording Events.
@discardableResult public func putEvents(_ input: PutEventsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "PutEvents", path: "/events", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds one or more items to an Items dataset. For more information see Importing Items Incrementally.
@discardableResult public func putItems(_ input: PutItemsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "PutItems", path: "/items", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds one or more users to a Users dataset. For more information see Importing Users Incrementally.
@discardableResult public func putUsers(_ input: PutUsersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "PutUsers", path: "/users", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension PersonalizeEvents {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: PersonalizeEvents, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| 48.32967 | 212 | 0.67417 |
fe71f41d9e023b4597448a1adc425871c91d3461 | 2,765 | //
// StaticTableViewController.swift
// iTorrent
//
// Created by Daniil Vinogradov on 10.11.2019.
// Copyright © 2019 XITRIX. All rights reserved.
//
import UIKit
class StaticTableViewController: ThemedUIViewController {
var useInsertStyle: Bool? {
nil
}
let disposalBag = DisposalBag()
override var toolBarIsHidden: Bool? {
true
}
var tableAnimation: UITableView.RowAnimation {
.top
}
var tableView: StaticTableView!
var data: [Section] = [] {
didSet {
tableView?.data = data
}
}
var initStyle: UITableView.Style = .grouped
override init() {
super.init()
}
init(style: UITableView.Style) {
super.init()
initStyle = style
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setup(style: UITableView.Style = .grouped) {}
override func loadView() {
super.loadView()
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .never
}
tableView = StaticTableView(frame: view.bounds, style: initStyle)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.colorType = .secondary
view.addSubview(tableView)
tableView.data = data
tableView.tableAnimation = tableAnimation
tableView.useInsertStyle = useInsertStyle
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
initSections()
updateData()
#if !targetEnvironment(macCatalyst)
KeyboardHelper.shared.visibleHeight.bind { [weak self] height in
guard let self = self else { return }
let offset = self.tableView.contentOffset
UIView.animate(withDuration: 0.3) {
self.tableView.contentInset.bottom = height
self.tableView.scrollIndicatorInsets.bottom = height
self.tableView.contentOffset = offset
}
}.dispose(with: disposalBag)
#endif
}
func initSections() {}
func updateData(animated: Bool = true) {
tableView?.updateData(animated: animated)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if useInsertStyle != nil,
previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass {
tableView.useInsertStyle = useInsertStyle
tableView.reloadData()
}
}
}
| 26.586538 | 97 | 0.602532 |
e6388143ef6f1b3cb647a0c46fa892f87a810118 | 1,166 | //
// UD_Open_LoraUITests.swift
// UD Open LoraUITests
//
// Created by Khoa Bao on 1/7/19.
// Copyright © 2019 Khoa Bao. All rights reserved.
//
import XCTest
class UD_Open_LoraUITests: 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.314286 | 182 | 0.689537 |
c1ac0980ab43702978bad33d8eb043be8ff6a028 | 6,271 | //
// JavascriptParserTests.swift
// SwiftHTMLParser
//
// Created by Reid Nantes on 2018-12-09.
//
import XCTest
@testable import SwiftHTMLParser
final class JavascriptParserTests: XCTestCase {
func testJavascriptSimple() {
guard let fileURL = TestsConfig.javascriptTestFilesDirectoryURL?
.appendingPathComponent("javascript-simple.html") else {
XCTFail("Could not get url to test file")
return
}
// get html string from file
var htmlStringResult: String? = nil
do {
htmlStringResult = try String(contentsOf: fileURL, encoding: .utf8)
} catch {
XCTFail("Could not open file at: \(fileURL.path)")
}
guard let htmlString = htmlStringResult else {
XCTFail("Could not open file at: \(fileURL.path)")
return
}
// create object from raw html file
guard let elementArray = try? HTMLParser.parse(htmlString) else {
XCTFail("Could not parse HTML")
return
}
// find matching elements by traversing the created html object
let nodeSelectorPath = [
ElementSelector().withTagName("html"),
ElementSelector().withTagName("body"),
ElementSelector().withTagName("script")
]
let matchingElements = HTMLTraverser.findElements(in: elementArray,
matching: nodeSelectorPath)
XCTAssertEqual(matchingElements[0].childElements.count, 0)
}
func testJavascriptComments() {
guard let fileURL = TestsConfig.javascriptTestFilesDirectoryURL?
.appendingPathComponent("javascript-comments.html") else {
XCTFail("Could not get url to test file")
return
}
// get html string from file
var htmlStringResult: String? = nil
do {
htmlStringResult = try String(contentsOf: fileURL, encoding: .utf8)
} catch {
XCTFail("Could not open file at: \(fileURL.path)")
}
guard let htmlString = htmlStringResult else {
XCTFail("Could not open file at: \(fileURL.path)")
return
}
// create object from raw html file
guard let elementArray = try? HTMLParser.parse(htmlString) else {
XCTFail("Could not parse HTML")
return
}
// find matching elements by traversing the created html object
let nodeSelectorPath = [
ElementSelector().withTagName("html"),
ElementSelector().withTagName("body"),
ElementSelector().withTagName("script")
]
let matchingElements = HTMLTraverser.findElements(in: elementArray, matching: nodeSelectorPath)
XCTAssertEqual(matchingElements[0].childElements.count, 0)
XCTAssertEqual(matchingElements[0].textNodes.count, 1)
}
func testJavascriptQuotes() {
guard let fileURL = TestsConfig.javascriptTestFilesDirectoryURL?
.appendingPathComponent("javascript-quotes.html") else {
XCTFail("Could not get url to test file")
return
}
// get html string from file
var htmlStringResult: String? = nil
do {
htmlStringResult = try String(contentsOf: fileURL, encoding: .utf8)
} catch {
XCTFail("Could not open file at: \(fileURL.path)")
}
guard let htmlString = htmlStringResult else {
XCTFail("Could not open file at: \(fileURL.path)")
return
}
// create object from raw html file
guard let elementArray = try? HTMLParser.parse(htmlString) else {
XCTFail("Could not parse HTML")
return
}
// find matching elements by traversing the created html object
let nodeSelectorPath = [
ElementSelector().withTagName("html"),
ElementSelector().withTagName("body"),
ElementSelector().withTagName("script")
]
let matchingElements = HTMLTraverser.findElements(in: elementArray, matching: nodeSelectorPath)
XCTAssertEqual(matchingElements[0].childElements.count, 0)
XCTAssertEqual(matchingElements[0].textNodes.count, 1)
XCTAssertEqual(matchingElements[0].textNodes[0].text.count, 803)
}
func testJavascriptQuotesWithEscapeCharacters() {
guard let fileURL = TestsConfig.javascriptTestFilesDirectoryURL?
.appendingPathComponent("javascript-quotes-with-escape-characters.html") else {
XCTFail("Could not get url to test file")
return
}
// get html string from file
var htmlStringResult: String? = nil
do {
htmlStringResult = try String(contentsOf: fileURL, encoding: .utf8)
} catch {
XCTFail("Could not open file at: \(fileURL.path)")
}
guard let htmlString = htmlStringResult else {
XCTFail("Could not open file at: \(fileURL.path)")
return
}
// create object from raw html file
guard let elementArray = try? HTMLParser.parse(htmlString) else {
XCTFail("Could not parse HTML")
return
}
XCTAssertEqual(elementArray.count, 2)
// find matching elements by traversing the created html object
let nodeSelectorPath = [
ElementSelector().withTagName("html"),
ElementSelector().withTagName("body"),
ElementSelector().withTagName("script")
]
let matchingElements = HTMLTraverser.findElements(in: elementArray, matching: nodeSelectorPath)
XCTAssertEqual(matchingElements.count, 1)
XCTAssertEqual(matchingElements[0].childElements.count, 0)
XCTAssertEqual(matchingElements[0].textNodes.count, 1)
}
static var allTests = [
("testJavascriptSimple", testJavascriptSimple),
("testJavascriptComments", testJavascriptComments),
("testJavascriptQuotes", testJavascriptQuotes),
("testJavascriptQuotesWithEscapeCharacters", testJavascriptQuotesWithEscapeCharacters),
]
}
| 35.834286 | 103 | 0.614256 |
3390faea0c215156b7fc91b0211f439404983870 | 385 | //
// MIGradientView.swift
// MessageInputManager
//
// Created by Akshay Kuchhadiya on 22/08/18.
//
import UIKit
/// Gradient view for backdrop to video type of assets
class MIGradientView: UIView {
// MARK: - Life cycle methods
override class var layerClass:Swift.AnyClass {
//Return Gradient layer as UIVies default layer.
return CAGradientLayer.classForCoder()
}
}
| 19.25 | 54 | 0.72987 |
5b3b32737190b69c6519d0c3de8cd4292b02f0aa | 632 | //
// CovidGraphsApp.swift
// CovidGraphs
//
// Created by Miguel de Icaza on 10/5/20.
//
import SwiftUI
@main
struct CovidGraphsApp: App {
@AppStorage ("locations")
var locations: String = "Massachusetts,California,Spain"
func makeLocations (input: String) -> [UpdatableStat]
{
var res: [UpdatableStat] = []
for x in input.split(separator: ",") {
res.append (UpdatableStat (code: String (x)))
}
return res
}
var body: some Scene {
WindowGroup {
ContentView(locations: makeLocations(input: locations))
}
}
}
| 20.387097 | 67 | 0.577532 |
9b576d4ef5882e130976e682adeeb2d20349c723 | 2,284 | //
// SceneDelegate.swift
// Original
//
// Created by 童玉龙 on 2021/12/21.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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).
}
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.
}
}
| 43.09434 | 147 | 0.712347 |
0ad5f83fa94d4dcbae348bd3d36843302b3c532c | 4,194 | //
// AMGFeedbackView.swift
//
// Created by Abel Gancsos on 9/1/17.
// Copyright © 2017 Abel Gancsos. All rights reserved.
//
import Foundation
import Cocoa
/// This class helps the user provide feedback to the developer
class AMGFeedbackView : NSWindow{
var apiBase : String = "http://www.abelgancsos.com:1137/API/feedback.php";
var apiAdd : String = "";
var inputView: NSTextView = NSTextView();
/// This is the default constructor for the view
///
/// - Parameter frame: Margin information for the new view
public init(frame : NSRect){
super.init(contentRect: frame, styleMask: [.borderless,.titled,.closable], backing: .retained, defer: true);
initializeComponents();
self.title = "Feedback";
self.autorecalculatesKeyViewLoop = true;
}
/// This method sets up all the objects for the view
private func initializeComponents(){
//self.contentView = NSView();
apiAdd = String(format: "%@?m=add&a=%@&t=",apiBase,(Bundle.main.bundleIdentifier?.replacingOccurrences(of: "com.abelgancsos.", with: ""))!);
initializeTextInput();
initializeButtons();
}
/// This method sets up the input field
private func initializeTextInput(){
//(self.contentView?.frame.size.height)! / 3
inputView = NSTextView(frame:NSRect(x: 0, y: 40, width: (self.contentView?.frame.size.width)!, height: (self.contentView?.frame.size.width)! / 2 + 60));
inputView.autoresizingMask = [.viewWidthSizable];
inputView.backgroundColor = NSColor.white;
self.contentView?.addSubview(inputView);
}
/// This method sets up the buttons for the view
private func initializeButtons(){
let cancelButton : NSButton = NSButton(frame: NSRect(x: 0, y: 0, width: self.contentView!.frame.size.width / 2, height: 40));
cancelButton.autoresizingMask = [.viewHeightSizable, .viewWidthSizable];
cancelButton.title = "Cancel";
cancelButton.target = self;
cancelButton.isBordered = true;
if(AMGRegistry().getValue(key: "GUI.Buttons.Borders") == "0"){
cancelButton.isBordered = false;
}
cancelButton.action = #selector(cancel);
self.contentView?.addSubview(cancelButton);
let submitButton : NSButton = NSButton(frame: NSRect(x: cancelButton.frame.size.width, y: cancelButton.frame.origin.y, width: self.contentView!.frame.size.width / 2, height: 40));
submitButton.autoresizingMask = [.viewHeightSizable, .viewWidthSizable];
submitButton.title = "Submit";
submitButton.target = self;
submitButton.isBordered = true;
if(AMGRegistry().getValue(key: "GUI.Buttons.Borders") == "0"){
submitButton.isBordered = false;
}
submitButton.action = #selector(submitFeedback);
self.contentView?.addSubview(submitButton);
}
/// This method will submit the feedback
public func submitFeedback(){
var result : String = "";
if(inputView.string != ""){
if(AMGCommon().server(domain: apiBase)){
do{
try result = String(contentsOf: URL(string: String(format: "%@%@",apiAdd,AMGCommon().urlEncode(text: inputView.string!)))!, encoding: String.Encoding.isoLatin2);
if(result == "SUCCESS"){
inputView.string = "";
if(AMGRegistry().getValue(key: "Silent") != "1"){
AMGCommon().alert(message: "Feedback has been submitted", title: "SUCCESS", fontSize: 13);
}
}
}
catch{
}
}
}
else{
if(AMGRegistry().getValue(key: "Silent") != "1"){
AMGCommon().alert(message: "Feedback cannot be blank", title: "Error 11390", fontSize: 13);
}
}
}
public func cancel(){
self.close();
}
/// This method will display the view
public func show(){
self.makeKeyAndOrderFront(self);
}
}
| 38.127273 | 187 | 0.593467 |
d953724760f269c7e760650a0c2ea76e353b66cd | 1,029 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "AgoraRtcKit",
defaultLocalization: "en",
platforms: [.iOS(.v8)],
products: [
.library(
name: "AgoraRtcKit",
targets: [
"AgoraRtcCryptoLoader","AgoraRtcKit"
]
),
],
targets: [
.binaryTarget(
name: "AgoraRtcCryptoLoader",
url: "https://download.agora.io/swiftpm/AgoraAudio_iOS_Preview/4.0.0-preview.2/AgoraRtcCryptoLoader.xcframework.zip",
checksum: "1dd8ef13a62768003d964c7aa33cf7ea29db01513d891b3e186088f5918ad1b6"
),
.binaryTarget(
name: "AgoraRtcKit",
url: "https://download.agora.io/swiftpm/AgoraAudio_iOS_Preview/4.0.0-preview.2/AgoraRtcKit.xcframework.zip",
checksum: "e05768bda18b77ccf12d50b1970ecfb249484a3e24fc850d70341223bbe8b45e"
),
]
)
| 33.193548 | 129 | 0.63654 |
d921ad509414e02c41040cdb30ee3b96da44d306 | 963 | //
// Observable.swift
// ExampleMVVM
//
// Created by Oleh Kudinov on 16.02.19.
//
import Foundation
public final class Observable<Value> {
struct Observer<Value> {
weak var observer: AnyObject?
let block: (Value) -> Void
}
private var observers = [Observer<Value>]()
public var value: Value {
didSet { notifyObservers() }
}
public init(_ value: Value) {
self.value = value
}
public func observe(on observer: AnyObject, observerBlock: @escaping (Value) -> Void) {
observers.append(Observer(observer: observer, block: observerBlock))
DispatchQueue.main.async { observerBlock(self.value) }
}
public func remove(observer: AnyObject) {
observers = observers.filter { $0.observer !== observer }
}
private func notifyObservers() {
for observer in observers {
DispatchQueue.main.async { observer.block(self.value) }
}
}
}
| 23.487805 | 91 | 0.624091 |
0e921d044959daf18d022c76bd9d7105258b8410 | 956 | //
// ViewController.swift
// ProgressOverlaySample
//
// Created by Maksim Libenson on 11/25/18.
// Copyright © 2018 Maksim Libenson. All rights reserved.
//
import Cocoa
import ProgressOverlay
class ViewController: NSViewController {
@IBOutlet weak var testView: NSView!
@IBOutlet weak var showOverlayButton: NSButtonCell!
@IBOutlet var disabledTextView: NSScrollView!
var showOverlay = false
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func showOverlay(_ sender: Any) {
showOverlay = !showOverlay
if showOverlay {
testView.showOverlay()
showOverlayButton.title = "Hide overlay"
} else {
testView.hideOverlay()
showOverlayButton.title = "Show overlay"
}
}
}
| 21.244444 | 58 | 0.620293 |
6926b016b7a121a3114fd4f211fcc733e10aba66 | 702 | //
// CabinSeatRow4Pos1SwitchRecline.swift
// VSSGraphQL
//
// Generated by VSSGraphQL on 21.10.2020.
// Copyright © 2020 High Mobility GmbH. All rights reserved.
//
import Foundation
public struct CabinSeatRow4Pos1SwitchRecline: GraphQLObjectType {
/// Seatback recline backward switch engaged
public var backward: Bool? = nil
/// Seatback recline forward switch engaged
public var forward: Bool? = nil
// MARK: GraphQLObjectType
public static var scalars: [String : Any] {
[
"backward" : Bool.self,
"forward" : Bool.self
]
}
public static var objects: [String : GraphQLObjectType.Type] {
[:]
}
} | 21.272727 | 66 | 0.636752 |
031dff0a3c2c8f32bf1b3ee96250749d6b5a0a3a | 872 | //
// SettingsViewController.swift
// Tippu
//
// Created by Nikhila Vinay on 8/27/17.
// Copyright © 2017 Nikhila Vinay. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.222222 | 106 | 0.673165 |
237bd1fbdf9ca41528ee0b276b28e0e228aa3136 | 5,183 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS GENERATED BY EASY BINDINGS, DO NOT MODIFY IT
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
enum RouteOrigin : Int, EnumPropertyProtocol, Hashable, CaseIterable {
case center = 0
case bottomLeft = 1
case middleBottom = 2
case bottomRight = 3
case middleRight = 4
case topRight = 5
case middleTop = 6
case topLeft = 7
case middleLeft = 8
//····················································································································
init? (string : String) {
switch string {
case "center" : self = .center // 0
case "bottomLeft" : self = .bottomLeft // 1
case "middleBottom" : self = .middleBottom // 2
case "bottomRight" : self = .bottomRight // 3
case "middleRight" : self = .middleRight // 4
case "topRight" : self = .topRight // 5
case "middleTop" : self = .middleTop // 6
case "topLeft" : self = .topLeft // 7
case "middleLeft" : self = .middleLeft // 8
case _ : return nil
}
}
//····················································································································
func descriptionForExplorer () -> String {
switch self {
case .center : return "center" // 0
case .bottomLeft : return "bottomLeft" // 1
case .middleBottom : return "middleBottom" // 2
case .bottomRight : return "bottomRight" // 3
case .middleRight : return "middleRight" // 4
case .topRight : return "topRight" // 5
case .middleTop : return "middleTop" // 6
case .topLeft : return "topLeft" // 7
case .middleLeft : return "middleLeft" // 8
}
}
//····················································································································
// Enum generic bindings utility functions
//····················································································································
static func buildfromRawValue (rawValue : Int) -> RouteOrigin? {
if let v = RouteOrigin (rawValue:rawValue) {
return v
}else{
return nil
}
}
//····················································································································
func enumfromRawValue (rawValue : Int) -> RouteOrigin {
var result = self
let v : RouteOrigin? = RouteOrigin (rawValue:rawValue) ;
if let unwrappedV = v {
result = unwrappedV
}
return result
}
//····················································································································
// EBStoredPropertyProtocol
//····················································································································
func ebHashValue () -> UInt32 {
return UInt32 (self.rawValue)
}
//····················································································································
func convertToNSObject () -> NSObject {
return NSNumber (value: self.rawValue)
}
//····················································································································
static func convertFromNSObject (object : NSObject) -> RouteOrigin {
var result = RouteOrigin.center
if let number = object as? NSNumber, let v = RouteOrigin (rawValue: number.intValue) {
result = v
}
return result
}
//····················································································································
static func unarchiveFromDataRange (_ inData : Data, _ inRange : NSRange) -> RouteOrigin? {
if let rawValue = inData.base62EncodedInt (range: inRange), let enumValue = RouteOrigin (rawValue: rawValue) {
return enumValue
}else{
return nil
}
}
//····················································································································
func appendPropertyValueTo (_ ioData : inout Data) {
ioData.append (base62Encoded: self.rawValue)
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
typealias EBReadOnlyProperty_RouteOrigin = EBReadOnlyEnumProperty <RouteOrigin>
typealias EBTransientProperty_RouteOrigin = EBTransientEnumProperty <RouteOrigin>
typealias EBReadWriteProperty_RouteOrigin = EBReadWriteEnumProperty <RouteOrigin>
typealias EBStoredProperty_RouteOrigin = EBStoredEnumProperty <RouteOrigin>
typealias EBPropertyProxy_RouteOrigin = EBPropertyEnumProxy <RouteOrigin>
typealias EBPreferencesProperty_RouteOrigin = EBStoredEnumProperty <RouteOrigin>
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 39.564885 | 120 | 0.405557 |
1a0b50b29846f004e5852059c4f2c592ce915392 | 664 | //
// ListView.swift
// Diagnosix
//
// Created by Aron Gates on 2/8/17.
// Copyright © 2017 Aron Gates. All rights reserved.
//
import UIKit
import SideMenu
class ListSegue: UIStoryboardSegue {
override func perform()
{
let source = self.source
let destination = self.destination
if let nav = source.navigationController as? UISideMenuNavigationController, let presentingNav = nav.presentingViewController as? UINavigationController
{
presentingNav.dismiss(animated: true, completion: nil)
presentingNav.pushViewController(destination, animated: false)
}
}
}
| 25.538462 | 160 | 0.664157 |
fe957fadcea6f5837525054b1d352dd2209e3fef | 3,873 | /*
AppDelegate.swift
AJRInterface
Copyright © 2021, AJ Raftis and AJRFoundation authors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of AJRInterface nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AJ RAFTIS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Cocoa
@NSApplicationMain
open class AppDelegate: NSObject, NSApplicationDelegate {
// internal var applicationHasStarted = false
open func applicationWillFinishLaunching(_ notification: Notification) {
_ = DocumentController()
}
open func applicationDidFinishLaunching(_ aNotification: Notification) {
// applicationHasStarted = true
}
open func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
// open func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
// // On startup, when asked to open an untitled file, open the last opened
// // file instead
// if !applicationHasStarted {
// // Get the recent documents
// if let documentController = NSDocumentController.shared as? DocumentController {
// var windowToTakeFullScreen : NSWindow? = nil
//
// for documentState in documentController.getPersistedDocumentStates() {
// let document = Document(state: documentState)
// document.makeWindowControllers()
// documentController.addDocument(document)
//
// if documentState.windowState.frame != NSRect.zero {
// document.windowController?.window?.setFrame(documentState.windowState.frame, display: false)
// }
// if documentState.windowState.isKey {
// document.windowController?.window?.makeKeyAndOrderFront(nil)
// } else {
// document.windowController?.window?.orderFront(nil)
// }
// if documentState.windowState.isMiniaturized {
// document.windowController?.window?.miniaturize(nil)
// }
// if documentState.windowState.isFullScreen {
// windowToTakeFullScreen = document.windowController?.window
// }
// }
//
// if let windowToTakeFullScreen = windowToTakeFullScreen {
// windowToTakeFullScreen.zoom(self)
// }
//
// return false
// }
// }
//
// return true
// }
}
| 41.645161 | 118 | 0.665376 |
eb4b7f79cabc926778b5978e006c550b3058e8cc | 796 | //
// PieSegmentShape.swift
//
//
// Created by Will Dale on 24/01/2021.
//
import SwiftUI
/**
Draws a pie segment.
*/
internal struct PieSegmentShape: Shape, Identifiable {
var id : UUID
var startAngle : Double
var amount : Double
internal func path(in rect: CGRect) -> Path {
let radius = min(rect.width, rect.height) / 2
let center = CGPoint(x: rect.width / 2, y: rect.height / 2)
var path = Path()
path.move(to: center)
path.addRelativeArc(center : center,
radius : radius,
startAngle : Angle(radians: startAngle),
delta : Angle(radians: amount))
return path
}
}
| 23.411765 | 69 | 0.505025 |
e54dc89ee12c294e64da6824e1dfabb9c060f2ae | 428 | //
// UPennLoginServiceDelegate.swift
// Penn Chart Live
//
// Created by Rashad Abdul-Salam on 4/23/19.
// Copyright © 2019 University of Pennsylvania Health System. All rights reserved.
//
import Foundation
protocol UPennLoginServiceDelegate {
func didSuccessfullyLoginUser(_ username: String)
func didReturnAutoFillCredentials(username: String, password: String)
func didFailToLoginUser(errorStr: String)
}
| 26.75 | 83 | 0.768692 |
fc7555afc83f73a75aff6183dcc91cd7bd7676a4 | 4,181 | //
// NetworkRequest.swift
// InstantMac
//
// Created by Paul Sevilla on 20/05/2018.
// Copyright © 2018 Monstar Lab Pte Ltd. All rights reserved.
//
import RxSwift
import Moya
import ObjectMapper
import SwiftyJSON
let WebServiceDidReturnTokenErrorNotificationName = Foundation.Notification.Name( "WebServiceDidReturnTokenError")
protocol WebServiceType {
associatedtype Provider
func requestJSON(path: Provider) -> Observable<JSON>
func requestObject<T: Codable>(path: Provider) -> Observable<T>
func requestCollection<T: Codable>(path: Provider) -> Observable<[T]>
}
struct WebService<U: TargetType>: WebServiceType {
private let provider: MoyaProvider<U>
init(provider: MoyaProvider<U> = MoyaProvider<U>()) {
self.provider = provider
}
// MARK: - Internal Methods
func requestJSON(path: U) -> Observable<JSON> {
return request(path: path)
.map { JSON($0.data) }
}
func requestObject<T: Codable>(path: U) -> Observable<T> {
return request(path: path)
.map {
do {
return try $0.map(T.self)
} catch {
throw WebServiceError.mapping
}
}
}
func requestCollection<T: Codable>(path: U) -> Observable<[T]> {
return request(path: path)
.map {
do {
return try $0.map([T].self)
} catch {
throw WebServiceError.mapping
}
}
}
// MARK: - Private Methods
private let disposeBag = DisposeBag()
private func request(path: U) -> Observable<Response> {
print("path : \(path.baseURL)\(path.path)")
print("BODY : \(path.task)")
print("USE HEADERS: \(String(describing: path.headers))")
return Observable.create { observer in
let request = self.provider.request(path, completion: { result in
switch result {
case let .success(response):
if 200..<300 ~= response.statusCode {
print("\(path.path) : \((try? response.mapJSON()) ?? "")")
observer.onNext(response)
observer.onCompleted()
} else {
let error = self.error(from: response)
observer.onError(error)
print("Request failed: [\(path.method.rawValue.uppercased()) \(path.path)] \(error.errorDescription ?? (try? response.mapString()) ?? "Unknown Error")")
}
case let .failure(error):
observer.onError(WebServiceError.moya(error: error))
print("Request failed: [\(path)] \(error.localizedDescription)")
}
})
return Disposables.create {
request.cancel()
}
}
}
private func error(from response: Response) -> WebServiceError {
do {
let object = try response.map(ErrorResponse.self)
var messages = [object.status?.message].compactMap { $0 }
let customMessages = object.data
if let message = object.message {
messages.insert(message, at: 0)
}
if let errorData = object.data {
for (_, value) in errorData {
if let errorsString = value as? [String] {
messages.append(contentsOf: errorsString)
}
}
}
return WebServiceError.api(code: object.status?.statusCode ?? -1, messages: messages, customMessages: customMessages)
} catch {
return WebServiceError.mapping
}
}
private func hasTokenRelatedError(response: Response) -> Bool {
if let responseArray = try? response.mapJSON() as? [String], let value = responseArray.first {
let tokenErrors = ["user_not_found", "token_expired", "token_invalid", "token_absent"]
return tokenErrors.contains(value)
}
return false
}
}
| 32.410853 | 168 | 0.544607 |
f5718c61d00707abbe8daa8768e85bd4c3156094 | 673 | //
// BarChartCell.swift
// bind WatchKit Extension
//
// Created by Jéssica Amaral on 15/06/21.
//
import SwiftUI
struct BarChartCell: View {
var value: Double
var barColor: String
var symbolType: String
var body: some View {
VStack{
RoundedRectangle(cornerRadius: 10)
.fill(Color(barColor))
.scaleEffect(CGSize(width: 0.7, height: value), anchor: .bottom)
Image(symbolType)
.resizable()
.aspectRatio(contentMode:.fit)
.frame(width: 10, height: 10, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
}
}
}
| 24.035714 | 107 | 0.567608 |
6a3356a618179fea262eb7cc488cda635537e5f2 | 636 | //
// ViewController.swift
// Example
//
// Created by JeffZhao on 2017-11-20.
// Copyright © 2017年 JeffZhao. All rights reserved.
//
import UIKit
private var key: Void?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.jz.setAssociatedObject(key: &key, value: "12");
print(jz.getAssociatedObject(key: &key)!)
// 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.
}
}
| 21.2 | 80 | 0.663522 |
f83e894dd77f448df487a25eda8dcb46abfda069 | 526 | //
// SecondViewController.swift
// TestHidingTabbar
//
// Created by Lin, Forrest on 8/17/15.
// Copyright © 2015 Shi, Forrest. All rights reserved.
//
import UIKit
class SecondViewController: 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.
}
}
| 20.230769 | 80 | 0.676806 |
225ee0d7689895f3212a06efe30e3a266635f331 | 5,430 | import LocalAuthentication
class TradeItDeviceManager {
private static let JAIL_BREAK_FILES = [
"/Applications/Cydia.app",
"/Applications/blackra1n.app",
"/Applications/FakeCarrier.app",
"/Applications/Icy.app",
"/Applications/IntelliScreen.app",
"/Applications/MxTube.app",
"/Applications/RockApp.app",
"/Applications/SBSettings.app",
"/Applications/WinterBoard.app",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist",
"/Library/MobileSubstrate/DynamicLibraries/Veency.plist",
"/private/var/lib/apt",
"/private/var/lib/cydia",
"/private/var/mobile/Library/SBSettings/Themes",
"/private/var/stash",
"/private/var/tmp/cydia.log",
"/System/Library/LaunchDaemons/com.ikey.bbot.plist",
"/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist",
"/bin/bash",
"/usr/bin/sshd",
"/etc/apt",
"/usr/libexec/sftp-server",
"/usr/sbin/sshd"
]
func authenticateUserWithTouchId(onSuccess: @escaping () -> Void, onFailure: @escaping () -> Void) {
var error: NSError?
let context = LAContext()
let onSuccessOnMainThread = {
DispatchQueue.main.async { onSuccess() }
}
let onFailureOnMainThread = {
DispatchQueue.main.async { onFailure() }
}
// If it is UITesting, it will bypass touch ID/security login
if ProcessInfo.processInfo.arguments.contains("isUITesting") {
print("UITesting: bypassing...")
onSuccessOnMainThread()
return
}
guard context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: &error) else {
print("deviceOwnerAuthentication is not available on this device: \(error.debugDescription)")
onSuccessOnMainThread()
return
}
context.evaluatePolicy(
LAPolicy.deviceOwnerAuthentication,
localizedReason: "You must authorize before proceeding",
reply: { success, evaluationError in
if success {
print("deviceOwnerAuthentication: succeeded")
onSuccessOnMainThread()
} else {
guard let error = evaluationError else {
print("deviceOwnerAuthentication: unknown failure")
onFailureOnMainThread()
return
}
switch error {
case LAError.authenticationFailed:
print("deviceOwnerAuthentication: invalid credentials")
onFailureOnMainThread()
case LAError.userCancel:
print("deviceOwnerAuthentication: cancelled by user")
onFailureOnMainThread()
case LAError.userFallback:
print("deviceOwnerAuthentication: user tapped the fallback button")
onFailureOnMainThread()
case LAError.systemCancel:
print("deviceOwnerAuthentication: canceled by system (another application went to foreground)")
onFailureOnMainThread()
case LAError.passcodeNotSet:
print("deviceOwnerAuthentication: passcode is not set")
onSuccessOnMainThread()
case LAError.touchIDNotAvailable:
print("deviceOwnerAuthentication: TouchID is not available on the device")
onSuccessOnMainThread()
case LAError.touchIDLockout:
print("deviceOwnerAuthentication: TouchID is locked out")
onFailureOnMainThread()
case LAError.appCancel:
print("deviceOwnerAuthentication: Authentication was canceled by application")
onFailureOnMainThread()
case LAError.invalidContext:
print("deviceOwnerAuthentication: LAContext passed to this call has been previously invalidated")
onFailureOnMainThread()
default:
print("deviceOwnerAuthentication: unknown failure")
onFailureOnMainThread()
}
}
}
)
}
static func isDeviceJailBroken() -> Bool {
guard TARGET_IPHONE_SIMULATOR != 1 else {
return false
}
// Check 1 : existence of files that are common for jailbroken devices
if !JAIL_BREAK_FILES.filter(FileManager.default.fileExists).isEmpty || UIApplication.shared.canOpenURL(URL(string:"cydia://package/com.example.package")!) {
return true
}
// Check 2 : Reading and writing in system directories (sandbox violation)
let stringToWrite = "Jailbreak Test"
do {
try stringToWrite.write(toFile: "/private/JailbreakTest.txt", atomically: true, encoding: String.Encoding.utf8)
//Device is jailbroken
return true
} catch {
return false
}
}
}
| 41.450382 | 164 | 0.564641 |
1653e56a422d6e8c5bbccf5688633b2216d49d8f | 1,827 | //
// FrozenReferenceTime.swift
// TrueTime
//
// Created by Michael Sanders on 10/26/16.
// Copyright © 2016 Instacart. All rights reserved.
//
import Foundation
import ObjCTrueTime
typealias FrozenTimeResult = Result<FrozenTime, NSError>
typealias FrozenTimeCallback = (FrozenTimeResult) -> Void
typealias FrozenNetworkTimeResult = Result<FrozenNetworkTime, NSError>
typealias FrozenNetworkTimeCallback = (FrozenNetworkTimeResult) -> Void
protocol FrozenTime {
var time: Date { get }
var uptime: timeval { get }
}
struct FrozenReferenceTime: FrozenTime {
let time: Date
let uptime: timeval
}
struct FrozenNetworkTime: FrozenTime {
let time: Date
let uptime: timeval
let serverResponse: NTPResponse
let startTime: ntp_time_t
let sampleSize: Int?
let host: String?
init(time: Date,
uptime: timeval,
serverResponse: NTPResponse,
startTime: ntp_time_t,
sampleSize: Int? = 0,
host: String? = nil) {
self.time = time
self.uptime = uptime
self.serverResponse = serverResponse
self.startTime = startTime
self.sampleSize = sampleSize
self.host = host
}
init(networkTime time: FrozenNetworkTime, sampleSize: Int, host: String) {
self.init(time: time.time,
uptime: time.uptime,
serverResponse: time.serverResponse,
startTime: time.startTime,
sampleSize: sampleSize,
host: host)
}
}
extension FrozenTime {
var uptimeInterval: TimeInterval {
let currentUptime = timeval.uptime()
return TimeInterval(milliseconds: currentUptime.milliseconds - uptime.milliseconds)
}
func now() -> Date {
return time.addingTimeInterval(uptimeInterval)
}
}
| 26.1 | 91 | 0.656814 |
fb3f71f7860ab40ffd9ff0d8f4b061562b5c69db | 3,383 | //
// DemuxJournalsTests.swift
// SlouchDBTests
//
// Created by Allen Ussher on 10/26/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import XCTest
import Yaml
import SlouchDB
class DemuxJournalsTests: 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 runInputOutputTests(named name: String) {
let path = Bundle(for: type(of: self)).path(forResource: name, ofType: "yml")!
var yaml: Yaml!
do {
let text = try String(contentsOfFile: path, encoding: .utf8)
yaml = try Yaml.load(text)
} catch {
print("Error with yaml \(error)")
assert(false)
}
guard let yamlDictionary: [Yaml : Yaml] = yaml.dictionary else { assert(false) }
guard let inputDictionary = yamlDictionary["input"]?.dictionary else { assert(false) }
guard let outputDictionary = yamlDictionary["output"]?.dictionary else { assert(false) }
guard let inputJournalYamls = inputDictionary["jr"]?.array else { assert(false) }
guard let inputCacheYaml = inputDictionary["cache"] else { assert(false) }
guard let outputPatchYaml = outputDictionary["patch"] else { assert(false) }
guard let outputCacheYaml = outputDictionary["cache"] else { assert(false) }
var inputJournals: [Journal] = []
for inputJournalYaml in inputJournalYamls {
if let journal = DeserializeJournal(yaml: inputJournalYaml) {
inputJournals.append(journal)
} else {
assert(false)
}
}
let inputCache = DeserializeJournalSet(yaml: inputCacheYaml)!
let outputCache = DeserializeJournalSet(yaml: outputCacheYaml)!
let outputPatch = DeserializeJournalSet(yaml: outputPatchYaml)!
let result = DemuxJournals(multiplexJournals: inputJournals, multiplexJournalCache: inputCache)
XCTAssertEqual(result.singleEntityJournalPatch, outputPatch)
XCTAssertEqual(result.newMultiplexJournalCache, outputCache)
}
func testAddOne() {
runInputOutputTests(named: "test_add_one")
}
func testModifyOneField() {
runInputOutputTests(named: "test_modify_one_field")
}
func testAddOneToNoCaches() {
runInputOutputTests(named: "test_add_one_to_no_caches")
}
func testIgnoreOldDiffs() {
runInputOutputTests(named: "test_ignore_old_diffs")
}
func testMergeInputJournals() {
runInputOutputTests(named: "test_merge_input_journals")
}
// MARK: Insert Tests
func testEmptyInputsShouldOutputNothing() {
let multiplexJournals: [MultiplexJournal] = []
let multiplexJournalCache = MultiplexJournalCache(journals: [:])
let result = DemuxJournals(multiplexJournals: multiplexJournals, multiplexJournalCache: multiplexJournalCache)
XCTAssertEqual(result.newMultiplexJournalCache.journals.count, 0)
XCTAssertEqual(result.singleEntityJournalPatch.journals.count, 0)
}
}
| 35.610526 | 118 | 0.658587 |
9c6c9858c4f646e2e340c4e894efe1a6f2178d48 | 2,041 | //
// NSQRESquare.swift
// inSquare
//
// Created by Corrado Pensa on 30/04/16.
// Copyright © 2016 Alessandro Steri. All rights reserved.
//
import Foundation
//enum SquareState {
// case Mercury, awoken, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
//}
class NSQRESquare: NSObject
{
/** Square id */
var id:String
/** Square State */
var state:String
/** Who favorite this Square */
var favorers:JSON
/** Square Messages, as Database id */
var messages:JSON
/** if user is on place */
var userLocated:String
/** id of Square creator */
var ownerId:String
/** Square State */
var name:String
/** Square State */
var type:Int
/** Last Message Date */
var lastMessageDate:String
/** Square latitude */
var latitude:Double
/** Square Longitude */
var longitude:Double
/** Created Date */
var createdAt:String
/** Last Message Date */
var views:Int
init(jsonSq: JSON)
{
let coordinates = jsonSq["_source"]["geo_loc"].string!.componentsSeparatedByString(",")
self.latitude = (coordinates[0] as NSString).doubleValue
self.longitude = (coordinates[1] as NSString).doubleValue
self.name = jsonSq["_source"]["name"].string!
self.id = jsonSq["_id"].string!
self.state = jsonSq["_source"]["state"].string!
self.favorers = jsonSq["_source"]["favorers"]
self.messages = jsonSq["_source"]["messages"]
self.userLocated = "\(jsonSq["_source"]["userLocated"])"
self.ownerId = jsonSq["_source"]["ownerId"].string!
self.type = jsonSq["_source"]["type"].int!
self.lastMessageDate = jsonSq["_source"]["lastMessageDate"].string!
self.createdAt = jsonSq["_source"]["createdAt"].string!
self.views = jsonSq["_source"]["views"].int!
print(self.id)
}
/** How many users favorited this square */
func favotiredBy() -> Int
{
return self.favorers.count
}
} | 27.581081 | 95 | 0.603136 |
235e97e6bb8a59e6529de6ef17fdacfd755f67b4 | 1,059 | //
// Secp256k1.swift
// EllipticCurveKit
//
// Created by Alexander Cyon on 2018-07-12.
// Copyright © 2018 Alexander Cyon. All rights reserved.
//
import Foundation
/// The curve E: `y² = x³ + ax + b` over Fp
/// `secp256k1` Also known as the `Bitcoin curve` (though used by Ethereum, Zilliqa, Radix)
public struct Secp256k1: EllipticCurve {
/// `2^256 −2^32 −2^9 −2^8 −2^7 −2^6 −2^4 − 1` <=> `2^256 - 2^32 - 977`
public static let P = Number(hexString: "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F")!
public static let a = Number(0)
public static let b = Number(7)
public static let G = Point(
x: Number(hexString: "0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")!,
y: Number(hexString: "0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")!
)
public static let N = Number(hexString: "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")!
public static let h = Number(1)
public static let name = CurveName.secp256k1
}
| 35.3 | 114 | 0.714825 |
0876520fead1f82b7c71434f8568b83fb5d4c2a5 | 4,887 | import MixboxFoundation
import XCTest
import MixboxInAppServices
import MixboxUiKit
final class GenericSerializationTests: BaseSerializationTestCase {
private let dataSetForCheckingSr5346: [CGFloat] = [
// Do not use CGFloat.greatestFiniteMagnitude, see test___dataSetForCheckingSr5346___is_set_up_properly
1.7976931348623157e+308,
1.7976931348623155e+308,
1.7976931348623153e+308,
1.797693134862315e+308,
1.7976931348623147e+308,
1.7976931348623145e+308,
1.7976931348623143e+308,
1.7976931348623141e+308,
1.7976931348623140e+308,
1.797693134862315e+307,
1.797693134862315e+306,
1.797693134862315e+305,
1.797693134862315e+304,
1.797693134862315e+303,
1.797693134862315e+302,
1.797693134862315e+301,
1.797693134862315e+300,
1.797693134862315e+200,
1.797693134862315e+100,
0,
-1.797693134862315e+100,
-1.7976931348623157e+308
]
// NSJSONSerialization fails to encode Double.greatestFiniteMagnitude properly.
//
// https://bugs.swift.org/browse/SR-5346
// The bug is still present on iOS 10.3.
//
// (lldb) po JSONDecoder().decode([Double].self, from: JSONEncoder().encode([1.7976931348623157e+308]))
// ▿ DecodingError
// ▿ dataCorrupted : Context
// - codingPath : 0 elements
// - debugDescription : "The given data was not valid JSON."
// ▿ underlyingError : Optional<Error>
// - some : Error Domain=NSCocoaErrorDomain Code=3840 "Number wound up as NaN around character 1." UserInfo={NSDebugDescription=Number wound up as NaN around character 1.}
// (lldb) po String(data: JSONEncoder().encode([1.7976931348623157e+308]), encoding: .utf8)
// ▿ Optional<String>
// - some : "[1.797693134862316e+308]"
//
// Test is disabled, because the bug is not fixed in GenericSerialization.
// Workaround was added to code of providing ViewHierarchy.
//
// The ideal fix is to use custom Encoder, custom Encoder will have these advantages:
// - It will not contain bugs
// - It can be simple (e.g. binary) and work much faster.
// Steps to implement it:
// - Refactor GenericSerialization to use data
// - See JSONEncoder and https://github.com/mikeash/BinaryCoder/blob/master/BinaryEncoder.swift
// to make custom BinaryEncoder (note that we don't need to use custom protocols like in mikeash's code).
// The interface of Codable is really enough. It is relatively simple.
// - Write a lot of tests.
func disabled_test___deserialize___can_deserialize_values_wounded_up_as_NaN() {
XCTAssertEqual(Double.greatestFiniteMagnitude, 1.7976931348623157e+308)
dataSetForCheckingSr5346.forEach {
checkSerialization($0)
}
}
func test___deserialize___can_deserialize_values_wounded_up_as_NaN___using_workaround() {
let patcher = FloatValuesForSr5346PatcherImpl(
iosVersionProvider: iosVersionProvider
)
dataSetForCheckingSr5346.forEach {
checkSerializationConsideringSr5346(
float: patcher.patched(float: $0)
)
}
}
func test___dataSetForCheckingSr5346___is_set_up_properly() {
// Note: if numbers mismatch, add numbers that reflect the boundary of Double.greatestFiniteMagnitude
XCTAssertEqual(CGFloat.greatestFiniteMagnitude, dataSetForCheckingSr5346.first)
}
private func checkSerializationConsideringSr5346(float: CGFloat) {
do {
let serialized = try serialize(object: float)
let deserialized: CGFloat = try deserialize(string: serialized, object: float)
XCTAssertEqual(
try convertFloatMimicingEncodingBugInNSJsonSerialization(float: float),
deserialized,
"CGFloat doesn't match itself after serialization+deserialization"
)
} catch {
XCTFail("\(error)")
}
}
private func convertFloatMimicingEncodingBugInNSJsonSerialization(float: CGFloat) throws -> CGFloat {
if iosVersionProvider.iosVersion().majorVersion <= 10 {
let stringFromFloat = NSNumber(value: Double(float)).stringValue
let numberFormatter: NumberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale(identifier: "en_US")
guard let number = numberFormatter.number(from: stringFromFloat) else {
throw ErrorString("Failed to convert \(stringFromFloat) to number")
}
return CGFloat(truncating: number)
} else {
return float
}
}
}
| 41.067227 | 181 | 0.658891 |
39485197adaf34b77fbf899848694ed35a7f6c54 | 2,433 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// -----------------------------------------------------------------------------
///
/// This file contains an extension to `ToolsVersion` that implements the generation of a Swift tools version specification from a `ToolsVersion` instance.
///
// -----------------------------------------------------------------------------
extension ToolsVersion {
// TODO: Add options for whitespace styles.
/// Returns a Swift tools version specification specifying the version to the given precision.
/// - Parameter leastSignificantVersion: The precision to which the version specifier follows the version.
/// - Returns: A Swift tools version specification specifying the version to the given precision.
public func specification(roundedTo leastSignificantVersion: LeastSignificantVersion = .automatic) -> String {
var versionSpecifier = "\(major).\(minor)"
switch leastSignificantVersion {
case .automatic:
// If the patch version is not zero, then it's included in the Swift tools version specification.
if patch != 0 { fallthrough }
case .patch:
versionSpecifier = "\(versionSpecifier).\(patch)"
case .minor:
break
}
return "// swift-tools-version:\(self < .v5_4 ? "" : " ")\(versionSpecifier)"
}
/// The least significant version to round to.
public enum LeastSignificantVersion {
/// The patch version is the least significant if and only if it's not zero. Otherwise, the minor version is the least significant.
case automatic
/// The minor version is the least significant.
case minor
/// The patch version is the least significant.
case patch
// Although `ToolsVersion` uses `Version` as its backing store, it discards all pre-release and build metadata.
// The versioning information ends at the patch version.
}
}
| 48.66 | 155 | 0.597205 |
bbad60eda35fe36271790c3fc9b692ecf7fdac90 | 10,737 | import UIKit
/// :nodoc:
public protocol DeprecatedStatusViewDelegate: class {}
/**
A protocol for listening in on changes made to a `StatusView`.
*/
@available(*, deprecated, message: "Add a target to StatusView for UIControl.Event.valueChanged instead.")
public protocol StatusViewDelegate: DeprecatedStatusViewDelegate {
/**
Indicates a value in the status view has changed by the user interacting with it.
*/
@available(*, deprecated, message: "Add a target to StatusView for UIControl.Event.valueChanged instead.")
func statusView(_ statusView: StatusView, valueChangedTo value: Double)
}
/// :nodoc:
private protocol StatusViewDelegateDeprecations {
func statusView(_ statusView: StatusView, valueChangedTo value: Double)
}
/**
:nodoc:
A translucent bar that responds to tap and swipe gestures, similar to a scrubber or stepper control, and expands and collapses to maximize screen real estate.
*/
@IBDesignable
public class StatusView: UIControl {
weak var activityIndicatorView: UIActivityIndicatorView!
weak var textLabel: UILabel!
public weak var delegate: DeprecatedStatusViewDelegate?
var panStartPoint: CGPoint?
var isCurrentlyVisible: Bool = false
@available(swift, obsoleted: 0.1, renamed: "isEnabled")
public var canChangeValue: Bool {
fatalError()
}
var value: Double = 0 {
didSet {
sendActions(for: .valueChanged)
(delegate as? StatusViewDelegateDeprecations)?.statusView(self, valueChangedTo: value)
}
}
var statuses: [Status] = []
/**
`Status` is a struct which stores information to be displayed by the `StatusView`
*/
public struct Status {
/**
A string that uniquely identifies the `Status`
*/
public var identifier: String
/**
The text that will appear on the `Status`
*/
public let title: String
/**
A boolean that indicates whether a `spinner` should be shown during animations
set to `false` by default
*/
public var spinner: Bool = false
/**
A TimeInterval that designates the length of time the `Status` will be displayed in seconds
To display the `Status` indefinitely, set `duration` to `.infinity`
*/
public let duration: TimeInterval
/**
A boolean that indicates whether showing and hiding of the `Status` should be animated
set to `true` by default
*/
public var animated: Bool = true
/**
A boolean that indicates whether the `Status` should respond to touch events
set to `false` by default
*/
public var interactive: Bool = false
/**
A typealias which is used to rank a `Status` by importance
A lower `priority` value corresponds to a higher priority
*/
public var priority: Priority
}
/**
`Priority` is used to display `Status`es by importance
Lower values correspond to higher priority.
*/
public typealias Priority = Int
// — Highest Priority —
// rerouting (value = 0)
// enable precise location (value = 1)
// simulation banner (value = 2)
// — Lowest Priority —
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
let activityIndicatorView = UIActivityIndicatorView(style: .white)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
addSubview(activityIndicatorView)
self.activityIndicatorView = activityIndicatorView
let textLabel = UILabel()
textLabel.contentMode = .bottom
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
textLabel.textColor = .white
addSubview(textLabel)
self.textLabel = textLabel
let heightConstraint = heightAnchor.constraint(equalToConstant: 30)
heightConstraint.priority = UILayoutPriority(rawValue: 999)
heightConstraint.isActive = true
textLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
textLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
activityIndicatorView.rightAnchor.constraint(equalTo: safeRightAnchor, constant: -10).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(StatusView.pan(_:)))
addGestureRecognizer(recognizer)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(StatusView.tap(_:)))
addGestureRecognizer(tapRecognizer)
}
@objc func pan(_ sender: UIPanGestureRecognizer) {
guard isEnabled else { return }
let location = sender.location(in: self)
if sender.state == .began {
panStartPoint = location
} else if sender.state == .changed {
guard let startPoint = panStartPoint else { return }
let offsetX = location.x - startPoint.x
let coefficient = (offsetX / bounds.width) / 20.0
value = Double(min(max(CGFloat(value) + coefficient, 0), 1))
}
}
@objc func tap(_ sender: UITapGestureRecognizer) {
guard isEnabled else { return }
let location = sender.location(in: self)
if sender.state == .ended {
let incrementer: Double
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
incrementer = location.x < bounds.midX ? 0.1 : -0.1
} else {
incrementer = location.x > bounds.midX ? 0.1 : -0.1
}
value = min(max(value + incrementer, 0), 1)
}
}
/**
Shows the status view for a specified amount of time.
`showStatus()` uses a default value for priority and the title input as identifier. To use these variables, use `show(_:)`
*/
@available(*, deprecated, message: "Add a status using show(_:) instead")
public func showStatus(title: String, spinner spin: Bool = false, duration: TimeInterval, animated: Bool = true, interactive: Bool = false) {
let status = Status(identifier: title, title: title, spinner: spin, duration: duration, animated: animated, interactive: interactive, priority: 1)
show(status)
}
/**
Adds a new status to statuses array.
*/
func show(_ status: Status) {
if let row = statuses.firstIndex(where: {$0.identifier.contains(status.identifier)}) {
statuses[row] = status
} else {
statuses.append(status)
}
manageStatuses()
}
/**
Manages showing and hiding Statuses and the status view itself.
*/
func manageStatuses(status: Status? = nil) {
if statuses.isEmpty {
hide(delay: status?.duration ?? 0, animated: status?.animated ?? true)
} else {
// if we hide a Status and there are Statuses left in the statuses array, show the Status with highest priority
guard let highestPriorityStatus = statuses.min(by: {$0.priority < $1.priority}) else { return }
show(status: highestPriorityStatus)
hide(with: highestPriorityStatus, delay: highestPriorityStatus.duration)
}
}
/**
Hides a given Status without hiding the status view.
*/
func hide(_ status: Status?) {
guard let row = statuses.firstIndex(where: {$0.identifier == status?.identifier}) else { return }
let removedStatus = statuses.remove(at: row)
manageStatuses(status: removedStatus)
}
func showSimulationStatus(speed: Int) {
let format = NSLocalizedString("USER_IN_SIMULATION_MODE", bundle: .mapboxNavigation, value: "Simulating Navigation at %@×", comment: "The text of a banner that appears during turn-by-turn navigation when route simulation is enabled.")
let title = String.localizedStringWithFormat(format, NumberFormatter.localizedString(from: speed as NSNumber, number: .decimal))
let simulationStatus = Status(identifier: "USER_IN_SIMULATION_MODE", title: title, duration: .infinity, interactive: true, priority: 2)
show(simulationStatus)
}
/**
Shows the status view with an optional spinner.
*/
public func show(status: Status) {
isEnabled = status.interactive
textLabel.text = status.title
activityIndicatorView.hidesWhenStopped = true
if (!status.spinner) { activityIndicatorView.stopAnimating() }
guard !isCurrentlyVisible, isHidden else { return }
let show = {
self.isHidden = false
self.textLabel.alpha = 1
if (status.spinner) { self.activityIndicatorView.isHidden = false }
self.superview?.layoutIfNeeded()
}
UIView.defaultAnimation(0.3, animations:show, completion:{ _ in
self.isCurrentlyVisible = true
guard status.spinner else { return }
self.activityIndicatorView.startAnimating()
})
}
/**
Hides the status view.
*/
public func hide(with status: Status? = nil, delay: TimeInterval = 0, animated: Bool = true) {
let hide = {
if status == nil {
self.isHidden = true
self.textLabel.alpha = 0
self.activityIndicatorView.isHidden = true
} else {
self.hide(status)
}
}
let animate = {
let fireTime = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: fireTime, execute: {
if status == nil {
guard !self.isHidden, self.isCurrentlyVisible else { return }
self.activityIndicatorView.stopAnimating()
UIView.defaultAnimation(0.3, delay: 0, animations: hide, completion: { _ in
self.isCurrentlyVisible = false
})
} else {
self.hide(status)
}
})
}
if animated {
animate()
} else {
hide()
}
}
}
| 37.41115 | 242 | 0.616839 |
145cc8264d79b07416f2325c802c6da3860580e8 | 503 | import UIKit
extension UIButton {
func applyShadowAndCornerRadius() {
self.layer.cornerRadius = 5.0
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 5.0
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowColor = UIColor.gray.cgColor
}
func disableButton(){
self.alpha = 0.5
self.isEnabled = false
}
func enableButton(){
self.alpha = 1.0
self.isEnabled = true
}
}
| 21.869565 | 65 | 0.592445 |
1edd46cc01dec4b39c470e086464844a09bcda79 | 10,213 | import Foundation
import AFNetworking
import Mantle
import WMF
open class PageHistoryFetcher: NSObject {
fileprivate let operationManager: AFHTTPSessionManager = {
let manager = AFHTTPSessionManager.wmf_createDefault()
manager.responseSerializer = PageHistoryResponseSerializer()
manager.requestSerializer = PageHistoryRequestSerializer()
return manager
}()
@objc open func fetchRevisionInfo(_ siteURL: URL, requestParams: PageHistoryRequestParameters, failure: @escaping WMFErrorHandler, success: @escaping (HistoryFetchResults) -> Void) -> Void {
operationManager.wmf_GETAndRetry(with: siteURL,
parameters: requestParams,
retry: nil,
success: { (operation, responseObject) in
MWNetworkActivityIndicatorManager.shared().pop()
guard let results = responseObject as? HistoryFetchResults else { return }
results.tackOn(requestParams.lastRevisionFromPreviousCall)
success(results)
},
failure: { (operation, error) in
MWNetworkActivityIndicatorManager.shared().pop()
guard let error = error else {
failure(NSError(domain: "", code: 0, userInfo: nil))
return
}
failure(error)
})
}
}
private typealias RevisionsByDay = [Int: PageHistorySection]
private typealias PagingInfo = (continueKey: String?, rvContinueKey: String?, batchComplete: Bool)
open class HistoryFetchResults: NSObject {
fileprivate let pagingInfo: PagingInfo
fileprivate let lastRevision: WMFPageHistoryRevision?
fileprivate var revisionsByDay: RevisionsByDay
@objc open func getPageHistoryRequestParameters(_ articleURL: URL) -> PageHistoryRequestParameters {
return PageHistoryRequestParameters(title: articleURL.wmf_title ?? "", pagingInfo: pagingInfo, lastRevisionFromPreviousCall: lastRevision)
}
@objc open func items() -> [PageHistorySection] {
return self.revisionsByDay.keys.sorted(by: <).flatMap() { self.revisionsByDay[$0] }
}
@objc open func batchComplete() -> Bool {
return self.pagingInfo.batchComplete
}
fileprivate func tackOn(_ lastRevisionFromPreviousCall: WMFPageHistoryRevision?) {
guard let previouslyParsedRevision = lastRevisionFromPreviousCall, let parentSize = items().first?.items.first?.articleSizeAtRevision else { return }
previouslyParsedRevision.revisionSize = previouslyParsedRevision.articleSizeAtRevision - parentSize
HistoryFetchResults.update(revisionsByDay: &revisionsByDay, revision: previouslyParsedRevision)
}
fileprivate init(pagingInfo: PagingInfo, revisionsByDay: RevisionsByDay, lastRevision: WMFPageHistoryRevision?) {
self.pagingInfo = pagingInfo
self.revisionsByDay = revisionsByDay
self.lastRevision = lastRevision
}
}
open class PageHistoryRequestParameters: NSObject {
fileprivate let pagingInfo: PagingInfo
fileprivate let lastRevisionFromPreviousCall: WMFPageHistoryRevision?
fileprivate let title: String
fileprivate init(title: String, pagingInfo: PagingInfo, lastRevisionFromPreviousCall: WMFPageHistoryRevision?) {
self.title = title
self.pagingInfo = pagingInfo
self.lastRevisionFromPreviousCall = lastRevisionFromPreviousCall
}
//TODO: get rid of this when the VC is swift and we can use default values in the other init
@objc public init(title: String) {
self.title = title
pagingInfo = (nil, nil, false)
lastRevisionFromPreviousCall = nil
}
}
open class PageHistoryRequestSerializer: AFHTTPRequestSerializer {
open override func request(bySerializingRequest request: URLRequest, withParameters parameters: Any?, error: NSErrorPointer) -> URLRequest? {
guard let pageHistoryParameters = parameters as? PageHistoryRequestParameters else {
assertionFailure("pagehistoryfetcher has incorrect parameter type")
return nil
}
return super.request(bySerializingRequest: request, withParameters: serializedParams(pageHistoryParameters), error: error)
}
fileprivate func serializedParams(_ requestParameters: PageHistoryRequestParameters) -> [String: AnyObject] {
var params: [String: AnyObject] = [
"action": "query" as AnyObject,
"prop": "revisions" as AnyObject,
"rvprop": "ids|timestamp|user|size|parsedcomment" as AnyObject,
"rvlimit": 51 as AnyObject,
"rvdir": "older" as AnyObject,
"titles": requestParameters.title as AnyObject,
"continue": requestParameters.pagingInfo.continueKey as AnyObject? ?? "" as AnyObject,
"format": "json" as AnyObject
//,"rvdiffto": -1 //Add this to fake out "error" api response.
]
if let rvContinueKey = requestParameters.pagingInfo.rvContinueKey {
params["rvcontinue"] = rvContinueKey as AnyObject?
}
return params
}
}
open class PageHistoryResponseSerializer: WMFApiJsonResponseSerializer {
open override func responseObject(for response: URLResponse?, data: Data?, error: NSErrorPointer) -> Any? {
guard let responseDict = super.responseObject(for: response, data: data, error: error) as? [String: AnyObject] else {
assertionFailure("couldn't parse page history response")
return nil
}
return parseSections(responseDict)
}
fileprivate func parseSections(_ responseDict: [String: AnyObject]) -> HistoryFetchResults? {
guard let pages = responseDict["query"]?["pages"] as? [String: AnyObject] else {
assertionFailure("couldn't parse page history response")
return nil
}
var lastRevision: WMFPageHistoryRevision?
var revisionsByDay = RevisionsByDay()
for (_, value) in pages {
let transformer = MTLJSONAdapter.arrayTransformer(withModelClass: WMFPageHistoryRevision.self)
guard let val = value["revisions"], let revisions = transformer?.transformedValue(val) as? [WMFPageHistoryRevision] else {
assertionFailure("couldn't parse page history revisions")
return nil
}
revisionsByDay = parse(revisions: revisions, existingRevisions: revisionsByDay)
if let earliestRevision = revisions.last, earliestRevision.parentID == 0 {
earliestRevision.revisionSize = earliestRevision.articleSizeAtRevision
HistoryFetchResults.update(revisionsByDay: &revisionsByDay, revision: earliestRevision)
} else {
lastRevision = revisions.last
}
}
return HistoryFetchResults(pagingInfo: parsePagingInfo(responseDict), revisionsByDay: revisionsByDay, lastRevision: lastRevision)
}
fileprivate func parsePagingInfo(_ responseDict: [String: AnyObject]) -> (continueKey: String?, rvContinueKey: String?, batchComplete: Bool) {
var continueKey: String? = nil
var rvContinueKey: String? = nil
if let continueInfo = responseDict["continue"] as? [String: AnyObject] {
continueKey = continueInfo["continue"] as? String
rvContinueKey = continueInfo["rvcontinue"] as? String
}
let batchComplete = responseDict["batchcomplete"] != nil
return (continueKey, rvContinueKey, batchComplete)
}
fileprivate typealias RevisionCurrentPrevious = (current: WMFPageHistoryRevision, previous: WMFPageHistoryRevision)
fileprivate func parse(revisions: [WMFPageHistoryRevision], existingRevisions: RevisionsByDay) -> RevisionsByDay {
return zip(revisions, revisions.dropFirst()).reduce(existingRevisions, { (revisionsByDay, itemPair: RevisionCurrentPrevious) -> RevisionsByDay in
var revisionsByDay = revisionsByDay
itemPair.current.revisionSize = itemPair.current.articleSizeAtRevision - itemPair.previous.articleSizeAtRevision
HistoryFetchResults.update(revisionsByDay:&revisionsByDay, revision: itemPair.current)
return revisionsByDay
})
}
}
extension HistoryFetchResults {
fileprivate static func update(revisionsByDay: inout RevisionsByDay, revision: WMFPageHistoryRevision) {
let distanceToToday = revision.daysFromToday()
guard revision.user != nil else {
return
}
if let existingRevisionsOnCurrentDay = revisionsByDay[distanceToToday] {
let sectionTitle = existingRevisionsOnCurrentDay.sectionTitle
let items = existingRevisionsOnCurrentDay.items + [revision]
revisionsByDay[distanceToToday] = PageHistorySection(sectionTitle: sectionTitle, items: items)
} else {
if let revisionDate = revision.revisionDate {
var title: String?
let getSectionTitle = {
title = DateFormatter.wmf_long().string(from: revisionDate)
}
if Thread.isMainThread {
getSectionTitle()
} else {
DispatchQueue.main.sync(execute: getSectionTitle)
}
guard let sectionTitle = title else { return }
let newSection = PageHistorySection(sectionTitle: sectionTitle, items: [revision])
revisionsByDay[distanceToToday] = newSection
}
}
}
}
| 48.866029 | 194 | 0.637423 |
f990101b9b4998a697c1cdeb2ee3089b73517347 | 1,864 | //
// RarityOfItems.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func rarityOfItems(inventory: [UDItem]) -> [UDItemRarity:Int] {
var rarityDictionary = [UDItemRarity.common: 0, UDItemRarity.uncommon: 0, UDItemRarity.rare: 0, UDItemRarity.legendary: 0]
var addCommon = 0
var addUncommon = 0
var addRare = 0
var addLegendary = 0
// print("Before loop: \(rarityDictionary)")
for item in inventory {
if item.rarity == UDItemRarity(rawValue: 0) {
addCommon += 1
rarityDictionary[UDItemRarity.common] = addCommon
// print(item.rarity)
// print(rarityDictionary)
}
if item.rarity == UDItemRarity(rawValue: 1) {
addUncommon += 1
rarityDictionary[UDItemRarity.uncommon] = addUncommon
// print(item.rarity)
// print(rarityDictionary)
}
if item.rarity == UDItemRarity(rawValue: 2) {
addRare += 1
rarityDictionary[UDItemRarity.rare] = addRare
// print(item.rarity)
// print(rarityDictionary)
}
if item.rarity == UDItemRarity(rawValue: 3) {
addLegendary += 1
rarityDictionary[UDItemRarity.legendary] = addLegendary
// print(item.rarity)
// print(rarityDictionary)
}
}
return rarityDictionary
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
| 36.54902 | 235 | 0.570279 |
8af9e647ddae09f9a83ba7d130d4cacdfa8c11d1 | 1,799 | import Foundation
import tree_sitter
public enum LanguageResource: CaseIterable, Hashable {
case go
case gomod
case java
case json
case markdown
case php
case python
case ruby
case swift
var queryDirectoryName: String {
switch self {
case .go:
return "go"
case .gomod:
return "gomod"
case .java:
return "java"
case .json:
return "json"
case .markdown:
return "markdown"
case .php:
return "php"
case .python:
return "python"
case .ruby:
return "ruby"
case .swift:
return "swift"
}
}
public var parser: UnsafeMutablePointer<TSLanguage> {
switch self {
case .go:
return tree_sitter_go()
case .gomod:
return tree_sitter_gomod()
case .java:
return tree_sitter_java()
case .json:
return tree_sitter_json()
case .markdown:
return tree_sitter_markdown()
case .php:
return tree_sitter_php()
case .python:
return tree_sitter_python()
case .ruby:
return tree_sitter_ruby()
case .swift:
return tree_sitter_swift()
}
}
public func scmFileURL(named name: String) -> URL? {
return Bundle.module.url(forResource: name,
withExtension: "scm",
subdirectory: "LanguageResources/\(queryDirectoryName)")
}
public var highlightQueryURL: URL? {
return scmFileURL(named: "highlights")
}
public var localsQueryURL: URL? {
return scmFileURL(named: "locals")
}
}
| 23.986667 | 89 | 0.528071 |
1ad1f682369c0c83ee938c64e84cf923348e30aa | 25,699 | //
// FileBrowserViewController.swift
// SeeLess
//
// Created by Adrian Labbé on 16-09-19.
// Copyright © 2019 Adrian Labbé. All rights reserved.
//
import UIKit
import QuickLook
import MobileCoreServices
/// The file browser used to manage files inside a project.
public class FileBrowserViewController: UITableViewController, UIDocumentPickerDelegate, UIContextMenuInteractionDelegate, UITableViewDragDelegate, UITableViewDropDelegate {
private struct LocalFile {
var url: URL
var directory: URL
}
/// A type of file.
enum FileType {
/// Python source.
case python
/// Blank file.
case blank
/// Folder.
case folder
}
/// FIles in the directory.
var files = [URL]()
/// The document managing the project.
var document: FolderDocument?
/// The directory to browse.
var directory: URL! {
didSet {
title = directory.lastPathComponent
load()
}
}
/// Loads directory.
func load() {
tableView.backgroundView = nil
do {
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [])
self.files = files
} catch {
files = []
let textView = UITextView()
textView.isEditable = false
textView.text = error.localizedDescription
tableView.backgroundView = textView
}
tableView.reloadData()
}
/// Creates a file with given file type.
///
/// - Parameters:
/// - type: The file type.
func createFile(type: FileType) {
if type == .python {
let navVC = UIStoryboard(name: "Template Chooser", bundle: nil).instantiateInitialViewController()!
((navVC as? UINavigationController)?.topViewController as? TemplateChooserTableViewController)?.importHandler = { url, _ in
if let url = url {
do {
try FileManager.default.copyItem(at: url, to: self.directory.appendingPathComponent(url.lastPathComponent))
} catch {
present(error: error)
}
}
}
self.present(navVC, animated: true, completion: nil)
return
}
func present(error: Error) {
let alert = UIAlertController(title: Localizable.Errors.errorCreatingFile, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
let alert = UIAlertController(title: (type == .python ? Localizable.Creation.createScriptTitle : (type == .folder ? Localizable.Creation.createFolderTitle : Localizable.Creation.createFileTitle)), message: (type == .folder ? Localizable.Creation.typeFolderName : Localizable.Creation.typeFileName), preferredStyle: .alert)
var textField: UITextField!
alert.addAction(UIAlertAction(title: Localizable.create, style: .default, handler: { (_) in
if true {
do {
var name = textField.text ?? Localizable.untitled
if name.replacingOccurrences(of: " ", with: "").isEmpty {
name = Localizable.untitled
}
if type == .folder {
try FileManager.default.createDirectory(at: self.directory.appendingPathComponent(name), withIntermediateDirectories: true, attributes: nil)
} else {
if !FileManager.default.createFile(atPath: self.directory.appendingPathComponent(name).path, contents: "".data(using: .utf8), attributes: nil) {
throw NSError(domain: "SeeLess.errorCreatingFile", code: 1, userInfo: [NSLocalizedDescriptionKey : "Error creating file"])
}
}
} catch {
present(error: error)
}
}
}))
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
alert.addTextField { (_textField) in
textField = _textField
textField.placeholder = Localizable.untitled
}
self.present(alert, animated: true, completion: nil)
}
/// Creates a new file.
@objc func createNewFile(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: Localizable.Creation.createFileTitle, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: Localizable.Creation.pythonScript, style: .default, handler: { (_) in
self.createFile(type: .python)
}))
alert.addAction(UIAlertAction(title: Localizable.Creation.blankFile, style: .default, handler: { (_) in
self.createFile(type: .blank)
}))
alert.addAction(UIAlertAction(title: Localizable.Creation.folder, style: .default, handler: { (_) in
self.createFile(type: .folder)
}))
alert.addAction(UIAlertAction(title: Localizable.Creation.importFromFiles, style: .default, handler: { (_) in
let vc = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
vc.allowsMultipleSelection = true
vc.delegate = self
self.present(vc, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
alert.popoverPresentationController?.barButtonItem = sender
present(alert, animated: true, completion: nil)
}
/// Closes the View Controller.
@objc func close() {
dismiss(animated: true, completion: nil)
}
/// Returns to the file browser.
@objc func goToFiles() {
let presenting = presentingViewController
dismiss(animated: true) {
presenting?.dismiss(animated: true, completion: nil)
}
}
// MARK: - Table view controller
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
if navigationController?.viewControllers.first == self {
var items = [UIBarButtonItem]()
if let parent = navigationController?.presentingViewController, parent is EditorViewController || parent is EditorSplitViewController || parent is EditorSplitViewController.NavigationController {
items.append(UIBarButtonItem(image: EditorSplitViewController.gridImage, style: .plain, target: self, action: #selector(goToFiles)))
}
items.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(close)))
navigationItem.leftBarButtonItems = items
}
}
public override func viewDidLoad() {
super.viewDidLoad()
clearsSelectionOnViewWillAppear = true
tableView.tableFooterView = UIView()
tableView.dragDelegate = self
tableView.dropDelegate = self
navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(createNewFile(_:)))]
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return files.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
let icloud = (files[indexPath.row].pathExtension == "icloud" && files[indexPath.row].lastPathComponent.hasPrefix("."))
if icloud {
var name = files[indexPath.row].deletingPathExtension().lastPathComponent
name.removeFirst()
cell.textLabel?.text = name
} else {
cell.textLabel?.text = files[indexPath.row].lastPathComponent
}
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: files[indexPath.row].path, isDirectory: &isDir) && isDir.boolValue {
if #available(iOS 13.0, *) {
cell.imageView?.image = UIImage(systemName: "folder.fill")
}
cell.accessoryType = .disclosureIndicator
} else {
if #available(iOS 13.0, *) {
if !icloud {
cell.imageView?.image = UIImage(systemName: "doc.fill")
} else {
cell.imageView?.image = UIImage(systemName: "icloud.and.arrow.down.fill")
}
}
cell.accessoryType = .none
}
cell.contentView.alpha = files[indexPath.row].lastPathComponent.hasPrefix(".") ? 0.5 : 1
if #available(iOS 13.0, *) {
let interaction = UIContextMenuInteraction(delegate: self)
cell.addInteraction(interaction)
}
return cell
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: files[indexPath.row].path, isDirectory: &isDir) && isDir.boolValue {
let browser = FileBrowserViewController()
browser.directory = files[indexPath.row]
browser.document = document
navigationController?.pushViewController(browser, animated: true)
} else {
let icloud = (files[indexPath.row].pathExtension == "icloud" && files[indexPath.row].lastPathComponent.hasPrefix("."))
var last = self.files[indexPath.row].deletingPathExtension().lastPathComponent
last.removeFirst()
let url: URL
if icloud {
url = files[indexPath.row].deletingLastPathComponent().appendingPathComponent(last)
} else {
url = files[indexPath.row]
}
if url.pathExtension.lowercased() == "py" {
if let editor = ((navigationController?.splitViewController as? EditorSplitViewController.ProjectSplitViewController)?.editor)?.editor {
editor.document?.editor = nil
editor.save { (_) in
let document = PyDocument(fileURL: url)
document.open { (_) in
#if !Xcode11
if #available(iOS 14.0, *) {
RecentDataSource.shared.recent.append(url)
}
#endif
editor.parent?.title = document.fileURL.deletingPathExtension().lastPathComponent
editor.document = document
editor.viewWillAppear(false)
if let parent = editor.parent?.navigationController {
self.navigationController?.splitViewController?.showDetailViewController(parent, sender: self)
}
if let action = self.navigationController?.splitViewController?.displayModeButtonItem.action {
_ = self.navigationController?.splitViewController?.displayModeButtonItem.target?.perform(action, with: self)
}
}
}
} else {
let doc = self.document
let presenting = presentingViewController
dismiss(animated: true) {
if presenting?.presentingViewController != nil {
let presentingPresenting = presenting?.presentingViewController
presenting?.dismiss(animated: true, completion: {
(presentingPresenting as? DocumentBrowserViewController)?.openDocument(url, run: false, folder: doc)
})
} else {
let browser = presenting as? DocumentBrowserViewController
browser?.openDocument(url, run: false, folder: doc)
}
}
}
} else {
class DataSource: NSObject, QLPreviewControllerDataSource {
var url: URL
init(url: URL) {
self.url = url
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return url as QLPreviewItem
}
}
let doc = PyDocument(fileURL: url)
doc.open { (_) in
let dataSource = DataSource(url: doc.fileURL)
let vc = QLPreviewController()
vc.dataSource = dataSource
self.present(vc, animated: true, completion: nil)
}
}
}
}
public override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
public override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
do {
try FileManager.default.removeItem(at: files[indexPath.row])
files.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
let alert = UIAlertController(title: Localizable.Errors.errorRemovingFile, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
}
// MARK: - Table view drag delegate
public func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let file = files[indexPath.row]
let item = UIDragItem(itemProvider: NSItemProvider())
item.itemProvider.registerFileRepresentation(forTypeIdentifier: (try? file.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier ?? kUTTypeItem as String, fileOptions: .openInPlace, visibility: .all) { (handler) -> Progress? in
handler(file, true, nil)
let progress = Progress(totalUnitCount: 1)
progress.completedUnitCount = 1
return progress
}
item.itemProvider.suggestedName = file.lastPathComponent
item.localObject = LocalFile(url: file, directory: directory)
return [item]
}
// MARK: - Table view drop delegate
public func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
return session.hasItemsConforming(toTypeIdentifiers: [kUTTypeItem as String])
}
public func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
for item in coordinator.items {
if item.dragItem.itemProvider.hasItemConformingToTypeIdentifier(kUTTypeItem as String) {
item.dragItem.itemProvider.loadInPlaceFileRepresentation(forTypeIdentifier: kUTTypeItem as String, completionHandler: { (file, inPlace, error) in
guard let destination = ((coordinator.destinationIndexPath != nil && coordinator.proposal.intent == .insertIntoDestinationIndexPath) ? self.files[coordinator.destinationIndexPath!.row] : self.directory) else {
return
}
if let error = error {
print(error.localizedDescription)
}
if let file = file {
let fileName = file.lastPathComponent
_ = file.startAccessingSecurityScopedResource()
if coordinator.proposal.operation == .move {
try? FileManager.default.moveItem(at: file, to: destination.appendingPathComponent(fileName))
} else if coordinator.proposal.operation == .copy {
try? FileManager.default.copyItem(at: file, to: destination.appendingPathComponent(fileName))
}
file.stopAccessingSecurityScopedResource()
DispatchQueue.main.async {
self.load()
}
}
})
}
}
}
public func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if let local = session.items.first?.localObject as? LocalFile, local.url.deletingLastPathComponent() != directory {
return UITableViewDropProposal(operation: .move)
}
var isDir: ObjCBool = false
if destinationIndexPath == nil || !(destinationIndexPath != nil && files.indices.contains(destinationIndexPath!.row) && FileManager.default.fileExists(atPath: files[destinationIndexPath!.row].path, isDirectory: &isDir) && isDir.boolValue) {
if destinationIndexPath == nil && (session.items.first?.localObject as? LocalFile)?.url.deletingLastPathComponent() == directory {
return UITableViewDropProposal(operation: .forbidden)
} else if session.items.first?.localObject == nil || (session.items.first?.localObject as? LocalFile)?.directory != directory {
return UITableViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
} else {
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
} else if destinationIndexPath != nil && files.indices.contains(destinationIndexPath!.row) && FileManager.default.fileExists(atPath: files[destinationIndexPath!.row].path, isDirectory: &isDir) && isDir.boolValue && (session.items.first?.localObject as? URL)?.deletingLastPathComponent() == files[destinationIndexPath!.row] {
return UITableViewDropProposal(operation: .forbidden)
} else if destinationIndexPath == nil && (session.items.first?.localObject as? LocalFile)?.url.deletingLastPathComponent() == directory {
return UITableViewDropProposal(operation: .forbidden)
} else if session.items.first?.localObject == nil {
return UITableViewDropProposal(operation: .copy, intent: .insertIntoDestinationIndexPath)
} else {
return UITableViewDropProposal(operation: .move, intent: .insertIntoDestinationIndexPath)
}
}
// MARK: - Document picker view controller delegate
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
func move(at index: Int) {
do {
try FileManager.default.moveItem(at: urls[index], to: directory.appendingPathComponent(urls[index].lastPathComponent))
if urls.indices.contains(index+1) {
move(at: index+1)
} else {
tableView.reloadData()
}
} catch {
let alert = UIAlertController(title: Localizable.Errors.errorCreatingFile, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: { _ in
if urls.indices.contains(index+1) {
move(at: index+1)
} else {
self.tableView.reloadData()
}
}))
present(alert, animated: true, completion: nil)
}
}
move(at: 0)
}
// MARK: - Context menu interaction delegate
@available(iOS 13.0, *)
public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
guard let cell = interaction.view as? UITableViewCell else {
return nil
}
let share = UIAction(title: Localizable.MenuItems.share, image: UIImage(systemName: "square.and.arrow.up")) { action in
guard let index = self.tableView.indexPath(for: cell), self.files.indices.contains(index.row) else {
return
}
let activityVC = UIActivityViewController(activityItems: [self.files[index.row]], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = cell
activityVC.popoverPresentationController?.sourceRect = cell.bounds
self.present(activityVC, animated: true, completion: nil)
}
let saveTo = UIAction(title: Localizable.MenuItems.saveToFiles, image: UIImage(systemName: "folder")) { action in
guard let index = self.tableView.indexPath(for: cell), self.files.indices.contains(index.row) else {
return
}
self.present(UIDocumentPickerViewController(url: self.files[index.row], in: .exportToService), animated: true, completion: nil)
}
let rename = UIAction(title: Localizable.MenuItems.rename, image: UIImage(systemName: "pencil")) { action in
guard let index = self.tableView.indexPath(for: cell), self.files.indices.contains(index.row) else {
return
}
let file = self.files[index.row]
var textField: UITextField!
let alert = UIAlertController(title: "\(Localizable.MenuItems.rename) '\(file.lastPathComponent)'", message: Localizable.Creation.typeFileName, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localizable.MenuItems.rename, style: .default, handler: { (_) in
do {
let name = textField.text ?? ""
if !name.isEmpty {
try FileManager.default.moveItem(at: file, to: file.deletingLastPathComponent().appendingPathComponent(name))
}
} catch {
let alert = UIAlertController(title: Localizable.Errors.errorRenamingFile, message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: Localizable.cancel, style: .cancel, handler: nil))
alert.addTextField { (_textField) in
textField = _textField
textField.placeholder = Localizable.untitled
textField.text = file.lastPathComponent
}
self.present(alert, animated: true, completion: nil)
}
let delete = UIAction(title: Localizable.MenuItems.remove, image: UIImage(systemName: "trash.fill"), attributes: .destructive) { action in
guard let index = self.tableView.indexPath(for: cell), self.files.indices.contains(index.row) else {
return
}
self.tableView(self.tableView, commit: .delete, forRowAt: index)
}
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { (_) -> UIMenu? in
guard let index = self.tableView.indexPath(for: cell), self.files.indices.contains(index.row) else {
return nil
}
return UIMenu(title: cell.textLabel?.text ?? "", children: [share, saveTo, rename, delete])
}
}
}
| 45.007005 | 332 | 0.567493 |
79743a22475da8746b9c677d9d28b461b3c62d8f | 5,061 | //
// AddTorrentAlert.swift
// Mission
//
// Created by Joe Diragi on 3/6/22.
//
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct AddTorrentDialog: View {
@ObservedObject var store: Store
@State var alertInput: String = ""
@State var downloadDir: String = ""
var body: some View {
VStack {
HStack {
Text("Add Torrent")
.font(.headline)
.padding(.leading, 20)
.padding(.bottom, 10)
.padding(.top, 20)
Button(action: {
store.isShowingAddAlert.toggle()
}, label: {
Image(systemName: "xmark.circle.fill")
.padding(.top, 20)
.padding(.bottom, 10)
.padding(.leading, 20)
.frame(alignment: .trailing)
}).buttonStyle(BorderlessButtonStyle())
}
Text("Add either a magnet link or .torrent file.")
.fixedSize(horizontal: true, vertical: true)
.font(.body)
.padding(.leading, 20)
.padding(.trailing, 20)
VStack(alignment: .leading, spacing: 0) {
Text("Magnet Link")
.font(.system(size: 10))
.padding(.top, 10)
.padding(.leading)
.padding(.bottom, 5)
TextField(
"Magnet link",
text: $alertInput
).onSubmit {
// TODO: Validate entry
}
.padding([.leading, .trailing])
}
.padding(.bottom, 5)
VStack(alignment: .leading, spacing: 0) {
Text("Download Destination")
.font(.system(size: 10))
.padding(.top, 10)
.padding(.leading)
.padding(.bottom, 5)
TextField(
"Download Destination",
text: $downloadDir
)
.padding([.leading, .trailing])
}
HStack {
Button("Upload file") {
// Show file chooser panel
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.allowedContentTypes = [.torrent]
if panel.runModal() == .OK {
// Convert the file to a base64 string
let fileData = try! Data.init(contentsOf: panel.url!)
let fileStream: String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let info = makeConfig(store: store)
addTorrent(fileUrl: fileStream, saveLocation: downloadDir, auth: info.auth, file: true, config: info.config, onAdd: { response in
if response.response == TransmissionResponse.success {
store.isShowingAddAlert.toggle()
showFilePicker(transferId: response.transferId, info: info)
}
})
}
}
.padding()
Spacer()
Button("Submit") {
// Send the magnet link to the server
let info = makeConfig(store: store)
addTorrent(fileUrl: alertInput, saveLocation: downloadDir, auth: info.auth, file: false, config: info.config, onAdd: { response in
if response.response == TransmissionResponse.success {
store.isShowingAddAlert.toggle()
showFilePicker(transferId: response.transferId, info: info)
}
})
}.padding()
}
}.interactiveDismissDisabled(false)
.onAppear {
downloadDir = store.defaultDownloadDir
}
}
func showFilePicker(transferId: Int, info: (config: TransmissionConfig, auth: TransmissionAuth)) {
getTransferFiles(transferId: transferId, info: info, onReceived: { f in
store.addTransferFilesList = f
store.transferToSetFiles = transferId
store.isShowingTransferFiles.toggle()
})
}
}
// This is needed to silence buildtime warnings related to the filepicker.
// `.allowedFileTypes` was deprecated in favor of this attrocity. No comment <3
extension UTType {
static var torrent: UTType {
UTType.types(tag: "torrent", tagClass: .filenameExtension, conformingTo: nil).first!
}
}
| 38.340909 | 153 | 0.47046 |
76dd6af20ef8dc45821c28e70fc381508f4d4d22 | 5,440 | //
// ViewController.swift
// Demo
//
// Created by ZERO on 2021/5/11.
//
import UIKit
import SnapKit
import OYMarqueeView
class ViewController: UIViewController {
lazy var dataSource: [[String: String]] = {
let dataSource = [
["type": "0", "content": "基于Swift5的轻量级跑马灯视图,支持横向或竖向滚动,仿cell复用机制支持视图复用,可使用约束布局,支持snapkit"],
["type": "0", "content": "https://github.com/OYForever/OYMarqueeView"],
["type": "1", "content": "image1"],
["type": "0", "content": "[email protected]"],
["type": "1", "content": "image2"],
["type": "1", "content": "image1"],
["type": "0", "content": "感谢观看"],
["type": "0", "content": "😁😁😁😁😁"]
]
return dataSource
}()
let marqueeViewH = OYMarqueeView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 50))
let marqueeViewV = OYMarqueeView(scrollDirection: .vertical)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(marqueeViewH)
marqueeViewH.backgroundColor = .green
marqueeViewH.dataSourse = self
marqueeViewH.register(TextView.self, forItemReuseIdentifier: String(describing: TextView.self))
marqueeViewH.register(ImgView.self, forItemReuseIdentifier: String(describing: ImgView.self))
view.addSubview(marqueeViewV)
marqueeViewV.backgroundColor = .green
marqueeViewV.dataSourse = self
marqueeViewV.register(TextView.self, forItemReuseIdentifier: String(describing: TextView.self))
marqueeViewV.register(ImgView.self, forItemReuseIdentifier: String(describing: ImgView.self))
marqueeViewV.snp.makeConstraints { (make) in
make.left.right.equalToSuperview().inset(20)
make.top.equalTo(marqueeViewH.snp.bottom).offset(100)
make.height.equalTo(300)
}
}
}
extension ViewController: OYMarqueeViewDataSource {
func numberOfItems(in marqueeView: OYMarqueeView) -> Int {
return dataSource.count
}
func marqueeView(_ marqueeView: OYMarqueeView, itemForIndexAt index: Int) -> OYMarqueeViewItem {
if dataSource[index]["type"] == "0" {
let item = marqueeView.dequeueReusableItem(withIdentifier: String(describing: TextView.self)) as! TextView
item.text = dataSource[index]["content"]!
return item
} else {
let item = marqueeView.dequeueReusableItem(withIdentifier: String(describing: ImgView.self)) as! ImgView
item.imgView.image = UIImage(named: dataSource[index]["content"]!)
return item
}
}
func marqueeView(_ marqueeView: OYMarqueeView, itemSizeForIndexAt index: Int) -> CGSize {
if dataSource[index]["type"] == "0" {
if marqueeView == marqueeViewH {
var size = dataSource[index]["content"]!.boundingRect(with: CGSize(width: Double(MAXFLOAT), height: 50.0), font: .systemFont(ofSize: 18))
size.height = 50
return size
} else {
return dataSource[index]["content"]!.boundingRect(with: CGSize(width: UIScreen.main.bounds.width - 40, height: CGFloat(MAXFLOAT)), font: .systemFont(ofSize: 18), lines: 0)
}
} else {
return CGSize(width: 50, height: 50)
}
}
}
extension String {
/// 计算单行文字size
func boundingRect(with constrainedSize: CGSize, font: UIFont, lineSpacing: CGFloat? = nil) -> CGSize {
let attritube = NSMutableAttributedString(string: self)
let range = NSRange(location: 0, length: attritube.length)
attritube.addAttributes([NSAttributedString.Key.font: font], range: range)
if lineSpacing != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing!
attritube.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: range)
}
let rect = attritube.boundingRect(with: constrainedSize, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
var size = rect.size
if let currentLineSpacing = lineSpacing {
// 文本的高度减去字体高度小于等于行间距,判断为当前只有1行
let spacing = size.height - font.lineHeight
if spacing <= currentLineSpacing && spacing > 0 {
size = CGSize(width: size.width, height: font.lineHeight)
}
}
size.height = CGFloat(ceilf(Float(size.height)))
size.width = CGFloat(ceilf(Float(size.width)))
return size
}
/// 计算多行文字size
func boundingRect(with constrainedSize: CGSize, font: UIFont, lineSpacing: CGFloat? = nil, lines: Int) -> CGSize {
if lines < 0 {
return .zero
}
let size = boundingRect(with: constrainedSize, font: font, lineSpacing: lineSpacing)
if lines == 0 {
return size
}
let currentLineSpacing = (lineSpacing == nil) ? (font.lineHeight - font.pointSize) : lineSpacing!
let maximumHeight = font.lineHeight * CGFloat(lines) + currentLineSpacing * CGFloat(lines - 1)
if size.height >= maximumHeight {
return CGSize(width: size.width, height: maximumHeight)
}
return size
}
}
| 40.902256 | 187 | 0.620404 |
e50db75c178296478632af0ad1cd472429d6d46f | 183 | //
// AST.swift
// Calculator
//
// Created by Domenic Wüthrich on 14.01.18.
// Copyright © 2018 Domenic Wüthrich. All rights reserved.
//
import Foundation
public class AST {}
| 15.25 | 59 | 0.68306 |
79e0ae6d68224b9cfeebf0836cf30784a7d99592 | 101,717 | public extension FontAwesome {
struct Solid {
public struct Status {
public static let ban = FontAwesome("\u{f05e}")
public static let batteryempty = FontAwesome("\u{f244}")
public static let batteryfull = FontAwesome("\u{f240}")
public static let batteryhalf = FontAwesome("\u{f242}")
public static let batteryquarter = FontAwesome("\u{f243}")
public static let batterythreequarters = FontAwesome("\u{f241}")
public static let calendarcheck = FontAwesome("\u{f274}")
public static let calendarday = FontAwesome("\u{f783}")
public static let calendarminus = FontAwesome("\u{f272}")
public static let calendarplus = FontAwesome("\u{f271}")
public static let calendartimes = FontAwesome("\u{f273}")
public static let calendarweek = FontAwesome("\u{f784}")
public static let commentslash = FontAwesome("\u{f4b3}")
public static let minus = FontAwesome("\u{f068}")
public static let minuscircle = FontAwesome("\u{f056}")
public static let minussquare = FontAwesome("\u{f146}")
public static let pluscircle = FontAwesome("\u{f055}")
public static let question = FontAwesome("\u{f128}")
public static let questioncircle = FontAwesome("\u{f059}")
public static let signinalt = FontAwesome("\u{f2f6}")
public static let signoutalt = FontAwesome("\u{f2f5}")
public static let signal = FontAwesome("\u{f012}")
public static let starhalf = FontAwesome("\u{f089}")
public static let starhalfalt = FontAwesome("\u{f5c0}")
public static let thermometerempty = FontAwesome("\u{f2cb}")
public static let thermometerfull = FontAwesome("\u{f2c7}")
public static let thermometerhalf = FontAwesome("\u{f2c9}")
public static let thermometerquarter = FontAwesome("\u{f2ca}")
public static let thermometerthreequarters = FontAwesome("\u{f2c8}")
public static let tintslash = FontAwesome("\u{f5c7}")
public static let toggleoff = FontAwesome("\u{f204}")
public static let toggleon = FontAwesome("\u{f205}")
public static let video = FontAwesome("\u{f03d}")
public static let videoslash = FontAwesome("\u{f4e2}")
public static let volumedown = FontAwesome("\u{f027}")
public static let volumemute = FontAwesome("\u{f6a9}")
public static let volumeoff = FontAwesome("\u{f026}")
public static let volumeup = FontAwesome("\u{f028}")
}
public static let status: [FontAwesome] = [
Status.ban,
Status.batteryempty,
Status.batteryfull,
Status.batteryhalf,
Status.batteryquarter,
Status.batterythreequarters,
Status.calendarcheck,
Status.calendarday,
Status.calendarminus,
Status.calendarplus,
Status.calendartimes,
Status.calendarweek,
Status.commentslash,
Status.minus,
Status.minuscircle,
Status.minussquare,
Status.pluscircle,
Status.question,
Status.questioncircle,
Status.signinalt,
Status.signoutalt,
Status.signal,
Status.starhalf,
Status.starhalfalt,
Status.thermometerempty,
Status.thermometerfull,
Status.thermometerhalf,
Status.thermometerquarter,
Status.thermometerthreequarters,
Status.tintslash,
Status.toggleoff,
Status.toggleon,
Status.video,
Status.videoslash,
Status.volumedown,
Status.volumemute,
Status.volumeoff,
Status.volumeup,
]
public struct ScienceFiction {
public static let jedi = FontAwesome("\u{f669}")
public static let journalwhills = FontAwesome("\u{f66a}")
}
public static let scienceFictions: [FontAwesome] = [
ScienceFiction.jedi,
ScienceFiction.journalwhills,
]
public struct Weather {
public static let cloudmeatball = FontAwesome("\u{f73b}")
public static let cloudmoonrain = FontAwesome("\u{f73c}")
public static let cloudrain = FontAwesome("\u{f73d}")
public static let cloudshowersheavy = FontAwesome("\u{f740}")
public static let meteor = FontAwesome("\u{f753}")
public static let poostorm = FontAwesome("\u{f75a}")
public static let smog = FontAwesome("\u{f75f}")
}
public static let weathers: [FontAwesome] = [
Weather.cloudmeatball,
Weather.cloudmoonrain,
Weather.cloudrain,
Weather.cloudshowersheavy,
Weather.meteor,
Weather.poostorm,
Weather.smog,
]
public struct Construction {
public static let brush = FontAwesome("\u{f55d}")
public static let draftingcompass = FontAwesome("\u{f568}")
public static let dumpster = FontAwesome("\u{f793}")
public static let hammer = FontAwesome("\u{f6e3}")
public static let hardhat = FontAwesome("\u{f807}")
public static let paintroller = FontAwesome("\u{f5aa}")
public static let pencilruler = FontAwesome("\u{f5ae}")
public static let ruler = FontAwesome("\u{f545}")
public static let truckpickup = FontAwesome("\u{f63c}")
}
public static let constructions: [FontAwesome] = [
Construction.brush,
Construction.draftingcompass,
Construction.dumpster,
Construction.hammer,
Construction.hardhat,
Construction.paintroller,
Construction.pencilruler,
Construction.ruler,
Construction.truckpickup,
]
public struct Childhood {
public static let robot = FontAwesome("\u{f544}")
}
public static let childhoods: [FontAwesome] = [
Childhood.robot,
]
public struct Business {
public static let businesstime = FontAwesome("\u{f64a}")
public static let chartarea = FontAwesome("\u{f1fe}")
public static let chartbar = FontAwesome("\u{f080}")
public static let chartline = FontAwesome("\u{f201}")
public static let chartpie = FontAwesome("\u{f200}")
public static let city = FontAwesome("\u{f64f}")
public static let columns = FontAwesome("\u{f0db}")
public static let copyright = FontAwesome("\u{f1f9}")
public static let edit = FontAwesome("\u{f044}")
public static let folder = FontAwesome("\u{f07b}")
public static let folderminus = FontAwesome("\u{f65d}")
public static let folderopen = FontAwesome("\u{f07c}")
public static let folderplus = FontAwesome("\u{f65e}")
public static let pensquare = FontAwesome("\u{f14b}")
public static let percent = FontAwesome("\u{f295}")
public static let projectdiagram = FontAwesome("\u{f542}")
public static let registered = FontAwesome("\u{f25d}")
public static let sitemap = FontAwesome("\u{f0e8}")
public static let stream = FontAwesome("\u{f550}")
public static let table = FontAwesome("\u{f0ce}")
public static let tasks = FontAwesome("\u{f0ae}")
public static let trademark = FontAwesome("\u{f25c}")
}
public static let business: [FontAwesome] = [
Business.businesstime,
Business.chartarea,
Business.chartbar,
Business.chartline,
Business.chartpie,
Business.city,
Business.columns,
Business.copyright,
Business.edit,
Business.folder,
Business.folderminus,
Business.folderopen,
Business.folderplus,
Business.pensquare,
Business.percent,
Business.projectdiagram,
Business.registered,
Business.sitemap,
Business.stream,
Business.table,
Business.tasks,
Business.trademark,
]
public struct Winter {
public static let icicles = FontAwesome("\u{f7ad}")
public static let skating = FontAwesome("\u{f7c5}")
public static let skiing = FontAwesome("\u{f7c9}")
public static let skiingnordic = FontAwesome("\u{f7ca}")
public static let snowboarding = FontAwesome("\u{f7ce}")
}
public static let winters: [FontAwesome] = [
Winter.icicles,
Winter.skating,
Winter.skiing,
Winter.skiingnordic,
Winter.snowboarding,
]
public struct Chess {
public static let squarefull = FontAwesome("\u{f45c}")
}
public static let chess: [FontAwesome] = [
Chess.squarefull,
]
public struct Household {
public static let chair = FontAwesome("\u{f6c0}")
public static let couch = FontAwesome("\u{f4b8}")
public static let toiletpaper = FontAwesome("\u{f71e}")
}
public static let households: [FontAwesome] = [
Household.chair,
Household.couch,
Household.toiletpaper,
]
public struct Holiday {
public static let snowman = FontAwesome("\u{f7d0}")
}
public static let holidays: [FontAwesome] = [
Holiday.snowman,
]
public struct Marketing {
public static let ad = FontAwesome("\u{f641}")
public static let commentdollar = FontAwesome("\u{f651}")
public static let commentsdollar = FontAwesome("\u{f653}")
public static let envelopeopentext = FontAwesome("\u{f658}")
public static let funneldollar = FontAwesome("\u{f662}")
public static let mailbulk = FontAwesome("\u{f674}")
public static let poll = FontAwesome("\u{f681}")
public static let pollh = FontAwesome("\u{f682}")
public static let searchdollar = FontAwesome("\u{f688}")
public static let searchlocation = FontAwesome("\u{f689}")
}
public static let marketings: [FontAwesome] = [
Marketing.ad,
Marketing.commentdollar,
Marketing.commentsdollar,
Marketing.envelopeopentext,
Marketing.funneldollar,
Marketing.mailbulk,
Marketing.poll,
Marketing.pollh,
Marketing.searchdollar,
Marketing.searchlocation,
]
public struct Beverage {
public static let winebottle = FontAwesome("\u{f72f}")
}
public static let beverages: [FontAwesome] = [
Beverage.winebottle,
]
public struct Science {
public static let atom = FontAwesome("\u{f5d2}")
public static let clipboardcheck = FontAwesome("\u{f46c}")
public static let eyedropper = FontAwesome("\u{f1fb}")
public static let filter = FontAwesome("\u{f0b0}")
public static let fire = FontAwesome("\u{f06d}")
public static let firealt = FontAwesome("\u{f7e4}")
public static let flask = FontAwesome("\u{f0c3}")
public static let frog = FontAwesome("\u{f52e}")
public static let magnet = FontAwesome("\u{f076}")
public static let seedling = FontAwesome("\u{f4d8}")
public static let skullcrossbones = FontAwesome("\u{f714}")
public static let temperaturehigh = FontAwesome("\u{f769}")
public static let temperaturelow = FontAwesome("\u{f76b}")
}
public static let sciences: [FontAwesome] = [
Science.atom,
Science.clipboardcheck,
Science.eyedropper,
Science.filter,
Science.fire,
Science.firealt,
Science.flask,
Science.frog,
Science.magnet,
Science.seedling,
Science.skullcrossbones,
Science.temperaturehigh,
Science.temperaturelow,
]
public struct Interfaces {
public static let barcode = FontAwesome("\u{f02a}")
public static let bars = FontAwesome("\u{f0c9}")
public static let check = FontAwesome("\u{f00c}")
public static let checkdouble = FontAwesome("\u{f560}")
public static let checksquare = FontAwesome("\u{f14a}")
public static let clouddownloadalt = FontAwesome("\u{f381}")
public static let clouduploadalt = FontAwesome("\u{f382}")
public static let ellipsish = FontAwesome("\u{f141}")
public static let ellipsisv = FontAwesome("\u{f142}")
public static let externallinkalt = FontAwesome("\u{f35d}")
public static let externallinksquarealt = FontAwesome("\u{f360}")
public static let filedownload = FontAwesome("\u{f56d}")
public static let fileexport = FontAwesome("\u{f56e}")
public static let fileimport = FontAwesome("\u{f56f}")
public static let fileupload = FontAwesome("\u{f574}")
public static let griphorizontal = FontAwesome("\u{f58d}")
public static let griplines = FontAwesome("\u{f7a4}")
public static let griplinesvertical = FontAwesome("\u{f7a5}")
public static let gripvertical = FontAwesome("\u{f58e}")
public static let hashtag = FontAwesome("\u{f292}")
public static let qrcode = FontAwesome("\u{f029}")
public static let sharealt = FontAwesome("\u{f1e0}")
public static let sharealtsquare = FontAwesome("\u{f1e1}")
public static let sharesquare = FontAwesome("\u{f14d}")
public static let sort = FontAwesome("\u{f0dc}")
public static let sortalphadown = FontAwesome("\u{f15d}")
public static let sortalphadownalt = FontAwesome("\u{f881}")
public static let sortalphaup = FontAwesome("\u{f15e}")
public static let sortalphaupalt = FontAwesome("\u{f882}")
public static let sortamountdown = FontAwesome("\u{f160}")
public static let sortamountdownalt = FontAwesome("\u{f884}")
public static let sortamountup = FontAwesome("\u{f161}")
public static let sortamountupalt = FontAwesome("\u{f885}")
public static let sortdown = FontAwesome("\u{f0dd}")
public static let sortnumericdown = FontAwesome("\u{f162}")
public static let sortnumericdownalt = FontAwesome("\u{f886}")
public static let sortnumericup = FontAwesome("\u{f163}")
public static let sortnumericupalt = FontAwesome("\u{f887}")
public static let sortup = FontAwesome("\u{f0de}")
public static let timescircle = FontAwesome("\u{f057}")
}
public static let interfaces: [FontAwesome] = [
Interfaces.barcode,
Interfaces.bars,
Interfaces.check,
Interfaces.checkdouble,
Interfaces.checksquare,
Interfaces.clouddownloadalt,
Interfaces.clouduploadalt,
Interfaces.ellipsish,
Interfaces.ellipsisv,
Interfaces.externallinkalt,
Interfaces.externallinksquarealt,
Interfaces.filedownload,
Interfaces.fileexport,
Interfaces.fileimport,
Interfaces.fileupload,
Interfaces.griphorizontal,
Interfaces.griplines,
Interfaces.griplinesvertical,
Interfaces.gripvertical,
Interfaces.hashtag,
Interfaces.qrcode,
Interfaces.sharealt,
Interfaces.sharealtsquare,
Interfaces.sharesquare,
Interfaces.sort,
Interfaces.sortalphadown,
Interfaces.sortalphadownalt,
Interfaces.sortalphaup,
Interfaces.sortalphaupalt,
Interfaces.sortamountdown,
Interfaces.sortamountdownalt,
Interfaces.sortamountup,
Interfaces.sortamountupalt,
Interfaces.sortdown,
Interfaces.sortnumericdown,
Interfaces.sortnumericdownalt,
Interfaces.sortnumericup,
Interfaces.sortnumericupalt,
Interfaces.sortup,
Interfaces.timescircle,
]
public struct Computers {
public static let database = FontAwesome("\u{f1c0}")
public static let desktop = FontAwesome("\u{f108}")
public static let download = FontAwesome("\u{f019}")
public static let ethernet = FontAwesome("\u{f796}")
public static let mouse = FontAwesome("\u{f8cc}")
public static let server = FontAwesome("\u{f233}")
public static let upload = FontAwesome("\u{f093}")
}
public static let computers: [FontAwesome] = [
Computers.database,
Computers.desktop,
Computers.download,
Computers.ethernet,
Computers.mouse,
Computers.server,
Computers.upload,
]
public struct Games {
public static let chess = FontAwesome("\u{f439}")
public static let chessbishop = FontAwesome("\u{f43a}")
public static let chessboard = FontAwesome("\u{f43c}")
public static let chessking = FontAwesome("\u{f43f}")
public static let chessknight = FontAwesome("\u{f441}")
public static let chesspawn = FontAwesome("\u{f443}")
public static let chessqueen = FontAwesome("\u{f445}")
public static let chessrook = FontAwesome("\u{f447}")
public static let ghost = FontAwesome("\u{f6e2}")
}
public static let games: [FontAwesome] = [
Games.chess,
Games.chessbishop,
Games.chessboard,
Games.chessking,
Games.chessknight,
Games.chesspawn,
Games.chessqueen,
Games.chessrook,
Games.ghost,
]
public struct Editors {
public static let aligncenter = FontAwesome("\u{f037}")
public static let alignjustify = FontAwesome("\u{f039}")
public static let alignleft = FontAwesome("\u{f036}")
public static let alignright = FontAwesome("\u{f038}")
public static let bold = FontAwesome("\u{f032}")
public static let borderall = FontAwesome("\u{f84c}")
public static let bordernone = FontAwesome("\u{f850}")
public static let borderstyle = FontAwesome("\u{f853}")
public static let clone = FontAwesome("\u{f24d}")
public static let font = FontAwesome("\u{f031}")
public static let heading = FontAwesome("\u{f1dc}")
public static let icursor = FontAwesome("\u{f246}")
public static let icons = FontAwesome("\u{f86d}")
public static let indent = FontAwesome("\u{f03c}")
public static let italic = FontAwesome("\u{f033}")
public static let link = FontAwesome("\u{f0c1}")
public static let list = FontAwesome("\u{f03a}")
public static let listalt = FontAwesome("\u{f022}")
public static let listol = FontAwesome("\u{f0cb}")
public static let listul = FontAwesome("\u{f0ca}")
public static let outdent = FontAwesome("\u{f03b}")
public static let paragraph = FontAwesome("\u{f1dd}")
public static let quoteleft = FontAwesome("\u{f10d}")
public static let quoteright = FontAwesome("\u{f10e}")
public static let redo = FontAwesome("\u{f01e}")
public static let redoalt = FontAwesome("\u{f2f9}")
public static let removeformat = FontAwesome("\u{f87d}")
public static let reply = FontAwesome("\u{f3e5}")
public static let replyall = FontAwesome("\u{f122}")
public static let share = FontAwesome("\u{f064}")
public static let spellcheck = FontAwesome("\u{f891}")
public static let strikethrough = FontAwesome("\u{f0cc}")
public static let subscript_ = FontAwesome("\u{f12c}")
public static let superscript = FontAwesome("\u{f12b}")
public static let sync = FontAwesome("\u{f021}")
public static let syncalt = FontAwesome("\u{f2f1}")
public static let textheight = FontAwesome("\u{f034}")
public static let textwidth = FontAwesome("\u{f035}")
public static let th = FontAwesome("\u{f00a}")
public static let thlarge = FontAwesome("\u{f009}")
public static let thlist = FontAwesome("\u{f00b}")
public static let trashrestore = FontAwesome("\u{f829}")
public static let trashrestorealt = FontAwesome("\u{f82a}")
public static let underline = FontAwesome("\u{f0cd}")
public static let undo = FontAwesome("\u{f0e2}")
public static let undoalt = FontAwesome("\u{f2ea}")
public static let unlink = FontAwesome("\u{f127}")
}
public static let editors: [FontAwesome] = [
Editors.aligncenter,
Editors.alignjustify,
Editors.alignleft,
Editors.alignright,
Editors.bold,
Editors.borderall,
Editors.bordernone,
Editors.borderstyle,
Editors.clone,
Editors.font,
Editors.heading,
Editors.icursor,
Editors.icons,
Editors.indent,
Editors.italic,
Editors.link,
Editors.list,
Editors.listalt,
Editors.listol,
Editors.listul,
Editors.outdent,
Editors.paragraph,
Editors.quoteleft,
Editors.quoteright,
Editors.redo,
Editors.redoalt,
Editors.removeformat,
Editors.reply,
Editors.replyall,
Editors.share,
Editors.spellcheck,
Editors.strikethrough,
Editors.subscript_,
Editors.superscript,
Editors.sync,
Editors.syncalt,
Editors.textheight,
Editors.textwidth,
Editors.th,
Editors.thlarge,
Editors.thlist,
Editors.trashrestore,
Editors.trashrestorealt,
Editors.underline,
Editors.undo,
Editors.undoalt,
Editors.unlink,
]
public struct Writing {
public static let blog = FontAwesome("\u{f781}")
}
public static let writings: [FontAwesome] = [
Writing.blog,
]
public struct Clothing {
public static let hatcowboy = FontAwesome("\u{f8c0}")
public static let hatcowboyside = FontAwesome("\u{f8c1}")
public static let socks = FontAwesome("\u{f696}")
public static let tshirt = FontAwesome("\u{f553}")
public static let usertie = FontAwesome("\u{f508}")
}
public static let clothings: [FontAwesome] = [
Clothing.hatcowboy,
Clothing.hatcowboyside,
Clothing.socks,
Clothing.tshirt,
Clothing.usertie,
]
public struct Music {
public static let fileaudio = FontAwesome("\u{f1c7}")
public static let recordvinyl = FontAwesome("\u{f8d9}")
public static let slidersh = FontAwesome("\u{f1de}")
}
public static let musics: [FontAwesome] = [
Music.fileaudio,
Music.recordvinyl,
Music.slidersh,
]
public struct PaymentsShopping {
public static let bell = FontAwesome("\u{f0f3}")
public static let bookmark = FontAwesome("\u{f02e}")
public static let bullhorn = FontAwesome("\u{f0a1}")
public static let camera = FontAwesome("\u{f030}")
public static let cameraretro = FontAwesome("\u{f083}")
public static let cartarrowdown = FontAwesome("\u{f218}")
public static let cartplus = FontAwesome("\u{f217}")
public static let certificate = FontAwesome("\u{f0a3}")
public static let creditcard = FontAwesome("\u{f09d}")
public static let gem = FontAwesome("\u{f3a5}")
public static let gift = FontAwesome("\u{f06b}")
public static let handshake = FontAwesome("\u{f2b5}")
public static let key = FontAwesome("\u{f084}")
public static let moneycheck = FontAwesome("\u{f53c}")
public static let moneycheckalt = FontAwesome("\u{f53d}")
public static let receipt = FontAwesome("\u{f543}")
public static let shoppingbag = FontAwesome("\u{f290}")
public static let shoppingbasket = FontAwesome("\u{f291}")
public static let shoppingcart = FontAwesome("\u{f07a}")
public static let star = FontAwesome("\u{f005}")
public static let tag = FontAwesome("\u{f02b}")
public static let tags = FontAwesome("\u{f02c}")
public static let thumbsdown = FontAwesome("\u{f165}")
public static let thumbsup = FontAwesome("\u{f164}")
public static let trophy = FontAwesome("\u{f091}")
}
public static let paymentsShoppings: [FontAwesome] = [
PaymentsShopping.bell,
PaymentsShopping.bookmark,
PaymentsShopping.bullhorn,
PaymentsShopping.camera,
PaymentsShopping.cameraretro,
PaymentsShopping.cartarrowdown,
PaymentsShopping.cartplus,
PaymentsShopping.certificate,
PaymentsShopping.creditcard,
PaymentsShopping.gem,
PaymentsShopping.gift,
PaymentsShopping.handshake,
PaymentsShopping.key,
PaymentsShopping.moneycheck,
PaymentsShopping.moneycheckalt,
PaymentsShopping.receipt,
PaymentsShopping.shoppingbag,
PaymentsShopping.shoppingbasket,
PaymentsShopping.shoppingcart,
PaymentsShopping.star,
PaymentsShopping.tag,
PaymentsShopping.tags,
PaymentsShopping.thumbsdown,
PaymentsShopping.thumbsup,
PaymentsShopping.trophy,
]
public struct Halloween {
public static let cat = FontAwesome("\u{f6be}")
public static let cloudmoon = FontAwesome("\u{f6c3}")
public static let crow = FontAwesome("\u{f520}")
public static let spider = FontAwesome("\u{f717}")
}
public static let halloweens: [FontAwesome] = [
Halloween.cat,
Halloween.cloudmoon,
Halloween.crow,
Halloween.spider,
]
public struct Education {
public static let bookopen = FontAwesome("\u{f518}")
public static let bookreader = FontAwesome("\u{f5da}")
public static let laptopcode = FontAwesome("\u{f5fc}")
public static let theatermasks = FontAwesome("\u{f630}")
}
public static let educations: [FontAwesome] = [
Education.bookopen,
Education.bookreader,
Education.laptopcode,
Education.theatermasks,
]
public struct Security {
public static let dungeon = FontAwesome("\u{f6d9}")
public static let filecontract = FontAwesome("\u{f56c}")
public static let filesignature = FontAwesome("\u{f573}")
public static let fingerprint = FontAwesome("\u{f577}")
public static let mask = FontAwesome("\u{f6fa}")
}
public static let securitys: [FontAwesome] = [
Security.dungeon,
Security.filecontract,
Security.filesignature,
Security.fingerprint,
Security.mask,
]
public struct Energy {
public static let solarpanel = FontAwesome("\u{f5ba}")
}
public static let energys: [FontAwesome] = [
Energy.solarpanel,
]
public struct Travel {
public static let archway = FontAwesome("\u{f557}")
public static let atlas = FontAwesome("\u{f558}")
public static let busalt = FontAwesome("\u{f55e}")
public static let caravan = FontAwesome("\u{f8ff}")
public static let cocktail = FontAwesome("\u{f561}")
public static let conciergebell = FontAwesome("\u{f562}")
public static let dumbbell = FontAwesome("\u{f44b}")
public static let glassmartinialt = FontAwesome("\u{f57b}")
public static let globeafrica = FontAwesome("\u{f57c}")
public static let globeamericas = FontAwesome("\u{f57d}")
public static let globeasia = FontAwesome("\u{f57e}")
public static let globeeurope = FontAwesome("\u{f7a2}")
public static let hottub = FontAwesome("\u{f593}")
public static let hotel = FontAwesome("\u{f594}")
public static let luggagecart = FontAwesome("\u{f59d}")
public static let mapmarked = FontAwesome("\u{f59f}")
public static let mapmarkedalt = FontAwesome("\u{f5a0}")
public static let monument = FontAwesome("\u{f5a6}")
public static let passport = FontAwesome("\u{f5ab}")
public static let planearrival = FontAwesome("\u{f5af}")
public static let planedeparture = FontAwesome("\u{f5b0}")
public static let shuttlevan = FontAwesome("\u{f5b6}")
public static let spa = FontAwesome("\u{f5bb}")
public static let suitcaserolling = FontAwesome("\u{f5c1}")
public static let swimmer = FontAwesome("\u{f5c4}")
public static let swimmingpool = FontAwesome("\u{f5c5}")
public static let umbrellabeach = FontAwesome("\u{f5ca}")
public static let wineglassalt = FontAwesome("\u{f5ce}")
}
public static let travels: [FontAwesome] = [
Travel.archway,
Travel.atlas,
Travel.busalt,
Travel.caravan,
Travel.cocktail,
Travel.conciergebell,
Travel.dumbbell,
Travel.glassmartinialt,
Travel.globeafrica,
Travel.globeamericas,
Travel.globeasia,
Travel.globeeurope,
Travel.hottub,
Travel.hotel,
Travel.luggagecart,
Travel.mapmarked,
Travel.mapmarkedalt,
Travel.monument,
Travel.passport,
Travel.planearrival,
Travel.planedeparture,
Travel.shuttlevan,
Travel.spa,
Travel.suitcaserolling,
Travel.swimmer,
Travel.swimmingpool,
Travel.umbrellabeach,
Travel.wineglassalt,
]
public struct Spring {
public static let broom = FontAwesome("\u{f51a}")
public static let cloudsun = FontAwesome("\u{f6c4}")
public static let cloudsunrain = FontAwesome("\u{f743}")
public static let rainbow = FontAwesome("\u{f75b}")
}
public static let springs: [FontAwesome] = [
Spring.broom,
Spring.cloudsun,
Spring.cloudsunrain,
Spring.rainbow,
]
public struct Mathematics {
public static let divide = FontAwesome("\u{f529}")
public static let equals = FontAwesome("\u{f52c}")
public static let greaterthan = FontAwesome("\u{f531}")
public static let greaterthanequal = FontAwesome("\u{f532}")
public static let infinity = FontAwesome("\u{f534}")
public static let lessthan = FontAwesome("\u{f536}")
public static let lessthanequal = FontAwesome("\u{f537}")
public static let notequal = FontAwesome("\u{f53e}")
public static let percentage = FontAwesome("\u{f541}")
public static let squarerootalt = FontAwesome("\u{f698}")
public static let times = FontAwesome("\u{f00d}")
public static let wavesquare = FontAwesome("\u{f83e}")
}
public static let mathematics: [FontAwesome] = [
Mathematics.divide,
Mathematics.equals,
Mathematics.greaterthan,
Mathematics.greaterthanequal,
Mathematics.infinity,
Mathematics.lessthan,
Mathematics.lessthanequal,
Mathematics.notequal,
Mathematics.percentage,
Mathematics.squarerootalt,
Mathematics.times,
Mathematics.wavesquare,
]
public struct Charity {
public static let parachutebox = FontAwesome("\u{f4cd}")
public static let ribbon = FontAwesome("\u{f4d6}")
}
public static let charitys: [FontAwesome] = [
Charity.parachutebox,
Charity.ribbon,
]
public struct Religion {
public static let ankh = FontAwesome("\u{f644}")
public static let bible = FontAwesome("\u{f647}")
public static let cross = FontAwesome("\u{f654}")
public static let hamsa = FontAwesome("\u{f665}")
public static let hanukiah = FontAwesome("\u{f6e6}")
public static let khanda = FontAwesome("\u{f66d}")
public static let menorah = FontAwesome("\u{f676}")
public static let om = FontAwesome("\u{f679}")
public static let pastafarianism = FontAwesome("\u{f67b}")
public static let peace = FontAwesome("\u{f67c}")
public static let quran = FontAwesome("\u{f687}")
public static let starandcrescent = FontAwesome("\u{f699}")
public static let starofdavid = FontAwesome("\u{f69a}")
public static let torah = FontAwesome("\u{f6a0}")
}
public static let religions: [FontAwesome] = [
Religion.ankh,
Religion.bible,
Religion.cross,
Religion.hamsa,
Religion.hanukiah,
Religion.khanda,
Religion.menorah,
Religion.om,
Religion.pastafarianism,
Religion.peace,
Religion.quran,
Religion.starandcrescent,
Religion.starofdavid,
Religion.torah,
]
public struct Finance {
public static let cashregister = FontAwesome("\u{f788}")
public static let coins = FontAwesome("\u{f51e}")
public static let donate = FontAwesome("\u{f4b9}")
public static let fileinvoice = FontAwesome("\u{f570}")
public static let fileinvoicedollar = FontAwesome("\u{f571}")
public static let piggybank = FontAwesome("\u{f4d3}")
}
public static let finances: [FontAwesome] = [
Finance.cashregister,
Finance.coins,
Finance.donate,
Finance.fileinvoice,
Finance.fileinvoicedollar,
Finance.piggybank,
]
public struct Food {
public static let bacon = FontAwesome("\u{f7e5}")
public static let breadslice = FontAwesome("\u{f7ec}")
public static let cheese = FontAwesome("\u{f7ef}")
public static let egg = FontAwesome("\u{f7fb}")
public static let hamburger = FontAwesome("\u{f805}")
public static let pizzaslice = FontAwesome("\u{f818}")
}
public static let foods: [FontAwesome] = [
Food.bacon,
Food.breadslice,
Food.cheese,
Food.egg,
Food.hamburger,
Food.pizzaslice,
]
public struct Hands {
public static let fistraised = FontAwesome("\u{f6de}")
public static let handholding = FontAwesome("\u{f4bd}")
public static let handholdingheart = FontAwesome("\u{f4be}")
public static let handholdingusd = FontAwesome("\u{f4c0}")
public static let handlizard = FontAwesome("\u{f258}")
public static let handmiddlefinger = FontAwesome("\u{f806}")
public static let handpaper = FontAwesome("\u{f256}")
public static let handpeace = FontAwesome("\u{f25b}")
public static let handpointdown = FontAwesome("\u{f0a7}")
public static let handpointleft = FontAwesome("\u{f0a5}")
public static let handpointright = FontAwesome("\u{f0a4}")
public static let handpointup = FontAwesome("\u{f0a6}")
public static let handpointer = FontAwesome("\u{f25a}")
public static let handrock = FontAwesome("\u{f255}")
public static let handscissors = FontAwesome("\u{f257}")
public static let handspock = FontAwesome("\u{f259}")
public static let hands = FontAwesome("\u{f4c2}")
public static let handshelping = FontAwesome("\u{f4c4}")
public static let prayinghands = FontAwesome("\u{f684}")
}
public static let hands: [FontAwesome] = [
Hands.fistraised,
Hands.handholding,
Hands.handholdingheart,
Hands.handholdingusd,
Hands.handlizard,
Hands.handmiddlefinger,
Hands.handpaper,
Hands.handpeace,
Hands.handpointdown,
Hands.handpointleft,
Hands.handpointright,
Hands.handpointup,
Hands.handpointer,
Hands.handrock,
Hands.handscissors,
Hands.handspock,
Hands.hands,
Hands.handshelping,
Hands.prayinghands,
]
public struct UsersPeople {
public static let baby = FontAwesome("\u{f77c}")
public static let biking = FontAwesome("\u{f84a}")
public static let chalkboardteacher = FontAwesome("\u{f51c}")
public static let child = FontAwesome("\u{f1ae}")
public static let female = FontAwesome("\u{f182}")
public static let hiking = FontAwesome("\u{f6ec}")
public static let idbadge = FontAwesome("\u{f2c1}")
public static let idcard = FontAwesome("\u{f2c2}")
public static let peoplecarry = FontAwesome("\u{f4ce}")
public static let personbooth = FontAwesome("\u{f756}")
public static let poo = FontAwesome("\u{f2fe}")
public static let portrait = FontAwesome("\u{f3e0}")
public static let poweroff = FontAwesome("\u{f011}")
public static let pray = FontAwesome("\u{f683}")
public static let running = FontAwesome("\u{f70c}")
public static let user = FontAwesome("\u{f007}")
public static let useralt = FontAwesome("\u{f406}")
public static let useraltslash = FontAwesome("\u{f4fa}")
public static let userastronaut = FontAwesome("\u{f4fb}")
public static let usercheck = FontAwesome("\u{f4fc}")
public static let usercircle = FontAwesome("\u{f2bd}")
public static let userclock = FontAwesome("\u{f4fd}")
public static let usercog = FontAwesome("\u{f4fe}")
public static let useredit = FontAwesome("\u{f4ff}")
public static let userfriends = FontAwesome("\u{f500}")
public static let usergraduate = FontAwesome("\u{f501}")
public static let userinjured = FontAwesome("\u{f728}")
public static let userlock = FontAwesome("\u{f502}")
public static let userminus = FontAwesome("\u{f503}")
public static let userninja = FontAwesome("\u{f504}")
public static let userplus = FontAwesome("\u{f234}")
public static let usersecret = FontAwesome("\u{f21b}")
public static let usershield = FontAwesome("\u{f505}")
public static let userslash = FontAwesome("\u{f506}")
public static let usertag = FontAwesome("\u{f507}")
public static let usertimes = FontAwesome("\u{f235}")
public static let users = FontAwesome("\u{f0c0}")
public static let userscog = FontAwesome("\u{f509}")
public static let walking = FontAwesome("\u{f554}")
}
public static let usersPeoples: [FontAwesome] = [
UsersPeople.baby,
UsersPeople.biking,
UsersPeople.chalkboardteacher,
UsersPeople.child,
UsersPeople.female,
UsersPeople.hiking,
UsersPeople.idbadge,
UsersPeople.idcard,
UsersPeople.peoplecarry,
UsersPeople.personbooth,
UsersPeople.poo,
UsersPeople.portrait,
UsersPeople.poweroff,
UsersPeople.pray,
UsersPeople.running,
UsersPeople.user,
UsersPeople.useralt,
UsersPeople.useraltslash,
UsersPeople.userastronaut,
UsersPeople.usercheck,
UsersPeople.usercircle,
UsersPeople.userclock,
UsersPeople.usercog,
UsersPeople.useredit,
UsersPeople.userfriends,
UsersPeople.usergraduate,
UsersPeople.userinjured,
UsersPeople.userlock,
UsersPeople.userminus,
UsersPeople.userninja,
UsersPeople.userplus,
UsersPeople.usersecret,
UsersPeople.usershield,
UsersPeople.userslash,
UsersPeople.usertag,
UsersPeople.usertimes,
UsersPeople.users,
UsersPeople.userscog,
UsersPeople.walking,
]
public struct Medical {
public static let allergies = FontAwesome("\u{f461}")
public static let ambulance = FontAwesome("\u{f0f9}")
public static let bandaid = FontAwesome("\u{f462}")
public static let biohazard = FontAwesome("\u{f780}")
public static let bone = FontAwesome("\u{f5d7}")
public static let bong = FontAwesome("\u{f55c}")
public static let bookmedical = FontAwesome("\u{f7e6}")
public static let brain = FontAwesome("\u{f5dc}")
public static let briefcasemedical = FontAwesome("\u{f469}")
public static let burn = FontAwesome("\u{f46a}")
public static let cannabis = FontAwesome("\u{f55f}")
public static let capsules = FontAwesome("\u{f46b}")
public static let clinicmedical = FontAwesome("\u{f7f2}")
public static let commentmedical = FontAwesome("\u{f7f5}")
public static let crutch = FontAwesome("\u{f7f7}")
public static let diagnoses = FontAwesome("\u{f470}")
public static let dna = FontAwesome("\u{f471}")
public static let filemedical = FontAwesome("\u{f477}")
public static let filemedicalalt = FontAwesome("\u{f478}")
public static let fileprescription = FontAwesome("\u{f572}")
public static let firstaid = FontAwesome("\u{f479}")
public static let heart = FontAwesome("\u{f004}")
public static let heartbeat = FontAwesome("\u{f21e}")
public static let hospital = FontAwesome("\u{f0f8}")
public static let hospitalalt = FontAwesome("\u{f47d}")
public static let hospitalsymbol = FontAwesome("\u{f47e}")
public static let idcardalt = FontAwesome("\u{f47f}")
public static let joint = FontAwesome("\u{f595}")
public static let laptopmedical = FontAwesome("\u{f812}")
public static let microscope = FontAwesome("\u{f610}")
public static let mortarpestle = FontAwesome("\u{f5a7}")
public static let notesmedical = FontAwesome("\u{f481}")
public static let pager = FontAwesome("\u{f815}")
public static let pills = FontAwesome("\u{f484}")
public static let plus = FontAwesome("\u{f067}")
public static let poop = FontAwesome("\u{f619}")
public static let prescription = FontAwesome("\u{f5b1}")
public static let prescriptionbottle = FontAwesome("\u{f485}")
public static let prescriptionbottlealt = FontAwesome("\u{f486}")
public static let procedures = FontAwesome("\u{f487}")
public static let radiation = FontAwesome("\u{f7b9}")
public static let radiationalt = FontAwesome("\u{f7ba}")
public static let smoking = FontAwesome("\u{f48d}")
public static let smokingban = FontAwesome("\u{f54d}")
public static let staroflife = FontAwesome("\u{f621}")
public static let stethoscope = FontAwesome("\u{f0f1}")
public static let syringe = FontAwesome("\u{f48e}")
public static let tablets = FontAwesome("\u{f490}")
public static let teeth = FontAwesome("\u{f62e}")
public static let teethopen = FontAwesome("\u{f62f}")
public static let thermometer = FontAwesome("\u{f491}")
public static let tooth = FontAwesome("\u{f5c9}")
public static let usermd = FontAwesome("\u{f0f0}")
public static let usernurse = FontAwesome("\u{f82f}")
public static let vial = FontAwesome("\u{f492}")
public static let vials = FontAwesome("\u{f493}")
public static let weight = FontAwesome("\u{f496}")
public static let xray = FontAwesome("\u{f497}")
}
public static let medicals: [FontAwesome] = [
Medical.allergies,
Medical.ambulance,
Medical.bandaid,
Medical.biohazard,
Medical.bone,
Medical.bong,
Medical.bookmedical,
Medical.brain,
Medical.briefcasemedical,
Medical.burn,
Medical.cannabis,
Medical.capsules,
Medical.clinicmedical,
Medical.commentmedical,
Medical.crutch,
Medical.diagnoses,
Medical.dna,
Medical.filemedical,
Medical.filemedicalalt,
Medical.fileprescription,
Medical.firstaid,
Medical.heart,
Medical.heartbeat,
Medical.hospital,
Medical.hospitalalt,
Medical.hospitalsymbol,
Medical.idcardalt,
Medical.joint,
Medical.laptopmedical,
Medical.microscope,
Medical.mortarpestle,
Medical.notesmedical,
Medical.pager,
Medical.pills,
Medical.plus,
Medical.poop,
Medical.prescription,
Medical.prescriptionbottle,
Medical.prescriptionbottlealt,
Medical.procedures,
Medical.radiation,
Medical.radiationalt,
Medical.smoking,
Medical.smokingban,
Medical.staroflife,
Medical.stethoscope,
Medical.syringe,
Medical.tablets,
Medical.teeth,
Medical.teethopen,
Medical.thermometer,
Medical.tooth,
Medical.usermd,
Medical.usernurse,
Medical.vial,
Medical.vials,
Medical.weight,
Medical.xray,
]
public struct Animals {
public static let dog = FontAwesome("\u{f6d3}")
public static let dove = FontAwesome("\u{f4ba}")
public static let hippo = FontAwesome("\u{f6ed}")
public static let horse = FontAwesome("\u{f6f0}")
public static let horsehead = FontAwesome("\u{f7ab}")
public static let kiwibird = FontAwesome("\u{f535}")
public static let otter = FontAwesome("\u{f700}")
}
public static let animals: [FontAwesome] = [
Animals.dog,
Animals.dove,
Animals.hippo,
Animals.horse,
Animals.horsehead,
Animals.kiwibird,
Animals.otter,
]
public struct Images {
public static let adjust = FontAwesome("\u{f042}")
public static let bolt = FontAwesome("\u{f0e7}")
public static let compress = FontAwesome("\u{f066}")
public static let compressarrowsalt = FontAwesome("\u{f78c}")
public static let expand = FontAwesome("\u{f065}")
}
public static let images: [FontAwesome] = [
Images.adjust,
Images.bolt,
Images.compress,
Images.compressarrowsalt,
Images.expand,
]
public struct Files {
public static let filearchive = FontAwesome("\u{f1c6}")
public static let filecode = FontAwesome("\u{f1c9}")
public static let fileexcel = FontAwesome("\u{f1c3}")
public static let fileimage = FontAwesome("\u{f1c5}")
public static let filepdf = FontAwesome("\u{f1c1}")
public static let filepowerpoint = FontAwesome("\u{f1c4}")
public static let filevideo = FontAwesome("\u{f1c8}")
public static let fileword = FontAwesome("\u{f1c2}")
public static let photovideo = FontAwesome("\u{f87c}")
}
public static let files: [FontAwesome] = [
Files.filearchive,
Files.filecode,
Files.fileexcel,
Files.fileimage,
Files.filepdf,
Files.filepowerpoint,
Files.filevideo,
Files.fileword,
Files.photovideo,
]
public struct Arrows {
public static let angledoubledown = FontAwesome("\u{f103}")
public static let angledoubleleft = FontAwesome("\u{f100}")
public static let angledoubleright = FontAwesome("\u{f101}")
public static let angledoubleup = FontAwesome("\u{f102}")
public static let angledown = FontAwesome("\u{f107}")
public static let angleleft = FontAwesome("\u{f104}")
public static let angleright = FontAwesome("\u{f105}")
public static let angleup = FontAwesome("\u{f106}")
public static let arrowaltcircledown = FontAwesome("\u{f358}")
public static let arrowaltcircleleft = FontAwesome("\u{f359}")
public static let arrowaltcircleright = FontAwesome("\u{f35a}")
public static let arrowaltcircleup = FontAwesome("\u{f35b}")
public static let arrowcircledown = FontAwesome("\u{f0ab}")
public static let arrowcircleleft = FontAwesome("\u{f0a8}")
public static let arrowcircleright = FontAwesome("\u{f0a9}")
public static let arrowcircleup = FontAwesome("\u{f0aa}")
public static let arrowdown = FontAwesome("\u{f063}")
public static let arrowleft = FontAwesome("\u{f060}")
public static let arrowright = FontAwesome("\u{f061}")
public static let arrowup = FontAwesome("\u{f062}")
public static let arrowsalt = FontAwesome("\u{f0b2}")
public static let arrowsalth = FontAwesome("\u{f337}")
public static let arrowsaltv = FontAwesome("\u{f338}")
public static let caretdown = FontAwesome("\u{f0d7}")
public static let caretleft = FontAwesome("\u{f0d9}")
public static let caretright = FontAwesome("\u{f0da}")
public static let caretsquaredown = FontAwesome("\u{f150}")
public static let caretsquareleft = FontAwesome("\u{f191}")
public static let caretsquareright = FontAwesome("\u{f152}")
public static let caretsquareup = FontAwesome("\u{f151}")
public static let caretup = FontAwesome("\u{f0d8}")
public static let chevroncircledown = FontAwesome("\u{f13a}")
public static let chevroncircleleft = FontAwesome("\u{f137}")
public static let chevroncircleright = FontAwesome("\u{f138}")
public static let chevroncircleup = FontAwesome("\u{f139}")
public static let chevrondown = FontAwesome("\u{f078}")
public static let chevronleft = FontAwesome("\u{f053}")
public static let chevronright = FontAwesome("\u{f054}")
public static let chevronup = FontAwesome("\u{f077}")
public static let exchangealt = FontAwesome("\u{f362}")
public static let leveldownalt = FontAwesome("\u{f3be}")
public static let levelupalt = FontAwesome("\u{f3bf}")
public static let longarrowaltdown = FontAwesome("\u{f309}")
public static let longarrowaltleft = FontAwesome("\u{f30a}")
public static let longarrowaltright = FontAwesome("\u{f30b}")
public static let longarrowaltup = FontAwesome("\u{f30c}")
public static let mousepointer = FontAwesome("\u{f245}")
public static let retweet = FontAwesome("\u{f079}")
}
public static let arrows: [FontAwesome] = [
Arrows.angledoubledown,
Arrows.angledoubleleft,
Arrows.angledoubleright,
Arrows.angledoubleup,
Arrows.angledown,
Arrows.angleleft,
Arrows.angleright,
Arrows.angleup,
Arrows.arrowaltcircledown,
Arrows.arrowaltcircleleft,
Arrows.arrowaltcircleright,
Arrows.arrowaltcircleup,
Arrows.arrowcircledown,
Arrows.arrowcircleleft,
Arrows.arrowcircleright,
Arrows.arrowcircleup,
Arrows.arrowdown,
Arrows.arrowleft,
Arrows.arrowright,
Arrows.arrowup,
Arrows.arrowsalt,
Arrows.arrowsalth,
Arrows.arrowsaltv,
Arrows.caretdown,
Arrows.caretleft,
Arrows.caretright,
Arrows.caretsquaredown,
Arrows.caretsquareleft,
Arrows.caretsquareright,
Arrows.caretsquareup,
Arrows.caretup,
Arrows.chevroncircledown,
Arrows.chevroncircleleft,
Arrows.chevroncircleright,
Arrows.chevroncircleup,
Arrows.chevrondown,
Arrows.chevronleft,
Arrows.chevronright,
Arrows.chevronup,
Arrows.exchangealt,
Arrows.leveldownalt,
Arrows.levelupalt,
Arrows.longarrowaltdown,
Arrows.longarrowaltleft,
Arrows.longarrowaltright,
Arrows.longarrowaltup,
Arrows.mousepointer,
Arrows.retweet,
]
public struct Others {
public static let filecsv = FontAwesome("\u{f6dd}")
public static let vrcardboard = FontAwesome("\u{f729}")
public static let blenderphone = FontAwesome("\u{f6b6}")
public static let dumpsterfire = FontAwesome("\u{f794}")
public static let skull = FontAwesome("\u{f54c}")
public static let fontawesomelogofull = FontAwesome("\u{f4e6}")
public static let weighthanging = FontAwesome("\u{f5cd}")
public static let signature = FontAwesome("\u{f5b7}")
public static let networkwired = FontAwesome("\u{f6ff}")
public static let backspace = FontAwesome("\u{f55a}")
public static let crown = FontAwesome("\u{f521}")
}
public static let others: [FontAwesome] = [
Others.filecsv,
Others.vrcardboard,
Others.blenderphone,
Others.dumpsterfire,
Others.skull,
Others.fontawesomelogofull,
Others.weighthanging,
Others.signature,
Others.networkwired,
Others.backspace,
Others.crown,
]
public struct Buildings {
public static let gopuram = FontAwesome("\u{f664}")
public static let housedamage = FontAwesome("\u{f6f1}")
public static let kaaba = FontAwesome("\u{f66b}")
public static let mosque = FontAwesome("\u{f678}")
public static let placeofworship = FontAwesome("\u{f67f}")
public static let store = FontAwesome("\u{f54e}")
public static let storealt = FontAwesome("\u{f54f}")
public static let synagogue = FontAwesome("\u{f69b}")
public static let toriigate = FontAwesome("\u{f6a1}")
public static let vihara = FontAwesome("\u{f6a7}")
}
public static let buildings: [FontAwesome] = [
Buildings.gopuram,
Buildings.housedamage,
Buildings.kaaba,
Buildings.mosque,
Buildings.placeofworship,
Buildings.store,
Buildings.storealt,
Buildings.synagogue,
Buildings.toriigate,
Buildings.vihara,
]
public struct Spinners {
public static let asterisk = FontAwesome("\u{f069}")
public static let bahai = FontAwesome("\u{f666}")
public static let circlenotch = FontAwesome("\u{f1ce}")
public static let compactdisc = FontAwesome("\u{f51f}")
public static let dharmachakra = FontAwesome("\u{f655}")
public static let fan = FontAwesome("\u{f863}")
public static let palette = FontAwesome("\u{f53f}")
public static let slash = FontAwesome("\u{f715}")
public static let spinner = FontAwesome("\u{f110}")
public static let yinyang = FontAwesome("\u{f6ad}")
}
public static let spinners: [FontAwesome] = [
Spinners.asterisk,
Spinners.bahai,
Spinners.circlenotch,
Spinners.compactdisc,
Spinners.dharmachakra,
Spinners.fan,
Spinners.palette,
Spinners.slash,
Spinners.spinner,
Spinners.yinyang,
]
public struct Autumn {
public static let campground = FontAwesome("\u{f6bb}")
public static let drumstickbite = FontAwesome("\u{f6d7}")
public static let footballball = FontAwesome("\u{f44e}")
public static let mountain = FontAwesome("\u{f6fc}")
public static let tractor = FontAwesome("\u{f722}")
}
public static let autumns: [FontAwesome] = [
Autumn.campground,
Autumn.drumstickbite,
Autumn.footballball,
Autumn.mountain,
Autumn.tractor,
]
public struct DateTime {
public static let clock = FontAwesome("\u{f017}")
public static let hourglassend = FontAwesome("\u{f253}")
public static let hourglasshalf = FontAwesome("\u{f252}")
public static let hourglassstart = FontAwesome("\u{f251}")
}
public static let dateTimes: [FontAwesome] = [
DateTime.clock,
DateTime.hourglassend,
DateTime.hourglasshalf,
DateTime.hourglassstart,
]
public struct Accessibility {
public static let audiodescription = FontAwesome("\u{f29e}")
public static let braille = FontAwesome("\u{f2a1}")
public static let closedcaptioning = FontAwesome("\u{f20a}")
public static let deaf = FontAwesome("\u{f2a4}")
public static let signlanguage = FontAwesome("\u{f2a7}")
public static let universalaccess = FontAwesome("\u{f29a}")
}
public static let accessibilitys: [FontAwesome] = [
Accessibility.audiodescription,
Accessibility.braille,
Accessibility.closedcaptioning,
Accessibility.deaf,
Accessibility.signlanguage,
Accessibility.universalaccess,
]
public struct Toggle {
public static let checkcircle = FontAwesome("\u{f058}")
public static let dotcircle = FontAwesome("\u{f192}")
}
public static let toggles: [FontAwesome] = [
Toggle.checkcircle,
Toggle.dotcircle,
]
public struct Genders {
public static let genderless = FontAwesome("\u{f22d}")
public static let mars = FontAwesome("\u{f222}")
public static let marsdouble = FontAwesome("\u{f227}")
public static let marsstroke = FontAwesome("\u{f229}")
public static let marsstrokeh = FontAwesome("\u{f22b}")
public static let marsstrokev = FontAwesome("\u{f22a}")
public static let mercury = FontAwesome("\u{f223}")
public static let neuter = FontAwesome("\u{f22c}")
public static let transgender = FontAwesome("\u{f224}")
public static let transgenderalt = FontAwesome("\u{f225}")
public static let venus = FontAwesome("\u{f221}")
public static let venusdouble = FontAwesome("\u{f226}")
public static let venusmars = FontAwesome("\u{f228}")
}
public static let genders: [FontAwesome] = [
Genders.genderless,
Genders.mars,
Genders.marsdouble,
Genders.marsstroke,
Genders.marsstrokeh,
Genders.marsstrokev,
Genders.mercury,
Genders.neuter,
Genders.transgender,
Genders.transgenderalt,
Genders.venus,
Genders.venusdouble,
Genders.venusmars,
]
public struct Pharmacy {
public static let history = FontAwesome("\u{f1da}")
}
public static let pharmacys: [FontAwesome] = [
Pharmacy.history,
]
public struct Logistics {
public static let box = FontAwesome("\u{f466}")
public static let boxes = FontAwesome("\u{f468}")
public static let clipboardlist = FontAwesome("\u{f46d}")
public static let dolly = FontAwesome("\u{f472}")
public static let dollyflatbed = FontAwesome("\u{f474}")
public static let pallet = FontAwesome("\u{f482}")
public static let shippingfast = FontAwesome("\u{f48b}")
public static let warehouse = FontAwesome("\u{f494}")
}
public static let logistics: [FontAwesome] = [
Logistics.box,
Logistics.boxes,
Logistics.clipboardlist,
Logistics.dolly,
Logistics.dollyflatbed,
Logistics.pallet,
Logistics.shippingfast,
Logistics.warehouse,
]
public struct Political {
public static let democrat = FontAwesome("\u{f747}")
public static let flagusa = FontAwesome("\u{f74d}")
public static let republican = FontAwesome("\u{f75e}")
public static let voteyea = FontAwesome("\u{f772}")
}
public static let politicals: [FontAwesome] = [
Political.democrat,
Political.flagusa,
Political.republican,
Political.voteyea,
]
public struct Chat {
public static let commentdots = FontAwesome("\u{f4ad}")
public static let sms = FontAwesome("\u{f7cd}")
}
public static let chats: [FontAwesome] = [
Chat.commentdots,
Chat.sms,
]
public struct Moving {
public static let boxopen = FontAwesome("\u{f49e}")
public static let sign = FontAwesome("\u{f4d9}")
public static let tape = FontAwesome("\u{f4db}")
public static let truckloading = FontAwesome("\u{f4de}")
public static let truckmoving = FontAwesome("\u{f4df}")
}
public static let movings: [FontAwesome] = [
Moving.boxopen,
Moving.sign,
Moving.tape,
Moving.truckloading,
Moving.truckmoving,
]
public struct Emoji {
public static let angry = FontAwesome("\u{f556}")
public static let dizzy = FontAwesome("\u{f567}")
public static let flushed = FontAwesome("\u{f579}")
public static let frown = FontAwesome("\u{f119}")
public static let frownopen = FontAwesome("\u{f57a}")
public static let grimace = FontAwesome("\u{f57f}")
public static let grin = FontAwesome("\u{f580}")
public static let grinalt = FontAwesome("\u{f581}")
public static let grinbeam = FontAwesome("\u{f582}")
public static let grinbeamsweat = FontAwesome("\u{f583}")
public static let grinhearts = FontAwesome("\u{f584}")
public static let grinsquint = FontAwesome("\u{f585}")
public static let grinsquinttears = FontAwesome("\u{f586}")
public static let grinstars = FontAwesome("\u{f587}")
public static let grintears = FontAwesome("\u{f588}")
public static let grintongue = FontAwesome("\u{f589}")
public static let grintonguesquint = FontAwesome("\u{f58a}")
public static let grintonguewink = FontAwesome("\u{f58b}")
public static let grinwink = FontAwesome("\u{f58c}")
public static let kiss = FontAwesome("\u{f596}")
public static let kissbeam = FontAwesome("\u{f597}")
public static let kisswinkheart = FontAwesome("\u{f598}")
public static let laugh = FontAwesome("\u{f599}")
public static let laughbeam = FontAwesome("\u{f59a}")
public static let laughsquint = FontAwesome("\u{f59b}")
public static let laughwink = FontAwesome("\u{f59c}")
public static let meh = FontAwesome("\u{f11a}")
public static let mehblank = FontAwesome("\u{f5a4}")
public static let mehrollingeyes = FontAwesome("\u{f5a5}")
public static let sadcry = FontAwesome("\u{f5b3}")
public static let sadtear = FontAwesome("\u{f5b4}")
public static let smile = FontAwesome("\u{f118}")
public static let smilebeam = FontAwesome("\u{f5b8}")
public static let smilewink = FontAwesome("\u{f4da}")
public static let surprise = FontAwesome("\u{f5c2}")
public static let tired = FontAwesome("\u{f5c8}")
}
public static let emojis: [FontAwesome] = [
Emoji.angry,
Emoji.dizzy,
Emoji.flushed,
Emoji.frown,
Emoji.frownopen,
Emoji.grimace,
Emoji.grin,
Emoji.grinalt,
Emoji.grinbeam,
Emoji.grinbeamsweat,
Emoji.grinhearts,
Emoji.grinsquint,
Emoji.grinsquinttears,
Emoji.grinstars,
Emoji.grintears,
Emoji.grintongue,
Emoji.grintonguesquint,
Emoji.grintonguewink,
Emoji.grinwink,
Emoji.kiss,
Emoji.kissbeam,
Emoji.kisswinkheart,
Emoji.laugh,
Emoji.laughbeam,
Emoji.laughsquint,
Emoji.laughwink,
Emoji.meh,
Emoji.mehblank,
Emoji.mehrollingeyes,
Emoji.sadcry,
Emoji.sadtear,
Emoji.smile,
Emoji.smilebeam,
Emoji.smilewink,
Emoji.surprise,
Emoji.tired,
]
public struct Automotive {
public static let airfreshener = FontAwesome("\u{f5d0}")
public static let caralt = FontAwesome("\u{f5de}")
public static let carbattery = FontAwesome("\u{f5df}")
public static let carcrash = FontAwesome("\u{f5e1}")
public static let carside = FontAwesome("\u{f5e4}")
public static let chargingstation = FontAwesome("\u{f5e7}")
public static let gaspump = FontAwesome("\u{f52f}")
public static let oilcan = FontAwesome("\u{f613}")
public static let trailer = FontAwesome("\u{f941}")
public static let truckmonster = FontAwesome("\u{f63b}")
}
public static let automotives: [FontAwesome] = [
Automotive.airfreshener,
Automotive.caralt,
Automotive.carbattery,
Automotive.carcrash,
Automotive.carside,
Automotive.chargingstation,
Automotive.gaspump,
Automotive.oilcan,
Automotive.trailer,
Automotive.truckmonster,
]
public struct Alert {
public static let exclamation = FontAwesome("\u{f12a}")
public static let exclamationcircle = FontAwesome("\u{f06a}")
public static let exclamationtriangle = FontAwesome("\u{f071}")
}
public static let alerts: [FontAwesome] = [
Alert.exclamation,
Alert.exclamationcircle,
Alert.exclamationtriangle,
]
public struct TabletopGaming {
public static let dragon = FontAwesome("\u{f6d5}")
}
public static let tabletopGamings: [FontAwesome] = [
TabletopGaming.dragon,
]
public struct Maritime {
public static let water = FontAwesome("\u{f773}")
public static let wind = FontAwesome("\u{f72e}")
}
public static let maritimes: [FontAwesome] = [
Maritime.water,
Maritime.wind,
]
public struct Sports {
public static let baseballball = FontAwesome("\u{f433}")
public static let basketballball = FontAwesome("\u{f434}")
public static let bowlingball = FontAwesome("\u{f436}")
public static let golfball = FontAwesome("\u{f450}")
public static let hockeypuck = FontAwesome("\u{f453}")
public static let quidditch = FontAwesome("\u{f458}")
public static let tabletennis = FontAwesome("\u{f45d}")
}
public static let sports: [FontAwesome] = [
Sports.baseballball,
Sports.basketballball,
Sports.bowlingball,
Sports.golfball,
Sports.hockeypuck,
Sports.quidditch,
Sports.tabletennis,
]
public struct FruitsVegetables {
public static let applealt = FontAwesome("\u{f5d1}")
public static let pepperhot = FontAwesome("\u{f816}")
}
public static let fruitsVegetables: [FontAwesome] = [
FruitsVegetables.applealt,
FruitsVegetables.pepperhot,
]
public struct Maps {
public static let anchor = FontAwesome("\u{f13d}")
public static let balancescale = FontAwesome("\u{f24e}")
public static let balancescaleleft = FontAwesome("\u{f515}")
public static let balancescaleright = FontAwesome("\u{f516}")
public static let bath = FontAwesome("\u{f2cd}")
public static let bed = FontAwesome("\u{f236}")
public static let beer = FontAwesome("\u{f0fc}")
public static let bellslash = FontAwesome("\u{f1f6}")
public static let bicycle = FontAwesome("\u{f206}")
public static let binoculars = FontAwesome("\u{f1e5}")
public static let birthdaycake = FontAwesome("\u{f1fd}")
public static let blind = FontAwesome("\u{f29d}")
public static let bomb = FontAwesome("\u{f1e2}")
public static let book = FontAwesome("\u{f02d}")
public static let briefcase = FontAwesome("\u{f0b1}")
public static let building = FontAwesome("\u{f1ad}")
public static let car = FontAwesome("\u{f1b9}")
public static let coffee = FontAwesome("\u{f0f4}")
public static let crosshairs = FontAwesome("\u{f05b}")
public static let directions = FontAwesome("\u{f5eb}")
public static let dollarsign = FontAwesome("\u{f155}")
public static let drawpolygon = FontAwesome("\u{f5ee}")
public static let eye = FontAwesome("\u{f06e}")
public static let eyeslash = FontAwesome("\u{f070}")
public static let fighterjet = FontAwesome("\u{f0fb}")
public static let fireextinguisher = FontAwesome("\u{f134}")
public static let flag = FontAwesome("\u{f024}")
public static let flagcheckered = FontAwesome("\u{f11e}")
public static let gamepad = FontAwesome("\u{f11b}")
public static let gavel = FontAwesome("\u{f0e3}")
public static let glassmartini = FontAwesome("\u{f000}")
public static let globe = FontAwesome("\u{f0ac}")
public static let graduationcap = FontAwesome("\u{f19d}")
public static let hsquare = FontAwesome("\u{f0fd}")
public static let helicopter = FontAwesome("\u{f533}")
public static let home = FontAwesome("\u{f015}")
public static let image = FontAwesome("\u{f03e}")
public static let images = FontAwesome("\u{f302}")
public static let industry = FontAwesome("\u{f275}")
public static let info = FontAwesome("\u{f129}")
public static let infocircle = FontAwesome("\u{f05a}")
public static let landmark = FontAwesome("\u{f66f}")
public static let layergroup = FontAwesome("\u{f5fd}")
public static let leaf = FontAwesome("\u{f06c}")
public static let lemon = FontAwesome("\u{f094}")
public static let lifering = FontAwesome("\u{f1cd}")
public static let lightbulb = FontAwesome("\u{f0eb}")
public static let locationarrow = FontAwesome("\u{f124}")
public static let lowvision = FontAwesome("\u{f2a8}")
public static let male = FontAwesome("\u{f183}")
public static let map = FontAwesome("\u{f279}")
public static let mapmarker = FontAwesome("\u{f041}")
public static let mapmarkeralt = FontAwesome("\u{f3c5}")
public static let mappin = FontAwesome("\u{f276}")
public static let mapsigns = FontAwesome("\u{f277}")
public static let medkit = FontAwesome("\u{f0fa}")
public static let moneybill = FontAwesome("\u{f0d6}")
public static let moneybillalt = FontAwesome("\u{f3d1}")
public static let motorcycle = FontAwesome("\u{f21c}")
public static let music = FontAwesome("\u{f001}")
public static let newspaper = FontAwesome("\u{f1ea}")
public static let parking = FontAwesome("\u{f540}")
public static let paw = FontAwesome("\u{f1b0}")
public static let phone = FontAwesome("\u{f095}")
public static let phonealt = FontAwesome("\u{f879}")
public static let phonesquare = FontAwesome("\u{f098}")
public static let phonesquarealt = FontAwesome("\u{f87b}")
public static let phonevolume = FontAwesome("\u{f2a0}")
public static let plane = FontAwesome("\u{f072}")
public static let plug = FontAwesome("\u{f1e6}")
public static let plussquare = FontAwesome("\u{f0fe}")
public static let print = FontAwesome("\u{f02f}")
public static let recycle = FontAwesome("\u{f1b8}")
public static let restroom = FontAwesome("\u{f7bd}")
public static let road = FontAwesome("\u{f018}")
public static let rocket = FontAwesome("\u{f135}")
public static let route = FontAwesome("\u{f4d7}")
public static let search = FontAwesome("\u{f002}")
public static let searchminus = FontAwesome("\u{f010}")
public static let searchplus = FontAwesome("\u{f00e}")
public static let ship = FontAwesome("\u{f21a}")
public static let shoeprints = FontAwesome("\u{f54b}")
public static let shower = FontAwesome("\u{f2cc}")
public static let snowplow = FontAwesome("\u{f7d2}")
public static let streetview = FontAwesome("\u{f21d}")
public static let subway = FontAwesome("\u{f239}")
public static let suitcase = FontAwesome("\u{f0f2}")
public static let taxi = FontAwesome("\u{f1ba}")
public static let thumbtack = FontAwesome("\u{f08d}")
public static let ticketalt = FontAwesome("\u{f3ff}")
public static let tint = FontAwesome("\u{f043}")
public static let trafficlight = FontAwesome("\u{f637}")
public static let train = FontAwesome("\u{f238}")
public static let tram = FontAwesome("\u{f7da}")
public static let tree = FontAwesome("\u{f1bb}")
public static let truck = FontAwesome("\u{f0d1}")
public static let tty = FontAwesome("\u{f1e4}")
public static let umbrella = FontAwesome("\u{f0e9}")
public static let university = FontAwesome("\u{f19c}")
public static let utensilspoon = FontAwesome("\u{f2e5}")
public static let utensils = FontAwesome("\u{f2e7}")
public static let wheelchair = FontAwesome("\u{f193}")
public static let wifi = FontAwesome("\u{f1eb}")
public static let wineglass = FontAwesome("\u{f4e3}")
public static let wrench = FontAwesome("\u{f0ad}")
}
public static let maps: [FontAwesome] = [
Maps.anchor,
Maps.balancescale,
Maps.balancescaleleft,
Maps.balancescaleright,
Maps.bath,
Maps.bed,
Maps.beer,
Maps.bellslash,
Maps.bicycle,
Maps.binoculars,
Maps.birthdaycake,
Maps.blind,
Maps.bomb,
Maps.book,
Maps.briefcase,
Maps.building,
Maps.car,
Maps.coffee,
Maps.crosshairs,
Maps.directions,
Maps.dollarsign,
Maps.drawpolygon,
Maps.eye,
Maps.eyeslash,
Maps.fighterjet,
Maps.fireextinguisher,
Maps.flag,
Maps.flagcheckered,
Maps.gamepad,
Maps.gavel,
Maps.glassmartini,
Maps.globe,
Maps.graduationcap,
Maps.hsquare,
Maps.helicopter,
Maps.home,
Maps.image,
Maps.images,
Maps.industry,
Maps.info,
Maps.infocircle,
Maps.landmark,
Maps.layergroup,
Maps.leaf,
Maps.lemon,
Maps.lifering,
Maps.lightbulb,
Maps.locationarrow,
Maps.lowvision,
Maps.male,
Maps.map,
Maps.mapmarker,
Maps.mapmarkeralt,
Maps.mappin,
Maps.mapsigns,
Maps.medkit,
Maps.moneybill,
Maps.moneybillalt,
Maps.motorcycle,
Maps.music,
Maps.newspaper,
Maps.parking,
Maps.paw,
Maps.phone,
Maps.phonealt,
Maps.phonesquare,
Maps.phonesquarealt,
Maps.phonevolume,
Maps.plane,
Maps.plug,
Maps.plussquare,
Maps.print,
Maps.recycle,
Maps.restroom,
Maps.road,
Maps.rocket,
Maps.route,
Maps.search,
Maps.searchminus,
Maps.searchplus,
Maps.ship,
Maps.shoeprints,
Maps.shower,
Maps.snowplow,
Maps.streetview,
Maps.subway,
Maps.suitcase,
Maps.taxi,
Maps.thumbtack,
Maps.ticketalt,
Maps.tint,
Maps.trafficlight,
Maps.train,
Maps.tram,
Maps.tree,
Maps.truck,
Maps.tty,
Maps.umbrella,
Maps.university,
Maps.utensilspoon,
Maps.utensils,
Maps.wheelchair,
Maps.wifi,
Maps.wineglass,
Maps.wrench,
]
public struct Shapes {
public static let circle = FontAwesome("\u{f111}")
public static let play = FontAwesome("\u{f04b}")
public static let shapes = FontAwesome("\u{f61f}")
public static let square = FontAwesome("\u{f0c8}")
}
public static let shapes: [FontAwesome] = [
Shapes.circle,
Shapes.play,
Shapes.shapes,
Shapes.square,
]
public struct Communication {
public static let addressbook = FontAwesome("\u{f2b9}")
public static let addresscard = FontAwesome("\u{f2bb}")
public static let americansignlanguageinterpreting = FontAwesome("\u{f2a3}")
public static let assistivelisteningsystems = FontAwesome("\u{f2a2}")
public static let at = FontAwesome("\u{f1fa}")
public static let chalkboard = FontAwesome("\u{f51b}")
public static let comment = FontAwesome("\u{f075}")
public static let commentalt = FontAwesome("\u{f27a}")
public static let comments = FontAwesome("\u{f086}")
public static let envelopesquare = FontAwesome("\u{f199}")
public static let inbox = FontAwesome("\u{f01c}")
public static let language = FontAwesome("\u{f1ab}")
public static let microphonealtslash = FontAwesome("\u{f539}")
public static let microphoneslash = FontAwesome("\u{f131}")
public static let phoneslash = FontAwesome("\u{f3dd}")
public static let rss = FontAwesome("\u{f09e}")
public static let rsssquare = FontAwesome("\u{f143}")
public static let voicemail = FontAwesome("\u{f897}")
}
public static let communications: [FontAwesome] = [
Communication.addressbook,
Communication.addresscard,
Communication.americansignlanguageinterpreting,
Communication.assistivelisteningsystems,
Communication.at,
Communication.chalkboard,
Communication.comment,
Communication.commentalt,
Communication.comments,
Communication.envelopesquare,
Communication.inbox,
Communication.language,
Communication.microphonealtslash,
Communication.microphoneslash,
Communication.phoneslash,
Communication.rss,
Communication.rsssquare,
Communication.voicemail,
]
public struct Summer {
public static let fish = FontAwesome("\u{f578}")
public static let hotdog = FontAwesome("\u{f80f}")
public static let icecream = FontAwesome("\u{f810}")
public static let volleyballball = FontAwesome("\u{f45f}")
}
public static let summers: [FontAwesome] = [
Summer.fish,
Summer.hotdog,
Summer.icecream,
Summer.volleyballball,
]
public struct AudioVideo {
public static let backward = FontAwesome("\u{f04a}")
public static let compressalt = FontAwesome("\u{f422}")
public static let eject = FontAwesome("\u{f052}")
public static let expandalt = FontAwesome("\u{f424}")
public static let expandarrowsalt = FontAwesome("\u{f31e}")
public static let fastbackward = FontAwesome("\u{f049}")
public static let fastforward = FontAwesome("\u{f050}")
public static let forward = FontAwesome("\u{f04e}")
public static let pause = FontAwesome("\u{f04c}")
public static let pausecircle = FontAwesome("\u{f28b}")
public static let playcircle = FontAwesome("\u{f144}")
public static let podcast = FontAwesome("\u{f2ce}")
public static let random = FontAwesome("\u{f074}")
public static let stepbackward = FontAwesome("\u{f048}")
public static let stepforward = FontAwesome("\u{f051}")
public static let stop = FontAwesome("\u{f04d}")
public static let stopcircle = FontAwesome("\u{f28d}")
}
public static let audioVideos: [FontAwesome] = [
AudioVideo.backward,
AudioVideo.compressalt,
AudioVideo.eject,
AudioVideo.expandalt,
AudioVideo.expandarrowsalt,
AudioVideo.fastbackward,
AudioVideo.fastforward,
AudioVideo.forward,
AudioVideo.pause,
AudioVideo.pausecircle,
AudioVideo.playcircle,
AudioVideo.podcast,
AudioVideo.random,
AudioVideo.stepbackward,
AudioVideo.stepforward,
AudioVideo.stop,
AudioVideo.stopcircle,
]
public struct Code {
public static let code = FontAwesome("\u{f121}")
public static let codebranch = FontAwesome("\u{f126}")
public static let terminal = FontAwesome("\u{f120}")
public static let windowclose = FontAwesome("\u{f410}")
public static let windowmaximize = FontAwesome("\u{f2d0}")
public static let windowminimize = FontAwesome("\u{f2d1}")
public static let windowrestore = FontAwesome("\u{f2d2}")
}
public static let codes: [FontAwesome] = [
Code.code,
Code.codebranch,
Code.terminal,
Code.windowclose,
Code.windowmaximize,
Code.windowminimize,
Code.windowrestore,
]
public struct Objects {
public static let archive = FontAwesome("\u{f187}")
public static let award = FontAwesome("\u{f559}")
public static let babycarriage = FontAwesome("\u{f77d}")
public static let blender = FontAwesome("\u{f517}")
public static let bookdead = FontAwesome("\u{f6b7}")
public static let broadcasttower = FontAwesome("\u{f519}")
public static let bug = FontAwesome("\u{f188}")
public static let bullseye = FontAwesome("\u{f140}")
public static let bus = FontAwesome("\u{f207}")
public static let calculator = FontAwesome("\u{f1ec}")
public static let calendar = FontAwesome("\u{f133}")
public static let calendaralt = FontAwesome("\u{f073}")
public static let candycane = FontAwesome("\u{f786}")
public static let carrot = FontAwesome("\u{f787}")
public static let church = FontAwesome("\u{f51d}")
public static let clipboard = FontAwesome("\u{f328}")
public static let cloud = FontAwesome("\u{f0c2}")
public static let cog = FontAwesome("\u{f013}")
public static let cogs = FontAwesome("\u{f085}")
public static let compass = FontAwesome("\u{f14e}")
public static let cookie = FontAwesome("\u{f563}")
public static let cookiebite = FontAwesome("\u{f564}")
public static let copy = FontAwesome("\u{f0c5}")
public static let cube = FontAwesome("\u{f1b2}")
public static let cubes = FontAwesome("\u{f1b3}")
public static let cut = FontAwesome("\u{f0c4}")
public static let dice = FontAwesome("\u{f522}")
public static let diced20 = FontAwesome("\u{f6cf}")
public static let diced6 = FontAwesome("\u{f6d1}")
public static let dicefive = FontAwesome("\u{f523}")
public static let dicefour = FontAwesome("\u{f524}")
public static let diceone = FontAwesome("\u{f525}")
public static let dicesix = FontAwesome("\u{f526}")
public static let dicethree = FontAwesome("\u{f527}")
public static let dicetwo = FontAwesome("\u{f528}")
public static let digitaltachograph = FontAwesome("\u{f566}")
public static let doorclosed = FontAwesome("\u{f52a}")
public static let dooropen = FontAwesome("\u{f52b}")
public static let drum = FontAwesome("\u{f569}")
public static let drumsteelpan = FontAwesome("\u{f56a}")
public static let envelope = FontAwesome("\u{f0e0}")
public static let envelopeopen = FontAwesome("\u{f2b6}")
public static let eraser = FontAwesome("\u{f12d}")
public static let fax = FontAwesome("\u{f1ac}")
public static let feather = FontAwesome("\u{f52d}")
public static let featheralt = FontAwesome("\u{f56b}")
public static let file = FontAwesome("\u{f15b}")
public static let filealt = FontAwesome("\u{f15c}")
public static let film = FontAwesome("\u{f008}")
public static let futbol = FontAwesome("\u{f1e3}")
public static let gifts = FontAwesome("\u{f79c}")
public static let glasscheers = FontAwesome("\u{f79f}")
public static let glasswhiskey = FontAwesome("\u{f7a0}")
public static let glasses = FontAwesome("\u{f530}")
public static let guitar = FontAwesome("\u{f7a6}")
public static let hatwizard = FontAwesome("\u{f6e8}")
public static let hdd = FontAwesome("\u{f0a0}")
public static let headphones = FontAwesome("\u{f025}")
public static let headphonesalt = FontAwesome("\u{f58f}")
public static let headset = FontAwesome("\u{f590}")
public static let heartbroken = FontAwesome("\u{f7a9}")
public static let highlighter = FontAwesome("\u{f591}")
public static let hollyberry = FontAwesome("\u{f7aa}")
public static let hourglass = FontAwesome("\u{f254}")
public static let igloo = FontAwesome("\u{f7ae}")
public static let keyboard = FontAwesome("\u{f11c}")
public static let laptop = FontAwesome("\u{f109}")
public static let lock = FontAwesome("\u{f023}")
public static let lockopen = FontAwesome("\u{f3c1}")
public static let magic = FontAwesome("\u{f0d0}")
public static let marker = FontAwesome("\u{f5a1}")
public static let medal = FontAwesome("\u{f5a2}")
public static let memory = FontAwesome("\u{f538}")
public static let microchip = FontAwesome("\u{f2db}")
public static let microphone = FontAwesome("\u{f130}")
public static let microphonealt = FontAwesome("\u{f3c9}")
public static let mitten = FontAwesome("\u{f7b5}")
public static let mobile = FontAwesome("\u{f10b}")
public static let mobilealt = FontAwesome("\u{f3cd}")
public static let moon = FontAwesome("\u{f186}")
public static let mughot = FontAwesome("\u{f7b6}")
public static let paintbrush = FontAwesome("\u{f1fc}")
public static let paperplane = FontAwesome("\u{f1d8}")
public static let paperclip = FontAwesome("\u{f0c6}")
public static let paste = FontAwesome("\u{f0ea}")
public static let pen = FontAwesome("\u{f304}")
public static let penalt = FontAwesome("\u{f305}")
public static let penfancy = FontAwesome("\u{f5ac}")
public static let pennib = FontAwesome("\u{f5ad}")
public static let pencilalt = FontAwesome("\u{f303}")
public static let puzzlepiece = FontAwesome("\u{f12e}")
public static let ring = FontAwesome("\u{f70b}")
public static let rulercombined = FontAwesome("\u{f546}")
public static let rulerhorizontal = FontAwesome("\u{f547}")
public static let rulervertical = FontAwesome("\u{f548}")
public static let satellite = FontAwesome("\u{f7bf}")
public static let satellitedish = FontAwesome("\u{f7c0}")
public static let save = FontAwesome("\u{f0c7}")
public static let school = FontAwesome("\u{f549}")
public static let screwdriver = FontAwesome("\u{f54a}")
public static let scroll = FontAwesome("\u{f70e}")
public static let sdcard = FontAwesome("\u{f7c2}")
public static let shieldalt = FontAwesome("\u{f3ed}")
public static let simcard = FontAwesome("\u{f7c4}")
public static let sleigh = FontAwesome("\u{f7cc}")
public static let snowflake = FontAwesome("\u{f2dc}")
public static let spaceshuttle = FontAwesome("\u{f197}")
public static let stickynote = FontAwesome("\u{f249}")
public static let stopwatch = FontAwesome("\u{f2f2}")
public static let stroopwafel = FontAwesome("\u{f551}")
public static let sun = FontAwesome("\u{f185}")
public static let tablet = FontAwesome("\u{f10a}")
public static let tabletalt = FontAwesome("\u{f3fa}")
public static let tachometeralt = FontAwesome("\u{f3fd}")
public static let toilet = FontAwesome("\u{f7d8}")
public static let toolbox = FontAwesome("\u{f552}")
public static let tools = FontAwesome("\u{f7d9}")
public static let trash = FontAwesome("\u{f1f8}")
public static let trashalt = FontAwesome("\u{f2ed}")
public static let tv = FontAwesome("\u{f26c}")
public static let unlock = FontAwesome("\u{f09c}")
public static let unlockalt = FontAwesome("\u{f13e}")
public static let wallet = FontAwesome("\u{f555}")
}
public static let objects: [FontAwesome] = [
Objects.archive,
Objects.award,
Objects.babycarriage,
Objects.blender,
Objects.bookdead,
Objects.broadcasttower,
Objects.bug,
Objects.bullseye,
Objects.bus,
Objects.calculator,
Objects.calendar,
Objects.calendaralt,
Objects.candycane,
Objects.carrot,
Objects.church,
Objects.clipboard,
Objects.cloud,
Objects.cog,
Objects.cogs,
Objects.compass,
Objects.cookie,
Objects.cookiebite,
Objects.copy,
Objects.cube,
Objects.cubes,
Objects.cut,
Objects.dice,
Objects.diced20,
Objects.diced6,
Objects.dicefive,
Objects.dicefour,
Objects.diceone,
Objects.dicesix,
Objects.dicethree,
Objects.dicetwo,
Objects.digitaltachograph,
Objects.doorclosed,
Objects.dooropen,
Objects.drum,
Objects.drumsteelpan,
Objects.envelope,
Objects.envelopeopen,
Objects.eraser,
Objects.fax,
Objects.feather,
Objects.featheralt,
Objects.file,
Objects.filealt,
Objects.film,
Objects.futbol,
Objects.gifts,
Objects.glasscheers,
Objects.glasswhiskey,
Objects.glasses,
Objects.guitar,
Objects.hatwizard,
Objects.hdd,
Objects.headphones,
Objects.headphonesalt,
Objects.headset,
Objects.heartbroken,
Objects.highlighter,
Objects.hollyberry,
Objects.hourglass,
Objects.igloo,
Objects.keyboard,
Objects.laptop,
Objects.lock,
Objects.lockopen,
Objects.magic,
Objects.marker,
Objects.medal,
Objects.memory,
Objects.microchip,
Objects.microphone,
Objects.microphonealt,
Objects.mitten,
Objects.mobile,
Objects.mobilealt,
Objects.moon,
Objects.mughot,
Objects.paintbrush,
Objects.paperplane,
Objects.paperclip,
Objects.paste,
Objects.pen,
Objects.penalt,
Objects.penfancy,
Objects.pennib,
Objects.pencilalt,
Objects.puzzlepiece,
Objects.ring,
Objects.rulercombined,
Objects.rulerhorizontal,
Objects.rulervertical,
Objects.satellite,
Objects.satellitedish,
Objects.save,
Objects.school,
Objects.screwdriver,
Objects.scroll,
Objects.sdcard,
Objects.shieldalt,
Objects.simcard,
Objects.sleigh,
Objects.snowflake,
Objects.spaceshuttle,
Objects.stickynote,
Objects.stopwatch,
Objects.stroopwafel,
Objects.sun,
Objects.tablet,
Objects.tabletalt,
Objects.tachometeralt,
Objects.toilet,
Objects.toolbox,
Objects.tools,
Objects.trash,
Objects.trashalt,
Objects.tv,
Objects.unlock,
Objects.unlockalt,
Objects.wallet,
]
public struct Currency {
public static let eurosign = FontAwesome("\u{f153}")
public static let hryvnia = FontAwesome("\u{f6f2}")
public static let lirasign = FontAwesome("\u{f195}")
public static let moneybillwave = FontAwesome("\u{f53a}")
public static let moneybillwavealt = FontAwesome("\u{f53b}")
public static let poundsign = FontAwesome("\u{f154}")
public static let rublesign = FontAwesome("\u{f158}")
public static let rupeesign = FontAwesome("\u{f156}")
public static let shekelsign = FontAwesome("\u{f20b}")
public static let tenge = FontAwesome("\u{f7d7}")
public static let wonsign = FontAwesome("\u{f159}")
public static let yensign = FontAwesome("\u{f157}")
}
public static let currencys: [FontAwesome] = [
Currency.eurosign,
Currency.hryvnia,
Currency.lirasign,
Currency.moneybillwave,
Currency.moneybillwavealt,
Currency.poundsign,
Currency.rublesign,
Currency.rupeesign,
Currency.shekelsign,
Currency.tenge,
Currency.wonsign,
Currency.yensign,
]
public struct Design {
public static let beziercurve = FontAwesome("\u{f55b}")
public static let crop = FontAwesome("\u{f125}")
public static let cropalt = FontAwesome("\u{f565}")
public static let fill = FontAwesome("\u{f575}")
public static let filldrip = FontAwesome("\u{f576}")
public static let objectgroup = FontAwesome("\u{f247}")
public static let objectungroup = FontAwesome("\u{f248}")
public static let splotch = FontAwesome("\u{f5bc}")
public static let spraycan = FontAwesome("\u{f5bd}")
public static let stamp = FontAwesome("\u{f5bf}")
public static let swatchbook = FontAwesome("\u{f5c3}")
public static let vectorsquare = FontAwesome("\u{f5cb}")
}
public static let designs: [FontAwesome] = [
Design.beziercurve,
Design.crop,
Design.cropalt,
Design.fill,
Design.filldrip,
Design.objectgroup,
Design.objectungroup,
Design.splotch,
Design.spraycan,
Design.stamp,
Design.swatchbook,
Design.vectorsquare,
]
}
}
| 44.710769 | 88 | 0.569374 |
392c24bc465525d8672f68bd6c48f115a79d68a1 | 2,176 | //
// AppDelegate.swift
// demo-swift
//
// Created by sidney.wang on 2018/6/29.
// Copyright © 2018年 sidney.wang. 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.297872 | 285 | 0.755055 |
678fec5d43ff7992ebdd0b9b4e42b89b14eb4f88 | 102 | import Foundation
struct RecentSpecies: Codable {
var timestamp: Date
var species: Species
}
| 14.571429 | 31 | 0.735294 |
d919d11f0079aaa443349dd91b5dd5a783597c26 | 1,666 | //
// ViewController.swift
// Example
//
// Created by 刘志达 on 2020/3/28.
// Copyright © 2020 joylife. All rights reserved.
//
import UIKit
import Canvas
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
lazy var imagePicker: UIImagePickerController = {
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.delegate = self
return picker
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onPickAction(_ sender: Any) {
present(imagePicker, animated: true)
}
@IBAction func onEditAction(_ sender: Any) {
guard let image = imageView.image else { return }
print(image)
let canvas = CanvasController(sourceImage: image, config: .init(fileURL: Bundle.main.url(forResource: "CanvasConfig", withExtension: "json")!))
canvas.modalPresentationStyle = .custom
present(canvas, animated: true)
}
}
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
imageView.image = (info[.originalImage] as? UIImage)
}
}
| 29.22807 | 151 | 0.683073 |
232efd69270ccdb23b49e9db9d25740a3ae8dba2 | 1,136 | //
// PatientFocusOverlayView.swift
// Treez.io
//
// Created by Dan on 28.09.2017.
// Copyright (c) 2017 STRV. All rights reserved.
//
import UIKit
class PatientFocusOverlayView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect)
{
let rectanglePath = UIBezierPath(rect: bounds.insetBy(dx: Constants.lineWidth, dy: Constants.lineWidth))
Constants.overlayColor.setStroke()
rectanglePath.lineWidth = 3.0
rectanglePath.stroke()
let horizontalMargin = bounds.size.width / 5.0
let verticalMargin = bounds.size.width / 10.0
let ovalPath = UIBezierPath(ovalIn: CGRect(x: horizontalMargin, y: verticalMargin, width: bounds.size.width - 2 * horizontalMargin, height: bounds.size.height - 2 * verticalMargin))
Constants.overlayColor.setStroke()
ovalPath.lineWidth = 3.0
ovalPath.stroke()
}
}
| 28.4 | 189 | 0.643486 |
bf638b339a9863ad8fe7324c33e9fc81f7bd5bcc | 1,550 | import Foundation
import SwiftLoader
public class Categories : NSObject {
private static var isLoaded = false
private static var numberOfAttempts = 0
private static var callBackViewController:DetailsViewController?
public static var categories:[AnyObject] = [AnyObject]()
public static func loadCategories() {
if self.numberOfAttempts++ < 3 {
APIService.sharedInstance.getCategories().then { object -> Void in
Categories.categories = object
Categories.categories.insert(CATEGORY_PLACEHOLDER, atIndex: 0)
self.isLoaded = true
if let callBackController = self.callBackViewController{
callBackController.reloadCategories()
}}
.catch { error in
let alert = UIAlertView(title: "Error", message: SERVICE_UNAVAILABLE, delegate: nil, cancelButtonTitle: "OK")
alert.promise().then { object -> Void in
self.isLoaded = false
Categories.loadCategories()
}
//TODO: Change to show unavailable screen on OK press
}
}
}
public static func resetNumberOfAttempts(){
self.numberOfAttempts = 0
}
public static func isNotLoaded() -> Bool{
return !isLoaded
}
static func setupCallback(viewController: DetailsViewController) {
callBackViewController = viewController
}
} | 36.046512 | 129 | 0.590968 |
2660b116313d0db833328f8bf3a6133694b32893 | 720 | //
// SampleAAView.swift
// SampleSwiftUI
//
// Created by yusaku maki on 2020/11/19.
//
import SwiftUI
struct SampleAAView: View {
@State var showHeart: Bool = false
var body: some View {
TabView {
self.contents
self.contents
}
.tabViewStyle(PageTabViewStyle())
}
var contents: some View {
ScrollView(.vertical) {
LazyVStack {
ForEach(1..<1000, id: \.self) { _ in
Text("HELLO WORLD HELLOWORLD")
Divider()
}
}
}
}
}
struct SampleAAView_Previews: PreviewProvider {
static var previews: some View {
SampleAAView()
}
}
| 18.947368 | 52 | 0.516667 |
168f17db74631da6574f571aa10c87f2c8573c48 | 1,210 | //
// Optimizer.swift
// Bender
//
// Created by Mathias Claassen on 5/18/17.
//
//
/// Processes a grpah imported from TensorFlow applying some optimizations/simplifications
public protocol TFOptimizer {
/// Optimize a grsph imported from TensorFlow. Nodes that are to be removed should be left without adjacencies
func optimize(graph: TFGraph)
}
public extension TFOptimizer {
/// Adds "Neuron" information to a node if the outgoing edge node is of a known neuron type.
/// This information can later be used by the 'activationNeuron' function
func addNeuronIfThere(node: TFNode) {
let outgoing = node.outgoingNodes()
if outgoing.count == 1, let next = (outgoing.first as? TFNode),
next.nodeDef.isTFReLuOp || next.nodeDef.isTFTanhOp || next.nodeDef.isTFSigmoidOp {
var neuron = Tensorflow_AttrValue()
neuron.value = Tensorflow_AttrValue.OneOf_Value.s(next.nodeDef.op.data(using: .utf8)!)
node.nodeDef.attr[Constants.CustomAttr.neuron] = neuron
for output in next.outgoingNodes() {
output.replace(incomingEdge: next, with: node)
}
next.strip()
}
}
}
| 31.842105 | 114 | 0.665289 |
ac44d916c5ba48b182ff176dee61fc3798b37cfa | 524 | //
// Photos.swift
// Swifterviewing
//
// Created by Dharma Teja Kanneganti on 10/07/21.
// Copyright © 2021 World Wide Technology Application Services. All rights reserved.
//
import Foundation
//MARk: - Photos Model
struct Photos : Codable
{
var albumId : Int
var id : Int
var title : String?
var url : String?
var thumbnailUrl : String?
enum CodingKeys: String, CodingKey
{
case albumId
case id
case title
case url
case thumbnailUrl
}
}
| 18.068966 | 85 | 0.622137 |
91f98ca2b6dca44cdc141d3e2ebde2dcdbff7af3 | 409 | //
// FormURLEncodedResponse.swift
// AstralTests
//
// Created by Julio Alorro on 2/3/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
struct FormURLEncodedResponse: Decodable {
enum CodingKeys: String, CodingKey {
case form
case headers
case url
}
public let form: BinData
public let headers: BinHeaders
public let url: URL
}
| 17.041667 | 52 | 0.665037 |
79f1c893654bb6c8d8b33784b3b732bcfba072fa | 476 | //
// Do not remove or alter the notices in this preamble.
// This software code is created for Online Payments on 16/07/2020
// Copyright © 2020 Global Collect Services. All rights reserved.
//
import Foundation
class StubBundle: Bundle {
override func path(forResource name: String?, ofType ext: String?) -> String? {
switch name! {
case "imageMapping":
return "imageMappingFile"
default:
return nil
}
}
}
| 23.8 | 83 | 0.638655 |
f519084ac02fe6faabc73ecf18fc7da883908244 | 1,071 | // Copyright 2021-present Xsolla (USA), Inc. 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 q
//
// 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 and permissions and
import Foundation
import XsollaSDKUtilities
final class GetUserInventoryItemsErrorHandler: APIBaseErrorHandler
{
override func setHandlers()
{
add(handler: APIServerCode400ErrorHandler())
add(handler: APIServerCode401ErrorHandler())
add(handler: APIServerCode403ErrorHandler())
add(handler: APIServerCode404ErrorHandler())
add(handler: APIServerCode422ErrorHandler())
add(handler: APIServerCode429ErrorHandler())
}
}
| 36.931034 | 75 | 0.743231 |
211ea0dd1d2e5266c96a1e8b92035f1f47e863ee | 2,181 | //
// AppDelegate.swift
// poseDemo
//
// Created by Dmitry Rybakov on 2019-03-21.
// Copyright © 2019 Dmitry Rybakov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.404255 | 285 | 0.755617 |
fb2d7ab1daf285275dce41ade711a104615ae4d0 | 954 | //
// goBotTests.swift
// goBotTests
//
// Created by Tosha on 8/18/16.
// Copyright © 2016 nicusa. All rights reserved.
//
import XCTest
@testable import goBot
class goBotTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 25.783784 | 111 | 0.627883 |
d934991fb7717c086fe6cd7d4ebd01133db0edc8 | 1,290 | //
// PasswordTableEntry.swift
// passKit
//
// Created by Yishi Lin on 2020/2/23.
// Copyright © 2020 Bob Sun. All rights reserved.
//
import Foundation
public class PasswordTableEntry: NSObject {
public let passwordEntity: PasswordEntity
@objc public let title: String
public let isDir: Bool
public let synced: Bool
public let categoryText: String
public init(_ entity: PasswordEntity) {
self.passwordEntity = entity
self.title = entity.name!
self.isDir = entity.isDir
self.synced = entity.synced
self.categoryText = entity.getCategoryText()
}
public func match(_ searchText: String) -> Bool {
return PasswordTableEntry.match(nameWithCategory: passwordEntity.nameWithCategory, searchText: searchText)
}
public static func match(nameWithCategory: String, searchText: String) -> Bool {
let titleSplit = nameWithCategory.split{ !($0.isLetter || $0.isNumber || $0 == ".") }
for str in titleSplit {
if (str.localizedCaseInsensitiveContains(searchText)) {
return true
}
if (searchText.localizedCaseInsensitiveContains(str)) {
return true
}
}
return false
}
}
| 28.666667 | 114 | 0.630233 |
fcad335adda7807bd22a21bd9fc21491b48f5f30 | 15,690 | //
// FavIcon
// Copyright © 2018 Leon Breedt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
#if os(OSX)
import Cocoa
public typealias ImageType = NSImage
#else
import UIKit
public typealias ImageType = UIImage
#endif
/// The result of downloading an icon.
public enum IconDownloadResult {
/// The icon was downloaded successfully.
/// - parameter image: The downloaded icon image.
/// - parameter url: The url for the downloaded icon image.
case success(image: ImageType, url: URL)
/// The icon failed to download
/// - parameter error: The error causing the download to fail.
case failure(error: Error)
}
/// Enumerates errors that could occur while scanning or downloading.
enum IconError: Error {
/// Invalid URL specified.
case invalidBaseURL
/// An invalid response was received while attempting to download an icon.
case invalidDownloadResponse
/// No icons were detected at the supplied URL.
case noIconsDetected
/// The icon image was corrupt, or is not of a supported file format.
case corruptImage
}
public final class FavIcon {
/// Scans a base URL, attempting to determine all of the supported icons that can
/// be used for favicon purposes.
///
/// It will do the following to determine possible icons that can be used:
///
/// - Check whether or not `/favicon.ico` exists.
/// - If the base URL returns an HTML page, parse the `<head>` section and check for `<link>`
/// and `<meta>` tags that reference icons using Apple, Microsoft and Google
/// conventions.
/// - If _Web Application Manifest JSON_ (`manifest.json`) files are referenced, or
/// _Microsoft browser configuration XML_ (`browserconfig.xml`) files
/// are referenced, download and parse them to check if they reference icons.
///
/// All of this work is performed in a background queue.
///
/// - parameter url: The base URL to scan.
/// - parameter completion: A closure to call when the scan has completed. The closure will be call
/// on the main queue.
public static func scan(_ url: URL,
completion: @escaping ([Icon]) -> Void) {
let htmlURL = url
let favIconURL = URL(string: "/favicon.ico", relativeTo: url as URL)!.absoluteURL
var icons = [Icon]()
let group = DispatchGroup()
group.enter()
downloadURL(favIconURL, method: "HEAD") { result in
defer { group.leave() }
switch result {
case .exists:
icons.append(Icon(url: favIconURL, type: .classic))
default:
return
}
}
group.enter()
downloadURL(htmlURL) { result in
defer { group.leave() }
if case .text(let text, let mimeType, let downloadedURL) = result {
guard mimeType == "text/html" else { return }
guard let data = text.data(using: .utf8) else { return }
let document = HTMLDocument(data: data)
icons.append(contentsOf: detectHTMLHeadIcons(document, baseURL: downloadedURL))
for manifestURL in extractWebAppManifestURLs(document, baseURL: downloadedURL) {
group.enter()
downloadURL(manifestURL) { result in
defer { group.leave() }
if case .text(let text, _, let downloadedURL) = result {
icons.append(contentsOf: detectWebAppManifestIcons(text, baseURL: downloadedURL))
}
}
}
let browserConfigResult = extractBrowserConfigURL(document, baseURL: url)
if let browserConfigURL = browserConfigResult.url, !browserConfigResult.disabled {
group.enter()
downloadURL(browserConfigURL) { result in
defer { group.leave() }
if case .text(let text, _, let downloadedURL) = result {
let document = XMLDocument(string: text)
icons.append(contentsOf: detectBrowserConfigXMLIcons(document, baseURL: downloadedURL))
}
}
}
}
}
group.notify(queue: .main) {
completion(icons)
}
}
/// Scans a base URL, attempting to determine all of the supported icons that can
/// be used for favicon purposes.
///
/// It will do the following to determine possible icons that can be used:
///
/// - Check whether or not `/favicon.ico` exists.
/// - If the base URL returns an HTML page, parse the `<head>` section and check for `<link>`
/// and `<meta>` tags that reference icons using Apple, Microsoft and Google
/// conventions.
/// - If _Web Application Manifest JSON_ (`manifest.json`) files are referenced, or
/// _Microsoft browser configuration XML_ (`browserconfig.xml`) files
/// are referenced, download and parse them to check if they reference icons.
///
/// All of this work is performed in a background queue.
///
/// - parameter url: The base URL to scan.
/// - parameter completion: A closure to call when the scan has completed. The closure will be call
/// on the main queue.
public static func scan(_ url: String, completion: @escaping ([Icon]) -> Void) throws {
guard let url = URL(string: url) else { throw IconError.invalidBaseURL }
scan(url, completion: completion)
}
/// Downloads an array of detected icons in the background.
///
/// - parameter icons: The icons to download.
/// - parameter completion: A closure to call when all download tasks have
/// results available (successful or otherwise). The closure
/// will be called on the main queue.
public static func download(_ icons: [Icon],
completion: @escaping ([IconDownloadResult]) -> Void) {
let urls = icons.map { $0.url }
downloadURLs(urls) { results in
DispatchQueue.main.async {
let downloadResults: [IconDownloadResult] = results.map { result in
switch result {
case .binary(let data, _, let url):
if let image = ImageType(data: data) {
return .success(image: image, url: url)
} else {
return .failure(error: IconError.corruptImage)
}
case .error(let error):
return .failure(error: error)
default:
return .failure(error: IconError.invalidDownloadResponse)
}
}
completion(sortResults(downloadResults))
}
}
}
/// Downloads all available icons by calling `scan(url:)` to discover the available icons, and then
/// performing background downloads of each icon.
///
/// - parameter url: The URL to scan for icons.
/// - parameter completion: A closure to call when all download tasks have results available
/// (successful or otherwise). The closure will be called on the main queue.
public static func downloadAll(_ url: URL, completion: @escaping ([IconDownloadResult]) -> Void) {
scan(url) { icons in
download(icons, completion: completion)
}
}
/// Downloads all available icons by calling `scan(url:)` to discover the available icons, and then
/// performing background downloads of each icon.
///
/// - parameter url: The URL to scan for icons.
/// - parameter completion: A closure to call when all download tasks have results available
/// (successful or otherwise). The closure will be called on the main queue.
public static func downloadAll(_ url: String, completion: @escaping ([IconDownloadResult]) -> Void) throws {
guard let url = URL(string: url) else { throw IconError.invalidBaseURL }
downloadAll(url, completion: completion)
}
/// Downloads the most preferred icon, by calling `scan(url:)` to discover available icons, and then choosing
/// the most preferable available icon. If both `width` and `height` are supplied, the icon closest to the
/// preferred size is chosen. Otherwise, the largest icon is chosen, if dimensions are known. If no icon
/// has dimensions, the icons are chosen by order of their `DetectedIconType` enumeration raw value.
///
/// - parameter url: The URL to scan for icons.
/// - parameter width: The preferred icon width, in pixels, or `nil`.
/// - parameter height: The preferred icon height, in pixels, or `nil`.
/// - parameter completion: A closure to call when the download task has produced results. The closure will
/// be called on the main queue.
/// - throws: An appropriate `IconError` if downloading was not successful.
public static func downloadPreferred(_ url: URL,
width: Int? = nil,
height: Int? = nil,
completion: @escaping (IconDownloadResult) -> Void) throws {
scan(url) { icons in
let sortedIcons = sortIcons(icons, preferredWidth: width, preferredHeight: height)
if sortedIcons.count == 0 {
DispatchQueue.main.async {
completion(.failure(error: IconError.noIconsDetected))
}
return
}
download(sortedIcons) { results in
let downloadResult: IconDownloadResult
let sortedResults = sortResults(results, preferredWidth: width, preferredHeight: height)
if sortedResults.count > 0 {
downloadResult = sortedResults[0]
} else {
downloadResult = .failure(error: IconError.noIconsDetected)
}
DispatchQueue.main.async {
completion(downloadResult)
}
}
}
}
/// Downloads the most preferred icon, by calling `scan(url:)` to discover available icons, and then choosing
/// the most preferable available icon. If both `width` and `height` are supplied, the icon closest to the
/// preferred size is chosen. Otherwise, the largest icon is chosen, if dimensions are known. If no icon
/// has dimensions, the icons are chosen by order of their `DetectedIconType` enumeration raw value.
///
/// - parameter url: The URL to scan for icons.
/// - parameter width: The preferred icon width, in pixels, or `nil`.
/// - parameter height: The preferred icon height, in pixels, or `nil`.
/// - parameter completion: A closure to call when the download task has produced results. The closure will
/// be called on the main queue.
/// - throws: An appropriate `IconError` if downloading was not successful.
public static func downloadPreferred(_ url: String,
width: Int? = nil,
height: Int? = nil,
completion: @escaping (IconDownloadResult) -> Void) throws {
guard let url = URL(string: url) else { throw IconError.invalidBaseURL }
try downloadPreferred(url, width: width, height: height, completion: completion)
}
static func sortIcons(_ icons: [Icon], preferredWidth: Int? = nil, preferredHeight: Int? = nil) -> [Icon] {
guard icons.count > 0 else { return [] }
let iconsInPreferredOrder = icons.sorted { left, right in
// Fall back to comparing dimensions.
if let preferredWidth = preferredWidth, let preferredHeight = preferredHeight,
let widthLeft = left.width, let heightLeft = left.height,
let widthRight = right.width, let heightRight = right.height {
// Which is closest to preferred size?
let deltaA = abs(widthLeft - preferredWidth) * abs(heightLeft - preferredHeight)
let deltaB = abs(widthRight - preferredWidth) * abs(heightRight - preferredHeight)
return deltaA < deltaB
} else {
if let areaLeft = left.area, let areaRight = right.area {
// Which is larger?
return areaRight < areaLeft
}
}
if left.area != nil {
// Only A has dimensions, prefer it.
return true
}
if right.area != nil {
// Only B has dimensions, prefer it.
return false
}
// Neither has dimensions, order by enum value
return left.type.rawValue < right.type.rawValue
}
return iconsInPreferredOrder
}
static func sortResults(_ results: [IconDownloadResult], preferredWidth: Int? = nil, preferredHeight: Int? = nil) -> [IconDownloadResult] {
guard results.count > 0 else { return [] }
let resultsInPreferredOrder = results.sorted { left, right in
switch (left, right) {
case (.success(let leftImage, _), .success(let rightImage, _)):
if let preferredWidth = preferredWidth, let preferredHeight = preferredHeight {
let widthLeft = leftImage.size.width
let heightLeft = leftImage.size.height
let widthRight = rightImage.size.width
let heightRight = rightImage.size.height
// Which is closest to preferred size?
let deltaA = abs(widthLeft - CGFloat(preferredWidth)) * abs(heightLeft - CGFloat(preferredHeight))
let deltaB = abs(widthRight - CGFloat(preferredWidth)) * abs(heightRight - CGFloat(preferredHeight))
return deltaA < deltaB
} else {
// Fall back to largest image.
return leftImage.area > rightImage.area
}
case (.success, .failure):
// An image is better than none.
return true
case (.failure, .success):
// An image is better than none.
return false
default:
return true
}
}
return resultsInPreferredOrder
}
}
extension Icon {
var area: Int? {
if let width = width, let height = height {
return width * height
}
return nil
}
}
extension ImageType {
var area: CGFloat {
return size.width * size.height
}
}
| 44.828571 | 143 | 0.581963 |
f968442234abc6bf050b0ccd33beeb25ab4387ed | 15,843 | /**
* (C) Copyright IBM Corp. 2016, 2019.
*
* 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.
**/
// swiftlint:disable function_body_length force_try force_unwrapping file_length
import XCTest
import Foundation
import AssistantV2
import RestKit
class AssistantV2Tests: XCTestCase {
private var assistant: Assistant!
private let assistantID = WatsonCredentials.AssistantV2ID
// MARK: - Test Configuration
/** Set up for each test by instantiating the service. */
override func setUp() {
super.setUp()
continueAfterFailure = false
instantiateAssistant()
}
static var allTests: [(String, (AssistantV2Tests) -> () throws -> Void)] {
return [
("testCreateSession", testCreateSession),
("testCreateSessionWithInvalidAssistantID", testCreateSessionWithInvalidAssistantID),
("testDeleteSession", testDeleteSession),
("testDeleteSessionWithInvalidSessionID", testDeleteSessionWithInvalidSessionID),
("testMessage", testMessage),
("testMessageWithInvalidSessionID", testMessageWithInvalidSessionID),
]
}
/** Instantiate Assistant. */
func instantiateAssistant() {
if let apiKey = WatsonCredentials.AssistantAPIKey {
assistant = Assistant(version: versionDate, apiKey: apiKey)
} else {
let username = WatsonCredentials.AssistantV2Username
let password = WatsonCredentials.AssistantV2Password
assistant = Assistant(version: versionDate, username: username, password: password)
}
if let url = WatsonCredentials.AssistantV2URL {
assistant.serviceURL = url
}
assistant.defaultHeaders["X-Watson-Learning-Opt-Out"] = "true"
assistant.defaultHeaders["X-Watson-Test"] = "true"
}
/** Wait for expectations. */
func waitForExpectations(timeout: TimeInterval = 10.0) {
waitForExpectations(timeout: timeout) { error in
XCTAssertNil(error, "Timeout")
}
}
// MARK: - Sessions
func testCreateSession() {
let description = "Create a session"
let expectation = self.expectation(description: description)
assistant.createSession(assistantID: assistantID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let session = response?.result else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(session.sessionID)
expectation.fulfill()
}
waitForExpectations()
}
func testCreateSessionWithInvalidAssistantID() {
let description = "Create a session"
let expectation = self.expectation(description: description)
let invalidID = "Invalid Assistant ID"
assistant.createSession(assistantID: invalidID) {
_, error in
if error == nil {
XCTFail(missingErrorMessage)
}
expectation.fulfill()
}
waitForExpectations()
}
func testDeleteSession() {
let description1 = "Create a session"
let expectation1 = self.expectation(description: description1)
var newSessionID: String?
assistant.createSession(assistantID: assistantID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let session = response?.result else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(session.sessionID)
newSessionID = session.sessionID
expectation1.fulfill()
}
waitForExpectations()
guard let sessionID = newSessionID else {
XCTFail("Failed to get the ID of the newly created session")
return
}
let description2 = "Delete the newly created session"
let expectation2 = self.expectation(description: description2)
assistant.deleteSession(assistantID: assistantID, sessionID: sessionID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
expectation2.fulfill()
}
waitForExpectations()
}
func testDeleteSessionWithInvalidSessionID() {
let description = "Delete an invalid session"
let expectation = self.expectation(description: description)
let invalidID = "Invalid Session ID"
assistant.deleteSession(assistantID: assistantID, sessionID: invalidID) {
_, error in
if error == nil {
XCTFail(missingErrorMessage)
}
expectation.fulfill()
}
waitForExpectations()
}
// MARK: - Messages
func testMessage() {
// Create a session
let description1 = "Create a session"
let expectation1 = self.expectation(description: description1)
var newSessionID: String?
assistant.createSession(assistantID: assistantID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let session = response?.result else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(session.sessionID)
newSessionID = session.sessionID
expectation1.fulfill()
}
waitForExpectations()
guard let sessionID = newSessionID else {
XCTFail("Failed to get the ID of the newly created session")
return
}
// First message from the bot
let description2 = "Start a conversation."
let expectation2 = self.expectation(description: description2)
assistant.message(assistantID: assistantID, sessionID: sessionID, input: nil, context: nil) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let message = response?.result else {
XCTFail(missingResultMessage)
return
}
let output = message.output
let context = message.context
// verify response message
guard let dialogRuntimeResponse = output.generic, dialogRuntimeResponse.count == 1 else {
XCTFail("Expected to receive a response message")
return
}
XCTAssertEqual(dialogRuntimeResponse[0].responseType, "text")
XCTAssertNotNil(dialogRuntimeResponse[0].text)
// verify context
XCTAssertNil(context)
expectation2.fulfill()
}
waitForExpectations()
// User responds to the bot
let description3 = "Continue a conversation."
let expectation3 = self.expectation(description: description3)
let messageInput = MessageInput(messageType: MessageInput.MessageType.text.rawValue, text: "I'm good, how are you?")
assistant.message(assistantID: assistantID, sessionID: sessionID, input: messageInput, context: nil) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let message = response?.result else {
XCTFail(missingResultMessage)
return
}
let output = message.output
let context = message.context
// verify response message
guard let dialogRuntimeResponse = output.generic, dialogRuntimeResponse.count == 1 else {
XCTFail("Expected to receive a response message")
return
}
XCTAssertEqual(dialogRuntimeResponse[0].responseType, "text")
XCTAssertNotNil(dialogRuntimeResponse[0].text)
// verify intents
guard let intents = output.intents, intents.count == 1 else {
XCTFail("Expected to receive one runtime intent")
return
}
XCTAssertEqual(intents[0].intent, "General_Greetings")
// verify context
XCTAssertNil(context)
expectation3.fulfill()
}
waitForExpectations()
}
// MARK: - Skill Contexts
func testMessageContextSkills() {
// Create a session
var newSessionID: String?
let expectation1 = self.expectation(description: "Create a session")
assistant.createSession(assistantID: assistantID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let session = response?.result else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(session.sessionID)
newSessionID = session.sessionID
expectation1.fulfill()
}
waitForExpectations()
guard let sessionID = newSessionID else {
XCTFail("Failed to get the ID of the newly created session")
return
}
// create global context with user ID
let system = MessageContextGlobalSystem(userID: "my_user_id")
let global = MessageContextGlobal(system: system)
// build user-defined context variables, put in skill-specific context for main skill
var userDefinedContext: [String: JSON] = [:]
userDefinedContext["account_number"] = .string("123456")
let mainSkillContext = MessageContextSkill(userDefined: userDefinedContext)
let skills = MessageContextSkills(additionalProperties: ["main skill": mainSkillContext])
let context = MessageContext(global: global, skills: skills)
let input = MessageInput(messageType: "text", text: "Hello", options: MessageInputOptions(returnContext: true))
// Start conversation with a non-empty context
let expectation2 = self.expectation(description: "Start a conversation.")
assistant.message(assistantID: assistantID, sessionID: sessionID, input: input, context: context) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let message = response?.result else {
XCTFail(missingResultMessage)
return
}
let output = message.output
// verify response message
guard let dialogRuntimeResponse = output.generic, dialogRuntimeResponse.count == 1 else {
XCTFail("Expected to receive a response message")
return
}
XCTAssertEqual(dialogRuntimeResponse[0].responseType, "text")
XCTAssertNotNil(dialogRuntimeResponse[0].text)
// verify context
XCTAssertNotNil(message.context)
XCTAssertNotNil(message.context?.skills)
XCTAssertNotNil(message.context?.skills?.additionalProperties)
XCTAssertTrue(message.context?.skills?.additionalProperties.keys.contains("main skill") ?? false)
expectation2.fulfill()
}
waitForExpectations()
}
func testMessageWithInvalidSessionID() {
let description = "Send message with an invalid session"
let expectation = self.expectation(description: description)
let invalidID = "Invalid Session ID"
assistant.message(assistantID: assistantID, sessionID: invalidID) {
_, error in
if error == nil {
XCTFail(missingErrorMessage)
}
expectation.fulfill()
}
waitForExpectations()
}
// MARK: - Search Skill
func testAssistantSearchSkill() {
let sessionExpectationDescription = "Create a session"
let sessionExpectation = self.expectation(description: sessionExpectationDescription)
// setup session
var newSessionID: String?
assistant.createSession(assistantID: assistantID) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let session = response?.result else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(session.sessionID)
newSessionID = session.sessionID
sessionExpectation.fulfill()
}
waitForExpectations()
guard let sessionID = newSessionID else {
XCTFail("Failed to get the ID of the newly created session")
return
}
let genericMessages: [String] = [
"Hello",
"Are you open on christmas",
"I\'d like to make an appointment",
"Tomorrow at 3pm",
"Make that thursday at 2pm"
]
// send multiple messages to get assistant going
for genericMessage in genericMessages {
let genericMessageDescription = "generic message"
let genericMessageExpectation = self.expectation(description: genericMessageDescription)
let messageInput = MessageInput(messageType: "text", text: genericMessage)
assistant.message(assistantID: assistantID, sessionID: sessionID, input: messageInput) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
XCTAssertNotNil(response?.result)
genericMessageExpectation.fulfill()
}
waitForExpectations()
}
// send a message that triggers search skill
let searchSkillMessageDescription = "search skill message"
let searchSkillMessageExpectation = self.expectation(description: searchSkillMessageDescription)
let searchSkillMessageInput = MessageInput(messageType: "text", text: "who did watson beat in jeopardy?")
assistant.message(assistantID: assistantID, sessionID: sessionID, input: searchSkillMessageInput) {
response, error in
if let error = error {
XCTFail(unexpectedErrorMessage(error))
return
}
guard let message = response?.result?.output.generic?[0] else {
XCTFail(missingResultMessage)
return
}
XCTAssertNotNil(message)
XCTAssert(message.responseType == "search")
searchSkillMessageExpectation.fulfill()
}
waitForExpectations()
}
}
| 33.353684 | 124 | 0.595405 |
f838133671fba6259fb1e6f2e63f2a0c32d263f4 | 356 | func permute<T>(_ a: [T], _ n: Int) {
if n == 0 {
print(a)
} else {
var a = a //to convert let
permute(a, n - 1)
for i in 0..<n {
a.swapAt(i, n)
permute(a, n - 1)
a.swapAt(i, n)
}
}
}
let xyz = "🐶😀🐮"
print("permutations \(xyz):")
permute(Array(xyz), xyz.count - 1)
| 19.777778 | 37 | 0.412921 |
1e7548e0bae24a5fc0a864c460ade898acadae44 | 1,311 | //
// Created by Joachim Kret on 22.07.2018.
// Copyright © 2018 JK. All rights reserved.
//
import Foundation
public final class SerialCancelable: Cancelable {
private let lock = NSLock()
private var cancelled = false
private var current: Cancelable?
public var isCancelled: Bool {
return cancelled
}
public var cancelable: Cancelable {
get {
return current ?? AnyCancelable { }
}
set (newCancelable) {
lock.lock(); defer { lock.unlock() }
let cancelable: Cancelable? = {
if cancelled {
return newCancelable
} else {
let toCancel = current
current = newCancelable
return toCancel
}
}()
cancelable?.cancel()
}
}
public init() { }
public func cancel() {
lock.lock(); defer { lock.unlock() }
if !cancelled {
cancelled = true
current?.cancel()
current = nil
}
}
}
| 21.491803 | 49 | 0.418002 |
01bb1853d92291cde30374348f2b4ab01965a61d | 1,792 | import CoreLocation
import Turf
#if canImport(MapboxMaps)
@testable import MapboxMaps
#else
@testable import MapboxMapsAnnotations
#endif
import XCTest
//swiftlint:disable explicit_acl explicit_top_level_acl
class PointAnnotationTests: XCTestCase {
var defaultCoordinate: CLLocationCoordinate2D!
override func setUp() {
defaultCoordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
}
override func tearDown() {
defaultCoordinate = nil
}
func testPointAnnotationDefaultValues() {
// Given state from setUp()
// When
let annotation = PointAnnotation(coordinate: defaultCoordinate)
// Then
XCTAssertNotNil(annotation.identifier)
XCTAssertTrue(annotation.type == .point)
XCTAssertNil(annotation.title)
XCTAssertFalse(annotation.isSelected)
XCTAssertFalse(annotation.isDraggable)
XCTAssertNil(annotation.image)
XCTAssertNotNil(annotation.coordinate)
}
func testPointAnnotationsHaveUniqueIdentifiers() {
// Given
let annotation1 = PointAnnotation(coordinate: defaultCoordinate)
// When
let annotation2 = PointAnnotation(coordinate: defaultCoordinate)
// Then
XCTAssertNotEqual(annotation1.identifier, annotation2.identifier)
}
func testUpdatingPointAnnotationImageProperty() {
// Given
var annotation = PointAnnotation(coordinate: defaultCoordinate)
let initialAnnotationImage = annotation.image
// When
annotation.image = UIImage.squareImage(with: UIColor.yellow,
size: CGSize(width: 100, height: 100))
// Then
XCTAssertNotEqual(initialAnnotationImage, annotation.image)
}
}
| 27.569231 | 85 | 0.684152 |
906aa33ea9709a4095a3f6a927f2905718458218 | 2,645 | //
// ViewController.swift
// MorseCode
//
// Created by Joshua Smith on 7/8/16.
// Copyright © 2016 iJoshSmith. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var blinkingView: UIView!
@IBOutlet weak var encodedMessageTextView: UITextView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var transmitMessageButton: UIButton!
private var morseTransmitter: MorseTransmitter!
private struct BlinkingViewColors {
static let on = UIColor.greenColor()
static let off = UIColor.lightGrayColor()
}
override func viewDidLoad() {
super.viewDidLoad()
morseTransmitter = MorseTransmitter(blinkingView: blinkingView,
onColor: BlinkingViewColors.on,
offColor: BlinkingViewColors.off)
blinkingView.backgroundColor = BlinkingViewColors.off
blinkingView.layer.cornerRadius = blinkingView.frame.width / 2.0;
}
@IBAction func handleTransmitMessageButton(sender: AnyObject) {
if let message = messageTextField.text where message.isEmpty == false {
transmit(message)
}
}
private func transmit(message: String) {
let morseEncoder = MorseEncoder(codingSystem: .InternationalMorseCode)
if let encodedMessage = morseEncoder.encode(message: message) {
showMorseCodeTextFor(encodedMessage)
beginTransmitting(encodedMessage)
}
else {
encodedMessageTextView.text = "Unable to encode at least one character in message."
}
}
private func showMorseCodeTextFor(encodedMessage: EncodedMessage) {
encodedMessageTextView.text = createMorseCodeText(from: encodedMessage)
encodedMessageTextView.font = UIFont(name: "Menlo", size: 16)
}
private func createMorseCodeText(from encodedMessage: EncodedMessage) -> String {
let transformation = MorseTransformation(
dot: ".",
dash: "-",
markSeparator: "",
symbolSeparator: " ",
termSeparator: "\n")
let characters = transformation.apply(to: encodedMessage)
return characters.joinWithSeparator("")
}
private func beginTransmitting(encodedMessage: EncodedMessage) {
transmitMessageButton.enabled = false
morseTransmitter.startTransmitting(encodedMessage: encodedMessage) { [weak self] in
self?.transmitMessageButton.enabled = true
}
}
}
| 34.802632 | 95 | 0.641588 |
615869027dd22310b60403c28cf1713c978790f9 | 5,507 | import Foundation
import os
import APIClient
/// A client that performs OAuth 2 authorization flows.
public class OAuth2Client
{
private let configuration: OAuth2Configuration
var ignoreStateCheckOnResponseErrorBecauseMyClientDoesntFollowTheStandard = false
/// Opaque value to be matched against the callback URL to avoid CSRF attacks.
/// See [10.12. Cross-Site Request Forgery](https://datatracker.ietf.org/doc/html/rfc6749#section-10.12)
/// Refreshed on every authorization request.
private var state: String = ""
private let log = Logger(subsystem: "dev.jano", category: "oauth2")
public init(configuration: OAuth2Configuration) {
self.configuration = configuration
}
public func createAuthorizationRequest(method: HTTPMethod = .get) throws -> URLRequest {
self.state = String.randomString(length: 32)
return try createTokenRequest(state: self.state, method: method)
}
public func isCallbackURL(url: URL) -> Bool
{
// check for URL callback
let callbackString = configuration.registration.callback.absoluteString
let isCallback = url.absoluteString.hasPrefix(callbackString)
let isHTTP = url.absoluteString.hasPrefix("http")
if !isHTTP && !isCallback {
log.warning("⚠️ Not a callback or HTTP URL. Expected: \(callbackString). Actual: \(url.absoluteString)")
if let queryItems = url.queryItemDictionary(),
let response = ResponseError(queryItemDictionary: queryItems) {
log.error("🚨🚨 Server returned an error: \(response.description)")
return true
}
}
return isCallback
}
public func handleCallback(url: URL) async throws -> AccessTokenResponse
{
log.debug("Decoding callback URL: \(url.absoluteString)")
guard let queryItems = url.queryItemDictionary() else {
// malformed callback URL
throw OAuth2Error.invalidCallbackURL(URL: url)
}
if let responseError = ResponseError(queryItemDictionary: queryItems) {
throw responseError
}
let authorizationResponse = try decodeTokenResponse(state, url)
let isSameState = authorizationResponse.state == state || state.isEmpty
guard isSameState && !ignoreStateCheckOnResponseErrorBecauseMyClientDoesntFollowTheStandard else {
throw OAuth2Error.stateMisMatch
}
let accessTokenRequest = try createAccessTokenRequest(
authSuccess: authorizationResponse,
registration: configuration
)
let responseData = try await NetworkClient().execute(accessTokenRequest)
let accessTokenResponse = try decodeAccessTokenResponse(responseData)
return accessTokenResponse
}
// MARK: -
/// - Returns: request for an OAuth2 authorization token
func createTokenRequest(state: String, method: HTTPMethod) throws -> URLRequest {
try AuthorizationRequest(
clientId: configuration.registration.key,
redirectUri: configuration.registration.callback.absoluteString,
state: state,
scope: nil
).urlRequest(authorizationRequestURL: configuration.endpoints.authorizationRequestURL, method: method)
}
/// - Returns: request for an OAuth2 authorization token response
/// - Throws: OAuth2Error.invalidCallbackURL if the callback is malformed
func decodeTokenResponse(_ state: String, _ url: URL) throws -> AuthorizationResponse
{
guard let dic = url.queryItemDictionary() else {
throw OAuth2Error.invalidCallbackURL(URL: url)
}
if let success = AuthorizationResponse(queryItemDictionary: dic) {
return success
} else if let failure = ResponseError(queryItemDictionary: dic) {
throw failure
} else {
throw OAuth2Error.invalidCallbackURL(URL: url)
}
}
// MARK: - Access token request
/// - Returns: request for an OAuth2 access token request
func createAccessTokenRequest(authSuccess: AuthorizationResponse,
registration: OAuth2Configuration) throws -> URLRequest {
try AccessTokenRequest(
code: authSuccess.code,
clientId: configuration.registration.key,
clientSecret: configuration.registration.secret,
redirectURI: configuration.registration.callback.absoluteString
).urlRequest(authorizationCodeGrantRequestURL: configuration.endpoints.authorizationCodeGrantRequestURL)
}
/// - Returns: access token response as a JSON token
func decodeAccessTokenResponse(_ data: Data) throws -> AccessTokenResponse {
try JSONDecoder().decode(AccessTokenResponse.self, from: data)
}
}
private extension String
{
/// Returns a random alphanumeric string with 32 characters.
/// Characters are chosen by SystemRandomNumberGenerator, which is cryptographically secure.
static func randomString(length: UInt) -> String {
var string = ""
guard length > 0 else { return string }
let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for _ in 1...length {
// Note that: Character("") is never used because alphabet is not empty
let char = alphabet.randomElement() ?? Character("")
string.append(char)
}
return string
}
}
| 40.19708 | 116 | 0.676593 |
f4b7de9038c96fb314d9813c9c506938f2723c39 | 20,839 | import XCTest
@testable import MapboxMaps
import Turf
// swiftlint:disable file_length orphaned_doc_comment type_body_length
class MigrationGuideIntegrationTests: IntegrationTestCase {
var view: UIView?
private var testRect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
override func setUpWithError() throws {
try super.setUpWithError()
try guardForMetalDevice()
ResourceOptionsManager.default.resourceOptions.accessToken = self.accessToken
}
override func tearDownWithError() throws {
try super.tearDownWithError()
view?.removeFromSuperview()
view = nil
ResourceOptionsManager.destroyDefault()
}
func testBasicMapViewController() throws {
let expectation = self.expectation(description: "load map view")
//-->
class BasicMapViewController: UIViewController {
var mapView: MapView!
var accessToken: String!
var completion: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
ResourceOptionsManager.default.resourceOptions.accessToken = self.accessToken
mapView = MapView(frame: view.bounds)
view.addSubview(mapView)
completion?()
}
}
//<--
let vc = BasicMapViewController(nibName: nil, bundle: nil)
vc.accessToken = accessToken
vc.completion = {
expectation.fulfill()
}
rootViewController?.view.addSubview(vc.view)
view = vc.view
wait(for: [expectation], timeout: 5)
}
func testMapLoadingEventsLifecycle() throws {
let expectation = self.expectation(description: "Map events")
expectation.expectedFulfillmentCount = 6
expectation.assertForOverFulfill = false
//-->
class BasicMapViewController: UIViewController {
var mapView: MapView!
var accessToken: String!
var handler: ((Event) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
ResourceOptionsManager.default.resourceOptions.accessToken = self.accessToken
mapView = MapView(frame: view.bounds)
view.addSubview(mapView)
/**
The closure is called when style data has been loaded. This is called
multiple times. Use the event data to determine what kind of style data
has been loaded.
When the type is `style` this event most closely matches
`-[MGLMapViewDelegate mapView:didFinishLoadingStyle:]` in SDK versions
prior to v10.
*/
mapView.mapboxMap.onEvery(.styleDataLoaded) { [weak self] (event) in
guard let data = event.data as? [String: Any],
let type = data["type"],
let handler = self?.handler else {
return
}
print("The map has finished loading style data of type = \(type)")
handler(event)
}
/**
The closure is called during the initialization of the map view and
after any `styleDataLoaded` events; it is called when the requested
style has been fully loaded, including the style, specified sprite and
source metadata.
This event is the last opportunity to modify the layout or appearance
of the current style before the map view is displayed to the user.
Adding a layer at this time to the map may result in the layer being
presented BEFORE the rest of the map has finished rendering.
Changes to sources or layers of the current style do not cause this
event to be emitted.
*/
mapView.mapboxMap.onNext(.styleLoaded) { (event) in
print("The map has finished loading style ... Event = \(event)")
self.handler?(event)
}
/**
The closure is called whenever the map finishes loading and the map has
rendered all visible tiles, either after the initial load OR after a
style change has forced a reload.
This is an ideal time to add any runtime styling or annotations to the
map and ensures that these layers would only be shown after the map has
been fully rendered.
*/
mapView.mapboxMap.onNext(.mapLoaded) { (event) in
print("The map has finished loading... Event = \(event)")
self.handler?(event)
}
/**
The closure is called whenever the map view is entering an idle state,
and no more drawing will be necessary until new data is loaded or there
is some interaction with the map.
- All currently requested tiles have been rendered
- All fade/transition animations have completed
*/
mapView.mapboxMap.onNext(.mapIdle) { (event) in
print("The map is idle... Event = \(event)")
self.handler?(event)
}
/**
The closure is called whenever the map has failed to load. This could
be because of a variety of reasons, including a network connection
failure or a failure to fetch the style from the server.
You can use the associated error message to notify the user that map
data is unavailable.
*/
mapView.mapboxMap.onNext(.mapLoadingError) { (event) in
guard let data = event.data as? [String: Any],
let type = data["type"],
let message = data["message"] else {
return
}
print("The map failed to load.. \(type) = \(message)")
}
}
}
//<--
let vc = BasicMapViewController(nibName: nil, bundle: nil)
vc.accessToken = accessToken
vc.handler = { _ in
expectation.fulfill()
}
rootViewController?.view.addSubview(vc.view)
view = vc.view
wait(for: [expectation], timeout: 5)
}
func testMapViewConfiguration() throws {
let mapView = MapView(frame: .zero)
let someBounds = CoordinateBounds(southwest: CLLocationCoordinate2D(latitude: 0, longitude: 0),
northeast: CLLocationCoordinate2D(latitude: 1, longitude: 1))
//-->
// Configure map to show a scale bar
mapView.ornaments.options.scaleBar.visibility = .visible
mapView.camera.options.restrictedCoordinateBounds = someBounds
//<--
}
func testAppDelegateConfig() throws {
//-->
//import UIKit
//import MapboxMaps
//
//@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let customHTTPService = CustomHttpService()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
HttpServiceFactory.setUserDefinedForCustom(customHTTPService)
return true
}
}
//<--
//-->
class CustomHttpService: HttpServiceInterface {
// MARK: - HttpServiceInterface protocol conformance
func request(for request: HttpRequest, callback: @escaping HttpResponseCallback) -> UInt64 {
// Make an API request
var urlRequest = URLRequest(url: URL(string: request.url)!)
let methodMap: [HttpMethod: String] = [
.get: "GET",
.head: "HEAD",
.post: "POST"
]
urlRequest.httpMethod = methodMap[request.method]!
urlRequest.httpBody = request.body
urlRequest.allHTTPHeaderFields = request.headers
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
// `HttpResponse` takes an `Expected` type. This is very similar to Swift's
// `Result` type. APIs using `Expected` are prone to future changes.
let result: Result<HttpResponseData, HttpRequestError>
if let error = error {
// Map NSURLError to HttpRequestErrorType
let requestError = HttpRequestError(type: .otherError, message: error.localizedDescription)
result = .failure(requestError)
} else if let response = response as? HTTPURLResponse,
let data = data {
// Keys are expected to be lowercase
var headers: [String: String] = [:]
for (key, value) in response.allHeaderFields {
guard let key = key as? String,
let value = value as? String else {
continue
}
headers[key.lowercased()] = value
}
let responseData = HttpResponseData(headers: headers, code: Int64(response.statusCode), data: data)
result = .success(responseData)
} else {
// Error
let requestError = HttpRequestError(type: .otherError, message: "Invalid response")
result = .failure(requestError)
}
let response = HttpResponse(request: request, result: result)
callback(response)
}
task.resume()
// Handle used to cancel requests
return UInt64(task.taskIdentifier)
}
//<--
func setMaxRequestsPerHostForMax(_ max: UInt8) {
fatalError("TODO")
}
func cancelRequest(forId id: UInt64, callback: @escaping ResultCallback) {
fatalError("TODO")
}
func supportsKeepCompression() -> Bool {
return false
}
func download(for options: DownloadOptions, callback: @escaping DownloadStatusCallback) -> UInt64 {
fatalError("TODO")
}
}
let appDelegate = AppDelegate()
_ = appDelegate.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)
}
func testSettingCamera() {
let frame = testRect
/*
### Set the map’s camera
The camera manager can be configured with an initial camera view.
To set the map’s camera, first create a `CameraOptions`
object, then direct the map to use it via the `MapInitOptions`.
`CameraOptions` parameters are optional, so only the required properties
need to be set.
*/
//-->
// Set the center coordinate of the map to Honolulu, Hawaii
let centerCoordinate = CLLocationCoordinate2D(latitude: 21.3069,
longitude: -157.8583)
// Create a camera
let camera = CameraOptions(center: centerCoordinate,
zoom: 14)
let options = MapInitOptions(cameraOptions: camera)
let mapView = MapView(frame: frame, mapInitOptions: options)
//<--
do {
/*
### Fit the camera to a given shape
In the Maps SDK v10, the approach to fitting the camera to a given shape
like that of pre-v10 versions.
In v10, call `camera(for:)` functions on the `MapboxMap` to create: a
camera for a given geometry, a camera that fits a set of rectangular
coordinate bounds or a camera based off of a collection of coordinates.
Then, call `ease(to:)` on `MapView.camera` to visibly transition
to the new camera.
Below is an example of setting the camera to a set of coordinates:
*/
//-->
let coordinates = [
CLLocationCoordinate2DMake(24, -89),
CLLocationCoordinate2DMake(24, -88),
CLLocationCoordinate2DMake(26, -88),
CLLocationCoordinate2DMake(26, -89),
CLLocationCoordinate2DMake(24, -89)
]
let camera = mapView.mapboxMap.camera(for: coordinates,
padding: .zero,
bearing: nil,
pitch: nil)
mapView.camera.ease(to: camera, duration: 10.0)
//<--
}
}
func testMapCameraOptions() {
let mapView = MapView(frame: .zero)
//-->
let sw = CLLocationCoordinate2DMake(-12, -46)
let ne = CLLocationCoordinate2DMake(2, 43)
let restrictedBounds = CoordinateBounds(southwest: sw, northeast: ne)
mapView.camera.options.minimumZoomLevel = 8.0
mapView.camera.options.maximumZoomLevel = 15.0
mapView.camera.options.restrictedCoordinateBounds = restrictedBounds
//<--
}
func testGeoJSONSource() {
//-->
var myGeoJSONSource = GeoJSONSource()
myGeoJSONSource.maxzoom = 14
//<--
let someTurfFeature = Feature(geometry: .point(Point(CLLocationCoordinate2D(latitude: 0, longitude: 0))))
let someTurfFeatureCollection = FeatureCollection(features: [someTurfFeature])
let someGeoJSONDocumentURL = Fixture.geoJSONURL(from: "polygon")!
//-->
// Setting the `data` property with a url pointing to a GeoJSON document
myGeoJSONSource.data = .url(someGeoJSONDocumentURL)
// Setting a Turf feature to the `data` property
myGeoJSONSource.data = .featureCollection(someTurfFeatureCollection)
//<--
}
func testAddGeoJSONSource() {
var myGeoJSONSource = GeoJSONSource()
myGeoJSONSource.maxzoom = 14
myGeoJSONSource.data = .url(Fixture.geoJSONURL(from: "polygon")!)
let mapView = MapView(frame: testRect)
let expectation = self.expectation(description: "Source was added")
mapView.mapboxMap.onNext(.styleLoaded) { _ in
do {
//-->
try mapView.mapboxMap.style.addSource(myGeoJSONSource, id: "my-geojson-source")
//<--
/*
As mentioned earlier, all `Layer`s are also Swift structs. The
following code sets up a background layer and sets its background
color to red:
*/
//-->
var myBackgroundLayer = BackgroundLayer(id: "my-background-layer")
myBackgroundLayer.backgroundColor = .constant(ColorRepresentable(color: .red))
//<--
/*
Once a layer is created, add it to the map:
*/
//-->
try mapView.mapboxMap.style.addLayer(myBackgroundLayer)
//<--
expectation.fulfill()
} catch {
XCTFail("Failed to add source: \(error)")
}
}
wait(for: [expectation], timeout: 5.0)
}
func testExpression() throws {
let mapView = MapView(frame: testRect)
let expectation = self.expectation(description: "layer updated")
mapView.mapboxMap.onNext(.styleLoaded) { _ in
do {
//-->
let expressionString =
"""
[
"interpolate",
["linear"],
["zoom"],
0,
"hsl(0, 79%, 53%)",
14,
"hsl(233, 80%, 47%)"
]
"""
if let expressionData = expressionString.data(using: .utf8) {
let expJSONObject = try JSONSerialization.jsonObject(with: expressionData, options: [])
try mapView.mapboxMap.style.setLayerProperty(for: "land",
property: "background-color",
value: expJSONObject)
}
//<--
expectation.fulfill()
} catch {
XCTFail("Failed with \(error)")
}
}
wait(for: [expectation], timeout: 10.0)
}
func todo_testAnnotationInteraction() {
//-->
class MyViewController: UIViewController, AnnotationInteractionDelegate {
@IBOutlet var mapView: MapView!
lazy var pointAnnotationManager: PointAnnotationManager = {
return mapView.annotations.makePointAnnotationManager()
}()
override func viewDidLoad() {
super.viewDidLoad()
mapView.mapboxMap.onNext(.mapLoaded) { _ in
self.pointAnnotationManager.delegate = self
let coordinate = CLLocationCoordinate2DMake(24, -89)
var pointAnnotation = PointAnnotation(coordinate: coordinate)
pointAnnotation.image = .default
self.pointAnnotationManager.syncAnnotations([pointAnnotation])
}
}
// MARK: - AnnotationInteractionDelegate
func annotationManager(_ manager: AnnotationManager,
didDetectTappedAnnotations annotations: [Annotation]) {
print("Annotations tapped: \(annotations)")
}
}
//<--
// TODO: Test above
}
func testEnableLocation() {
let mapView = MapView(frame: testRect)
//-->
mapView.location.options.puckType = .puck2D()
//<--
let customLocationProvider = LocationProviderMock(options: LocationOptions())
//-->
mapView.location.overrideLocationProvider(with: customLocationProvider)
//<--
}
func testAdd3DTerrain() {
let mapView = MapView(frame: testRect)
let expectation = self.expectation(description: "Source was added")
mapView.mapboxMap.onNext(.styleLoaded) { _ in
do {
//-->
// Add terrain
var demSource = RasterDemSource()
demSource.url = "mapbox://mapbox.mapbox-terrain-dem-v1"
demSource.tileSize = 512
demSource.maxzoom = 14.0
try mapView.mapboxMap.style.addSource(demSource, id: "mapbox-dem")
var terrain = Terrain(sourceId: "mapbox-dem")
terrain.exaggeration = .constant(1.5)
// Add sky layer
try mapView.mapboxMap.style.setTerrain(terrain)
var skyLayer = SkyLayer(id: "sky-layer")
skyLayer.skyType = .constant(.atmosphere)
skyLayer.skyAtmosphereSun = .constant([0.0, 0.0])
skyLayer.skyAtmosphereSunIntensity = .constant(15.0)
try mapView.mapboxMap.style.addLayer(skyLayer)
//<--
expectation.fulfill()
} catch {
XCTFail("Failed to add source: \(error)")
}
}
wait(for: [expectation], timeout: 5.0)
}
func testCacheManager() {
let expectation = self.expectation(description: "Cache manager invalidated")
let didInvalidate = {
expectation.fulfill()
}
//-->
// Default cache size and paths
let resourceOptions = ResourceOptions(accessToken: accessToken)
let cacheManager = CacheManager(options: resourceOptions)
cacheManager.invalidateAmbientCache { _ in
// Business logic
didInvalidate()
}
//<--
wait(for: [expectation], timeout: 5.0)
}
}
| 37.412926 | 153 | 0.535678 |
0811d0a9caf3d5611cbddbbbc012fa18679d3412 | 24,151 | //
// JRAPIManager.swift
// Jarvis
//
// Created by Sandesh Kumar on 08/02/16.
// Copyright © 2016 One97. All rights reserved.
//
import UIKit
import AdSupport
import jarvis_utility_ios
import jarvis_network_ios
import WebKit
public let kSsoToken: String = "sso_token"
public let kwalletToken: String = "wallet_token"
public let kTokenType: String = "token_type"
public let kVersion: String = "version"
public let kClient: String = "client"
public let kDeviceIdentifier: String = "deviceIdentifier"
public let kLatitude: String = "lat"
public let kLongitude: String = "long"
public let kDeviceManufacturer: String = "deviceManufacturer"
public let kDeviceName: String = "deviceName"
public let kOsVersion: String = "osVersion"
public let kNetworkType: String = "networkType"
public let kLanguage: String = "language"
public let kChannelForDigitalCatalog: String = "channel"
public let kLocale: String = "locale"
public let kLangId: String = "lang_id"
public let kUserAgent: String = "User-Agent"
public let kChannelIPhone: String = "B2C_IPHONE"
public class JRAPIManager: NSObject {
fileprivate static let sharedInstance = JRAPIManager()
public let siteIdDefault: Int
public let childSiteIdDefault: Int
public var sessionId: String?
@objc public var version: String?
@objc public var client: String?
@objc public var deviceIdentifier: String?
private var wkWebView: WKWebView?
private let kPersistentDefaultUAKey = "default_persistent_user_agent"
public var userAgent: String? {
get {
if internalUserAgent == nil {
fetchUserAgent(completion: nil)
return getDefaultUA()
}
return internalUserAgent
}
}
@objc public var referrerValue: String {
return UserDefaults.standard.string(forKey: "AdwordsReferrerKey") ?? "";
}
fileprivate var internalUserAgent: String?
fileprivate var osVersion: String?
@objc class public func sharedManager() -> JRAPIManager {
return sharedInstance
}
override public init() {
version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
//client
if JRCommonManager.shared.moduleConfig.varient == .mall{
client = "mall-iosapp"
}else{
client = "iosapp"
}
//site id
if JRCommonManager.shared.moduleConfig.varient == .mall{
siteIdDefault = 2
childSiteIdDefault = 6
}else{
siteIdDefault = 1
childSiteIdDefault = 1
}
//Storing UUID in Keychain!!,just because paytm team wants it to be same for one-user one device
//Since in previous cases , the UUIDString was getting altered ,on deletion and reinstallation of the app.As a fix we are storing it in Keychain..
let uniqueId = JRUtility.savedDeviceId()
/* if let id = FXKeychain.default().object(forKey: JRUUID) as? String {
uniqueId = id
} else {
uniqueId = UIDevice.current.identifierForVendor?.uuidString
FXKeychain.default().setObject(uniqueId, forKey: JRUUID)
}*/
let model = UIDevice.current.model
// if let uniqueId = uniqueId {
deviceIdentifier = "Apple" + "-\(model)-\(uniqueId)"
// }
osVersion = UIDevice.current.systemVersion
super.init()
sessionId = self.uniqueSessionId()
}
fileprivate func uniqueSessionId() -> String? {
return NSUUID().uuidString
}
fileprivate func appendParams(params: String, inUrl url: String, encode: Bool) -> String {
// In case if the url contains "?" then remove "?" from params. url already has some query params.
var params: String = params
if url.range(of: "?") != nil {
params = params.replacingOccurrences(of: "?", with: "&")
}
var finalURL: String!
if encode {
finalURL = url
// Check if the url needs encoding. Encoding without check will lead to double encoding. Expecting a url string.
if URL(string: url) == nil, let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
finalURL = encodedUrl
}
// Encode the params before appending.
finalURL.append(params.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
} else {
// Encode the params before appending. Ideally we should not be encoding the params as the encode is false but a few verticals (hotels) has stopped functioning. It will bring back the chances of double encoding but we need to wait until verticals make necessary changes.
finalURL = url.appending(params.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
}
//CAI-5957: Adding Localization query params in every API
//Check if catalog append lang_id
if (finalURL.contains("https://catalog.paytm.com/") || finalURL.contains("https://storefront.paytm.com/")) && !finalURL.contains(kLangId){
if let locale = LanguageManager.shared.getCurrentLocale(), let langCode = locale.languageCode{
let paramToAppend: String = "&" + kLangId + "=" + "\(JRUtility.getLangId(forLangCode : langCode + "-IN"))"
finalURL = finalURL.appending(paramToAppend.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
}else{
let paramToAppend: String = "&" + kLangId + "=" + "\(JRUtility.getLangId(forLangCode : "en-IN"))"
finalURL = finalURL.appending(paramToAppend.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
}
}
return finalURL
}
// Appending Site ID and Child Site ID
fileprivate func defaultParamsWithSiteID(urlString:String?) -> String? {
var defaultPrms:String?
if let urlString = urlString, var defaultParam = defaultParams(encode: false) {
if apiRequiresSiteIds(urlString) {
let siteIds: [AnyHashable : Any] = siteIdParams()
let urlLowerCased: String = urlString.lowercased()
for (key, value) in siteIds {
if let key = key as? String, urlLowerCased.contains(key.lowercased()) == false {
defaultParam += "&\(key)=\(value)"
}
}
}
defaultPrms = defaultParam
}
return defaultPrms
}
public func defaultParamsDictionary() -> [AnyHashable:Any] {
var params = [AnyHashable:Any]()
params[kVersion] = version ?? ""
params[kClient] = client ?? ""
params[kDeviceIdentifier] = deviceIdentifier ?? ""
params[kDeviceManufacturer] = "Apple"
params[kDeviceName] = JRUtility.platformString
params[kOsVersion] = osVersion ?? ""
//CAI-5957: Adding Localization query params in every API
if let locale = LanguageManager.shared.getCurrentLocale(), let langCode = locale.languageCode{
params[kLocale] = langCode + "-IN"
params[kLanguage] = langCode + "-IN"
}else{
params[kLocale] = "en-IN"
params[kLanguage] = "en-IN"
}
params[kNetworkType] = Reachability()?.userSelectedNetworkType() ?? ""
if let locationInfo = JRLocationManager.shared.currentLocationInfo {
if let lat = locationInfo["lat"] as? Double {
params[kLatitude] = lat
}
if let long = locationInfo["long"] as? Double {
params[kLongitude] = long
}
}
return params
}
public func fundTrnasferParamDictionary() -> [AnyHashable : Any] {
var params: [AnyHashable:Any] = [AnyHashable:Any]()
params[kClient] = client ?? ""
params[kDeviceIdentifier] = deviceIdentifier ?? ""
params[kDeviceManufacturer] = "Apple"
params[kDeviceName] = JRUtility.platformString
if let ip = JRUtility.getIPAddressForCellOrWireless() {
params["ipAddress"] = ip
}else {
params["ipAddress"] = "127.0.0.1"
}
params[kLanguage] = "en-IN"
params[kLatitude] = "0"
params[kLongitude] = "0"
if let locationInfo = JRLocationManager.shared.currentLocationInfo {
if let lat = locationInfo["lat"] as? Double {
params[kLatitude] = "\(lat)"
}
if let long = locationInfo["long"] as? Double {
params[kLongitude] = "\(long)"
}
}
params["location"] = JRCommonUtility.getLocationString() //address
params[kNetworkType] = Reachability()?.userSelectedNetworkType() ?? ""
params[kOsVersion] = osVersion ?? ""
params[kVersion] = version ?? ""
params[kUserAgent] = kChannelIPhone
return params
}
public func siteIdParams() -> [AnyHashable:Any] {
var params = [AnyHashable:Any]()
params["site_id"] = JRCommonManager.shared.applicationDelegate?.getSiteId() ?? siteIdDefault
params["child_site_id"] = JRCommonManager.shared.applicationDelegate?.getChildSiteId() ?? childSiteIdDefault
return params
}
public func defaultParams(encode: Bool) -> String? {
var defaultParams: String = "?"
let params: [AnyHashable : Any] = defaultParamsDictionary()
for (key, value) in params {
if defaultParams.length > 1 {
defaultParams.append("&")
}
defaultParams.append("\(key)=\(value)")
}
return encode ? defaultParams.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) : defaultParams
}
public func apiRequiresSiteIds(_ url: String) -> Bool {
var requires: Bool = false
let domains: [String] = siteIdDependentAPIDomains()
let urlLowerCased: String = url.lowercased()
for domain in domains {
if urlLowerCased.contains(domain.lowercased()) {
requires = true
break
}
}
return requires
}
/// Returns the default params dictionary along with siteID paramaters if applicable
///
/// - Parameter urlString: urlString to check if the url requires siteIDs
public func defaultParamsWithSiteIDs(for urlString:String?) ->[AnyHashable:Any]? {
guard let urlString = urlString else {
return nil
}
var params: [AnyHashable : Any] = defaultParamsDictionary()
if apiRequiresSiteIds(urlString) {
let siteIds: [AnyHashable : Any] = siteIdParams()
params += siteIds
}
return params
}
public func siteIdDependentAPIDomains() -> [String] {
var domains: [String] = [String]()
domains.append("cart")
domains.append("search")
domains.append("promosearch")
domains.append("middleware.paytmmall.com")
domains.append("exchange-productservice.paytmmall.com")
domains.append("storefront.paytm.com")
if JRCommonManager.shared.moduleConfig.varient == .mall{
domains.append("product_codes")
}else{
domains.append("catalog")
domains.append("hotels")
}
return domains
}
public func isURLContainsDefaultParams(_ url: String?) -> Bool {
return url?.range(of: kDeviceIdentifier)?.lowerBound != nil
}
public func containsSSOToken(url: String?) -> Bool {
guard let url = url else {
return false
}
return url.range(of: kSsoToken)?.lowerBound != nil
}
public func containsWalletToken(url: String?) -> Bool {
guard let url = url else {
return false
}
return url.range(of: kwalletToken)?.lowerBound != nil
}
public func containsTokenType(url: String?) -> Bool {
guard let url = url else {
return false
}
return url.range(of: kTokenType)?.lowerBound != nil
}
public func containsLocale(url: String?) -> Bool {
guard let url = url else {
return false
}
return url.range(of: kLocale)?.lowerBound != nil
}
public func containsChannel(url: String?) -> Bool {
guard let url = url else {
return false
}
return url.range(of: kChannelForDigitalCatalog)?.lowerBound != nil
}
@objc public func urlByAppendingDefaultParams(_ url: String?, encoded encode: Bool) -> String? {
if !isURLContainsDefaultParams(url) {
let defaultParam: String? = defaultParamsWithSiteID(urlString: url)
if let defaultParam = defaultParam, let url = url {
return appendParams(params: defaultParam, inUrl: url, encode: encode)
}
}
return url
}
@objc public func urlByAppendingDefaultParams(_ url: String?) -> String? {
return urlByAppendingDefaultParams(url, encoded: true)
}
public func urlByAppendingDefaultParamsForUPI(_ url: String?) -> String? {
func getLanguageCodeForSelectedLanguage() -> String {
if let locale = LanguageManager.shared.getCurrentLocale(), let langCode = locale.languageCode{
return langCode.replacingOccurrences(of: "-IN", with: "")
}
return "en"
}
if let urlStr = url, var urlStringWithParams = urlByAppendingDefaultParams(urlStr) {
if urlStringWithParams.range(of: "languages")?.lowerBound == nil {
let language: String = getLanguageCodeForSelectedLanguage()
urlStringWithParams = urlStringWithParams + String(format: "&languages=%@", language)
}
return urlStringWithParams
}
return nil
}
@objc public func urlByAppendingOtherParamForDigitalCatalog(_ url: String?) -> String? {
if !isURLContainsDefaultParams(url) {
var defaultParam: String? = defaultParamsWithSiteID(urlString: url)
if defaultParam != nil {
if false == containsLocale(url: defaultParam){
if let regionCode = Locale.current.regionCode, let languageCode = Locale.current.languageCode {
defaultParam = defaultParam! + "&\(kLocale)=\(languageCode)-\(regionCode)"
}
}
if false == containsChannel(url: defaultParam) {
defaultParam = defaultParam! + "&\(kChannelForDigitalCatalog)=ios"
}
return appendParams(params: defaultParam!, inUrl: url ?? "", encode: true)
}
}
return url
}
@objc public func urlByAppendingSSOtoken(_ url: String?) -> String? {
var params: String? = nil
if false == containsSSOToken(url: url), let ssoToken = JRCommonManager.shared.applicationDelegate?.getSSOToken() {
params = String(format: "?%@=%@", kSsoToken, ssoToken)
}
if let params = params, let url = url {
return appendParams(params: params, inUrl: url, encode: true)
} else {
return url
}
}
@objc public func urlByAppendingDefaultParamsWithSSOToken(_ url: String?) -> String? {
var params: String? = nil
if false == isURLContainsDefaultParams(url) {
params = defaultParamsWithSiteID(urlString: url)
}
if false == containsSSOToken(url: url), let ssoToken = JRCommonManager.shared.applicationDelegate?.getSSOToken(){
if params == nil {
params = String(format: "?%@=%@", kSsoToken, ssoToken)
} else {
params?.append(String(format: "&%@=%@", kSsoToken, ssoToken))
}
}
if let params = params, let url = url {
return appendParams(params: params, inUrl: url, encode: true)
} else {
return url
}
}
@objc public func urlByUpdatingSSOToken(_ url: String?, handler: ((_ url: String?) -> Void)?) {
if let url = url {
do {
let regex: NSRegularExpression = try NSRegularExpression(pattern: String(format: "%@=(.*)&", kSsoToken), options: .caseInsensitive)
regex.enumerateMatches(in: url, options: .reportCompletion, range:NSMakeRange(0, url.length)) { (match: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let match = match, match.numberOfRanges > 0 {
let insideString: String = (url as NSString).substring(with: match.range(at: 0))
if let token = JRCommonManager.shared.applicationDelegate?.getSSOToken() {
let newsso: String = kSsoToken + "=" + token + "&"
let result: String = url.replacingOccurrences(of: insideString, with: newsso)
handler?(result)
return
}
handler?(nil)
return
}
}
}
catch {
}
}
}
@objc public func urlByAppendingDefaultParamsWithWalletTokenAndSSOToken(_ url: String?) -> String? {
var params: String? = nil
if false == isURLContainsDefaultParams(url) {
params = defaultParamsWithSiteID(urlString: url)
}
var appendTokenType: Bool = false
if false == containsWalletToken(url: url), let walletToken = JRCommonManager.shared.applicationDelegate?.getWalletToken(){
if params == nil {
params = String(format: "?%@=%@", kwalletToken, walletToken)
} else {
params?.append(String(format: "&%@=%@", kwalletToken, walletToken))
}
appendTokenType = true
}
if false == containsSSOToken(url: url), let ssoToken = JRCommonManager.shared.applicationDelegate?.getSSOToken() {
if params == nil {
params = String(format: "?%@=%@", kSsoToken, ssoToken)
} else {
params?.append(String(format: "&%@=%@", kSsoToken, ssoToken))
}
appendTokenType = true
}
if appendTokenType, false == containsTokenType(url: url) {
if params == nil {
params = String(format: "?%@=%@", kTokenType, "oauth")
} else {
params?.append(String(format: "&%@=%@", kTokenType, "oauth"))
}
}
if let params = params, let url = url {
return appendParams(params: params, inUrl: url, encode: true)
} else {
return url
}
}
@objc public func urlByAppendingDefaultParamsWithoutWalletAndSSOToken(_ url: String?) -> String? {
var params: String? = nil
if false == isURLContainsDefaultParams(url) {
params = defaultParamsWithSiteID(urlString: url)
}
if false == containsTokenType(url: url) {
if params == nil {
params = String(format: "?%@=%@", kTokenType, "oauth")
} else {
params?.append(String(format: "&%@=%@", kTokenType, "oauth"))
}
}
if let params = params, let url = url {
return appendParams(params: params, inUrl: url, encode: true)
} else {
return url
}
}
@objc public func urlByAppendingDefaultParamsWithWalletToken(_ url: String?) -> String? {
var params: String? = nil
if false == isURLContainsDefaultParams(url) {
params = defaultParamsWithSiteID(urlString: url)
}
if false == containsWalletToken(url: url), let walletToken = JRCommonManager.shared.applicationDelegate?.getWalletToken() {
if params == nil {
params = String(format: "?%@=%@", kwalletToken, walletToken)
} else {
params?.append(String(format: "&%@=%@", kwalletToken, walletToken))
}
}
if let params = params, let url = url {
return appendParams(params: params, inUrl: url, encode: true)
} else {
return url
}
}
@objc public func urlByAppendingProductImageSizeAndQualityToUrl(_ url: String?) -> String? {
var url: String? = url
url = urlByAppendingDefaultParamsWithSSOToken(url)
var height: CGFloat = JRSwiftConstants.windowHeigth
var width: CGFloat = JRSwiftConstants.windowWidth
if UIScreen.main.scale == 2.0 {
width *= 2
height *= 2
}
if url?.range(of: "?")?.lowerBound != nil {
return url?.appending(String(format: "&resolution=%dx%d&quality=high", width, height))
}
return url?.appending(String(format: "?resolution=%dx%d&quality=high", width, height))
}
@objc public func getIDFAIdentifier()-> String?{
// Check if Advertising Tracking is Enabled
if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
// Set the IDFA
return ASIdentifierManager.shared().advertisingIdentifier.uuidString
}
return nil
}
/*
* append fetch strategy
*/
@objc public func urlByAppendingFetchStrategy( _ url: String? ,fetchParam: String ) -> String?{
if let urlStr = url{
var urlStrate: String = urlStr
if urlStr.range(of: "fetch_strategy")?.lowerBound == nil && !fetchParam.isEmpty {
urlStrate = urlStr + String(format: "?fetch_strategy=%@", fetchParam)
}
return urlByAppendingDefaultParams(urlStrate)
}
return ""
}
}
//MARK: user agent methods
extension JRAPIManager {
public func fetchUserAgent(completion: ((String?)->Void)?) {
guard let ua = internalUserAgent else {
extractUserAgent {[weak self] (uaStr) in
guard let weakSelf = self else {
return
}
weakSelf.internalUserAgent = uaStr
if uaStr != nil {
UserDefaults.standard.set(uaStr!, forKey: weakSelf.kPersistentDefaultUAKey)
}
completion?(uaStr)
}
return
}
completion?(ua)
}
private func extractUserAgent(completion: ((String?)->Void)?) {
DispatchQueue.main.async {
if self.wkWebView == nil {
self.wkWebView = WKWebView()
}
self.wkWebView?.evaluateJavaScript("navigator.userAgent", completionHandler: {[weak self] (userAgent, error) in
completion?(userAgent as? String)
self?.wkWebView = nil
})
}
}
private func getDefaultUA()-> String {
guard let persistentUA = UserDefaults.standard.string(forKey: kPersistentDefaultUAKey) else {
let iOSVersion = UIDevice.current.systemVersion.replacingOccurrences(of: ".", with: "_")
return "Mozilla/5.0 (iPhone; CPU iPhone OS \(iOSVersion) like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile"
}
return persistentUA
}
}
| 38.457006 | 282 | 0.575877 |
f9b7462473335f3d757f2034ab2979aba5ba6563 | 21,031 | //
// GDWebViewController.swift
// GDWebBrowserClient
//
// Created by Alex G on 03.12.14.
// Copyright (c) 2015 Alexey Gordiyenko. All rights reserved.
//
//MIT License
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import WebKit
public enum GDWebViewControllerProgressIndicatorStyle {
case activityIndicator
case progressView
case both
case none
}
@objc public protocol GDWebViewControllerDelegate {
@objc optional func webViewController(_ webViewController: GDWebViewController, didChangeURL newURL: URL?)
@objc optional func webViewController(_ webViewController: GDWebViewController, didChangeTitle newTitle: NSString?)
@objc optional func webViewController(_ webViewController: GDWebViewController, didFinishLoading loadedURL: URL?)
@objc optional func webViewController(_ webViewController: GDWebViewController, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void)
@objc optional func webViewController(_ webViewController: GDWebViewController, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void)
@objc optional func webViewController(_ webViewController: GDWebViewController, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
open class GDWebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, GDWebViewNavigationToolbarDelegate {
// MARK: Public Properties
/** An object to serve as a delegate which conforms to GDWebViewNavigationToolbarDelegate protocol. */
open weak var delegate: GDWebViewControllerDelegate?
/** The style of progress indication visualization. Can be one of four values: .ActivityIndicator, .ProgressView, .Both, .None*/
open var progressIndicatorStyle: GDWebViewControllerProgressIndicatorStyle = .both
/** A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations. The default value is false. */
open var allowsBackForwardNavigationGestures: Bool {
get {
return webView.allowsBackForwardNavigationGestures
}
set(value) {
webView.allowsBackForwardNavigationGestures = value
}
}
/** A boolean value if set to true shows the toolbar; otherwise, hides it. */
open var showsToolbar: Bool {
set(value) {
self.toolbarHeight = value ? 44 : 0
}
get {
return self.toolbarHeight == 44
}
}
/** A boolean value if set to true shows the refresh control (or stop control while loading) on the toolbar; otherwise, hides it. */
open var showsStopRefreshControl: Bool {
get {
return toolbarContainer.showsStopRefreshControl
}
set(value) {
toolbarContainer.showsStopRefreshControl = value
}
}
/** The navigation toolbar object (read-only). */
open var toolbar: GDWebViewNavigationToolbar {
get {
return toolbarContainer
}
}
/** Boolean flag which indicates whether JavaScript alerts are allowed. Default is `true`. */
open var allowJavaScriptAlerts = true
public var webView: WKWebView!
// MARK: Private Properties
fileprivate var progressView: UIProgressView!
fileprivate var toolbarContainer: GDWebViewNavigationToolbar!
fileprivate var toolbarHeightConstraint: NSLayoutConstraint!
fileprivate var toolbarHeight: CGFloat = 0
fileprivate var navControllerUsesBackSwipe: Bool = false
lazy fileprivate var activityIndicator: UIActivityIndicatorView! = {
var activityIndicator = UIActivityIndicatorView()
activityIndicator.backgroundColor = UIColor(white: 0, alpha: 0.2)
#if swift(>=4.2)
activityIndicator.style = .whiteLarge
#else
activityIndicator.activityIndicatorViewStyle = .whiteLarge
#endif
activityIndicator.hidesWhenStopped = true
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(activityIndicator)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[activityIndicator]-0-|", options: [], metrics: nil, views: ["activityIndicator": activityIndicator]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[activityIndicator]-0-[toolbarContainer]|", options: [], metrics: nil, views: ["activityIndicator": activityIndicator, "toolbarContainer": self.toolbarContainer, "topGuide": self.topLayoutGuide]))
return activityIndicator
}()
// MARK: Public Methods
/**
Navigates to an URL created from provided string.
- parameter URLString: The string that represents an URL.
*/
// TODO: Earlier `scheme` property was optional. Now it isn't true. Need to check that scheme is always
open func loadURLWithString(_ URLString: String) {
if let URL = URL(string: URLString) {
if (URL.scheme != "") && (URL.host != nil) {
loadURL(URL)
} else {
loadURLWithString("http://\(URLString)")
}
}
}
/**
Navigates to the URL.
- parameter URL: The URL for a request.
- parameter cachePolicy: The cache policy for a request. Optional. Default value is .UseProtocolCachePolicy.
- parameter timeoutInterval: The timeout interval for a request, in seconds. Optional. Default value is 0.
*/
open func loadURL(_ URL: Foundation.URL, cachePolicy: NSURLRequest.CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 0) {
webView.load(URLRequest(url: URL, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
/**
Evaluates the given JavaScript string.
- parameter javaScriptString: The JavaScript string to evaluate.
- parameter completionHandler: A block to invoke when script evaluation completes or fails.
The completionHandler is passed the result of the script evaluation or an error.
*/
open func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
webView.evaluateJavaScript(javaScriptString, completionHandler: completionHandler as! ((Any?, Error?) -> Void)?)
}
/**
Shows or hides toolbar.
- parameter show: A Boolean value if set to true shows the toolbar; otherwise, hides it.
- parameter animated: A Boolean value if set to true animates the transition; otherwise, does not.
*/
open func showToolbar(_ show: Bool, animated: Bool) {
self.showsToolbar = show
if toolbarHeightConstraint != nil {
toolbarHeightConstraint.constant = self.toolbarHeight
if animated {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.view.layoutIfNeeded()
})
} else {
self.view.layoutIfNeeded()
}
}
}
@objc open func goBack(){
webView.goBack()
}
@objc open func goForward(){
webView.goForward()
}
@objc open func stopLoading(){
webView.stopLoading()
}
@objc open func reload(){
webView.reload()
}
// MARK: GDWebViewNavigationToolbarDelegate Methods
func webViewNavigationToolbarGoBack(_ toolbar: GDWebViewNavigationToolbar) {
webView.goBack()
}
func webViewNavigationToolbarGoForward(_ toolbar: GDWebViewNavigationToolbar) {
webView.goForward()
}
func webViewNavigationToolbarRefresh(_ toolbar: GDWebViewNavigationToolbar) {
webView.reload()
}
func webViewNavigationToolbarStop(_ toolbar: GDWebViewNavigationToolbar) {
webView.stopLoading()
}
// MARK: WKNavigationDelegate Methods
open func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showLoading(false)
if error._code == NSURLErrorCancelled {
return
}
showError(error.localizedDescription)
}
open func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
showLoading(false)
if error._code == NSURLErrorCancelled {
return
}
showError(error.localizedDescription)
}
open func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard ((delegate?.webViewController?(self, didReceiveAuthenticationChallenge: challenge, completionHandler: { (disposition, credential) -> Void in
completionHandler(disposition, credential)
})) != nil)
else {
completionHandler(.performDefaultHandling, nil)
return
}
}
open func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
}
open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showLoading(true)
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard ((delegate?.webViewController?(self, decidePolicyForNavigationAction: navigationAction, decisionHandler: { (policy) -> Void in
decisionHandler(policy)
if policy == .cancel {
self.showError("This navigation is prohibited.")
}
})) != nil)
else {
decisionHandler(.allow);
return
}
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
guard ((delegate?.webViewController?(self, decidePolicyForNavigationResponse: navigationResponse, decisionHandler: { (policy) -> Void in
decisionHandler(policy)
if policy == .cancel {
self.showError("This navigation response is prohibited.")
}
})) != nil)
else {
decisionHandler(.allow)
return
}
}
open func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil, let url = navigationAction.request.url{
if url.description.lowercased().range(of: "http://") != nil || url.description.lowercased().range(of: "https://") != nil {
webView.load(navigationAction.request)
}
}
return nil
}
// MARK: WKUIDelegate Methods
open func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
if !allowJavaScriptAlerts {
return
}
let alertController: UIAlertController = UIAlertController(title: message, message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: {(action: UIAlertAction) -> Void in
completionHandler()
}))
self.present(alertController, animated: true, completion: nil)
}
// MARK: Some Private Methods
fileprivate func showError(_ errorString: String?) {
let alertView = UIAlertController(title: "Error", message: errorString, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertView, animated: true, completion: nil)
}
fileprivate func showLoading(_ animate: Bool) {
if animate {
if (progressIndicatorStyle == .activityIndicator) || (progressIndicatorStyle == .both) {
activityIndicator.startAnimating()
}
toolbar.loadDidStart()
} else if activityIndicator != nil {
if (progressIndicatorStyle == .activityIndicator) || (progressIndicatorStyle == .both) {
activityIndicator.stopAnimating()
}
toolbar.loadDidFinish()
}
}
fileprivate func progressChanged(_ newValue: NSNumber) {
if progressView == nil {
progressView = UIProgressView()
progressView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(progressView)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[progressView]-0-|", options: [], metrics: nil, views: ["progressView": progressView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[progressView(2)]", options: [], metrics: nil, views: ["progressView": progressView, "topGuide": self.topLayoutGuide]))
}
progressView.progress = newValue.floatValue
if progressView.progress == 1 {
progressView.progress = 0
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.progressView.alpha = 0
})
} else if progressView.alpha == 0 {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.progressView.alpha = 1
})
}
}
fileprivate func backForwardListChanged() {
if self.navControllerUsesBackSwipe && self.allowsBackForwardNavigationGestures {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = !webView.canGoBack
}
toolbarContainer.backButtonItem?.isEnabled = webView.canGoBack
toolbarContainer.forwardButtonItem?.isEnabled = webView.canGoForward
}
// MARK: KVO
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else {return}
switch keyPath {
case "estimatedProgress":
if (progressIndicatorStyle == .progressView) || (progressIndicatorStyle == .both) {
if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
progressChanged(newValue)
}
}
case "URL":
delegate?.webViewController?(self, didChangeURL: webView.url)
case "title":
delegate?.webViewController?(self, didChangeTitle: webView.title as NSString?)
case "loading":
if let val = change?[NSKeyValueChangeKey.newKey] as? Bool {
if !val {
showLoading(false)
backForwardListChanged()
delegate?.webViewController?(self, didFinishLoading: webView.url)
}
}
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
// MARK: Overrides
// Override this property getter to show bottom toolbar above other toolbars
override open var edgesForExtendedLayout: UIRectEdge {
get {
return UIRectEdge(rawValue: super.edgesForExtendedLayout.rawValue ^ UIRectEdge.bottom.rawValue)
}
set {
super.edgesForExtendedLayout = newValue
}
}
// MARK: Life Cycle
override open func viewDidLoad() {
super.viewDidLoad()
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonTapped))
self.navigationItem.rightBarButtonItem = doneButton
// Set up toolbarContainer
self.view.addSubview(toolbarContainer)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[toolbarContainer]-0-|", options: [], metrics: nil, views: ["toolbarContainer": toolbarContainer]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[toolbarContainer]-0-|", options: [], metrics: nil, views: ["toolbarContainer": toolbarContainer]))
toolbarHeightConstraint = NSLayoutConstraint(item: toolbarContainer, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: toolbarHeight)
toolbarContainer.addConstraint(toolbarHeightConstraint)
// Set up webView
self.view.addSubview(webView)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[webView]-0-|", options: [], metrics: nil, views: ["webView": webView as WKWebView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[webView]-0-[toolbarContainer]|", options: [], metrics: nil, views: ["webView": webView as WKWebView, "toolbarContainer": toolbarContainer, "topGuide": self.topLayoutGuide]))
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
webView.removeObserver(self, forKeyPath: "estimatedProgress")
webView.removeObserver(self, forKeyPath: "URL")
webView.removeObserver(self, forKeyPath: "title")
webView.removeObserver(self, forKeyPath: "loading")
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let navVC = self.navigationController {
if let gestureRecognizer = navVC.interactivePopGestureRecognizer {
navControllerUsesBackSwipe = gestureRecognizer.isEnabled
} else {
navControllerUsesBackSwipe = false
}
}
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if navControllerUsesBackSwipe {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
webView.stopLoading()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
func commonInit() {
webView = WKWebView()
webView.navigationDelegate = self
webView.uiDelegate = self
webView.translatesAutoresizingMaskIntoConstraints = false
toolbarContainer = GDWebViewNavigationToolbar(delegate: self)
toolbarContainer.translatesAutoresizingMaskIntoConstraints = false
}
@objc func doneButtonTapped() {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
| 43.814583 | 462 | 0.668775 |
64444d0f31f280c40f6f0273da313ac791ba7efc | 547 | //
// StatusImageView.swift
// SwiftUI-Basics
//
// Created by Dinesh Nagarajan on 19/12/20.
// Copyright © 2020 Mac-OBS-09. All rights reserved.
//
import Foundation
import SwiftUI
struct StatusImageView: View {
@State var outerCircleColor: Color = Color.black
@State var statusImage: String = ""
var body: some View {
Image(statusImage).resizable()
.clipShape(Circle()).frame(width: 60, height: 60).clipShape(Circle()).overlay(Circle().stroke(outerCircleColor, lineWidth: 2)).shadow(radius: 0)
}
}
| 26.047619 | 156 | 0.674589 |
1a5c9f0802f73c176c37d654437d4ad7c43f094d | 433 | //
// Copyright © 2020 Paris Android User Group. All rights reserved.
//
import Foundation
class UserPrefs {
private let favoriteTalksKey = "favoriteTalks"
func getFavoriteTalks() -> [String] {
return UserDefaults.standard.stringArray(forKey: favoriteTalksKey) ?? []
}
func setFavoriteTalks(_ favoriteTalks: [String]) {
UserDefaults.standard.set(favoriteTalks, forKey: favoriteTalksKey)
}
}
| 22.789474 | 80 | 0.699769 |
ac8e1a5f6ed58d5f0ef9560730449f05473df710 | 839 | import Foundation
import ProjectDescription
import TuistCore
import TuistGraph
extension TuistGraph.DeploymentTarget {
/// Maps a ProjectDescription.DeploymentTarget instance into a TuistCore.DeploymentTarget instance.
/// - Parameters:
/// - manifest: Manifest representation of deployment target model.
/// - generatorPaths: Generator paths.
static func from(manifest: ProjectDescription.DeploymentTarget) -> TuistGraph.DeploymentTarget {
switch manifest {
case let .iOS(version, devices):
return .iOS(version, DeploymentDevice(rawValue: devices.rawValue))
case let .macOS(version):
return .macOS(version)
case let .watchOS(version):
return .watchOS(version)
case let .tvOS(version):
return .tvOS(version)
}
}
}
| 34.958333 | 103 | 0.67938 |
Subsets and Splits