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
|
---|---|---|---|---|---|
f5fe38e53fd0ce57baf95036eadb784e9db6ce17 | 446 | import Foundation
final class MainThreadQueue: Queue {
let counter = Atomic(0)
func execute(_ work: @escaping () -> Void) {
let count = counter.modify { $0 += 1 }
if Thread.isMainThread && count == 1 {
work()
counter.modify { $0 -= 1 }
} else {
DispatchQueue.main.async {
work()
self.counter.modify { $0 -= 1 }
}
}
}
}
| 22.3 | 48 | 0.466368 |
7992d06ba8640996d023853772aa324bcc0c8222 | 1,003 | import Foundation
final class DataLoader<Key: Hashable, Value> {
public typealias BatchLoad = (Set<Key>) throws -> [Key: Value]
private var batchLoad: BatchLoad
private var cache: [Key: Result<Value?, Error>] = [:]
private var pendingLoads: Set<Key> = []
public init(_ batchLoad: @escaping BatchLoad) {
self.batchLoad = batchLoad
}
subscript(key: Key) -> PossiblyDeferred<Value?> {
if let cachedResult = cache[key] {
return .immediate(cachedResult)
}
pendingLoads.insert(key)
return .deferred { try self.load(key) }
}
private func load(_ key: Key) throws -> Value? {
if let cachedResult = cache[key] {
return try cachedResult.get()
}
assert(pendingLoads.contains(key))
let values = try batchLoad(pendingLoads)
for key in pendingLoads {
cache[key] = .success(values[key])
}
pendingLoads.removeAll()
return values[key]
}
func removeAll() {
cache.removeAll()
}
}
| 21.804348 | 64 | 0.631107 |
618a93c47405a31f0ccca1892d458f4d6132e1af | 1,414 | //===--- SuperChars.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test tests the performance of ASCII Character comparison.
import TestsUtils
@inline(never)
public func run_SuperChars(_ N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",
"«", // throw in some unicode to make it slower
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"á", "お",
"S", "T", "U",
"🇯🇵",
"V", "W", "X", "Y", "Z", "/", "f", "Z", "z", "6", "7", "C", "j", "f", "9",
"🇯🇵🇺🇸", "🇯🇵🇺🇸🇨🇳", "🇯🇵🇺🇸🇨🇳🇩🇪",
"g", "g", "I", "J", "K", "c", "x", "i", ".",
"🇯🇵🇺🇸🇨🇳🇩🇪", "🇯🇵🇺🇸", "🇯🇵🇺🇸🇨🇳",
"2", "a", "t", "i", "o", "e", "q", "n", "X", "Y", "Z", "?", "m", "Z", ","
]
for _ in 0...N {
for firstChar in alphabet {
for middleChar in alphabet {
for lastChar in alphabet {
_ = ((firstChar == middleChar) != (middleChar < lastChar))
}
}
}
}
}
| 32.883721 | 80 | 0.446252 |
e2040f6258807f832696e2f8fa7db4e066b36588 | 14,570 | import Combine
import LoopKitUI
import SwiftDate
import SwiftUI
extension Home {
final class StateModel: BaseStateModel<Provider> {
@Injected() var broadcaster: Broadcaster!
@Injected() var apsManager: APSManager!
@Injected() var nightscoutManager: NightscoutManager!
private let timer = DispatchTimer(timeInterval: 5)
private(set) var filteredHours = 24
@Published var glucose: [BloodGlucose] = []
@Published var suggestion: Suggestion?
@Published var enactedSuggestion: Suggestion?
@Published var recentGlucose: BloodGlucose?
@Published var glucoseDelta: Int?
@Published var tempBasals: [PumpHistoryEvent] = []
@Published var boluses: [PumpHistoryEvent] = []
@Published var suspensions: [PumpHistoryEvent] = []
@Published var maxBasal: Decimal = 2
@Published var autotunedBasalProfile: [BasalProfileEntry] = []
@Published var basalProfile: [BasalProfileEntry] = []
@Published var tempTargets: [TempTarget] = []
@Published var carbs: [CarbsEntry] = []
@Published var timerDate = Date()
@Published var closedLoop = false
@Published var pumpSuspended = false
@Published var isLooping = false
@Published var statusTitle = ""
@Published var lastLoopDate: Date = .distantPast
@Published var tempRate: Decimal?
@Published var battery: Battery?
@Published var reservoir: Decimal?
@Published var pumpName = ""
@Published var pumpExpiresAtDate: Date?
@Published var tempTarget: TempTarget?
@Published var setupPump = false
@Published var errorMessage: String? = nil
@Published var errorDate: Date? = nil
@Published var bolusProgress: Decimal?
@Published var eventualBG: Int?
@Published var carbsRequired: Decimal?
@Published var allowManualTemp = false
@Published var units: GlucoseUnits = .mmolL
@Published var pumpDisplayState: PumpDisplayState?
@Published var alarm: GlucoseAlarm?
@Published var animatedBackground = false
override func subscribe() {
setupGlucose()
setupBasals()
setupBoluses()
setupSuspensions()
setupPumpSettings()
setupBasalProfile()
setupTempTargets()
setupCarbs()
setupBattery()
setupReservoir()
suggestion = provider.suggestion
enactedSuggestion = provider.enactedSuggestion
units = settingsManager.settings.units
allowManualTemp = !settingsManager.settings.closedLoop
closedLoop = settingsManager.settings.closedLoop
lastLoopDate = apsManager.lastLoopDate
carbsRequired = suggestion?.carbsReq
alarm = provider.glucoseStorage.alarm
setStatusTitle()
setupCurrentTempTarget()
broadcaster.register(GlucoseObserver.self, observer: self)
broadcaster.register(SuggestionObserver.self, observer: self)
broadcaster.register(SettingsObserver.self, observer: self)
broadcaster.register(PumpHistoryObserver.self, observer: self)
broadcaster.register(PumpSettingsObserver.self, observer: self)
broadcaster.register(BasalProfileObserver.self, observer: self)
broadcaster.register(TempTargetsObserver.self, observer: self)
broadcaster.register(CarbsObserver.self, observer: self)
broadcaster.register(EnactedSuggestionObserver.self, observer: self)
broadcaster.register(PumpBatteryObserver.self, observer: self)
broadcaster.register(PumpReservoirObserver.self, observer: self)
animatedBackground = settingsManager.settings.animatedBackground
timer.eventHandler = {
DispatchQueue.main.async { [weak self] in
self?.timerDate = Date()
self?.setupCurrentTempTarget()
}
}
timer.resume()
apsManager.isLooping
.receive(on: DispatchQueue.main)
.weakAssign(to: \.isLooping, on: self)
.store(in: &lifetime)
apsManager.lastLoopDateSubject
.receive(on: DispatchQueue.main)
.weakAssign(to: \.lastLoopDate, on: self)
.store(in: &lifetime)
apsManager.pumpName
.receive(on: DispatchQueue.main)
.weakAssign(to: \.pumpName, on: self)
.store(in: &lifetime)
apsManager.pumpExpiresAtDate
.receive(on: DispatchQueue.main)
.weakAssign(to: \.pumpExpiresAtDate, on: self)
.store(in: &lifetime)
apsManager.lastError
.receive(on: DispatchQueue.main)
.map { [weak self] error in
self?.errorDate = error == nil ? nil : Date()
if let error = error {
info(.default, error.localizedDescription)
}
return error?.localizedDescription
}
.weakAssign(to: \.errorMessage, on: self)
.store(in: &lifetime)
apsManager.bolusProgress
.receive(on: DispatchQueue.main)
.weakAssign(to: \.bolusProgress, on: self)
.store(in: &lifetime)
apsManager.pumpDisplayState
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
guard let self = self else { return }
self.pumpDisplayState = state
if state == nil {
self.reservoir = nil
self.battery = nil
self.pumpName = ""
self.pumpExpiresAtDate = nil
self.setupPump = false
} else {
self.setupBattery()
self.setupReservoir()
}
}
.store(in: &lifetime)
$setupPump
.sink { [weak self] show in
guard let self = self else { return }
if show, let pumpManager = self.provider.apsManager.pumpManager {
let view = PumpConfig.PumpSettingsView(pumpManager: pumpManager, completionDelegate: self).asAny()
self.router.mainSecondaryModalView.send(view)
} else {
self.router.mainSecondaryModalView.send(nil)
}
}
.store(in: &lifetime)
}
func addCarbs() {
showModal(for: .addCarbs)
}
func runLoop() {
provider.heartbeatNow()
}
func cancelBolus() {
apsManager.cancelBolus()
}
private func setupGlucose() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.glucose = self.provider.filteredGlucose(hours: self.filteredHours)
self.recentGlucose = self.glucose.last
if self.glucose.count >= 2 {
self.glucoseDelta = (self.recentGlucose?.glucose ?? 0) - (self.glucose[self.glucose.count - 2].glucose ?? 0)
} else {
self.glucoseDelta = nil
}
self.alarm = self.provider.glucoseStorage.alarm
}
}
private func setupBasals() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.tempBasals = self.provider.pumpHistory(hours: self.filteredHours).filter {
$0.type == .tempBasal || $0.type == .tempBasalDuration
}
let lastTempBasal = Array(self.tempBasals.suffix(2))
guard lastTempBasal.count == 2 else {
self.tempRate = nil
return
}
guard let lastRate = lastTempBasal[0].rate, let lastDuration = lastTempBasal[1].durationMin else {
self.tempRate = nil
return
}
let lastDate = lastTempBasal[0].timestamp
guard Date().timeIntervalSince(lastDate.addingTimeInterval(lastDuration.minutes.timeInterval)) < 0 else {
self.tempRate = nil
return
}
self.tempRate = lastRate
}
}
private func setupBoluses() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.boluses = self.provider.pumpHistory(hours: self.filteredHours).filter {
$0.type == .bolus
}
}
}
private func setupSuspensions() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.suspensions = self.provider.pumpHistory(hours: self.filteredHours).filter {
$0.type == .pumpSuspend || $0.type == .pumpResume
}
let last = self.suspensions.last
let tbr = self.tempBasals.first { $0.timestamp > (last?.timestamp ?? .distantPast) }
self.pumpSuspended = tbr == nil && last?.type == .pumpSuspend
}
}
private func setupPumpSettings() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.maxBasal = self.provider.pumpSettings().maxBasal
}
}
private func setupBasalProfile() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.autotunedBasalProfile = self.provider.autotunedBasalProfile()
self.basalProfile = self.provider.basalProfile()
}
}
private func setupTempTargets() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.tempTargets = self.provider.tempTargets(hours: self.filteredHours)
}
}
private func setupCarbs() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.carbs = self.provider.carbs(hours: self.filteredHours)
}
}
private func setStatusTitle() {
guard let suggestion = suggestion else {
statusTitle = "No suggestion"
return
}
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
if closedLoop,
let enactedSuggestion = enactedSuggestion,
let timestamp = enactedSuggestion.timestamp,
enactedSuggestion.deliverAt == suggestion.deliverAt, enactedSuggestion.recieved == true
{
statusTitle = "Enacted at \(dateFormatter.string(from: timestamp))"
} else if let suggestedDate = suggestion.deliverAt {
statusTitle = "Suggested at \(dateFormatter.string(from: suggestedDate))"
} else {
statusTitle = "Suggested"
}
eventualBG = suggestion.eventualBG
}
private func setupReservoir() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.reservoir = self.provider.pumpReservoir()
}
}
private func setupBattery() {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.battery = self.provider.pumpBattery()
}
}
private func setupCurrentTempTarget() {
tempTarget = provider.tempTarget()
}
func openCGM() {
guard var url = nightscoutManager.cgmURL else { return }
switch url.absoluteString {
case "http://127.0.0.1:1979":
url = URL(string: "spikeapp://")!
case "http://127.0.0.1:17580":
url = URL(string: "diabox://")!
case CGMType.libreTransmitter.appURL?.absoluteString:
showModal(for: .libreConfig)
default: break
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
extension Home.StateModel:
GlucoseObserver,
SuggestionObserver,
SettingsObserver,
PumpHistoryObserver,
PumpSettingsObserver,
BasalProfileObserver,
TempTargetsObserver,
CarbsObserver,
EnactedSuggestionObserver,
PumpBatteryObserver,
PumpReservoirObserver
{
func glucoseDidUpdate(_: [BloodGlucose]) {
setupGlucose()
}
func suggestionDidUpdate(_ suggestion: Suggestion) {
self.suggestion = suggestion
carbsRequired = suggestion.carbsReq
setStatusTitle()
}
func settingsDidChange(_ settings: FreeAPSSettings) {
allowManualTemp = !settings.closedLoop
closedLoop = settingsManager.settings.closedLoop
units = settingsManager.settings.units
animatedBackground = settingsManager.settings.animatedBackground
setupGlucose()
}
func pumpHistoryDidUpdate(_: [PumpHistoryEvent]) {
setupBasals()
setupBoluses()
setupSuspensions()
}
func pumpSettingsDidChange(_: PumpSettings) {
setupPumpSettings()
}
func basalProfileDidChange(_: [BasalProfileEntry]) {
setupBasalProfile()
}
func tempTargetsDidUpdate(_: [TempTarget]) {
setupTempTargets()
}
func carbsDidUpdate(_: [CarbsEntry]) {
setupCarbs()
}
func enactedSuggestionDidUpdate(_ suggestion: Suggestion) {
enactedSuggestion = suggestion
setStatusTitle()
}
func pumpBatteryDidChange(_: Battery) {
setupBattery()
}
func pumpReservoirDidChange(_: Decimal) {
setupReservoir()
}
}
extension Home.StateModel: CompletionDelegate {
func completionNotifyingDidComplete(_: CompletionNotifying) {
setupPump = false
}
}
| 36.60804 | 128 | 0.563281 |
679fff92a89d05a94caa87cb993aa19fdcc16dd6 | 673 | //
// Interchangeable.swift
// MusicXML
//
// Created by James Bean on 5/16/19.
//
/// The interchangeable type is used to represent the second in a pair of interchangeable dual time
/// signatures, such as the 6/8 in 3/4 (6/8).
public struct Interchangeable {
// MARK: - Instance Properties
// MARK: Attributes
public let symbol: TimeSymbol
public let separator: TimeSeparator
// FIXME: Add Elements
// MARK: - Initializers
public init(symbol: TimeSymbol, separator: TimeSeparator) {
self.symbol = symbol
self.separator = separator
}
}
extension Interchangeable: Equatable {}
extension Interchangeable: Codable {}
| 22.433333 | 99 | 0.684993 |
33035747044184199c1ddfb6a190a149b028bd48 | 18,369 | // BaseButtonBarPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
public var settings = ButtonBarPagerTabStripSettings()
public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarCellType>!
public var changeCurrentIndex: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ animated: Bool) -> Void)?
public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
@IBOutlet public weak var buttonBarView: ButtonBarView!
lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
return self.calculateWidths()
}()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
let buttonBarViewAux = buttonBarView ?? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: settings.style.buttonBarLeftContentInset ?? 35, bottom: 0, right: settings.style.buttonBarRightContentInset ?? 35)
let buttonBarHeight = settings.style.buttonBarHeight ?? 44
let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
buttonBar.backgroundColor = .orange
buttonBar.selectedBar.backgroundColor = .black
buttonBar.autoresizingMask = .flexibleWidth
var newContainerViewFrame = containerView.frame
newContainerViewFrame.origin.y = buttonBarHeight
newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y)
containerView.frame = newContainerViewFrame
return buttonBar
}()
buttonBarView = buttonBarViewAux
if buttonBarView.superview == nil {
view.addSubview(buttonBarView)
}
if buttonBarView.delegate == nil {
buttonBarView.delegate = self
}
if buttonBarView.dataSource == nil {
buttonBarView.dataSource = self
}
buttonBarView.scrollsToTop = false
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = settings.style.buttonBarMinimumInteritemSpacing ?? flowLayout.minimumInteritemSpacing
flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing
let sectionInset = flowLayout.sectionInset
flowLayout.sectionInset = UIEdgeInsets(top: sectionInset.top, left: settings.style.buttonBarLeftContentInset ?? sectionInset.left, bottom: sectionInset.bottom, right: settings.style.buttonBarRightContentInset ?? sectionInset.right)
buttonBarView.showsHorizontalScrollIndicator = false
buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor
buttonBarView.bar.backgroundColor = settings.style.barBackgroundColor
buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor
buttonBarView.selectedBarVerticalAlignment = settings.style.selectedBarVerticalAlignment
buttonBarView.selectedBarHeight = settings.style.selectedBarHeight
// register button bar item cell
switch buttonBarItemSpec! {
case .nibFile(let nibName, let bundle, _):
buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell")
case .cellClass:
buttonBarView.register(ButtonBarCellType.self, forCellWithReuseIdentifier:"Cell")
}
//-
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonBarView.layoutIfNeeded()
isViewAppearing = true
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewAppearing = false
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isViewAppearing || isViewRotating else { return }
// Force the UICollectionViewFlowLayout to get laid out again with the new size if
// a) The view is appearing. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called for a second time
// when the view is shown and when the view *frame(s)* are actually set
// (we need the view frame's to have been set to work out the size's and on the
// first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
// aren't set correctly)
// b) The view is rotating. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
// *new* frame so that the buttonBarView cell's actually get resized correctly
cachedCellWidths = calculateWidths()
buttonBarView.collectionViewLayout.invalidateLayout()
// When the view first appears or is rotated we also need to ensure that the barButtonView's
// selectedBar is resized and its contentOffset/scroll is set correctly (the selected
// tab/cell may end up either skewed or off screen after a rotation otherwise)
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
}
// MARK: - View Rotation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: - Public Methods
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
buttonBarView.reloadData()
cachedCellWidths = calculateWidths()
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
}
open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
var numberOfLargeCells = 0
var totalWidthOfLargeCells: CGFloat = 0
for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
totalWidthOfLargeCells += minimumCellWidthValue
numberOfLargeCells += 1
}
guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
let numberOfCells = minimumCellWidths.count
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
let numberOfSmallCells = numberOfCells - numberOfLargeCells
let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
if let changeCurrentIndex = changeCurrentIndex {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndex(oldCell, newCell, true)
}
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
}
}
// MARK: - UICollectionViewDelegateFlowLayut
@objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
}
return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.item != currentIndex else { return }
buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
shouldUpdateButtonBarView = false
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(oldCell, newCell, true)
}
}
moveToViewController(at: indexPath.item)
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
}
let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
configure(cell: cell, for: indicatorInfo)
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false)
}
}
return cell
}
// MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
super.scrollViewDidEndScrollingAnimation(scrollView)
guard scrollView == containerView else { return }
shouldUpdateButtonBarView = true
}
open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
fatalError("You must override this method to set up ButtonBarView cell accordingly")
}
private func calculateWidths() -> [CGFloat] {
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let numberOfCells = viewControllers.count
var minimumCellWidths = [CGFloat]()
var collectionViewContentWidth: CGFloat = 0
for viewController in viewControllers {
let childController = viewController as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
switch buttonBarItemSpec! {
case .cellClass(let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
case .nibFile(_, _, let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
}
}
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
collectionViewContentWidth += cellSpacingTotal
let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth {
return minimumCellWidths
} else {
let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
var stretchedCellWidths = [CGFloat]()
for minimumCellWidthValue in minimumCellWidths {
let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
stretchedCellWidths.append(cellWidth)
}
return stretchedCellWidths
}
}
private var shouldUpdateButtonBarView = true
}
open class ExampleBaseButtonBarPagerTabStripViewController: BaseButtonBarPagerTabStripViewController<ButtonBarViewCell> {
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open func initialize() {
var bundle = Bundle(for: ButtonBarViewCell.self)
if let resourcePath = bundle.path(forResource: "XLPagerTabStrip", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: bundle, width: { [weak self] (childItemInfo) -> CGFloat in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = self?.settings.style.buttonBarItemFont ?? label.font
label.text = childItemInfo.title
let labelSize = label.intrinsicContentSize
return labelSize.width + CGFloat(self?.settings.style.buttonBarItemLeftRightMargin ?? 8 * 2)
})
}
open override func configure(cell: ButtonBarViewCell, for indicatorInfo: IndicatorInfo) {
cell.label.text = indicatorInfo.title
cell.accessibilityLabel = indicatorInfo.accessibilityLabel
if let image = indicatorInfo.image {
cell.imageView.image = image
}
if let highlightedImage = indicatorInfo.highlightedImage {
cell.imageView.highlightedImage = highlightedImage
}
}
}
| 51.889831 | 239 | 0.715717 |
ebdc2de2edfa8f42cf2c333b4b70377de4d74d7c | 1,938 | //
// MarketDataPublisher.swift
// breadwallet
//
// Created by Adrian Corscadden on 2020-09-09.
// Copyright © 2020 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import Combine
// import CoinGecko
struct MarketDataViewModel {
let data: MarketData?
var marketCap: String { format(value: data?.marketCap, decimals: 0) }
var totalVolume: String { format(value: data?.totalVolume, decimals: 0) }
var high24h: String { format(value: data?.high24h, decimals: 2) }
var low24h: String { format(value: data?.low24h, decimals: 2) }
private func format(value: Double?, decimals: Int) -> String {
guard let val = value else { return " " }
return formatter(decimals: decimals).string(from: NSNumber(value: val)) ?? " "
}
private func formatter(decimals: Int) -> NumberFormatter {
let nf = NumberFormatter()
nf.numberStyle = .currency
nf.minimumFractionDigits = decimals
nf.maximumFractionDigits = decimals
nf.currencySymbol = Rate.symbolMap[Store.state.defaultCurrencyCode]
return nf
}
}
@available(iOS 13.0, *)
class MarketDataPublisher: ObservableObject {
@Published var viewModel = MarketDataViewModel(data: nil)
let currencyId: String
let fiatId: String
init(currencyId: String, fiatId: String) {
self.currencyId = currencyId
self.fiatId = fiatId
}
private let client = CoinGeckoClient()
func fetch() {
let resource = Resources.coin(currencyId: currencyId, vs: fiatId) { (result: Result<MarketData, CoinGeckoError>) in
guard case .success(let data) = result else { return }
DispatchQueue.main.async {
self.viewModel = MarketDataViewModel(data: data)
}
}
client.load(resource)
}
}
| 30.28125 | 123 | 0.645511 |
085b67b75eb0decb2388cb898557267a305e4206 | 2,618 | //
// NyTimesTests.swift
// NyTimesTests
//
// Created by Kivanda, Narendra on 22/11/20.
//
import XCTest
@testable import NyTimes
class NyTimesTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testFetchArticlesWebservice() {
let serverUrl = "https://api.nytimes.com/svc/mostpopular/v2/viewed/1.json?api-key=GLdHw57A1S543pjSPVbQsAYe1OMO9GlA"
let testExpectation = expectation(description: "GET \(serverUrl)")
NetworkLayer.shared.get(url: serverUrl, parameters: nil) { response in
guard response.error == nil else {
XCTFail(response.error?.localizedDescription ?? "GENERAL_ERROR_MESSAGE")
return
}
switch response.result {
case .success:
guard let _ = response.data else {
XCTAssert(true)
testExpectation.fulfill()
return
}
let articleModel : ArticleModel
do {
articleModel = try JSONDecoder().decode(ArticleModel.self, from: response.data!)
} catch let error {
XCTFail(error.localizedDescription)
return
}
testExpectation.fulfill()
XCTAssert(articleModel.status == "OK")
case .failure(let error):
XCTFail(error.localizedDescription)
return
}
}
waitForExpectations(timeout: 30) { error in
XCTAssert( error == nil)
}
}
func testFetchImageWebservice() {
let serverUrl = "https://static01.nyt.com/images/2020/11/24/multimedia/24xp-monolith4/24xp-monolith4-thumbStandard.jpg"
let testExpectation = expectation(description: "GET \(serverUrl)")
NetworkLayer.shared.getImage(url: serverUrl) { responseData in
guard responseData == nil else {
testExpectation.fulfill()
XCTAssert(true)
return
}
XCTFail("Image download error")
}
waitForExpectations(timeout: 30) { error in
XCTAssert( error == nil)
}
}
}
| 31.926829 | 127 | 0.55233 |
5ddd8cf66753147403bf97e4c0b38943c20a5c4b | 108 | public struct TMDBTVEpisodeAccountStates: Codable {
public let id: Int
public let rated: TMDBBool
}
| 21.6 | 51 | 0.75 |
111d897947568adcc1ac709b350a0da885fd7662 | 1,477 | //
// String+Localized.swift
// Visionranger
//
// Created by Colin Tessarzick on 06.11.21.
//
// Copyright © 2020-2021 Visionranger e.K. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
@_spi(VSN) public extension String {
enum Localized {
public static var close: String {
return VSNLocalizedString("Close", comment: "Text for close button")
}
}
}
| 39.918919 | 81 | 0.727827 |
3867ab467c3185084252a4179d55cc62d70bdf98 | 1,557 | //
// DispatchQueue+Swifty.swift
// Swifty
//
// Created by 王荣庆 on 2019/9/14.
// Copyright © 2019 RyukieSama. All rights reserved.
//
import Foundation
public extension DispatchQueue {
static private let spin = Spin()
static private var tracker: Set<String> = []
static func once(name: String, _ block: () -> Void) {
spin.lock(); defer { spin.unlock() }
guard !tracker.contains(name) else {
return
}
block()
tracker.insert(name)
}
}
final class Spin: Lockable {
private let locker: Lockable
init() {
if #available(iOS 10.0, macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
locker = UnfairLock()
} else {
locker = Mutex()
}
}
func lock() {
locker.lock()
}
func unlock() {
locker.unlock()
}
}
protocol Lockable: class {
func lock()
func unlock()
}
@available(iOS 10.0, OSX 10.12, watchOS 3.0, tvOS 10.0, *)
final class UnfairLock: Lockable {
private var unfairLock = os_unfair_lock_s()
func lock() {
os_unfair_lock_lock(&unfairLock)
}
func unlock() {
os_unfair_lock_unlock(&unfairLock)
}
}
final class Mutex: Lockable {
private var mutex = pthread_mutex_t()
init() {
pthread_mutex_init(&mutex, nil)
}
deinit {
pthread_mutex_destroy(&mutex)
}
func lock() {
pthread_mutex_lock(&mutex)
}
func unlock() {
pthread_mutex_unlock(&mutex)
}
}
| 18.987805 | 73 | 0.55684 |
9c59647d0efe6251b8c2cc22fec054ca274c8497 | 824 | //
// FolderDetailsFolderDetailsPresenterTests.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import XCTest
@testable import TOTP
class FolderDetailsPresenterTest: 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()
}
class MockInteractor: FolderDetailsInteractorInput {
}
class MockRouter: FolderDetailsRouterInput {
}
class MockViewController: FolderDetailsViewInput {
func setupInitialState() {
}
}
}
| 21.128205 | 111 | 0.679612 |
7a138438d652fc0ed0752fbc65824aa45844db73 | 8,779 | //
// SearchIndicator.swift
// Rescue
//
// Created by Alex Chen on 2015/2/27.
// Copyright (c) 2015年 KKAwesome. All rights reserved.
//
import Foundation
import UIKit
protocol SearchIndicatorDelegate{
func didStartSearchIndicator()
func didStopSearchIndicator()
}
class SearchIndicator: UIView {
let searchTime = 30.0
let circleOutsideRingLayer = CAShapeLayer()
let circleInsideRingLayer = CAShapeLayer()
let circleAnimationLineLayer = CAShapeLayer()
let originFrame: CGRect?
let recognizer: UITapGestureRecognizer?
let label: UILabel?
let titleLabel: UILabel?
let imageView = UIImageView()
let fullRotation = CGFloat(M_PI * 2)
let duration = 0.6
let delay = 0.0
let options = UIViewKeyframeAnimationOptions.CalculationModeLinear
var delegate: SearchIndicatorDelegate?
var isSearching = false
override init(frame: CGRect) {
super.init(frame: frame)
self.originFrame = frame
createLayer()
recognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
self.label = UILabel(frame: CGRectMake(-42, -160, 100, 100))
self.label!.text = ""
self.label!.font = self.label!.font.fontWithSize(40)
self.titleLabel = UILabel(frame: CGRectMake(-90, -140, 200, 100))
self.titleLabel!.text = "點選按鈕搜尋"
self.titleLabel!.font = self.titleLabel!.font.fontWithSize(32)
self.imageView = UIImageView(frame: CGRectMake(-40, -40, 80, 80))
self.imageView.image = UIImage(named: "near-me")
self.addSubview(self.imageView)
self.addSubview(self.label!)
self.addSubview(self.titleLabel!)
self.addGestureRecognizer(recognizer!)
}
func handleTap(gestureRecognizer: UITapGestureRecognizer){
start()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func start(){
isSearching = true
self.delegate?.didStartSearchIndicator()
CATransaction.begin()
CATransaction.setCompletionBlock({
UIView.animateKeyframesWithDuration(self.duration, delay: self.delay, options: self.options, animations: {
// each keyframe needs to be added here
// within each keyframe the relativeStartTime and relativeDuration need to be values between 0.0 and 1.0
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1/3, animations: {
// start at 0.00s (5s × 0)
// duration 1.67s (5s × 1/3)
// end at 1.67s (0.00s + 1.67s)
self.imageView.transform = CGAffineTransformMakeRotation(1/3 * self.fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
self.imageView.transform = CGAffineTransformMakeRotation(2/3 * self.fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
self.imageView.transform = CGAffineTransformMakeRotation(3/3 * self.fullRotation)
})
}, completion: {finished in
UIView.animateWithDuration(0.38, delay: 0.0, options: .CurveEaseOut, animations: {
self.label!.text = ""
self.transform = CGAffineTransformMakeScale(1, 1)
self.frame.origin.y = self.originFrame!.origin.y
self.frame.origin.x = self.originFrame!.origin.x
}, completion: { finised in
self.addGestureRecognizer(self.recognizer!)
self.circleAnimationLineLayer.opacity = 0
self.titleLabel!.text = "點選按鈕搜尋"
self.delegate?.didStopSearchIndicator()
self.isSearching = false
})
})
})
UIView.animateKeyframesWithDuration(duration, delay: delay, options: options, animations: {
// each keyframe needs to be added here
// within each keyframe the relativeStartTime and relativeDuration need to be values between 0.0 and 1.0
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1/3, animations: {
// start at 0.00s (5s × 0)
// duration 1.67s (5s × 1/3)
// end at 1.67s (0.00s + 1.67s)
self.imageView.transform = CGAffineTransformMakeRotation(1/3 * self.fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
self.imageView.transform = CGAffineTransformMakeRotation(2/3 * self.fullRotation)
})
UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
self.imageView.transform = CGAffineTransformMakeRotation(3/3 * self.fullRotation)
})
}, completion: {finished in
UIView.animateWithDuration(0.5, delay: 0.6, options: .CurveEaseOut, animations: {
let oldPosition = self.frame.origin.x
self.transform = CGAffineTransformMakeScale(0.6, 0.6)
let newPosition = self.frame.origin.x - oldPosition
self.frame.origin.y += 150
self.frame.origin.x -= newPosition
self.titleLabel?.text=""
println(self.frame.origin.x)
}, completion: { finised in
self.label!.text = "搜尋"
self.circleAnimationLineLayer.opacity = 1
})
})
self.removeGestureRecognizer(self.recognizer!)
let strokEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokEndAnimation.fromValue = 0
strokEndAnimation.toValue = 1.08
strokEndAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
strokEndAnimation.beginTime = CACurrentMediaTime() + 1.8
strokEndAnimation.duration = searchTime
strokEndAnimation.removedOnCompletion = false
circleAnimationLineLayer.addAnimation(strokEndAnimation, forKey: "strokeEnd")
CATransaction.commit()
}
func createLayer(){
let width = originFrame?.width
var linePath = UIBezierPath(arcCenter: CGPointMake(0, 0), radius: CGFloat(width!+1), startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)
var outLinePath = UIBezierPath(arcCenter: CGPointMake(0, 0), radius: CGFloat(width!+6), startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)
var path = UIBezierPath(arcCenter: CGPointMake(0, 0), radius: CGFloat(width!), startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)
circleOutsideRingLayer.path = outLinePath.CGPath
circleOutsideRingLayer.strokeColor = UIColor(red: 252/255, green: 143/255, blue: 46/255, alpha: 1).CGColor
circleOutsideRingLayer.lineWidth = 4
circleOutsideRingLayer.fillColor = nil
circleOutsideRingLayer.contentsScale = UIScreen.mainScreen().scale
circleInsideRingLayer.path = path.CGPath
circleInsideRingLayer.strokeColor = nil
circleInsideRingLayer.lineWidth = 1.65
circleInsideRingLayer.fillColor = UIColor(red: 252/255, green: 143/255, blue: 46/255, alpha: 1).CGColor
circleInsideRingLayer.contentsScale = UIScreen.mainScreen().scale
circleAnimationLineLayer.path = linePath.CGPath
circleAnimationLineLayer.strokeColor = UIColor(red: 252/255, green: 143/255, blue: 46/255, alpha: 1).CGColor
circleAnimationLineLayer.lineWidth = 6
circleAnimationLineLayer.fillColor = nil
circleAnimationLineLayer.contentsScale = UIScreen.mainScreen().scale
circleAnimationLineLayer.opacity = 0
self.layer.addSublayer(circleInsideRingLayer)
self.layer.addSublayer(circleOutsideRingLayer)
self.layer.addSublayer(circleAnimationLineLayer)
}
} | 40.086758 | 178 | 0.590728 |
61e499f6b02cb47ce3ec9bc708e163cdfa1f8283 | 1,251 | // Copyright (c) 2019 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
/// Represents type of a container entry.
public enum ContainerEntryType {
/// Block special file.
case blockSpecial
/// Character special file.
case characterSpecial
/// Contiguous file.
case contiguous
/// Directory.
case directory
/// FIFO special file.
case fifo
/// Hard link.
case hardLink
/// Regular file.
case regular
/// Socket.
case socket
/// Symbolic link.
case symbolicLink
/// Entry type is unknown.
case unknown
/// This initalizer's semantics assume conversion from UNIX type, which, by definition, doesn't have `unknown` type.
init?(_ unixType: UInt32) {
switch unixType {
case 0o010000:
self = .fifo
case 0o020000:
self = .characterSpecial
case 0o040000:
self = .directory
case 0o060000:
self = .blockSpecial
case 0o100000:
self = .regular
case 0o120000:
self = .symbolicLink
case 0o140000:
self = .socket
default:
return nil
}
}
}
| 23.166667 | 120 | 0.586731 |
dddaca863c6d2d5b2c214683a1985841dca5e64e | 464 | //
// Style.swift
// ForYouAndMe
//
// Created by Leonardo Passeri on 30/04/2020.
// Copyright © 2020 Balzo srl. All rights reserved.
//
import UIKit
public protocol View {}
extension UIView: View {}
public extension View {
func apply(style: Style<Self>) {
style.stylize(self)
}
}
public class Style<T> {
let stylize: ((T) -> Void)
public init(stylize: @escaping (T) -> Void) {
self.stylize = stylize
}
}
| 16 | 52 | 0.601293 |
4603cc01d11690771938429b978376c6d00267df | 1,188 | //
// StateAssembly.swift
// weather_forecast
//
// Created by Thinh Nguyen on 9/30/20.
// Copyright © 2020 Thinh Nguyen. All rights reserved.
// Email: [email protected]
//
import Foundation
import Swinject
import ReSwift
import RxSwift
final class StateAssembly {
}
// MARK: - Assembly
extension StateAssembly: Assembly {
func assemble(container: Container) {
Log.debug(message: "[StateAssembly] was initialized")
// MARK: - Forecast Section
// MARK: GetForecastObservable
container.register(GetForecastObservable.self, name: ForecastStateType.GetForecast.rawValue) { r in
let appStateStore: Store<AppState> = r.resolve(Store.self)!
return appStateStore.state.forecastState.getForecastState.asObservable()
}
// MARK: GetForecastByCoordinateObservable
container.register(GetForecastByCoordinateObservable.self, name: ForecastStateType.GetForecastByCoordinate.rawValue) { r in
let appStateStore: Store<AppState> = r.resolve(Store.self)!
return appStateStore.state.forecastState.getForecastByCoordinateState.asObservable()
}
}
}
| 31.263158 | 131 | 0.701178 |
fbe8fae19ff8c40611ad94b1e925e866db6db8c1 | 777 | // RUN: %target-swift-frontend -emit-ir -verify %s
// RUN: %target-swift-frontend -emit-ir -verify -disable-requirement-machine-concrete-contraction %s
protocol P1 {
associatedtype A2 : P2 where A2.A1 == Self
}
protocol P2 {
associatedtype A1 : P1 where A1.A2 == Self
var property: Int { get }
}
extension P2 {
var property: Int { return 0 }
}
class C1 : P1 {
// expected-warning@-1 {{non-final class 'C1' cannot safely conform to protocol 'P1', which requires that 'Self.A2.A1' is exactly equal to 'Self'; this is an error in Swift 6}}
class A2 : P2 {
// expected-warning@-1 {{non-final class 'C1.A2' cannot safely conform to protocol 'P2', which requires that 'Self.A1.A2' is exactly equal to 'Self'; this is an error in Swift 6}}
typealias A1 = C1
}
}
| 32.375 | 181 | 0.687259 |
eb8274aadc2048b9d70c79e6b1d400548affb2e2 | 878 | //
// VidePlayerView.swift
// Youtube Transition
//
// Created by 王庆华 on 2021/10/8.
//
import SwiftUI
import AVKit
struct VidePlayerView: UIViewControllerRepresentable {
var video :String
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
var bound_url = Bundle.main.path(forResource: video, ofType: "mp4")
let video_url = URL(fileURLWithPath: bound_url!)
let player = AVPlayer(url: video_url)
controller.player = player
controller.showsPlaybackControls = true
controller.videoGravity = .resizeAspectFill
controller.player?.play()
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
}
| 23.72973 | 95 | 0.646925 |
11170978060cfb74e081668884bcb5f903cf9f4e | 749 | //
// InstructionsSubtitleTableViewCell.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 11/6/16.
// Copyright © 2016 MercadoPago. All rights reserved.
//
import UIKit
class InstructionsSubtitleTableViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
title.font = Utils.getFont(size: title.font.pointSize)
title.text = ""
}
func fillCell(instruction: Instruction) {
if instruction.hasSubtitle() {
let attributedTitle = NSMutableAttributedString(string: instruction.subtitle!, attributes: [NSFontAttributeName: Utils.getFont(size: 22)])
self.title.attributedText = attributedTitle
}
}
}
| 26.75 | 150 | 0.686248 |
0a2118251f94e559822ecebb919a65a8225f1ea9 | 3,625 | //
// PostFeedVC.swift
// SiskaLabs
//
// Created by S on 11/17/20.
//
import UIKit
public class PostFeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var posts = [Dictionary<String, Any>]()
var users = [Dictionary<String, Any>]()
var postImages = [Dictionary<String, Any>]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TextAndImageTableViewCell.nib(), forCellReuseIdentifier: TextAndImageTableViewCell.identifier)
tableView.register(TextOnlyTableViewCell.nib(), forCellReuseIdentifier: TextOnlyTableViewCell.identifier)
}
override func viewWillAppear(_ animated: Bool) {
self.returnAllPosts()
}
func returnAllPosts() {
CFDataService.instance.returnPosts { (returnedPosts) in
var postsArray = returnedPosts
postsArray.sort { ($0["publishDate"] as! String) > ($1["publishDate"] as! String) }
self.posts = postsArray
CFDataService.instance.returnUsers { (returnedUsers) in
self.users = returnedUsers
self.returnAllImages()
}
}
}
func returnAllImages() {
for post in self.posts {
let postImageID = post["postImageID"] as! String
if postImageID != "nil" {
StorageService.instance.fetchPostImageData(forID: postImageID) { (data) in
let dict = [postImageID: UIImage(data: data)!]
self.postImages.append(dict)
self.tableView.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var poster = String()
var postImage = UIImage()
let post = self.posts[indexPath.row]
let postText = post["text"] as! String
let postImageID = post["postImageID"] as! String
for user in self.users {
if user["uid"] as! String == post["posterUID"] as! String {
let returnedPoster = user["name"] as! String
let publishDate = determineDateFormat(dateAsString: post["publishDate"] as! String)
poster = returnedPoster + " | " + publishDate
}
}
if postImageID == "nil" {
let cell = tableView.dequeueReusableCell(withIdentifier: TextOnlyTableViewCell.identifier, for: indexPath) as! TextOnlyTableViewCell
cell.configureTextOnlyCell(poster: poster, text: postText)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: TextAndImageTableViewCell.identifier, for: indexPath) as! TextAndImageTableViewCell
for image in self.postImages {
if let img = image[post["postImageID"] as! String] {
postImage = img as! UIImage
}
}
cell.configureTextAndImageCell(poster: poster, text: postText, image: postImage)
return cell
}
}
func determineDateFormat(dateAsString: String) -> String {
let receivedDate = Double(dateAsString)!
let eventDate = Date(timeIntervalSince1970: receivedDate)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let dateString = dateFormatter.string(from: eventDate)
return dateString
}
}
| 34.52381 | 152 | 0.615172 |
71fc7536c1f56499e183c3d9479a74fa48d89cec | 1,188 | //
// DFA.swift
// ParsecMock
//
// Created by Keith on 2018/7/10.
// Copyright © 2018 Keith. All rights reserved.
//
import PaversFRP
public struct DFA<State, Sym>
where State: Hashable, Sym: Hashable {
public let alphabet: Set<Sym>
public let transition: (State, Sym) -> State
public let initial: State
public let finals: Set<State>
}
extension DFA {
public var accessibleStates : Set<State> {
var preAccessibleStates: Set<State> = [initial]
var currentAccessibleStates: Set<State> = [initial]
var newAddedStates: Set<State> = [initial]
repeat {
preAccessibleStates = currentAccessibleStates
newAddedStates = nextAccessibleStates(of: newAddedStates, with: transition, and: alphabet)
currentAccessibleStates = newAddedStates <> currentAccessibleStates
} while currentAccessibleStates != preAccessibleStates
return currentAccessibleStates
}
}
extension DFA {
public func extendedTransition<C>(_ state: State, _ symbols: C) -> State
where C: BidirectionalCollection, C.Element == Sym {
guard let a = symbols.last else { return state }
return transition(extendedTransition(state, symbols.dropLast()), a)
}
}
| 29.7 | 96 | 0.717172 |
8f8f76b7af135cec33344eab8a0bbf9416df91b7 | 876 | //
// Topic.swift
// RubyChina
//
// Created by Jianqiu Xiao on 2018/3/23.
// Copyright © 2018 Jianqiu Xiao. All rights reserved.
//
import Ladybug
struct Topic: JSONCodable {
var id: Int?
var title: String?
var createdAt: Date?
var repliesCount: Int?
var repliedAt: Date?
var nodeId: Int?
var nodeName: String?
var body: String?
var bodyHTML: String?
var hits: Int?
var abilities: Ability?
var user: User?
static let transformersByPropertyKey: [PropertyKey: JSONTransformer] = [
"createdAt": "created_at" <- format("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"),
"repliesCount": "replies_count",
"repliedAt": "replied_at" <- format("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"),
"nodeId": "node_id",
"nodeName": "node_name",
"bodyHTML": "body_html",
"user": User.transformer,
]
}
| 24.333333 | 78 | 0.618721 |
5643c3e35a7b087b028605919a6d90ffcd6eb9d1 | 3,307 | //
// AuthenticationClient+Check.swift
// SwiftyAuthingExample
//
// Created by XiangWei on 2021/9/10.
//
import Apollo
import Alamofire
extension AuthenticationClient
{
//MARK:--检查密码强度
/// Check Password Strength.
/// 检查密码强度
/// - parameter password: 密码
/// - parameter completion: 服务器端返回的数据
/// - returns: N/A
///
/// 检查密码强度,详情请见: https://docs.authing.co/security/config-user-pool-password-level.html
///
public func checkPasswordStrength(password: String, completion: @escaping ((GraphQLResult<CheckPasswordStrengthQuery.Data>) -> Void)) {
Network.shared.apollo.fetch(query: CheckPasswordStrengthQuery(password: password), cachePolicy: self.cachePolicy ?? .fetchIgnoringCacheCompletely) { result in
switch result {
case .failure(let error):
print("Failure: \(error)")
case .success(let graphQLResult):
completion(graphQLResult)
print("\(#function) success")
}
}
}
/// Check Password Strength.
/// 检查密码强度
/// - parameter password: 密码
/// - parameter completion: 服务器端返回的数据
/// - returns: N/A
///
/// 检查密码强度,详情请见: https://docs.authing.co/security/config-user-pool-password-level.html
///
public func checkPasswordStrengthWithResult(password: String, completion: @escaping ((Result<GraphQLResult<CheckPasswordStrengthQuery.Data>, Error>) -> Void)) {
Network.shared.apollo.fetch(query: CheckPasswordStrengthQuery(password: password), cachePolicy: self.cachePolicy ?? .fetchIgnoringCacheCompletely) { result in
completion(result)
print("\(#function) success")
}
}
//MARK:--检测 Token 登录状态
/// Check Login Status.
/// 检测 Token 登录状态
/// - parameter token: token 用户的登录凭证 token
/// - parameter completion: 服务器端返回的数据
/// - returns: N/A
///
/// 检测 Token 登录状态
///
public func checkLoginStatus(token: String, completion: @escaping ((GraphQLResult<CheckLoginStatusQuery.Data>) -> Void)) {
UserDefaults.standard.setValue("", forKey: Config.keyAccessToken)
Network.shared.apollo.fetch(query: CheckLoginStatusQuery(token: token), cachePolicy: self.cachePolicy ?? .fetchIgnoringCacheCompletely) { result in
switch result {
case .failure(let error):
print("Failure: \(error)")
case .success(let graphQLResult):
completion(graphQLResult)
print("\(#function) success")
}
}
}
/// Check Login Status.
/// 检测 Token 登录状态
/// - parameter token: token 用户的登录凭证 token
/// - parameter completion: 服务器端返回的数据
/// - returns: N/A
///
/// 检测 Token 登录状态
///
public func checkLoginStatusWithResult(token: String, completion: @escaping ((Result<GraphQLResult<CheckLoginStatusQuery.Data>, Error>) -> Void)) {
UserDefaults.standard.setValue("", forKey: Config.keyAccessToken)
Network.shared.apollo.fetch(query: CheckLoginStatusQuery(token: token), cachePolicy: self.cachePolicy ?? .fetchIgnoringCacheCompletely) { result in
completion(result)
print("\(#function) success")
}
}
}
| 36.340659 | 166 | 0.6202 |
2311084c69c86c8a70d590717d2986cafc5bf9ce | 59,732 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import XCTest
import Amplify
import AmplifyPlugins
import AWSPluginsCore
import AWSCore
import AWSMobileClient
@testable import amplify_auth_cognito
// Test Data
var _data: NSMutableDictionary = [:]
var _args: Dictionary<String, Any> = [:]
var _attributes: Dictionary<String, String> = [:]
var _options: Dictionary<String, Any> = [:]
let _username: String = "testuser"
let _password: String = "mytestpassword"
let _newPassword: String = "newPassword"
let _oldPassword: String = "oldPassword"
let _email: String = "[email protected]"
let _phoneNumber: String = "+15555555555"
let _confirmationCode: String = "confirmationCode"
let _userId: String = "123"
let _accessKey: String = "myAccessKey"
let _secretKey: String = "mySecretKey"
let _idToken: String = "myToken"
let _accessToken: String = "myAccessToken"
let _refreshToken: String = "myRefreshToken"
class amplify_auth_cognito_tests: XCTestCase {
var plugin: SwiftAuthCognito = SwiftAuthCognito()
var mockCognito: AuthCognitoBridge = AuthCognitoBridge()
var errorHandler: AuthErrorHandler = AuthErrorHandler()
override func setUpWithError() throws {
plugin = SwiftAuthCognito.init(cognito: mockCognito)
_data = [:]
_args = ["data" : _data]
_attributes = [:]
_options = [:]
}
override func tearDownWithError() throws {}
func test_signUpSuccessEmail() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let signUpRes = Result<AuthSignUpResult,AuthError>.success(
AuthSignUpResult(AuthSignUpStep.confirmUser(AuthCodeDeliveryDetails(destination: DeliveryDestination.email(_email)), ["foo": "bar"])))
let signUpData = FlutterSignUpResult(res: signUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["email" : _email]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( false, res.isSignUpComplete )
XCTAssertEqual( "CONFIRM_SIGN_UP_STEP", res.signUpStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual(_email, codeDeliveryJson["destination"]!)
XCTAssertEqual("bar", additionalInfoJson["foo"]!)
} else {
XCTFail()
}
})
}
func test_signUpSuccessPhone() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let signUpRes = Result<AuthSignUpResult,AuthError>.success(
AuthSignUpResult(AuthSignUpStep.confirmUser(AuthCodeDeliveryDetails(destination: DeliveryDestination.phone(_phoneNumber)), ["foo": "bar"])))
let signUpData = FlutterSignUpResult(res: signUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["phone_number" : _phoneNumber]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( false, res.isSignUpComplete )
XCTAssertEqual( "CONFIRM_SIGN_UP_STEP", res.signUpStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual(_phoneNumber, codeDeliveryJson["destination"]!)
XCTAssertEqual("bar", additionalInfoJson["foo"]!)
} else {
XCTFail()
}
})
}
func test_signUpSuccessSMS() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let signUpRes = Result<AuthSignUpResult,AuthError>.success(
AuthSignUpResult(AuthSignUpStep.confirmUser(AuthCodeDeliveryDetails(destination: DeliveryDestination.sms(_phoneNumber)), ["foo": "bar"])))
let signUpData = FlutterSignUpResult(res: signUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["sms" : _phoneNumber]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( false, res.isSignUpComplete )
XCTAssertEqual( "CONFIRM_SIGN_UP_STEP", res.signUpStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
XCTAssertEqual(_phoneNumber, codeDeliveryJson["destination"]!)
} else {
XCTFail()
}
})
}
func test_signUpSuccessCustom() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let signUpRes = Result<AuthSignUpResult,AuthError>.success(
AuthSignUpResult(AuthSignUpStep.confirmUser(AuthCodeDeliveryDetails(destination: DeliveryDestination.unknown(_phoneNumber)), ["foo": "bar"])))
let signUpData = FlutterSignUpResult(res: signUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["custom" : _phoneNumber]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( false, res.isSignUpComplete )
XCTAssertEqual( "CONFIRM_SIGN_UP_STEP", res.signUpStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
XCTAssertEqual(_phoneNumber, codeDeliveryJson["destination"]!)
} else {
XCTFail()
}
})
}
func test_signUpSuccessComplete() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let signUpRes = Result<AuthSignUpResult,AuthError>.success(AuthSignUpResult(AuthSignUpStep.done))
let signUpData = FlutterSignUpResult(res: signUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["email" : _email]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( "DONE", res.signUpStep)
XCTAssertEqual( true, res.isSignUpComplete)
} else {
XCTFail()
}
})
}
func test_signUpValidation() {
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
var rawData: NSMutableDictionary = ["options":rawOptions]
// Throws with no password
XCTAssertThrowsError(try FlutterSignUpRequest.validate(dict: rawData))
// Throws with no options
rawData = ["password": _password]
XCTAssertThrowsError(try FlutterSignUpRequest.validate(dict: rawData))
}
func test_signUpFormatAttributes() {
let rawAttributes: Dictionary<String, Any> = ["email": _email, "customAttribute": "female"]
let rawOptions: Dictionary<String, Any> = ["userAttributes": rawAttributes]
let rawData: NSMutableDictionary = ["options":rawOptions, "username": _username, "password": _password]
let request = FlutterSignUpRequest(dict: rawData);
XCTAssertEqual(2, request.userAttributes.count)
}
func test_signUpError() {
class SignUpMock: AuthCognitoBridge {
override func onSignUp(flutterResult: @escaping FlutterResult, request: FlutterSignUpRequest){
let authError = AuthError.service("Username exists", MockErrorConstants.userNameExistsError, AWSCognitoAuthError.usernameExists)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: SignUpMock())
_attributes = ["email" : _email]
_options = ["userAttributes": _attributes]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "UsernameExistsException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.usernameExists)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.userNameExistsError, details?["recoverySuggestion"])
XCTAssertEqual( "Username exists", details?["message"])
} else {
XCTFail()
}
})
}
func test_confirmSignUpSuccess() {
class ConfirmSignUpMock: AuthCognitoBridge {
override func onConfirmSignUp(flutterResult: @escaping FlutterResult, request: FlutterConfirmSignUpRequest){
let confirmSignUpRes = Result<AuthSignUpResult,AuthError>.success(AuthSignUpResult(AuthSignUpStep.done))
let signUpData = FlutterSignUpResult(res: confirmSignUpRes)
flutterResult(signUpData)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmSignUpMock())
_data = [
"username": _username,
"confirmationCode": _confirmationCode,
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmSignUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignUpResult {
XCTAssertEqual( true, res.isSignUpComplete )
XCTAssertEqual( "DONE", res.signUpStep)
} else {
XCTFail()
}
})
}
func test_confirmSignUpError() {
class ConfirmSignUpMock: AuthCognitoBridge {
override func onConfirmSignUp(flutterResult: @escaping FlutterResult, request: FlutterConfirmSignUpRequest){
let authError = AuthError.service("Code expired", MockErrorConstants.codeExpiredError, AWSCognitoAuthError.codeExpired)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmSignUpMock())
_data = [
"username": _username,
"confirmationCode": _confirmationCode,
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmSignUp", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "CodeExpiredException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.codeExpired)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.codeExpiredError, details?["recoverySuggestion"])
XCTAssertEqual( "Code expired", details?["message"])
} else {
XCTFail()
}
})
}
func test_confirmSignUpValidation() {
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
var rawData: NSMutableDictionary = ["username": _username]
// Throws with no confirmation code
XCTAssertThrowsError(try FlutterConfirmSignUpRequest.validate(dict: rawData))
// Throws with no username
rawData = ["confirmationCode": _confirmationCode]
XCTAssertThrowsError(try FlutterConfirmSignUpRequest.validate(dict: rawData))
// Succeeds with options
rawData = ["options": rawOptions]
XCTAssertNoThrow(try FlutterConfirmSignUpRequest.validate(dict: rawData))
}
func test_resendSignUpCodeSuccessEmail() {
class ResendSignUpCodeMock: AuthCognitoBridge {
override func onResendSignUpCode(flutterResult: @escaping FlutterResult, request: FlutterResendSignUpCodeRequest) {
let resendCodeRes = Result<AuthCodeDeliveryDetails, AuthError>.success(AuthCodeDeliveryDetails(destination: DeliveryDestination.email(_email)))
let resendData = FlutterResendSignUpCodeResult(res: resendCodeRes)
flutterResult(resendData)
}
}
plugin = SwiftAuthCognito.init(cognito: ResendSignUpCodeMock())
_data = ["username": _username]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resendSignUpCode", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterResendSignUpCodeResult {
XCTAssertEqual( _email, res.codeDeliveryDetails["destination"] )
XCTAssertEqual( "email", res.codeDeliveryDetails["attributeName"] )
XCTAssertEqual( _email, (res.toJSON()["codeDeliveryDetails"] as! [String: String])["destination"])
} else {
XCTFail()
}
})
}
func test_resendSignUpCodeSuccessSMS() {
class ResendSignUpCodeMock: AuthCognitoBridge {
override func onResendSignUpCode(flutterResult: @escaping FlutterResult, request: FlutterResendSignUpCodeRequest) {
let resendCodeRes = Result<AuthCodeDeliveryDetails, AuthError>.success(AuthCodeDeliveryDetails(destination: DeliveryDestination.sms(_phoneNumber)))
let resendData = FlutterResendSignUpCodeResult(res: resendCodeRes)
flutterResult(resendData)
}
}
plugin = SwiftAuthCognito.init(cognito: ResendSignUpCodeMock())
_data = ["username": "sms"]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resendSignUpCode", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterResendSignUpCodeResult {
XCTAssertEqual( _phoneNumber, res.codeDeliveryDetails["destination"] )
XCTAssertEqual( "sms", res.codeDeliveryDetails["attributeName"] )
XCTAssertEqual( _phoneNumber, (res.toJSON()["codeDeliveryDetails"] as! [String: String])["destination"])
} else {
XCTFail()
}
})
}
func test_resendSignUpCodeSuccessCustom() {
class ResendSignUpCodeMock: AuthCognitoBridge {
override func onResendSignUpCode(flutterResult: @escaping FlutterResult, request: FlutterResendSignUpCodeRequest) {
let resendCodeRes = Result<AuthCodeDeliveryDetails, AuthError>.success(AuthCodeDeliveryDetails(destination: DeliveryDestination.unknown(_phoneNumber)))
let resendData = FlutterResendSignUpCodeResult(res: resendCodeRes)
flutterResult(resendData)
}
}
plugin = SwiftAuthCognito.init(cognito: ResendSignUpCodeMock())
_data = ["username": "custom"]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resendSignUpCode", arguments: _args)
plugin.handle( call, result: {(result)->Void in
if let res = result as? FlutterResendSignUpCodeResult {
XCTAssertEqual( _phoneNumber, res.codeDeliveryDetails["destination"] )
XCTAssertEqual( "unknown", res.codeDeliveryDetails["attributeName"] )
XCTAssertEqual( _phoneNumber, (res.toJSON()["codeDeliveryDetails"] as! [String: String])["destination"])
} else {
XCTFail()
}
})
}
func test_resendSignUpCodeSuccessPhone() {
class ResendSignUpCodeMock: AuthCognitoBridge {
override func onResendSignUpCode(flutterResult: @escaping FlutterResult, request: FlutterResendSignUpCodeRequest) {
let resendCodeRes = Result<AuthCodeDeliveryDetails, AuthError>.success(AuthCodeDeliveryDetails(destination: DeliveryDestination.phone(_phoneNumber)))
let resendData = FlutterResendSignUpCodeResult(res: resendCodeRes)
flutterResult(resendData)
}
}
plugin = SwiftAuthCognito.init(cognito: ResendSignUpCodeMock())
_data = ["username": "phone"]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resendSignUpCode", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterResendSignUpCodeResult {
XCTAssertEqual( _phoneNumber, res.codeDeliveryDetails["destination"] )
XCTAssertEqual( "phone", res.codeDeliveryDetails["attributeName"] )
XCTAssertEqual( _phoneNumber, (res.toJSON()["codeDeliveryDetails"] as! [String: String])["destination"])
} else {
XCTFail()
}
})
}
func test_resendSignUpCodeError() {
class ResendSignUpCodeMock: AuthCognitoBridge {
override func onResendSignUpCode(flutterResult: @escaping FlutterResult, request: FlutterResendSignUpCodeRequest) {
let authError = AuthError.service("Could not deliver code", MockErrorConstants.codeDeliveryError, AWSCognitoAuthError.codeDelivery)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: ResendSignUpCodeMock())
_data = ["username": _username]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resendSignUpCode", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "CodeDeliveryFailureException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.codeDelivery)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.codeDeliveryError, details?["recoverySuggestion"])
XCTAssertEqual( "Could not deliver code", details?["message"])
} else {
XCTFail()
}
})
}
func test_signInSuccessSMS() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let signInRes = Result<AuthSignInResult, AuthError>.success(
AuthSignInResult(nextStep:
AuthSignInStep.confirmSignInWithSMSMFACode(AuthCodeDeliveryDetails(destination: DeliveryDestination.sms(_phoneNumber)), ["foo": "bar"]))
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_options = ["email": _email]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( false, res.isSignedIn )
XCTAssertEqual( "CONFIRM_SIGN_IN_WITH_SMS_MFA_CODE", res.signInStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual(_phoneNumber, codeDeliveryJson["destination"]!)
XCTAssertEqual("bar", additionalInfoJson["foo"])
} else {
XCTFail()
}
})
}
func test_signInSuccessResetPassword() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let signInRes = Result<AuthSignInResult, AuthError>.success(
AuthSignInResult(nextStep:
AuthSignInStep.resetPassword(["foo": "bar"]))
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_options = ["delivery": "resetPassword"]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( false, res.isSignedIn )
XCTAssertEqual( "RESET_PASSWORD", res.signInStep)
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual("bar", additionalInfoJson["foo"])
} else {
XCTFail()
}
})
}
func test_signInSuccessCustomChallenge() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let signInRes = Result<AuthSignInResult, AuthError>.success(
AuthSignInResult(nextStep:
AuthSignInStep.confirmSignInWithCustomChallenge(["foo": "bar"]))
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_options = ["delivery": "confirmSignInWithCustomChallenge"]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( false, res.isSignedIn )
XCTAssertEqual( "CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE", res.signInStep)
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual("bar", additionalInfoJson["foo"])
} else {
XCTFail()
}
})
}
func test_signInSuccessNewPassword() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let signInRes = Result<AuthSignInResult, AuthError>.success(
AuthSignInResult(nextStep:
AuthSignInStep.confirmSignInWithNewPassword(["foo": "bar"]))
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_options = ["delivery": "confirmSignInWithNewPassword"]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( false, res.isSignedIn )
XCTAssertEqual( "CONFIRM_SIGN_IN_WITH_NEW_PASSWORD", res.signInStep)
let additionalInfoJson = ((res.toJSON()["nextStep"] as! [String: Any])["additionalInfo"] as! [String: String])
XCTAssertEqual("bar", additionalInfoJson["foo"])
} else {
XCTFail()
}
})
}
func test_signInSuccessDone() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let signInRes = Result<AuthSignInResult, AuthError>.success(
AuthSignInResult(nextStep:
AuthSignInStep.done)
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_options = ["delivery": "done"]
_data = [
"username": _username,
"password": _password,
"options": _options
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle( call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( true, res.isSignedIn )
XCTAssertEqual( "DONE", res.signInStep)
} else {
XCTFail()
}
})
}
func test_signInValidation() {
var rawData: NSMutableDictionary = ["username":_username]
// Throws with username only
XCTAssertThrowsError(try FlutterSignInRequest.validate(dict: rawData))
// Throws with password only
rawData = ["password": _password]
XCTAssertThrowsError(try FlutterSignInRequest.validate(dict: rawData))
// Succeeds with options only
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
rawData = ["options": rawOptions]
XCTAssertNoThrow(try FlutterSignInRequest.validate(dict: rawData))
}
func test_signInError() {
class SignInMock: AuthCognitoBridge {
override func onSignIn(flutterResult: @escaping FlutterResult, request: FlutterSignInRequest) {
let authError = AuthError.service("Reset password", MockErrorConstants.passwordResetRequired, AWSCognitoAuthError.passwordResetRequired)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInMock())
_data = [
"username": _username,
"password": _password,
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "PasswordResetRequiredException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.passwordResetRequired)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.passwordResetRequired, details?["recoverySuggestion"])
XCTAssertEqual( "Reset password", details?["message"])
} else {
XCTFail()
}
})
}
func test_confirmSignInSuccess() {
class ConfirmSignInMock: AuthCognitoBridge {
override func onConfirmSignIn(flutterResult: @escaping FlutterResult, request: FlutterConfirmSignInRequest) {
let confirmSignUpRes = Result<AuthSignInResult,AuthError>.success(AuthSignInResult(nextStep: AuthSignInStep.done))
let signInData = FlutterSignInResult(res: confirmSignUpRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmSignInMock())
_data = ["confirmationCode": _confirmationCode]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmSignIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( true, res.isSignedIn )
XCTAssertEqual( "DONE", res.signInStep)
} else {
XCTFail()
}
})
}
func test_confirmSignInError() {
class ConfirmSignInMock: AuthCognitoBridge {
override func onConfirmSignIn(flutterResult: @escaping FlutterResult, request: FlutterConfirmSignInRequest) {
let authError = AuthError.service("Could not deliver code", MockErrorConstants.codeDeliveryError, AWSCognitoAuthError.codeDelivery)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmSignInMock())
_data = ["confirmationCode": _confirmationCode]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmSignIn", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "CodeDeliveryFailureException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.codeDelivery)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.codeDeliveryError, details?["recoverySuggestion"])
XCTAssertEqual( "Could not deliver code", details?["message"])
} else {
XCTFail()
}
})
}
func test_confirmSignInValidation() {
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
var rawData: NSMutableDictionary = [:]
// Throws with no confirmation code
XCTAssertThrowsError(try FlutterConfirmSignInRequest.validate(dict: rawData))
// Succeeds with options
rawData = ["options": rawOptions]
XCTAssertNoThrow(try FlutterConfirmSignInRequest.validate(dict: rawData))
}
func test_updatePasswordSuccess() {
class UpdatePasswordMock: AuthCognitoBridge {
override func onUpdatePassword(flutterResult: @escaping FlutterResult, request: FlutterUpdatePasswordRequest) {
let emptyMap: Dictionary<String, Any> = [:]
flutterResult(emptyMap)
}
}
plugin = SwiftAuthCognito.init(cognito: UpdatePasswordMock())
_data = [
"oldPassword": _oldPassword,
"newPassword": _newPassword,
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "updatePassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? Dictionary<String, Any> {
XCTAssertEqual( 0, res.count )
} else {
XCTFail()
}
})
}
func test_updatePasswordValidation() {
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
var rawData: NSMutableDictionary = ["oldPassword": _oldPassword]
// Throws without newpassword
XCTAssertThrowsError(try FlutterUpdatePasswordRequest.validate(dict: rawData))
// Throws without oldpassword
rawData = ["newPassword": _newPassword]
XCTAssertThrowsError(try FlutterUpdatePasswordRequest.validate(dict: rawData))
// Succeeds with options
rawData = ["options": rawOptions]
XCTAssertNoThrow(try FlutterUpdatePasswordRequest.validate(dict: rawData))
}
func test_updatePasswordError() {
class UpdatePasswordMock: AuthCognitoBridge {
override func onUpdatePassword(flutterResult: @escaping FlutterResult, request: FlutterUpdatePasswordRequest) {
let authError = AuthError.service("Invalid password", MockErrorConstants.invalidPasswordError, AWSCognitoAuthError.invalidPassword)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: UpdatePasswordMock())
_data = [
"oldPassword": _oldPassword,
"newPassword": _newPassword,
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "updatePassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "InvalidPasswordException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.invalidPassword)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.invalidPasswordError, details?["recoverySuggestion"])
XCTAssertEqual( "Invalid password", details?["message"])
} else {
XCTFail()
}
})
}
func test_resetPasswordSuccess() {
class ResetPasswordMock: AuthCognitoBridge {
override func onResetPassword(flutterResult: @escaping FlutterResult, request: FlutterResetPasswordRequest) {
let resetRes = Result<AuthResetPasswordResult,AuthError>.success(
AuthResetPasswordResult(
isPasswordReset: true,
nextStep: AuthResetPasswordStep.confirmResetPasswordWithCode(
AuthCodeDeliveryDetails(destination: DeliveryDestination.email("[email protected]")),
nil)
)
)
let resetData = FlutterResetPasswordResult(res: resetRes)
flutterResult(resetData)
}
}
plugin = SwiftAuthCognito.init(cognito: ResetPasswordMock())
_data = ["username": _username]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resetPassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterResetPasswordResult {
XCTAssertEqual( true, res.isPasswordReset )
XCTAssertEqual( "CONFIRM_RESET_PASSWORD_WITH_CODE", res.resetPasswordStep)
let codeDeliveryJson = ((res.toJSON()["nextStep"] as! [String: Any])["codeDeliveryDetails"] as! [String: String])
XCTAssertEqual(_email, codeDeliveryJson["destination"])
} else {
XCTFail()
}
})
}
func test_resetPasswordValidation() {
var rawData: NSMutableDictionary = [:]
// Throws with no args
XCTAssertThrowsError(try FlutterResetPasswordRequest.validate(dict: rawData))
// Succeeds with options
let rawOptions: Dictionary<String, Any> = ["foo": "bar"]
rawData = ["options": rawOptions]
XCTAssertNoThrow(try FlutterResetPasswordRequest.validate(dict: rawData))
}
func test_resetPasswordError() {
class ResetPasswordMock: AuthCognitoBridge {
override func onResetPassword(flutterResult: @escaping FlutterResult, request: FlutterResetPasswordRequest) {
let authError = AuthError.service("Invalid password", MockErrorConstants.invalidPasswordError, AWSCognitoAuthError.invalidPassword)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: ResetPasswordMock())
_data = ["username": _username]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "resetPassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "InvalidPasswordException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.invalidPassword)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.invalidPasswordError, details?["recoverySuggestion"])
XCTAssertEqual( "Invalid password", details?["message"])
} else {
XCTFail()
}
})
}
func test_confirmPasswordSuccess() {
class ConfirmPasswordMock: AuthCognitoBridge {
override func onConfirmPassword(flutterResult: @escaping FlutterResult, request: FlutterConfirmPasswordRequest) {
let emptyMap: Dictionary<String, Any> = [:]
flutterResult(emptyMap)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmPasswordMock())
_data = [
"username": _username,
"newPassword": _newPassword,
"confirmationCode": _confirmationCode
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmPassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? Dictionary<String, Any> {
XCTAssertEqual( 0, res.count )
} else {
XCTFail()
}
})
}
func test_confirmPasswordValidation() {
var rawData: NSMutableDictionary = ["username": _username, "confirmationCode" : _confirmationCode]
// Throws with no password
XCTAssertThrowsError(try FlutterConfirmPasswordRequest.validate(dict: rawData))
// Throws with no username
rawData = ["newPassword": _newPassword, "confirmationCode" : _confirmationCode]
XCTAssertThrowsError(try FlutterConfirmPasswordRequest.validate(dict: rawData))
// Throws without code
rawData = ["newPassword": _newPassword, "username" : _username]
XCTAssertThrowsError(try FlutterConfirmPasswordRequest.validate(dict: rawData))
// Succeeds with required params
rawData = ["newPassword": _newPassword, "username" : _username, "confirmationCode" : _confirmationCode]
XCTAssertNoThrow(try FlutterConfirmPasswordRequest.validate(dict: rawData))
}
func test_confirmPasswordError() {
class ConfirmPasswordMock: AuthCognitoBridge {
override func onConfirmPassword(flutterResult: @escaping FlutterResult, request: FlutterConfirmPasswordRequest) {
let authError = AuthError.service("Invalid parameter", MockErrorConstants.invalidParameterError, AWSCognitoAuthError.invalidParameter)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: ConfirmPasswordMock())
_data = [
"username": _username,
"newPassword": _newPassword,
"confirmationCode": _confirmationCode
]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "confirmPassword", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "InvalidParameterException", res.code )
XCTAssertEqual( "Optional(AmplifyPlugins.AWSCognitoAuthError.invalidParameter)", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.invalidParameterError, details?["recoverySuggestion"])
XCTAssertEqual( "Invalid parameter", details?["message"])
} else {
XCTFail()
}
})
}
func test_signOutSuccess() {
class SignOutMock: AuthCognitoBridge {
override func onSignOut(flutterResult: @escaping FlutterResult, request: FlutterSignOutRequest) {
let emptyMap: Dictionary<String, Any> = [:]
flutterResult(emptyMap)
}
}
plugin = SwiftAuthCognito.init(cognito: SignOutMock())
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signOut", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? Dictionary<String, Any> {
XCTAssertEqual( 0, res.count )
} else {
XCTFail()
}
})
}
func test_signOutError() {
class SignOutMock: AuthCognitoBridge {
override func onSignOut(flutterResult: @escaping FlutterResult, request: FlutterSignOutRequest) {
let authError = AuthError.invalidState("Invalid state", MockErrorConstants.invalidStateError, nil)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: SignOutMock())
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signOut", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "AuthException", res.code )
XCTAssertEqual( "nil", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.invalidStateError, details?["recoverySuggestion"])
XCTAssertEqual( "Invalid state", details?["message"])
} else {
XCTFail()
}
})
}
func test_getCurrentUserSuccess() {
class CurrentUserMock: AuthCognitoBridge {
override func onGetCurrentUser(flutterResult: @escaping FlutterResult) {
struct TestUser: AuthUser {
public var username: String
public var userId: String
}
let resetRes = TestUser(username: _username, userId: _userId)
let resetData = FlutterAuthUserResult(res: resetRes)
flutterResult(resetData)
}
}
plugin = SwiftAuthCognito.init(cognito: CurrentUserMock())
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "getCurrentUser" , arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterAuthUserResult {
XCTAssertEqual( _username, res.username )
XCTAssertEqual( _userId, res.userId)
XCTAssertEqual( _userId, res.toJSON()["userId"] as! String)
} else {
XCTFail()
}
})
}
func test_getCurrentUserError() {
class CurrentUserMock: AuthCognitoBridge {
override func onGetCurrentUser(flutterResult: @escaping FlutterResult) {
let authError = AuthError.invalidState("Invalid state", MockErrorConstants.invalidStateError, nil)
errorHandler.handleAuthError(authError: authError, flutterResult: flutterResult)
}
}
plugin = SwiftAuthCognito.init(cognito: CurrentUserMock())
let call = FlutterMethodCall(methodName: "getCurrentUser", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterError {
let details = res.details as? Dictionary<String, String>
XCTAssertEqual( "AuthException", res.code )
XCTAssertEqual( "nil", details?["underlyingException"])
XCTAssertEqual( MockErrorConstants.invalidStateError, details?["recoverySuggestion"])
XCTAssertEqual( "Invalid state", details?["message"])
} else {
XCTFail()
}
})
}
func test_fetchCognitoSessionSuccess() {
class FetchSessionMock: AuthCognitoBridge {
override func onFetchSession(flutterResult: @escaping FlutterResult, request: FlutterFetchSessionRequest) {
let creds = FakeCredentials(accessKey: _accessKey, secretKey: _secretKey)
let tokens = FakeTokens(idToken: _idToken, accessToken: _accessToken, refreshToken: _refreshToken)
let authSession = FakeCognitoSession(
isSignedIn: true,
userSubResult: .success("testsub"),
identityIdResult: .success("testid"),
awsCredentialsResult: Result<AuthAWSCredentials, AuthError>.success(creds),
cognitoTokensResult: Result<AuthCognitoTokens, AuthError>.success(tokens)
)
let sessionData = Result<AuthSession,AuthError>.success(authSession)
do {
let fetchSessionData = try FlutterFetchCognitoSessionResult(res: sessionData)
flutterResult(fetchSessionData)
} catch {
errorHandler.handleAuthError(authError: error as! AuthError, flutterResult: flutterResult)
}
}
}
plugin = SwiftAuthCognito.init(cognito: FetchSessionMock())
_options = ["getAWSCredentials": true]
_data = ["options": _options]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "fetchAuthSession", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterFetchCognitoSessionResult {
XCTAssertEqual(true, res.isSignedIn)
XCTAssertEqual("testid", res.identityId)
XCTAssertEqual("testsub", res.userSub)
XCTAssertEqual(5, res.toJSON().count)
} else {
XCTFail()
}
})
}
func test_fetchSessionSuccess() {
class FetchSessionMock: AuthCognitoBridge {
override func onFetchSession(flutterResult: @escaping FlutterResult, request: FlutterFetchSessionRequest) {
let authSession = FakeSession(isSignedIn: true)
let sessionData = Result<AuthSession,AuthError>.success(authSession)
do {
let signUpData = try FlutterFetchSessionResult(res: sessionData)
flutterResult(signUpData)
} catch {
errorHandler.handleAuthError(authError: error as! AuthError, flutterResult: flutterResult)
}
}
}
plugin = SwiftAuthCognito.init(cognito: FetchSessionMock())
_options = ["getAWSCredentials": false]
_data = ["options": _options]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "fetchAuthSession", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterFetchSessionResult {
XCTAssertEqual(true, res.isSignedIn)
XCTAssertEqual(true, res.toJSON()["isSignedIn"] as? Bool)
XCTAssertEqual(1, res.toJSON().count)
} else {
XCTFail()
}
})
}
func test_fetchSessionNoOptions() {
class FetchSessionMock: AuthCognitoBridge {
override func onFetchSession(flutterResult: @escaping FlutterResult, request: FlutterFetchSessionRequest) {
let authSession = FakeSession(isSignedIn: true)
let sessionData = Result<AuthSession,AuthError>.success(authSession)
do {
let signUpData = try FlutterFetchSessionResult(res: sessionData)
flutterResult(signUpData)
} catch {
errorHandler.handleAuthError(authError: error as! AuthError, flutterResult: flutterResult)
}
}
}
plugin = SwiftAuthCognito.init(cognito: FetchSessionMock())
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "fetchAuthSession", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterFetchSessionResult {
XCTAssertEqual(true, res.isSignedIn)
XCTAssertEqual(true, res.toJSON()["isSignedIn"] as? Bool)
XCTAssertEqual(1, res.toJSON().count)
} else {
XCTFail()
}
})
}
func test_guestAccess() {
class FetchSessionMock: AuthCognitoBridge {
override func onFetchSession(flutterResult: @escaping FlutterResult, request: FlutterFetchSessionRequest) {
let authError = AuthError.signedOut("", "")
let creds = FakeCredentials(accessKey: _accessKey, secretKey: _secretKey)
let authSession = FakeCognitoSession(
isSignedIn: false,
// guest access should result in userSub failure (i.e. no UserPool User)
userSubResult: .failure(authError),
identityIdResult: .success("testid"),
awsCredentialsResult: Result<AuthAWSCredentials, AuthError>.success(creds),
// guest access should result in cognito tokens failure (i.e. no UserPool User)
cognitoTokensResult: Result<AuthCognitoTokens, AuthError>.failure(authError)
)
let sessionData = Result<AuthSession,AuthError>.success(authSession)
do {
let fetchSessionData = try FlutterFetchCognitoSessionResult(res: sessionData)
flutterResult(fetchSessionData)
} catch {
errorHandler.handleAuthError(authError: error as! AuthError, flutterResult: flutterResult)
}
}
}
plugin = SwiftAuthCognito.init(cognito: FetchSessionMock())
_options = ["getAWSCredentials": false]
_data = ["options": _options]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "fetchAuthSession", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterFetchCognitoSessionResult {
XCTAssertEqual(false, res.toJSON()["isSignedIn"] as? Bool)
XCTAssertEqual("testid", res.toJSON()["identityId"] as? String)
// userSub error will result in map with one 'error' key
XCTAssertEqual(1, (res.toJSON()["tokens"] as? [String: String])!.count)
// credentials map should have access key and secret key
XCTAssertEqual(2, (res.toJSON()["credentials"] as? [String: String])!.count)
} else {
XCTFail()
}
})
}
func test_UserPoolOnly() {
class FetchSessionMock: AuthCognitoBridge {
override func onFetchSession(flutterResult: @escaping FlutterResult, request: FlutterFetchSessionRequest) {
let authError = AuthError.service("", "", AWSCognitoAuthError.invalidAccountTypeException)
let tokens = FakeTokens(idToken: _idToken, accessToken: _accessToken, refreshToken: _refreshToken)
let authSession = FakeCognitoSession(
isSignedIn: true,
userSubResult: .success("testsub"),
identityIdResult: .failure(authError),
awsCredentialsResult: Result<AuthAWSCredentials, AuthError>.failure(authError),
cognitoTokensResult: Result<AuthCognitoTokens, AuthError>.success(tokens)
)
let sessionData = Result<AuthSession,AuthError>.success(authSession)
do {
let fetchSessionData = try FlutterFetchCognitoSessionResult(res: sessionData)
flutterResult(fetchSessionData)
} catch {
errorHandler.handleAuthError(authError: error as! AuthError, flutterResult: flutterResult)
}
}
}
plugin = SwiftAuthCognito.init(cognito: FetchSessionMock())
_options = ["getAWSCredentials": false]
_data = ["options": _options]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "fetchAuthSession", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterFetchCognitoSessionResult {
XCTAssertEqual(true, res.toJSON()["isSignedIn"] as? Bool)
// no identity pool will result in nil identityId
XCTAssertEqual(nil, res.toJSON()["identityId"] as? String)
// all tokens should be present with userpool-only access
XCTAssertEqual(3, (res.toJSON()["tokens"] as? [String: String])!.count)
// credentials map should be empty
XCTAssertEqual(0, (res.toJSON()["credentials"] as? [String: String])!.count)
} else {
XCTFail()
}
})
}
func test_signInWithWebUI() {
class SignInWithWebUIMock: AuthCognitoBridge {
override func onSignInWithWebUI(flutterResult: @escaping FlutterResult) {
let signInRes = Result<AuthSignInResult,AuthError>.success(
AuthSignInResult(nextStep: AuthSignInStep.done)
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInWithWebUIMock())
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signInWithWebUI", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( "DONE", res.signInStep)
} else {
XCTFail()
}
})
}
func test_signInWithSocialWebUI() {
class SignInWithSocialWebUIMock: AuthCognitoBridge {
override func onSignInWithSocialWebUI(flutterResult: @escaping FlutterResult, request: FlutterSignInWithWebUIRequest) {
let signInRes = Result<AuthSignInResult,AuthError>.success(
AuthSignInResult(nextStep: AuthSignInStep.done)
)
let signInData = FlutterSignInResult(res: signInRes)
flutterResult(signInData)
}
}
plugin = SwiftAuthCognito.init(cognito: SignInWithSocialWebUIMock())
_data = ["authProvider": "login_with_amazon"]
_args = ["data": _data]
let call = FlutterMethodCall(methodName: "signInWithWebUI", arguments: _args)
plugin.handle(call, result: {(result)->Void in
if let res = result as? FlutterSignInResult {
XCTAssertEqual( "DONE", res.signInStep)
} else {
XCTFail()
}
})
}
}
| 44.213175 | 169 | 0.600281 |
28a8070dea488376a9d528c0a011baf026e8c370 | 1,471 | import Foundation
struct Tortilla {
enum Type {
case Wheat,
Corn
}
var dough : Type
}
struct Meat {
enum Type {
case Beef,
Chicken,
Fish,
Shrimp,
Pork
}
var type : Type
}
struct Sauce {
enum Type {
case Salsa,
Guacamole,
Cream
}
var flavor : Type
}
class TacoBuilder {
var tortilla: Tortilla?
var meat: Meat?
var sauce: Sauce?
typealias BuilderClosure = (TacoBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct Taco : CustomStringConvertible {
let tortilla: Tortilla
let meat: Meat
let sauce: Sauce
init?(builder: TacoBuilder) {
if let tortilla = builder.tortilla, meat = builder.meat, sauce = builder.sauce {
self.tortilla = tortilla
self.meat = meat
self.sauce = sauce
} else {
return nil
}
}
var description:String {
return "Taco wrapped with \(self.tortilla.dough), filled with \(self.meat.type) and flourished with \(self.sauce.flavor)"
}
}
let tacoBuilder = TacoBuilder { builder in
builder.tortilla = Tortilla(dough: .Wheat)
builder.meat = Meat(type: .Beef)
builder.sauce = Sauce(flavor: .Salsa)
}
let wheatBeefSalsaTaco = Taco(builder:tacoBuilder)
let anotherTaco = Taco(builder:tacoBuilder)
| 18.160494 | 129 | 0.57172 |
5df2dc2d1e284651824490ed5bf25939e4174458 | 7,362 | import CoreBluetooth
import Foundation
import RxSwift
class CBPeripheralDelegateWrapper: NSObject, CBPeripheralDelegate {
let peripheralDidUpdateName = PublishSubject<String?>()
let peripheralDidModifyServices = PublishSubject<[CBService]>()
let peripheralDidReadRSSI = PublishSubject<(Int, Error?)>()
let peripheralDidDiscoverServices = PublishSubject<([CBService]?, Error?)>()
let peripheralDidDiscoverIncludedServicesForService = PublishSubject<(CBService, Error?)>()
let peripheralDidDiscoverCharacteristicsForService = PublishSubject<(CBService, Error?)>()
let peripheralDidUpdateValueForCharacteristic = PublishSubject<(CBCharacteristic, Error?)>()
let peripheralDidWriteValueForCharacteristic = PublishSubject<(CBCharacteristic, Error?)>()
let peripheralDidUpdateNotificationStateForCharacteristic =
PublishSubject<(CBCharacteristic, Error?)>()
let peripheralDidDiscoverDescriptorsForCharacteristic =
PublishSubject<(CBCharacteristic, Error?)>()
let peripheralDidUpdateValueForDescriptor = PublishSubject<(CBDescriptor, Error?)>()
let peripheralDidWriteValueForDescriptor = PublishSubject<(CBDescriptor, Error?)>()
let peripheralIsReadyToSendWriteWithoutResponse = PublishSubject<Void>()
let peripheralDidOpenL2CAPChannel = PublishSubject<(Any?, Error?)>()
func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didUpdateName(name: \(String(describing: peripheral.name)))
""")
peripheralDidUpdateName.onNext(peripheral.name)
}
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didModifyServices(services:
[\(invalidatedServices.logDescription))]
""")
peripheralDidModifyServices.onNext(invalidatedServices)
}
func peripheral(_ peripheral: CBPeripheral, didReadRSSI rssi: NSNumber, error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didReadRSSI(rssi: \(rssi),
error: \(String(describing: error)))
""")
peripheralDidReadRSSI.onNext((rssi.intValue, error))
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didDiscoverServices(services
: \(String(describing: peripheral.services?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidDiscoverServices.onNext((peripheral.services, error))
}
func peripheral(_ peripheral: CBPeripheral,
didDiscoverIncludedServicesFor service: CBService,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didDiscoverIncludedServices(for:
\(service.logDescription), includedServices:
\(String(describing: service.includedServices?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidDiscoverIncludedServicesForService.onNext((service, error))
}
func peripheral(_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service: CBService,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didDiscoverCharacteristicsFor(for:
\(service.logDescription), characteristics:
\(String(describing: service.characteristics?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidDiscoverCharacteristicsForService.onNext((service, error))
}
func peripheral(_ peripheral: CBPeripheral,
didUpdateValueFor characteristic: CBCharacteristic,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didUpdateValueFor(for:\(characteristic.logDescription),
value: \(String(describing: characteristic.value?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidUpdateValueForCharacteristic
.onNext((characteristic, error))
}
func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor characteristic: CBCharacteristic,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didWriteValueFor(for:\(characteristic.logDescription),
value: \(String(describing: characteristic.value?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidWriteValueForCharacteristic
.onNext((characteristic, error))
}
func peripheral(_ peripheral: CBPeripheral,
didUpdateNotificationStateFor characteristic: CBCharacteristic,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didUpdateNotificationStateFor(
for:\(characteristic.logDescription), isNotifying: \(characteristic.isNotifying),
error: \(String(describing: error)))
""")
peripheralDidUpdateNotificationStateForCharacteristic
.onNext((characteristic, error))
}
func peripheral(_ peripheral: CBPeripheral,
didDiscoverDescriptorsFor characteristic: CBCharacteristic,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didDiscoverDescriptorsFor
(for:\(characteristic.logDescription), descriptors:
\(String(describing: characteristic.descriptors?.logDescription)),
error: \(String(describing: error)))
""")
peripheralDidDiscoverDescriptorsForCharacteristic
.onNext((characteristic, error))
}
func peripheral(_ peripheral: CBPeripheral,
didUpdateValueFor descriptor: CBDescriptor,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didUpdateValueFor(for:\(descriptor.logDescription),
value: \(String(describing: descriptor.value)), error: \(String(describing: error)))
""")
peripheralDidUpdateValueForDescriptor.onNext((descriptor, error))
}
func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor descriptor: CBDescriptor,
error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didWriteValueFor(for:\(descriptor.logDescription),
error: \(String(describing: error)))
""")
peripheralDidWriteValueForDescriptor.onNext((descriptor, error))
}
func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) peripheralIsReady(toSendWriteWithoutResponse)
""")
peripheralIsReadyToSendWriteWithoutResponse.onNext(())
}
@available(OSX 10.13, iOS 11, *)
func peripheral(_ peripheral: CBPeripheral, didOpen channel: CBL2CAPChannel?, error: Error?) {
RxBluetoothKitLog.d("""
\(peripheral.logDescription) didOpenL2CAPChannel(for:\(peripheral.logDescription),
error: \(String(describing: error)))
""")
peripheralDidOpenL2CAPChannel.onNext((channel, error))
}
}
| 44.890244 | 101 | 0.680793 |
4b7d1ffe67764a7719e38cd33fd322368aef48dd | 1,626 | import UIKit
final class TabItemView: UIView {
private(set) var titleLabel: UILabel = UILabel()
public var textColor: UIColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0)
public var selectedTextColor: UIColor = .white
public var isSelected: Bool = false {
didSet {
if isSelected {
titleLabel.textColor = selectedTextColor
} else {
titleLabel.textColor = textColor
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func layoutSubviews() {
super.layoutSubviews()
}
private func setupLabel() {
titleLabel = UILabel(frame: bounds)
titleLabel.textAlignment = .center
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
titleLabel.textColor = UIColor(red: 140/255, green: 140/255, blue: 140/255, alpha: 1.0)
titleLabel.backgroundColor = UIColor.clear
addSubview(titleLabel)
layoutLabel()
}
private func layoutLabel() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: self.topAnchor),
titleLabel.widthAnchor.constraint(equalTo: self.widthAnchor),
titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
| 29.563636 | 100 | 0.635916 |
1ae2c5013765f51d52a9e83e097b8c6c0dc8cb89 | 2,166 | //
// AppDelegate.swift
// Tip Calc
//
// Created by Les Wang on 12/27/17.
// Copyright © 2017 Les 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.085106 | 285 | 0.753924 |
e88853322c7cbba495ab62958db5f0a89062b4c2 | 1,413 | let s1 = """
\(
45
)
"""
let s2 = """
\(
45
)
"""
let s3 = """
\(
45
)
"""
let s4 = """
foo \( 45 /*
comment content
*/) bar
"""
// RUN: %sourcekitd-test -req=format -line=2 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=3 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=4 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=9 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=10 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=14 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=15 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=16 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=20 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=21 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=22 %s >>%t.response
// RUN: %FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: " )"
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: " )"
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: ")"
// CHECK: key.sourcetext: " foo \\( 45 /*"
// CHECK: key.sourcetext: " comment content"
// CHECK: key.sourcetext: " */) bar"
| 24.362069 | 62 | 0.586695 |
64cd7f887337c274aea66d9a7d017cce667aec0a | 4,128 | //
// MapSkin.swift
// Tiles
//
// Created by Gerrit Grunwald on 29.09.17.
// Copyright © 2017 Gerrit Grunwald. All rights reserved.
//
import UIKit
import MapKit
class MapSkin: Skin, MKMapViewDelegate {
private var map : MKMapView = MKMapView()
private let marker = MKPointAnnotation()
// ******************** Constructors **************
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// ******************** Methods *******************
override func update(cmd: String) {
guard let tile = control else { return }
if (cmd == Helper.INIT) {
width = self.frame.width
height = self.frame.height
size = width < height ? width : height
centerX = width * 0.5
centerY = height * 0.5
map.frame = CGRect(x: size * 0.05, y: size * 0.15, width: width * 0.9, height: height - size * 0.27)
map.mapType = MKMapType.standard
map.isZoomEnabled = true
map.isScrollEnabled = true
map.backgroundColor = UIColor.red
map.delegate = self
map.addAnnotation(marker)
tile.addSubview(map)
} else if (cmd == Helper.REDRAW) {
setNeedsDisplay()
}
}
override func update<T>(prop: String, value: T) {
if (prop == "value") {
}
}
// ******************** Redraw ********************
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
guard let tile = control else { return }
UIGraphicsPushContext(ctx)
width = self.frame.width
height = self.frame.height
size = width < height ? width : height
centerX = width * 0.5
centerY = height * 0.5
// Background
let path = UIBezierPath(roundedRect: bounds, cornerRadius: size * 0.025)
ctx.setFillColor(tile.bkgColor.cgColor)
ctx.addPath(path.cgPath)
ctx.fillPath()
let smallFont = UIFont.init(name: "Lato-Regular", size: size * 0.06)
// Tile Title
drawText(label : tile.titleLabel,
font : smallFont!,
text : tile.title,
frame : CGRect(x: size * 0.05, y: size * 0.05, width: width - size * 0.1, height: size * 0.08),
fgdColor: tile.fgdColor,
bkgColor: tile.bkgColor,
radius : 0,
align : tile.titleAlignment)
// Tile Text
if (tile.textVisible) {
drawText(label : tile.textLabel,
font : smallFont!,
text : tile.text,
frame : CGRect(x: size * 0.05, y: height - size * 0.11, width: width - size * 0.1, height: size * 0.08),
fgdColor: tile.fgdColor,
bkgColor: tile.bkgColor,
radius : 0,
align : tile.textAlignment)
} else {
tile.textLabel.textColor = UIColor.clear
}
// Map
let location = CLLocationCoordinate2D(latitude: tile.location.latitude, longitude: tile.location.longitude)
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, 100, 100)
let marker = MKPointAnnotation()
marker.coordinate = CLLocationCoordinate2D(latitude: tile.location.latitude, longitude: tile.location.longitude)
marker.title = tile.location.name
map.frame = CGRect(x: size * 0.05, y: size * 0.15, width: width * 0.9, height: height - size * (tile.textVisible ? 0.27 : 0.205))
map.setRegion(coordinateRegion, animated: true)
map.setCenter(location, animated: true)
UIGraphicsPopContext()
}
}
| 34.689076 | 148 | 0.507994 |
160bfc33bfe8b595c0a09c7afcc4b0166c037475 | 5,013 | import Foundation
import TuistSupport
public enum CloudSessionControllerError: FatalError, Equatable {
case missingParameters
case authenticationError(String)
case invalidParameters([String])
/// Error description.
public var description: String {
switch self {
case let .authenticationError(error):
return error
case .missingParameters:
return "The result from the authentication contains no parameters. We expect an account and token."
case let .invalidParameters(parameters):
return "The result from the authentication contains invalid parameters: \(parameters.joined(separator: ", ")). We expect an account and token."
}
}
/// Error type.
public var type: ErrorType {
switch self {
case .authenticationError: return .abort
case .invalidParameters: return .abort
case .missingParameters: return .abort
}
}
}
public protocol CloudSessionControlling: AnyObject {
/// It authenticates the user for the server with the given URL.
/// - Parameter serverURL: Server URL.
func authenticate(serverURL: URL) throws
/// Prints the session for the server with the given URL.
/// - Parameter serverURL: Server URL.
func printSession(serverURL: URL) throws
/// Removes the session for the server with the given URL.
/// - Parameter serverURL: Server URL.
func logout(serverURL: URL) throws
}
public final class CloudSessionController: CloudSessionControlling {
static let port: UInt16 = 4545
/// Credentials store.
private let credentialsStore: CredentialsStoring
/// HTTP redirect listener.
private let httpRedirectListener: HTTPRedirectListening
/// Utility to check whether we are running Tuist on CI.
let ciChecker: CIChecking
/// Utility to send the user to a web page to authenticate.
let opener: Opening
public convenience init() {
self.init(credentialsStore: CredentialsStore(),
httpRedirectListener: HTTPRedirectListener(),
ciChecker: CIChecker(),
opener: Opener())
}
init(credentialsStore: CredentialsStoring,
httpRedirectListener: HTTPRedirectListening,
ciChecker: CIChecking,
opener: Opening) {
self.credentialsStore = credentialsStore
self.httpRedirectListener = httpRedirectListener
self.ciChecker = ciChecker
self.opener = opener
}
// MARK: - CloudSessionControlling
public func authenticate(serverURL: URL) throws {
var components = URLComponents(url: serverURL, resolvingAgainstBaseURL: false)!
components.path = "/auth"
components.queryItems = nil
let authURL = components.url!
logger.notice("Opening \(authURL.absoluteString) to start the authentication flow")
try opener.open(url: authURL)
let redirectMessage = "Switch back to your terminal to continue the authentication."
let result = httpRedirectListener.listen(port: CloudSessionController.port,
path: "auth",
redirectMessage: redirectMessage)
switch result {
case let .failure(error): throw error
case let .success(parameters):
guard let parameters = parameters else {
throw CloudSessionControllerError.missingParameters
}
if let error = parameters["error"] {
throw CloudSessionControllerError.authenticationError(error)
} else if let token = parameters["token"], let account = parameters["account"] {
logger.notice("Successfully authenticated. Storing credentials...")
let credentials = Credentials(token: token, account: account)
try credentialsStore.store(credentials: credentials, serverURL: serverURL)
logger.notice("Credentials stored successfully", metadata: .success)
} else {
throw CloudSessionControllerError.invalidParameters(Array(parameters.keys))
}
}
}
public func printSession(serverURL: URL) throws {
if let credentials = try credentialsStore.read(serverURL: serverURL) {
let output = """
These are the credentials for the server with URL \(serverURL.absoluteString):
- Account: \(credentials.account)
- Token: \(credentials.token)
"""
logger.notice("\(output)")
} else {
logger.notice("There are no sessions for the server with URL \(serverURL.absoluteString)")
}
}
public func logout(serverURL: URL) throws {
logger.notice("Removing session for server with URL \(serverURL.absoluteString)")
try credentialsStore.delete(serverURL: serverURL)
logger.notice("Session deleted successfully", metadata: .success)
}
}
| 38.561538 | 155 | 0.648314 |
b98d157eb7fdb6f528480e953400d946bef041ec | 467 | // swift-tools-version:5.0
//
// Package.swift
//
import PackageDescription
let package = Package(
name: "SlideMenuControllerSwift",
platforms: [
.iOS(.v8)
],
products: [
.library(
name: "SlideMenuControllerSwift",
targets: ["SlideMenuControllerSwift"])
],
targets: [
.target(
name: "SlideMenuControllerSwift",
path: "Source")
],
swiftLanguageVersions: [.v5]
) | 19.458333 | 50 | 0.561028 |
216161f8a01f23b815139d9051102f146f2fd356 | 611 | //
// Functions.swift
// ITMRed
//
// Created by Mathieu Lecoupeur on 30/06/2017.
// Copyright © 2017 mathieu lecoupeur. All rights reserved.
//
import Foundation
internal func min<C: Comparable, R: Any>(valuesToCompare: [C], valuesToReturn: [R]) -> R? {
guard valuesToCompare.count == valuesToReturn.count else {
return nil
}
var minIndex = 0
var minValue = valuesToCompare[0]
for (index, value) in valuesToCompare.enumerated() where value < minValue {
minValue = value
minIndex = index
}
return valuesToReturn[minIndex]
}
| 21.821429 | 91 | 0.633388 |
fe9643d0dc499e0cac2545d53dd3039ce0e75ea3 | 9,050 | //
// Broadcaster.swift
// Arlene Live Streams
//
// Created by Hermes on 2/6/20.
// Copyright © 2020 Hermes. All rights reserved.
//
import UIKit
import AgoraRtcKit
class Broadcaster: UIViewController, AgoraRtcEngineDelegate {
var agoraKit: AgoraRtcEngineKit! // Agora.io Video Engine reference
public var channelName: String! // name of the channel to join
public var localVideoView: UIView! // video stream of local camera
public var remoteVideoViews: [UInt: UIView] = [:]
var dataStreamId: Int! = 27 // id for data stream
var streamIsEnabled: Int32 = -1 // acts as a flag to keep track if the data stream is enabled
// MARK: UI properties
public var micBtn: UIButton!
public var micBtnFrame: CGRect?
public var micBtnImage: UIImage?
public var micBtnTextLabel: String = "un-mute"
public var muteBtnImage: UIImage?
public var muteBtnTextLabel: String = "mute"
public var backBtn: UIButton!
public var backBtnFrame: CGRect?
public var backBtnImage: UIImage?
public var backBtnTextLabel: String = "x"
public var debug = true
override func viewDidLoad() {
super.viewDidLoad()
// Add Agora setup
guard let agoraAppID = AgoraARKit.agoraAppId else { return }
let agoraKit = AgoraRtcEngineKit.sharedEngine(withAppId: agoraAppID, delegate: self) // - init engine
agoraKit.setChannelProfile(.liveBroadcasting) // - set channel profile
agoraKit.setClientRole(.broadcaster)
self.agoraKit = agoraKit
createUI()
setupLocalVideo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
joinChannel()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// do something when the view has appeared
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
leaveChannel()
}
// MARK: UI
func createUI() {
// add remote video view
let localVideoView = UIView()
localVideoView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
localVideoView.backgroundColor = UIColor.lightGray
self.view.insertSubview(localVideoView, at: 0)
self.localVideoView = localVideoView
// mic button
let micBtn = UIButton()
if let micBtnFrame = self.micBtnFrame {
micBtn.frame = micBtnFrame
} else {
micBtn.frame = CGRect(x: self.view.frame.midX-37.5, y: self.view.frame.maxY-100, width: 75, height: 75)
}
if let micBtnImage = self.micBtnImage {
micBtn.setImage(micBtnImage, for: .normal)
} else {
micBtn.setTitle(muteBtnTextLabel, for: .normal)
}
micBtn.addTarget(self, action: #selector(toggleMic), for: .touchDown)
self.view.insertSubview(micBtn, at: 2)
self.micBtn = micBtn
// back button
let backBtn = UIButton()
if let backBtnFrame = self.backBtnFrame {
backBtn.frame = backBtnFrame
} else {
backBtn.frame = CGRect(x: self.view.frame.maxX-55, y: self.view.frame.minY + 20, width: 30, height: 30)
}
if let backBtnImage = self.backBtnImage {
backBtn.setImage(backBtnImage, for: .normal)
} else {
backBtn.setTitle(backBtnTextLabel, for: .normal)
}
backBtn.addTarget(self, action: #selector(popView), for: .touchUpInside)
self.view.insertSubview(backBtn, at: 2)
// add branded logo to remote view
guard let agoraLogo = UIImage(named: "arlene-brandmark") else { return }
let remoteViewBagroundImage = UIImageView(image: agoraLogo)
remoteViewBagroundImage.frame = CGRect(
x: localVideoView.frame.midX - 56.5, y: localVideoView.frame.midY - 100,
width: 117, height: 126
)
remoteViewBagroundImage.alpha = 0.25
localVideoView.insertSubview(remoteViewBagroundImage, at: 1)
}
// MARK: Button Events
@IBAction func popView() {
leaveChannel()
self.dismiss(animated: true, completion: nil)
}
@IBAction func toggleMic() {
if let activeMicImg = micBtnImage, let disabledMicImg = muteBtnImage {
if self.micBtn.imageView?.image == activeMicImg {
self.micBtn.setImage(disabledMicImg, for: .normal)
self.agoraKit.muteLocalAudioStream(true)
if debug {
print("disable local mic")
}
} else {
self.micBtn.setImage(activeMicImg, for: .normal)
self.agoraKit.muteLocalAudioStream(false)
if debug {
print("enable local mic")
}
}
} else {
if self.micBtn.titleLabel?.text == micBtnTextLabel {
micBtn.setTitle(muteBtnTextLabel, for: .normal)
if debug {
print("disable local mic")
}
} else {
micBtn.setTitle(micBtnTextLabel, for: .normal)
if debug {
print("enable local mic")
}
}
}
}
// MARK: Agora Implementation
func setupLocalVideo() {
guard let localVideoView = self.localVideoView else { return }
// enable the local video stream
self.agoraKit.enableVideo()
// Set video configuration
let videoConfig = AgoraVideoEncoderConfiguration(
size: AgoraVideoDimension840x480, frameRate: .fps15,
bitrate: AgoraVideoBitrateStandard, orientationMode: .fixedPortrait
)
self.agoraKit.setVideoEncoderConfiguration(videoConfig)
// Set up local video view
let videoCanvas = AgoraRtcVideoCanvas()
videoCanvas.uid = 0
videoCanvas.view = localVideoView
videoCanvas.renderMode = .hidden
// Set the local video view.
self.agoraKit.setupLocalVideo(videoCanvas)
guard let videoView = localVideoView.subviews.first else { return }
videoView.layer.cornerRadius = 25
}
func joinChannel() {
// Set audio route to speaker
self.agoraKit.setDefaultAudioRouteToSpeakerphone(true)
// get the token - returns nil if no value is set
let token = AgoraARKit.agoraToken
// Join the channel
self.agoraKit.joinChannel(
byToken: token, channelId: self.channelName, info: nil, uid: 0
) { (channel, uid, elapsed) in
if self.debug {
print("Successfully joined: \(channel), with \(uid): \(elapsed) secongs ago")
}
}
UIApplication.shared.isIdleTimerDisabled = true // Disable idle timmer
}
func leaveChannel() {
UIApplication.shared.isIdleTimerDisabled = false // Enable idle timer
guard self.agoraKit != nil else { return }
self.agoraKit.leaveChannel(nil) // leave channel and end chat
}
// MARK: Agora event handler
func rtcEngine(
_ engine: AgoraRtcEngineKit, remoteVideoStateChangedOfUid uid: UInt,
state: AgoraVideoRemoteState, reason: AgoraVideoRemoteStateReason, elapsed: Int
) {
if state == .starting {
lprint("firstRemoteVideoStarting for Uid: \(uid)", .verbose)
} else if state == .decoding {
lprint("firstRemoteVideoDecoded for Uid: \(uid)", .verbose)
var remoteView: UIView
if let existingRemoteView = self.remoteVideoViews[uid] {
remoteView = existingRemoteView
} else {
remoteView = createRemoteView(remoteViews: self.remoteVideoViews, view: self.view)
}
let videoCanvas = AgoraRtcVideoCanvas()
videoCanvas.uid = uid
videoCanvas.view = remoteView
videoCanvas.renderMode = .hidden
agoraKit.setupRemoteVideo(videoCanvas)
self.view.insertSubview(remoteView, at: 2)
self.remoteVideoViews[uid] = remoteView
// create the data stream
self.streamIsEnabled = self.agoraKit.createDataStream(&self.dataStreamId, reliable: true, ordered: true)
if debug {
print("Data Stream initiated - STATUS: \(self.streamIsEnabled)")
}
}
}
func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
guard let remoteVideoView = self.remoteVideoViews[uid] else { return }
remoteVideoView.removeFromSuperview() // remove the remote view from the super view
self.remoteVideoViews.removeValue(forKey: uid) // remove the remote view from the dictionary
adjustRemoteViews(remoteViews: self.remoteVideoViews, view: self.view)
}
}
| 37.396694 | 117 | 0.615028 |
0a36bf62006b81dbdc568b5a0fd68829c87c41cc | 94 | import XCTest
@testable import ParseyTests
XCTMain([
testCase(ParseyTests.allTests),
])
| 13.428571 | 36 | 0.755319 |
76c34b3c2ce64a4eb651abe9b5dcfb20cdb66178 | 315 | //
// OuterEnum.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public enum OuterEnum: String, Codable, CaseIterable {
case placed = "placed"
case approved = "approved"
case delivered = "delivered"
}
| 17.5 | 54 | 0.71746 |
ab770e12f92ad960a419f9872436e515874a9e29 | 672 | //
// UIView+NDUtils.swift
// NDUtils
//
// Created by Nguyen Duc Hiep on 8/10/20.
// Copyright © 2020 Nguyen Duc Hiep. All rights reserved.
//
extension UIView {
@available(iOS 10.0, *)
@inlinable
public func nd_shake(
in duration: TimeInterval = 0.5, translation: CGPoint = .init(x: 10, y: 0)
) {
__nd_shake(withDuration: duration, translation: translation)
}
@inlinable
@discardableResult
public func nd_enableSeparator(
heigth: CGFloat = 1, leading: CGFloat = 16, trailing: CGFloat = 16, color: UIColor
) -> UIView {
return self.__nd_enableSeparator(withHeight: heigth, leading: leading, trailing: trailing, color: color)
}
}
| 25.846154 | 108 | 0.6875 |
8fbdc1510c4c6d5bd8456808c4ccc4be2f2e18df | 136 | // Created by dasdom on 22.02.20.
//
//
import Foundation
struct TypedLine : Equatable {
let type: LineType
let text: String
}
| 12.363636 | 34 | 0.669118 |
1ae8593ad463d5a27b6020540e0f46e26360a5f4 | 2,358 | import Foundation
import UIKit
protocol EventStatsConfigurator {
static func configureDataSource(_ snapshot: inout NSDiffableDataSourceSnapshot<String, InsightRow>, _ qual: [String: Any]?, _ playoff: [String: Any]?)
}
extension EventStatsConfigurator {
static func highScoreRow(title: String, key: String, qual: [String: Any]?, playoff: [String: Any]?) -> InsightRow {
return InsightRow(title: title, qual: highScoreString(qual, key), playoff: highScoreString(playoff, key))
}
private static func highScoreString(_ dict: [String: Any]?, _ key: String) -> String? {
guard let dict = dict else {
return nil
}
guard let highScoreData = dict[key] as? [Any] else {
return nil
}
guard highScoreData.count == 3 else {
return nil
}
return "\(highScoreData[0]) in \(highScoreData[2])"
}
static func scoreRow(title: String, key: String, qual: [String: Any]?, playoff: [String: Any]?) -> InsightRow {
return InsightRow(title: title, qual: scoreFor(qual, key), playoff: scoreFor(playoff, key))
}
private static func scoreFor(_ dict: [String: Any]?, _ key: String) -> String? {
guard let dict = dict else {
return nil
}
guard let val = dict[key] as? Double else {
return nil
}
return String(format: "%.2f", val)
}
static func bonusRow(title: String, key: String, qual: [String: Any]?, playoff: [String: Any]?) -> InsightRow {
return InsightRow(title: title, qual: bonusStat(qual, key), playoff: bonusStat(playoff, key))
}
private static func bonusStat(_ dict: [String: Any]?, _ key: String) -> String? {
guard let dict = dict else {
return nil
}
guard let bonusData = dict[key] as? [Any] else {
return nil
}
let quotient: String = {
if let val = bonusData.safeItem(at: 2) as? Double {
return "\(String(format: "%.2f", val))%"
}
return "--"
}()
return "\(bonusData.safeItem(at: 0) ?? "--") / \(bonusData.safeItem(at: 1) ?? "--") = \(quotient)"
}
static func filterEmptyInsights(_ rows: [InsightRow]) -> [InsightRow] {
return rows.filter({ $0.qual != nil || $0.playoff != nil })
}
}
| 35.727273 | 154 | 0.583121 |
21fd6446dde6cae2b9e8607799d1acb1025ca28d | 954 | //
// GoogleMapsView.swift
// SMOO
//
// Created by 허재 on 2021/05/23.
//
import SwiftUI
import GoogleMaps
struct GoogleMapsView: UIViewRepresentable {
let eventLocation: Location
let users: [UserWithLocation]
private let zoom: Float = 15.0
func makeUIView(context: Self.Context) -> GMSMapView {
let camera = GMSCameraPosition.camera(withLatitude: eventLocation.lat, longitude: eventLocation.long, zoom: 17)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: Context) {
for user in users {
let marker: GMSMarker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: user.loc.lat, longitude: user.loc.long)
marker.title = user.userName
marker.icon = UIImage(named: "marker")
marker.map = mapView
}
}
}
| 27.257143 | 119 | 0.642558 |
b95799295aec370bf91725058502653889b22797 | 1,707 | //
// HostMenuTableViewCell.swift
// CD
//
// Created by Vladislav Simovic on 12/26/16.
// Copyright © 2016 CustomDeal. All rights reserved.
//
import UIKit
class HostMenuTableViewCell: UITableViewCell {
// MARK: - Properties
@IBOutlet weak var avatarImageView : UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var countryLabel : UILabel!
@IBOutlet weak var descriptionLabel : UILabel!
@IBOutlet weak var separatorView : UIView!
// MARK: - Cell lifecycle
override func awakeFromNib() {
super.awakeFromNib()
// prepare avatar
self.avatarImageView.layer.cornerRadius = 43 / 2.0
self.avatarImageView.layer.masksToBounds = true
self.avatarImageView.layer.borderWidth = 2.0;
self.avatarImageView.layer.borderColor = UIColor.white.cgColor
}
// MARK: - Helper methods
func populateCellWithRaiderList(hostRiderList: HostRiderList, isLastCell: Bool) {
self.nameLabel.text = hostRiderList.travelerFullName
self.countryLabel.text = hostRiderList.travelerCountry
self.descriptionLabel.text = hostRiderList.riderListDetails
// set avatar if exists
self.avatarImageView.image = nil
if let photoURL = hostRiderList.travelerPictureUrl {
self.avatarImageView.af_setImage(withURL: URL(string: photoURL)!)
}
// set separator
self.separatorView.isHidden = isLastCell
}
// MARK: - Type methods
class func cellIdentifier() -> String {
return String(describing:self)
}
class func cellHeight() -> CGFloat {
return 100
}
}
| 28.45 | 85 | 0.653779 |
ff435fed66aa89d52f409a8e4457618c6aebf308 | 926 | //
// CursorTests.swift
// RxPaginator_Tests
//
// Created by zhzh liu on 2019/4/18.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
@testable import RxPaginator
class CursorTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func test_CursorInit() {
let cursor = Cursor(minPosition: "minPosition", maxPosition: "maxPosition")
XCTAssertEqual("minPosition", cursor.minPosition)
XCTAssertEqual("maxPosition", cursor.maxPosition)
}
func test_CursorInitial() {
let cursor = Cursor.initial
XCTAssertNil(cursor.minPosition)
XCTAssertNil(cursor.maxPosition)
}
func test_CursorFirst() {
let cursor = Cursor(minPosition: "minPosition", maxPosition: "maxPosition")
let first = cursor.first()
XCTAssertNil(first.minPosition)
XCTAssertNil(first.maxPosition)
}
}
| 23.15 | 83 | 0.664147 |
0394e49ae1e1428d861fa3bffb516017fd72df34 | 627 | //
// AlternativeScheduleUseCase.swift
// OperantKit
//
// Created by Yuto Mizutani on 2018/11/22.
//
import RxSwift
public class AlternativeScheduleUseCase: CompoundScheduleUseCaseBase, ScheduleUseCase {
public func decision(_ entity: ResponseEntity, isUpdateIfReinforcement: Bool) -> Single<ResultEntity> {
let result: Single<ResultEntity> = Single.zip(subSchedules.map { $0.decision(entity, isUpdateIfReinforcement: false) })
.map { ResultEntity(!$0.filter { $0.isReinforcement }.isEmpty, entity) }
return !isUpdateIfReinforcement ? result : updateValueIfReinforcement(result)
}
}
| 33 | 127 | 0.733652 |
75b6e0adb7d5b4510677cb7b9a83c86c30a188b6 | 5,675 | //
// StringUtility.swift
// FDJUtility
//
// Created by mac on 2019/7/25.
//
import Foundation
import CommonCrypto
import UIKit
public extension String {
func md5String() -> String {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let hash = NSMutableString()
for i in 0 ..< Int(CC_MD5_DIGEST_LENGTH) {
hash.appendFormat("%02x", result[i])
}
result.deallocate()
return String(format: hash as String)
}
func md5Data() -> Data {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let dataBuffer = UnsafeBufferPointer<UInt8>.init(start: result, count: Int(CC_MD5_DIGEST_LENGTH))
defer {
result.deallocate()
}
return Data(buffer: dataBuffer)
}
func sha1String() -> String {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA1_DIGEST_LENGTH))
CC_SHA1(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let hash = NSMutableString()
for i in 0 ..< Int(CC_SHA1_DIGEST_LENGTH) {
hash.appendFormat("%02x", result[i])
}
result.deallocate()
return String(format: hash as String)
}
func sha1Data() -> Data {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA1_DIGEST_LENGTH))
CC_SHA1(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let dataBuffer = UnsafeBufferPointer<UInt8>.init(start: result, count: Int(CC_MD5_DIGEST_LENGTH))
defer {
result.deallocate()
}
return Data(buffer: dataBuffer)
}
func sha256String() -> String {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let hash = NSMutableString()
for i in 0 ..< Int(CC_SHA256_DIGEST_LENGTH) {
hash.appendFormat("%02x", result[i])
}
result.deallocate()
return String(format: hash as String)
}
func sha256Data() -> Data {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let dataBuffer = UnsafeBufferPointer<UInt8>.init(start: result, count: Int(CC_MD5_DIGEST_LENGTH))
defer {
result.deallocate()
}
return Data(buffer: dataBuffer)
}
func sha512String() -> String {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA512_DIGEST_LENGTH))
CC_SHA512(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let hash = NSMutableString()
for i in 0 ..< Int(CC_SHA512_DIGEST_LENGTH) {
hash.appendFormat("%02x", result[i])
}
result.deallocate()
return String(format: hash as String)
}
func sha512Data() -> Data {
let cString = self.cString(using: .utf8)
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA512_DIGEST_LENGTH))
CC_SHA512(cString!, CUnsignedInt(self.lengthOfBytes(using: .utf8)), result)
let dataBuffer = UnsafeBufferPointer<UInt8>.init(start: result, count: Int(CC_MD5_DIGEST_LENGTH))
defer {
result.deallocate()
}
return Data(buffer: dataBuffer)
}
func base64String() -> String? {
let data = self.data(using: .utf8)
return data?.base64EncodedString()
}
func base64Data() -> Data? {
let data = self.data(using: .utf8)
return data?.base64EncodedData()
}
}
public extension String {
func toAttribute(size:Float, hex:UInt32, alpha:Float = 1, weight:UIFont.Weight = .regular, lineSpacing:Float = 2, layoutVertical:Bool = false) -> NSAttributedString {
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = CGFloat(lineSpacing)
let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: CGFloat(size), weight: weight), NSAttributedString.Key.foregroundColor:UIColor.hex(hex: hex), NSAttributedString.Key.paragraphStyle:paragraph,NSAttributedString.Key.verticalGlyphForm:NSNumber(value: layoutVertical ? 1 : 0)]
return NSAttributedString(string: self, attributes: attributes)
}
}
public extension NSAttributedString {
convenience init(string:String, font:UIFont, color:UIColor) {
self.init(string:string, attributes:[NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:color])
}
}
| 31.181319 | 303 | 0.604581 |
f545dd5e0b39f7c872ba0e5b6475053f7a5350cf | 2,912 | //
// UserAccountVC.swift
// Memoria-iOS
//
// Created by 村松龍之介 on 2018/12/05.
// Copyright © 2018 nerco studio. All rights reserved.
//
import UIKit
import Firebase
class UserAccountVC: UITableViewController, EventTrackable {
/// TableViewのセル。rowValueはtag番号を示す
enum SelectableCell: Int {
case signOut = 91
}
@IBOutlet weak var currentEmail: UILabel!
// MARK: - ライフサイクル
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("userAccountSettings", comment: "")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
trackScreen()
currentEmail.text = Auth.auth().currentUser?.email
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//セルの選択解除
tableView.deselectRow(at: indexPath, animated: true)
//選択されたセルのtagからセルのケースを当てはめる
guard let cell = tableView.cellForRow(at: indexPath),
let selectedCell = SelectableCell.init(rawValue: cell.tag) else { return }
// セルによって処理を振り分け
switch selectedCell {
case .signOut:
DialogBox.showDestructiveAlert(on: self,
title: NSLocalizedString("signOutTitle", comment: ""),
message: NSLocalizedString("signOutMessage", comment: ""),
destructiveTitle: NSLocalizedString("signOutButton", comment: "")) {
// [START signout]
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
Log.info("Sign outに成功")
} catch let signOutError as NSError {
Log.warn("Error signing out:", signOutError)
}
}
}
}
/// セクションのヘッダータイトル
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return NSLocalizedString("updateUserAccount", comment: "")
default: return nil
}
}
/// セクションのフッタータイトル
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch section {
default: return nil
}
}
// この画面に戻ってくるUnwind Segueで使用
@IBAction func returnToUserAccountVC(segue: UIStoryboardSegue) {}
}
| 34.258824 | 111 | 0.547047 |
ef345c4035f5c818ac9c187e79bca1483e6fc856 | 1,700 | //
// ChildViewController.swift
// Pods-ZBottomSheet_Example
//
// Created by sudansuwal on 8/21/20.
//
import UIKit
public class ChildViewController: UIViewController {
var sheetView: UISheetView!
var background: UIView = UIView()
var tapGesture: UITapGestureRecognizer!
public override func viewDidLoad() {
super.viewDidLoad()
setupBackgroundView()
setupGesture()
sheetView.presentView(parent: self)
}
//add background layer
func setupBackgroundView() {
background = UIView(frame: self.view.frame)
self.view.addSubview(background)
background.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
NSLayoutConstraint(item: background, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: background, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: background, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: background, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 0)
])
background.backgroundColor = .black
background.alpha = 0.1
}
func setupGesture() {
tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
background.addGestureRecognizer(tapGesture)
}
@objc func onTap() {
sheetView.state = .Hidden
}
}
| 34.693878 | 159 | 0.670588 |
160f475231e24bf704401dcf58f037fea99a285e | 1,928 | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
//
// This is a GENERATED FILE, changes made here WILL BE LOST.
//
import Foundation
public final class OntologyAddress {
public static func == (lhs: OntologyAddress, rhs: OntologyAddress) -> Bool {
return TWOntologyAddressEqual(lhs.rawValue, rhs.rawValue)
}
public static func isValidString(string: String) -> Bool {
let stringString = TWStringCreateWithNSString(string)
defer {
TWStringDelete(stringString)
}
return TWOntologyAddressIsValidString(stringString)
}
public var description: String {
return TWStringNSString(TWOntologyAddressDescription(rawValue))
}
public var keyHash: Data {
return TWDataNSData(TWOntologyAddressKeyHash(rawValue))
}
let rawValue: OpaquePointer
init(rawValue: OpaquePointer) {
self.rawValue = rawValue
}
public init?(data: Data) {
let dataData = TWDataCreateWithNSData(data)
defer {
TWDataDelete(dataData)
}
guard let rawValue = TWOntologyAddressCreateWithData(dataData) else {
return nil
}
self.rawValue = rawValue
}
public init?(string: String) {
let stringString = TWStringCreateWithNSString(string)
defer {
TWStringDelete(stringString)
}
guard let rawValue = TWOntologyAddressCreateWithString(stringString) else {
return nil
}
self.rawValue = rawValue
}
public init(publicKey: PublicKey) {
rawValue = TWOntologyAddressCreateWithPublicKey(publicKey.rawValue)
}
deinit {
TWOntologyAddressDelete(rawValue)
}
}
| 27.15493 | 83 | 0.662863 |
2f0a328be0b1d4a3ddef523ee71be14f1908ae94 | 903 | //
// NetworkTools.swift
// Alamofire的测试
//
// Created by 1 on 16/9/19.
// Copyright © 2016年 小码哥. All rights reserved.
//
//import UIKit
//import Alamofire
//
//enum MethodType {
// case GET
// case POST
//}
//
//class NetworkTools {
// class func requestData(type : MethodType, URLString : String, parameters : [String : NSString]? = nil, finishedCallback : @escaping (_ result : AnyObject) -> ()) {
//
// // 1.获取类型
// let method = type == .GET ? Method.GET : Method.POST
// // 2.发送网络请求
// Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) in
// // 3.获取结果
// guard let result = response.result.value else {
// print(response.result.error)
// return
// }
// // 4.将结果回调出去
// finishedCallback(result: result)
// }
// }
//}
| 26.558824 | 169 | 0.54928 |
2331674c08616d0989bf657f033a74dabfcb02df | 1,821 | //
// PostDetailsViewController.swift
// Instagram
//
// Created by Claire Chen on 6/28/17.
// Copyright © 2017 Claire Chen. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class PostDetailsViewController: UIViewController {
//Outlets
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var postImageView: PFImageView!
@IBOutlet weak var likesLabel: UILabel!
@IBOutlet weak var captionLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
//Variable
var post: PFObject?
var user: PFUser?
override func viewDidLoad() {
super.viewDidLoad()
usernameLabel.text = user?.username
captionLabel.text = post?["caption"] as! String
let likes = post?["likesCount"] as! Int
likesLabel.text = "Liked by " + String(likes)
postImageView.file = post?["media"] as? PFFile
postImageView.loadInBackground()
//some date formatting
let date = NSDate()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from:post?.createdAt as! Date)
timestampLabel.text = dateString
// 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.
}
*/
}
| 28.453125 | 106 | 0.656782 |
f8a0cb1711c786d5c8b0c34f69ab636c1d9e918f | 3,541 | //
// Server.swift
// InquirySDKLib
//
// Created by Sepehr Behroozi on 6/25/18.
// Copyright © 2018 Ayantech. All rights reserved.
//
import Foundation
internal let kResponseSuccessCode = "G00000"
class Server {
static var logger: ATNetworkLogging = DefaultATNetworkLogger()
fileprivate static var defaultUrlSession: URLSession = {
var config = URLSessionConfiguration.default
if ATRequest.Configuration.noProxy {
config.connectionProxyDictionary = [:]
}
let result = URLSession(configuration: config)
return result
}()
class func sendSyncRequest(req: ATRequest) -> (Data?, URLResponse?, Error?) {
logger.logRequest(url: req.url, method: req.method, headers: req.headers, body: req.body)
Utils.runOnMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
let r = NSMutableURLRequest(url: URL(string: req.url)!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: ATRequest.Configuration.timeout)
r.httpMethod = req.method.rawValue
req.headers.forEach { r.addValue($0.value, forHTTPHeaderField: $0.key) }
r.httpBody = req.body
let result = URLSession.shared.synchronousDataTask(with: r as URLRequest)
Utils.runOnMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
let responseCode = (result.1 as? HTTPURLResponse)?.statusCode ?? -1
let responseHeaders = ((result.1 as? HTTPURLResponse)?.allHeaderFields as? [String: String]) ?? [:]
logger.logResponse(
requestUrl: req.url,
requestMethod: req.method,
requestHeaders: req.headers,
requestBody: req.body,
responseCode: responseCode,
responseHeaders: responseHeaders,
responseBody: result.0
)
return result
}
class func sendRequest(req: ATRequest, responseHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
logger.logRequest(url: req.url, method: req.method, headers: req.headers, body: req.body)
Utils.runOnMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
let r = NSMutableURLRequest(url: URL(string: req.url)!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: ATRequest.Configuration.timeout)
r.httpMethod = req.method.rawValue
req.headers.forEach { r.addValue($0.value, forHTTPHeaderField: $0.key) }
r.httpBody = req.body
req.task = Server.defaultUrlSession.dataTask(with: r as URLRequest) { (data, response, error) in
let responseCode = (response as? HTTPURLResponse)?.statusCode ?? -1
let responseHeaders = ((response as? HTTPURLResponse)?.allHeaderFields as? [String: String]) ?? [:]
logger.logResponse(
requestUrl: req.url,
requestMethod: req.method,
requestHeaders: req.headers,
requestBody: req.body,
responseCode: responseCode,
responseHeaders: responseHeaders,
responseBody: data
)
Utils.runOnMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
req.task = nil
responseHandler(data, response, error)
}
}
req.task?.resume()
}
}
| 39.786517 | 181 | 0.637391 |
3a4581ed8899f5b723e0e8169b783f3274f9390b | 553 | //
// Plugin.swift
// DesktopCore
//
// Created by Nghia Tran on 10/18/18.
// Copyright © 2018 com.nsproxy.proxy. All rights reserved.
//
import Foundation
/// Plugins for Networking service
public protocol PluginType {
@discardableResult
func process(_ urlRequest: URLRequest) -> URLRequest
}
/// Logger
/// Log all on-going URLRequest
public struct LoggerPlugin: PluginType {
@discardableResult
public func process(_ urlRequest: URLRequest) -> URLRequest {
print("Log \(urlRequest)")
return urlRequest
}
}
| 19.75 | 65 | 0.688969 |
16fd9f52efbe0effe503c95b5a5a76cb328333fe | 1,820 | import XCTest
@testable import The_Blue_Alliance
class EventAllianceCellViewModelTestCase: CoreDataTestCase {
func test_init() {
let alliance = EventAlliance.init(entity: EventAlliance.entity(), insertInto: persistentContainer.viewContext)
alliance.addToPicks(NSOrderedSet(array: [
TeamKey.insert(withKey: "frc1", in: persistentContainer.viewContext),
TeamKey.insert(withKey: "frc3", in: persistentContainer.viewContext),
TeamKey.insert(withKey: "frc2", in: persistentContainer.viewContext),
TeamKey.insert(withKey: "frc4", in: persistentContainer.viewContext)
]))
let first = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2)
XCTAssertEqual(first.picks, ["frc1", "frc3", "frc2", "frc4"])
XCTAssertEqual(first.allianceName, "Alliance 2")
XCTAssertNil(first.allianceLevel)
XCTAssertFalse(first.hasAllianceLevel)
alliance.name = "Alliance 3"
let second = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2)
XCTAssertEqual(second.picks, ["frc1", "frc3", "frc2", "frc4"])
XCTAssertEqual(second.allianceName, "Alliance 3")
XCTAssertNil(first.allianceLevel)
XCTAssertFalse(first.hasAllianceLevel)
let status = EventStatusPlayoff.init(entity: EventStatusPlayoff.entity(), insertInto: persistentContainer.viewContext)
status.level = "f"
status.status = "won"
alliance.status = status
let third = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2)
XCTAssertEqual(third.picks, ["frc1", "frc3", "frc2", "frc4"])
XCTAssertEqual(third.allianceName, "Alliance 3")
XCTAssertEqual(third.allianceLevel, "W")
XCTAssert(third.hasAllianceLevel)
}
}
| 45.5 | 126 | 0.693956 |
d6350338d89f2b592e4a981b2b9098299ed7653a | 551 | //
// ExternalURL.swift
// Coremelysis
//
// Created by Artur Carneiro on 27/09/20.
// Copyright © 2020 Rafael Galdino. All rights reserved.
//
import Foundation
/// Type responsible for managing external URLs, such as Coremelysis's GitHub repository and license.
enum ExternalURL: String {
case gitHub = "https://github.com/Galdineris/Coremelysis"
case sentimentPolarity = "https://github.com/cocoa-ai/SentimentCoreMLDemo/blob/master/README.md#model"
case license = "https://github.com/Galdineris/Coremelysis/blob/master/LICENSE"
}
| 32.411765 | 106 | 0.745917 |
ed035eb06e4c1e4fc822be4938763bc1b3b6709f | 1,304 | //
// SnapshotActionSheetUtils.swift
// InAppViewDebugger
//
// Created by Indragie Karunaratne on 4/9/19.
// Copyright © 2019 Indragie Karunaratne. All rights reserved.
//
import UIKit
func makeActionSheet(snapshot: Snapshot, sourceView: UIView, sourcePoint: CGPoint, focusAction: @escaping (Snapshot) -> Void) -> UIAlertController {
let actionSheet = UIAlertController(title: nil, message: snapshot.element.description, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: NSLocalizedString("Focus", comment: "Focus on the hierarchy associated with this element"), style: .default) { _ in
focusAction(snapshot)
})
actionSheet.addAction(UIAlertAction(title: NSLocalizedString("Log Description", comment: "Log the description of this element"), style: .default) { _ in
Logger.log(snapshot.element.description)
})
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel the action"), style: .cancel, handler: nil)
actionSheet.addAction(cancel)
actionSheet.preferredAction = cancel
actionSheet.popoverPresentationController?.sourceView = sourceView
actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: sourcePoint, size: .zero)
return actionSheet
}
| 40.75 | 162 | 0.739264 |
e5f23aeb138b1e842f369a75c66f41ab9f7915a7 | 561 | //
// StudentCoreData.swift
// one
//
// Created by sidney on 2021/10/6.
//
import Foundation
import CoreData
class StudentCoreData {
static let shared = StudentCoreData()
let entityName = "Student"
private init() {}
func insertData(context: NSManagedObjectContext) -> Student {
let entity: Student = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Student
entity.name = "李四\(arc4random() % 20)"
entity.age = Int16((arc4random() % 100))
return entity
}
}
| 22.44 | 119 | 0.648841 |
386054d5ca96814dfab83b947e6dfa5a68f72ead | 1,412 | //
// TypeHolderExample.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import AnyCodable
internal struct TypeHolderExample: Codable, Hashable {
internal var stringItem: String
internal var numberItem: Double
internal var integerItem: Int
internal var boolItem: Bool
internal var arrayItem: [Int]
internal init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) {
self.stringItem = stringItem
self.numberItem = numberItem
self.integerItem = integerItem
self.boolItem = boolItem
self.arrayItem = arrayItem
}
internal enum CodingKeys: String, CodingKey, CaseIterable {
case stringItem = "string_item"
case numberItem = "number_item"
case integerItem = "integer_item"
case boolItem = "bool_item"
case arrayItem = "array_item"
}
// Encodable protocol methods
internal func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(stringItem, forKey: .stringItem)
try container.encode(numberItem, forKey: .numberItem)
try container.encode(integerItem, forKey: .integerItem)
try container.encode(boolItem, forKey: .boolItem)
try container.encode(arrayItem, forKey: .arrayItem)
}
}
| 29.416667 | 111 | 0.689802 |
d993a231fc218519e33bc3a55afc125474c2a7fd | 925 | //
// PrefetchFeedController.swift
// TestTapptitude
//
// Created by Alexandru Tudose on 17/01/2017.
// Copyright © 2017 Tapptitude. All rights reserved.
//
import Tapptitude
import UIKit
class PrefetchFeedController: CollectionFeedController {
override func viewDidLoad() {
let dataSource = DataSource<String>(loadPage: API.getHackerNews(page:callback:))
self.dataSource = dataSource
self.cellController = MultiCollectionCellController(TextItemCellController())
}
}
extension TextItemCellController: CollectionCellPrefetcher {
public func prefetchItems(_ items: [String], at indexPaths: [IndexPath], in collectionView: UICollectionView) {
print("prefetch", items.first!)
}
public func cancelPrefetchItems(_ items: [String], at indexPaths: [IndexPath], in collectionView: UICollectionView) {
print("cancelPrefetchItems", items)
}
}
| 28.90625 | 121 | 0.716757 |
e4ee17cc9356b813c55993c7987669339244f099 | 2,160 | import Foundation
import Cache
public struct DiskStatePersister<Value_: Codable, P_: Parameters & Codable, E_: DatasourceError & Codable>: StatePersister {
public typealias Value = Value_
public typealias P = P_
public typealias E = E_
public typealias StatePersistenceKey = String
private let key: StatePersistenceKey
private let storage: Storage<PersistedState>?
public init(key: StatePersistenceKey, storage: Storage<PersistedState>?) {
self.key = key
self.storage = storage
}
public init(key: StatePersistenceKey, diskConfig: DiskConfig? = nil, memoryConfig: MemoryConfig? = nil) {
var fallbackDiskConfig: DiskConfig {
return DiskConfig(name: key)
}
var fallbackMemoryConfig: MemoryConfig {
return MemoryConfig(expiry: .never, countLimit: 10, totalCostLimit: 10)
}
var transformer: Transformer<PersistedState> {
return Transformer.init(toData: { state -> Data in
return try JSONEncoder().encode(state)
}, fromData: { data -> PersistedState in
return try JSONDecoder().decode(State.self, from: data)
})
}
let storage = try? Storage<State>.init(diskConfig: diskConfig ?? fallbackDiskConfig, memoryConfig: memoryConfig ?? fallbackMemoryConfig, transformer: transformer)
self.init(key: key, storage: storage)
}
public func persist(_ state: PersistedState) {
try? storage?.setObject(state, forKey: "latestValue")
}
public func load(_ parameters: P) -> PersistedState? {
guard let storage = self.storage else {
return nil
}
do {
let state = try storage.object(forKey: "latestValue")
if (state.loadImpulse?.parameters.isCacheCompatible(parameters) ?? false) {
return state
} else {
return nil
}
} catch {
return nil
}
}
public func purge() {
try? storage?.removeAll()
}
}
| 31.764706 | 170 | 0.595833 |
f90b47b6c4bb46afafc432f3cfc1318b7e2f4ce8 | 1,633 | //
// ViewController.swift
// RunModalDemo
//
// Created by xdf_yanqing on 2020/9/3.
// Copyright © 2020 xdf_yanqing. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
var timer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer(timeInterval: 1, repeats: true) { (timer) in
DispatchQueue.main.async {
debugPrint("123456789")
}
debugPrint("123456789")
}
debugPrint(String(format:"%p",(RunLoop.current)))
RunLoop.current.add(timer, forMode: .common)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func show(_ sender: NSButton) {
// DispatchQueue.main.async {
// let window = NSWindow(contentViewController: PPController())
// NSApp.runModal(for: window)
// }
}
}
class PPController: NSViewController {
override func loadView() {
self.view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
}
var timer : Timer?
override func viewDidAppear() {
super.viewDidAppear()
debugPrint(String(format:"%p",(RunLoop.current)))
}
override func viewDidLoad() {
super.viewDidLoad()
// self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
// debugPrint("123")
// })
}
deinit {
debugPrint(#function)
}
}
| 23.666667 | 100 | 0.575015 |
ab96b5addb72aecd3384e4e967dad3ca7b3c6f73 | 1,480 | import Foundation
import ios_combined
import Nuke
import UIKit
final class SpeakerViewController: UIViewController {
@IBOutlet weak var userImageView: UIImageView! {
didSet {
userImageView.clipsToBounds = true
userImageView.layer.cornerRadius = userImageView.bounds.width / 2
}
}
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var tagLabel: UILabel!
@IBOutlet weak var biographyLabel: UILabel!
private var speaker: Speaker!
static func instantiate(speaker: Speaker) -> SpeakerViewController {
guard let viewController = UIStoryboard(name: "SpeakerViewController", bundle: .main).instantiateInitialViewController() as? SpeakerViewController else { fatalError() }
viewController.speaker = speaker
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = .black
}
private func setupUI() {
if
let imageUrl = speaker.imageUrl,
let url = URL(string: imageUrl) {
Nuke.loadImage(with: url, into: userImageView)
}
userNameLabel.text = speaker.name
tagLabel.text = speaker.tagLine
biographyLabel.text = speaker.bio
}
}
| 29.6 | 176 | 0.672973 |
c1e1fc0602b54806d1b56cd4061134b3e9fceac9 | 2,272 | //
// SignupProfileViewController.swift
// Interests
//
// Created by _ on 6/20/15.
// Copyright © 2015 Developers Academy. All rights reserved.
//
import UIKit
import Photos
class SignupProfileViewController: UIViewController
{
@IBOutlet weak var userProfileImageView: UIImageView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var containerView: UIView!
private var profileImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
usernameTextField.becomeFirstResponder()
userProfileImageView.layer.cornerRadius = userProfileImageView.bounds.width / 2
userProfileImageView.layer.masksToBounds = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
@IBAction func pickProfileImage(_ tap: UITapGestureRecognizer) {
let authorization = PHPhotoLibrary.authorizationStatus()
if authorization == .notDetermined {
PHPhotoLibrary.requestAuthorization { _ in
DispatchQueue.main.async {
self.pickProfileImage(tap)
}
}
}
if authorization == .authorized {
let controller = ImagePickerSheetController()
controller.addAction(action: ImageAction(title: NSLocalizedString("Take Photo or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Use this one", comment: "Action Title"), handler: { _ in
self.presentCamera()
}, secondaryHandler: { (action, numberOfPhotos) in
controller.getSelectedImagesWithCompletion(completion: { images in
self.profileImage = images[0]
self.userProfileImageView.image = self.profileImage
})
}))
controller.addAction(action: ImageAction(title: NSLocalizedString("Cancel", comment: "Action Title"), style: .Cancel, handler: nil, secondaryHandler: nil))
self.present(controller, animated: true, completion: nil)
}
}
func presentCamera()
{
print("拍照")
}
}
| 27.373494 | 218 | 0.621039 |
38fe37779ec2b6a6542b2b2287934f288773dbf5 | 6,323 | //
/**
* Copyright (c) 2019 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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 MetalKit
import MathLib
public enum TextureUtils {
public static func loadTexture(url: URL) throws -> MTLTexture? {
let textureLoader = MTKTextureLoader(device: MetalContext.device)
let textureLoaderOptions: [MTKTextureLoader.Option: Any] = [.origin: MTKTextureLoader.Origin.bottomLeft,
.SRGB: false,
.generateMipmaps: NSNumber(booleanLiteral: true)]
let texture = try textureLoader.newTexture(URL: url,
options: textureLoaderOptions)
print("loaded texture: \(url.lastPathComponent)")
return texture
}
public static func loadTexture(texture: MDLTexture) throws -> MTLTexture? {
let textureLoader = MTKTextureLoader(device: MetalContext.device)
let textureLoaderOptions: [MTKTextureLoader.Option: Any] =
[.origin: MTKTextureLoader.Origin.bottomLeft,
.SRGB: false,
.generateMipmaps: NSNumber(booleanLiteral: true)]
let texture = try? textureLoader.newTexture(texture: texture,
options: textureLoaderOptions)
return texture
}
public static func loadCubeTexture(imageName: String) throws -> MTLTexture {
let textureLoader = MTKTextureLoader(device: MetalContext.device)
if let texture = MDLTexture(cubeWithImagesNamed: [imageName]) {
let options: [MTKTextureLoader.Option: Any] =
[.origin: MTKTextureLoader.Origin.topLeft,
.SRGB: false,
.generateMipmaps: NSNumber(booleanLiteral: false)]
return try textureLoader.newTexture(texture: texture, options: options)
}
let texture = try textureLoader.newTexture(name: imageName, scaleFactor: 1.0,
bundle: .main)
return texture
}
public static func loadTextureArray(urls: [URL]) -> MTLTexture? {
var textures: [MTLTexture] = []
for url in urls {
do {
if let texture = try self.loadTexture(url: url) {
textures.append(texture)
}
}
catch {
fatalError(error.localizedDescription)
}
}
guard textures.count > 0 else { return nil }
let descriptor = MTLTextureDescriptor()
descriptor.textureType = .type2DArray
descriptor.pixelFormat = textures[0].pixelFormat
descriptor.width = textures[0].width
descriptor.height = textures[0].height
descriptor.arrayLength = textures.count
let arrayTexture = MetalContext.device.makeTexture(descriptor: descriptor)!
let commandBuffer = MetalContext.commandQueue.makeCommandBuffer()!
let blitEncoder = commandBuffer.makeBlitCommandEncoder()!
let origin = MTLOrigin(x: 0, y: 0, z: 0)
let size = MTLSize(width: arrayTexture.width,
height: arrayTexture.height, depth: 1)
for (index, texture) in textures.enumerated() {
blitEncoder.copy(from: texture, sourceSlice: 0, sourceLevel: 0,
sourceOrigin: origin, sourceSize: size,
to: arrayTexture, destinationSlice: index,
destinationLevel: 0, destinationOrigin: origin)
}
blitEncoder.endEncoding()
commandBuffer.commit()
return arrayTexture
}
public static func buildTexture(size: Int2,
label: String,
pixelFormat: MTLPixelFormat = .rgba8Unorm,
usage: MTLTextureUsage = [.shaderRead],
storage: MTLStorageMode = .managed) -> MTLTexture {
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat,
width: size.width,
height: size.height,
mipmapped: false)
descriptor.sampleCount = 1
descriptor.storageMode = storage
descriptor.textureType = .type2D
descriptor.usage = usage
guard let texture = MetalContext.device.makeTexture(descriptor: descriptor) else {
fatalError("Texture not created")
}
texture.label = label
return texture
}
}
| 48.267176 | 117 | 0.61047 |
d50e3ace05aee6034f920af8d7ac56e368631ea8 | 6,170 | //
// SwifterPlaces.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET geo/id/:place_id
Returns all the information about a known place.
*/
public func getGeoIDWithPlaceID(placeID: String, success: ((place: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "geo/id/\(placeID).json"
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], success: { json, _ in
success?(place: json.object)
}, failure: failure)
}
/**
GET geo/reverse_geocode
Given a latitude and a longitude, searches for up to 20 places that can be used as a place_id when updating a status.
This request is an informative call and will deliver generalized results about geography.
*/
public func getGeoReverseGeocodeWithLat(lat: Double, long: Double, accuracy: String? = nil, granularity: String? = nil, maxResults: Int? = nil, callback: String? = nil, success: ((place: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "geo/reverse_geocode.json"
var parameters = Dictionary<String, Any>()
parameters["lat"] = lat
parameters["long"] = long
parameters["accuracy"] ??= accuracy
parameters["granularity"] ??= granularity
parameters["max_results"] ??= maxResults
parameters["callback"] ??= callback
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(place: json.object)
}, failure: failure)
}
/**
GET geo/search
Search for places that can be attached to a statuses/update. Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status.
Conceptually, a query can be made from the user's location, retrieve a list of places, have the user validate the location he or she is at, and then send the ID of this location with a call to POST statuses/update.
This is the recommended method to use find places that can be attached to statuses/update. Unlike GET geo/reverse_geocode which provides raw data access, this endpoint can potentially re-order places with regards to the user who is authenticated. This approach is also preferred for interactive place matching with the user.
*/
public func getGeoSearchWithLat(lat: Double? = nil, long: Double? = nil, query: String? = nil, ipAddress: String? = nil, accuracy: String? = nil, granularity: String? = nil, maxResults: Int? = nil, containedWithin: String? = nil, attributeStreetAddress: String? = nil, callback: String? = nil, success: ((places: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
assert(lat != nil || long != nil || query != nil || ipAddress != nil, "At least one of the following parameters must be provided to access this resource: lat, long, ipAddress, or query")
let path = "geo/search.json"
var parameters = Dictionary<String, Any>()
parameters["lat"] ??= lat
parameters["long"] ??= long
parameters["query"] ??= query
parameters["ipAddress"] ??= ipAddress
parameters["accuracy"] ??= accuracy
parameters["granularity"] ??= granularity
parameters["max_results"] ??= maxResults
parameters["contained_within"] ??= containedWithin
parameters["attribute:street_address"] ??= attributeStreetAddress
parameters["callback"] ??= callback
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(places: json.array)
}, failure: failure)
}
/**
GET geo/similar_places
Locates places near the given coordinates which are similar in name.
Conceptually you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one.
The token contained in the response is the token needed to be able to create a new place.
*/
public func getGeoSimilarPlacesWithLat(lat: Double, long: Double, name: String, containedWithin: String? = nil, attributeStreetAddress: String? = nil, callback: String? = nil, success: ((places: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "geo/similar_places.json"
var parameters = Dictionary<String, Any>()
parameters["lat"] = lat
parameters["long"] = long
parameters["name"] = name
parameters["contained_within"] ??= containedWithin
parameters["attribute:street_address"] ??= attributeStreetAddress
parameters["callback"] ??= callback
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(places: json.array)
}, failure: failure)
}
}
| 49.36 | 381 | 0.684279 |
5d6c899a986af12e7a6f7f86d956e51260c7929a | 3,047 | // RUN: %target-parse-verify-swift
func canonical_empty_protocol() -> protocol<> {
return 1
}
protocol P1 {
func p1()
func f(_: Int) -> Int
}
protocol P2 : P1 {
func p2()
}
protocol P3 {
func p3()
}
protocol P4 : P3 {
func p4()
func f(_: Double) -> Double
}
typealias Any = protocol<>
typealias Any2 = protocol< >
// Okay to inherit a typealias for a protocol<> type.
protocol P5 : Any { }
extension Int : P5 { }
typealias Bogus = protocol<P1, Int> // expected-error{{non-protocol type 'Int' cannot be used within 'protocol<...>'}}
func testEquality() {
// Remove duplicates from protocol-conformance types.
let x1 : (_ : protocol<P2, P4>) -> ()
let x2 : (_ : protocol<P3, P4, P2, P1>) -> ()
x1 = x2
_ = x1
// Singleton protocol-conformance types, after duplication, are the same as
// simply naming the protocol type.
let x3 : (_ : protocol<P2, P1>) -> ()
let x4 : (_ : P2) -> ()
x3 = x4
_ = x3
// Empty protocol-conformance types are empty.
let x5 : (_ : Any) -> ()
let x6 : (_ : Any2) -> ()
x5 = x6
_ = x5
let x7 : (_ : protocol<P1, P3>) -> ()
let x8 : (_ : protocol<P2>) -> ()
x7 = x8 // expected-error{{cannot assign value of type '(P2) -> ()' to type '(protocol<P1, P3>) -> ()'}}
_ = x7
}
// Name lookup into protocol-conformance types
func testLookup() {
let x1 : protocol<P2, P1, P4>
x1.p1()
x1.p2()
x1.p3()
x1.p4()
var _ : Int = x1.f(1)
var _ : Double = x1.f(1.0)
}
protocol REPLPrintable {
func replPrint()
}
protocol SuperREPLPrintable : REPLPrintable {
func superReplPrint()
}
protocol FooProtocol {
func format(_ kind: UnicodeScalar, layout: String) -> String
}
struct SuperPrint : REPLPrintable, FooProtocol, SuperREPLPrintable {
func replPrint() {}
func superReplPrint() {}
func format(_ kind: UnicodeScalar, layout: String) -> String {}
}
struct Struct1 {}
extension Struct1 : REPLPrintable, FooProtocol {
func replPrint() {}
func format(_ kind: UnicodeScalar, layout: String) -> String {}
}
func accept_manyPrintable(_: protocol<REPLPrintable, FooProtocol>) {}
func return_superPrintable() -> protocol<FooProtocol, SuperREPLPrintable> {}
func testConversion() {
// Conversions for literals.
var x : protocol<REPLPrintable, FooProtocol> = Struct1()
accept_manyPrintable(Struct1())
// Conversions for nominal types that conform to a number of protocols.
let sp : SuperPrint
x = sp
accept_manyPrintable(sp)
// Conversions among existential types.
var x2 : protocol<SuperREPLPrintable, FooProtocol>
x2 = x // expected-error{{value of type 'protocol<FooProtocol, REPLPrintable>' does not conform to 'protocol<FooProtocol, SuperREPLPrintable>' in assignment}}
x = x2
// Subtyping
var _ : () -> protocol<FooProtocol, SuperREPLPrintable> = return_superPrintable
// FIXME: closures make ABI conversions explicit. rdar://problem/19517003
var _ : () -> protocol<FooProtocol, REPLPrintable> = { return_superPrintable() }
}
// Test the parser's splitting of >= into > and =.
var x : protocol<P5>=17
| 24.376 | 160 | 0.663604 |
46b02ec02e82599fbf82a91a57e10c052eb73209 | 1,500 | //
// Core+UIView.swift
// Core
//
// Created by Daniel Tarazona on 5/26/21.
//
import Foundation
import UIKit
extension UIView {
@discardableResult func autolayout() -> Self {
self.translatesAutoresizingMaskIntoConstraints = false
return self
}
func anchorToView(_ view: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) {
activate([
self.trailingAnchor.constraint(
equalTo: view.trailingAnchor,
constant: insets.right),
self.leadingAnchor.constraint(
equalTo: view.leadingAnchor,
constant: insets.left),
self.topAnchor.constraint(
equalTo: view.topAnchor,
constant: insets.top),
self.bottomAnchor.constraint(
equalTo: view.bottomAnchor,
constant: insets.bottom)
])
}
func anchorToLayoutGuide(_ layoutGuide: UILayoutGuide) {
activate([
self.trailingAnchor.constraint(
equalTo: layoutGuide.trailingAnchor),
self.leadingAnchor.constraint(
equalTo: layoutGuide.leadingAnchor),
self.topAnchor.constraint(
equalTo: layoutGuide.topAnchor),
self.bottomAnchor.constraint(
equalTo: layoutGuide.bottomAnchor)
])
}
func activate(_ layoutConstraints: [NSLayoutConstraint]) {
NSLayoutConstraint.activate(layoutConstraints)
}
}
| 28.846154 | 81 | 0.597333 |
e68ca534403a8e14cce7d7e778b96c5f2a82e4c0 | 1,792 | /*
License Agreement for FDA My Studies
Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. 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.
Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as
Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”).
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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
class FeedBackTableViewCell: UITableViewCell {
@IBOutlet var labelHeadingText: UILabel?
@IBOutlet var textViewFeedbackText: UITextView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 44.8 | 110 | 0.773996 |
1c0437472c6ec74c397abae84305c4ac323aa8a0 | 2,720 | //
// ParallaxBaseFlowLayout.swift
// parallax-animation
//
// Created by Martin Prusa on 22/09/2016.
// Copyright © 2016 Martin Prusa. All rights reserved.
//
import UIKit
class ParallaxBaseFlowLayout: UICollectionViewFlowLayout {
override class var layoutAttributesClass: AnyClass {
get {
return ParallaxLayoutAttributes.classForCoder()
}
}
convenience init(direction: UICollectionViewScrollDirection, itemSize: CGSize?) {
self.init()
if let size = itemSize {
self.itemSize = size
}
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = direction
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
extension ParallaxBaseFlowLayout {
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attrs:[ParallaxLayoutAttributes]? = super.layoutAttributesForElements(in: rect) as? [ParallaxLayoutAttributes]
if let attrsNotNil = attrs {
for attributes: ParallaxLayoutAttributes in attrsNotNil {
update(attributes: attributes)
}
}
return attrs
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attrs:ParallaxLayoutAttributes? = super.layoutAttributesForItem(at: indexPath) as? ParallaxLayoutAttributes
if let attrsNotNil = attrs {
update(attributes: attrsNotNil)
}
return attrs
}
private func update(attributes: ParallaxLayoutAttributes) {
attributes.parallaxValue = parallaxValue(forAttributes: attributes, direction: scrollDirection)
attributes.parallaxDirection = scrollDirection
attributes.parallaxPagingEnabled = collectionView!.isPagingEnabled
}
private func parallaxValue(forAttributes attributes: ParallaxLayoutAttributes, direction: UICollectionViewScrollDirection) -> CGFloat {
let position: CGFloat = direction == .vertical ? collectionView!.contentOffset.y + 64 : collectionView!.contentOffset.x
let final: CGFloat = direction == .vertical ? attributes.frame.minY : attributes.frame.minX
let missing: CGFloat = final - position
let parallaxValue: CGFloat = missing / (direction == .vertical ? collectionView!.frame.size.height : collectionView!.frame.size.width)
return parallaxValue
}
}
| 28.333333 | 142 | 0.673162 |
21118d90a82f7a05d44bfb96fa654348b0e9c26f | 3,324 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: unittest_swift_json.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protos/unittest_swift_json.proto
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _3: SwiftProtobuf.ProtobufAPIVersion_3 {}
typealias Version = _3
}
struct ProtobufUnittest_SwiftJSONTest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// This case was omitted from test_messages_proto3.proto
var repeatedNullValue: [SwiftProtobuf.Google_Protobuf_NullValue] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
#if swift(>=5.5) && canImport(_Concurrency)
extension ProtobufUnittest_SwiftJSONTest: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_SwiftJSONTest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SwiftJSONTest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
318: .standard(proto: "repeated_null_value"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 318: try { try decoder.decodeRepeatedEnumField(value: &self.repeatedNullValue) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.repeatedNullValue.isEmpty {
try visitor.visitPackedEnumField(value: self.repeatedNullValue, fieldNumber: 318)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_SwiftJSONTest, rhs: ProtobufUnittest_SwiftJSONTest) -> Bool {
if lhs.repeatedNullValue != rhs.repeatedNullValue {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 39.571429 | 142 | 0.759326 |
2f8cef01df67dabec875e44a46dd23a373763fb5 | 480 | //
// CategoryCell.swift
// Yelp
//
// Created by Kumawat, Diwakar on 4/9/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import UIKit
class CategoryCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 19.2 | 65 | 0.65625 |
69ae68e9df6e7f47a1eef8f1cbc09fadd120a5ee | 428 | //
// ObjHref.swift
// BeeFun
//
// Created by WengHengcong on 15/09/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
import ObjectMapper
/*
{
"href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347"
}
*/
class ObjHref: NSObject, Mappable {
var href: String?
required init?(map: Map) {
}
func mapping(map: Map) {
href <- map["href"]
}
}
| 15.851852 | 73 | 0.600467 |
1a44dbc66a7433cc20bc218ef08abb6588469870 | 1,228 | //
// Metaphone.swift
//
// Created by Mark Hamilton on 4/6/16.
// Copyright © 2016 dryverless. (http://www.dryverless.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Reserving Pod Name | 47.230769 | 81 | 0.754072 |
23f438dadac200c78f6bcf063dac7c99657d4f71 | 638 | import Foundation
import RxSwift
protocol FilesRepositoryProtocol: BaseApiRepositoryProtocol {
func uploadImage(imageURL: URL) -> Single<MediaFile?>
func uploadImage(image: UIImage?) -> Single<MediaFile?>
func getFile(fileID: Int) -> Single<MediaFile?>
func downloadPackage(realmMediaFile: RealmMediaFile) -> Observable<VideoPackageProgress>
func createPresignURL(filename: String, parentType: MediaFile.ParentType) -> Single<PresignMediaFileURL>
func uploadFile(fileURL: URL, presignMediaFileURL: PresignMediaFileURL) -> Single<Void>
func confirmUpload(id: String) -> Single<Void>
}
| 35.444444 | 108 | 0.744514 |
e47f136ed511484efa4b097c95218a9a1cbdfbfd | 2,130 | //
// RxMath.swift
//
// Copyright (c) 2019 Greg Pape (http://www.gpape.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import RxSwift
import RxCocoa
extension ObservableType where Element: FloatingPoint {
/// Clamps elements to between 0 and 1.
public func clamp() -> Observable<Element> {
return clamp(min: 0, max: 1)
}
/// Clamps elements to between `min` and `max`.
public func clamp(min: Element, max: Element) -> Observable<Element> {
return map { n in
let v = n < min ? min : n
return v > max ? max : v
}
}
}
extension SharedSequence where Element: FloatingPoint {
/// Clamps elements to between 0 and 1.
public func clamp() -> SharedSequence<SharingStrategy, Element> {
return clamp(min: 0, max: 1)
}
/// Clamps elements to between `min` and `max`.
public func clamp(min: Element, max: Element) -> SharedSequence<SharingStrategy, Element> {
return map { n in
let v = n < min ? min : n
return v > max ? max : v
}
}
}
| 34.918033 | 95 | 0.674178 |
643e2ab83c34f0f1102bfb5c5bf714d97e2a8214 | 2,850 | //
// JsonController.swift
// AnimationPractice
//
// Created by Tomoyuki Tsujimoto on 2019/01/21.
//
import Foundation
import UIKit
struct WebsiteDescription: Decodable {
let name: String
let description: String
let courses: [Course]
}
struct Course: Decodable {
let id: Int?
let name: String?
let link: String?
let imageUrl: String?
// Swift 2/3/ObjC
// init(json: [String: Any]) {
// id = json["id"] as? Int ?? -1
// name = json["name"] as? String ?? ""
// link = json["link"] as? String ?? ""
// imageUrl = json["imageUrl"] as? String ?? ""
// }
}
class JsonController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Json"
// // 1. Course
// let jsonUrlString = "https://api.letsbuildthatapp.com/jsondecodable/course"
// // 2. Courses
// let jsonUrlString = "https://api.letsbuildthatapp.com/jsondecodable/courses"
// // 3. Course Detail
// let jsonUrlString = "https://api.letsbuildthatapp.com/jsondecodable/website_description"
// 4. Courses widh Missing field
let jsonUrlString = "https://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, res, err) in
print("success")
guard let data = data else { return }
// let dataAsString = String(data: data, encoding: String.Encoding.utf8)
// print(dataAsString)
do {
// // Swift 2/3/ObjC
// guard let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any] else { return }
// print(json)
// let course = Course(json: json)
// print(course.name)
// Swift 4
// // 1. Courses
// let courses = try JSONDecoder().decode(Course.self, from: data)
// print(courses)
// // 2. Courses
// let courses = try JSONDecoder().decode([Course].self, from: data)
// print(courses)
// // 3. Course Detail
// let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
// print(websiteDescription)
// 4. Courses widh Missing field
let courses = try JSONDecoder().decode([Course].self, from: data)
print(courses)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
}
| 32.758621 | 174 | 0.546667 |
fe6bea000239f74d924a173e6fa6b2cdc787ffb7 | 187 | public extension DirectoryConfig {
@available(*, deprecated, renamed: "detect")
public static var `default`: () -> DirectoryConfig {
return DirectoryConfig.detect
}
}
| 26.714286 | 56 | 0.673797 |
5bf41fcb38ec78b265edefab698a4ed35c1b011a | 3,807 | //
// MMNetworking.swift
// MMImageLoader
//
// Created by Mohamed Maail on 5/26/16.
// Copyright © 2016 Mohamed Maail. All rights reserved.
//
import Foundation
class MMNetworking: NSObject, URLSessionTaskDelegate{
static let sharedManager = MMNetworking()
var Session = URLSession()
let URLCache = Foundation.URLCache(memoryCapacity: 50 * 1024 * 1024, diskCapacity: 0, diskPath: nil)//Allocate 50MB of Memory
let URLRequestTimeOutInterval = 30.0
let CacheStoragePolicy = Foundation.URLCache.StoragePolicy.allowedInMemoryOnly //can change here to allow disk cache
let RequestCachePolicy = NSURLRequest.CachePolicy.returnCacheDataElseLoad
let requestLimit = 10 //set number of connections at a given time
override init() {
super.init()
let URLConfig = URLSessionConfiguration.default
URLConfig.requestCachePolicy = NSURLRequest.CachePolicy.returnCacheDataElseLoad
URLConfig.urlCache = URLCache
URLConfig.httpMaximumConnectionsPerHost = requestLimit //set number of connections at a given time. currently set to 10
self.Session = URLSession(configuration: URLConfig, delegate: self, delegateQueue: nil)
}
/*!
*
* Make a NSURLRequest
*
* @param NSURL
* @return Status, Data
*/
func makeRequest(_ URL: String, completion: @escaping (_ Status:Bool, _ Data:Data) -> ()){
let nsURL = Foundation.URL(string: URL)
let URLRequest = Foundation.URLRequest(url: nsURL!, cachePolicy: self.RequestCachePolicy, timeoutInterval: URLRequestTimeOutInterval)
checkCache(URLRequest) { (Status, Data) in
if Status{
print("MMNetworkingInfo: Data loaded from cache for (\(URL))" )
completion(Status, Data)
}else{
let task = self.Session.dataTask(with: nsURL!, completionHandler: {(data, response, error) in
if let errorUnwrapped = error{
print("MMNetworkingErrorDescription:" + errorUnwrapped.localizedDescription)
completion(false, Foundation.Data())
}else{
if let dataUnwrapped = data{
//cache here
self.URLCache.storeCachedResponse(CachedURLResponse(response:response!, data:dataUnwrapped, userInfo:nil, storagePolicy:self.CacheStoragePolicy), for: URLRequest)
DispatchQueue.main.async { () -> Void in
completion(true, dataUnwrapped)
}
}else{
completion(true, Foundation.Data())
}
}
})
task.resume()
}
}
}
/*!
*
* Check whether cache exists for NSURLRequest
*
* @param NSURLRequest
* @return Status, Data
*/
func checkCache(_ URLRequest: Foundation.URLRequest, completion: (_ Status:Bool, _ Data:Data) -> ()){
if let response = URLCache.cachedResponse(for: URLRequest) {
if response.data.count > 0 {
completion(true, response.data)
}else{
completion(false, Data())
}
}else{
completion(false, Data())
}
}
/*!
*
* Cancel a connection
*
* @param NSURL
* @return void
*/
func cancelConnection(_ URL:Foundation.URL) {
self.Session.dataTask(with: URL).cancel()
}
}
| 36.961165 | 190 | 0.554242 |
dde3a56dd67a7d55023fc527f6766ce3efe893fc | 615 |
import Foundation
import Flutter
class MyFlutterViewFactory: NSObject,FlutterPlatformViewFactory {
var messenger:FlutterBinaryMessenger
init(messenger:FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
return MyFlutterView(frame,viewID: viewId,args: args,messenger: messenger)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
| 27.954545 | 117 | 0.717073 |
18074dc4667b20d328911a1cfec85865c619e165 | 4,621 | //
// AppDelegate.swift
// Movie Hunter
//
// Created by Thiago Gasbarro Jesus on 07/01/21.
// Copyright © 2021 Thiago Gasbarro Jesus. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Movie_Hunter")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.642105 | 285 | 0.687946 |
cc8ef574e3f9a8994d2b56c77473aa63703b6779 | 1,709 | //
// OP_TUCK.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// The item at the top of the stack is copied and inserted before the second-to-top item.
public struct OpTuck: OpCodeProtocol {
public var value: UInt8 { 0x7d }
public var name: String { "OP_TUCK" }
// input : x1 x2
// output : x2 x1 x2
public func mainProcess(_ context: ScriptExecutionContext) throws {
try context.assertStackHeightGreaterThanOrEqual(2)
let x: Data = context.data(at: -1)
let count: Int = context.stack.count
context.stack.insert(x, at: count - 2)
}
}
| 41.682927 | 89 | 0.723815 |
38f059aae5aed56064bdf8a9f4cf61bdc65a646a | 493 | //
// AppInfoViewController.swift
// BELL
//
// Created by 최은지 on 11/06/2020.
// Copyright © 2020 최은지. All rights reserved.
//
import UIKit
class AppInfoViewController: UIViewController {
@IBOutlet weak var openButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.openButton.layer.borderColor = UIColor.gray.cgColor
self.openButton.layer.borderWidth = 1
self.openButton.layer.cornerRadius = 5
}
}
| 18.961538 | 64 | 0.651116 |
f5e2f5f784d8436739cd2431f7cf2ff144fb7866 | 1,139 | //
// NibLoadable.swift
// StateView
//
// Created by Alberto Aznar de los Ríos on 23/05/2019.
// Copyright © 2019 Alberto Aznar de los Ríos. All rights reserved.
//
import UIKit
// MARK: Protocol Definition
/** Make your UIView subclasses conform to this protocol when:
* they *are* NIB-based, and
* this class is used as the XIB's root view
*
* to be able to instantiate them from the NIB in a type-safe manner
*/
protocol NibLoadable: class {
/// The nib file to use to load a new instance of the View designed in a XIB
static var nib: UINib { get }
}
// MARK: Default implementation
extension NibLoadable {
/* By default, use the nib which have the same name as the name of the class,
and located in the bundle of that class */
static var nib: UINib {
var nibName = String(describing: self)
#if os(tvOS)
nibName += "-TV"
#endif
return UINib(nibName: nibName, bundle: Bundle(for: self))
}
/// Use to create the view with the nib
static var view: Self {
return nib.instantiate(withOwner: Self.self, options: nil)[0] as! Self
}
}
| 27.119048 | 81 | 0.65496 |
1c6fccb9dfd9ac7a40fb139f27d15f8db3e38b8e | 3,777 | enum Color {
case Red
case Black
}
indirect enum Tree {
case Leaf
case Node(Color, Tree, UInt64, Bool, Tree)
}
func balance1(_ kv : UInt64, _ vv : Bool, _ t : Tree, _ n : Tree) -> Tree {
switch n {
case let .Node(_, .Node(.Red, l, kx, vx, r1), ky, vy, r2):
return .Node(.Red, .Node(.Black, l, kx, vx, r1), ky, vy, .Node(.Black, r2, kv, vv, t))
case let .Node(_, l1, ky, vy, .Node(.Red, l2, kx, vx, r)):
return .Node(.Red, .Node(.Black, l1, ky, vy, l2), kx, vx, .Node(.Black, r, kv, vv, t))
case let .Node(_, l, ky, vy, r):
return .Node(.Black, .Node(.Red, l, ky, vy, r), kv, vv, t)
default:
return .Leaf
}
}
func balance2(_ t : Tree, _ kv : UInt64, _ vv : Bool, _ n : Tree) -> Tree {
switch n {
case let .Node(_, .Node(.Red, l, kx1, vx1, r1), ky, vy, r2):
return .Node(.Red, .Node(.Black, t, kv, vv, l), kx1, vx1, .Node(.Black, r1, ky, vy, r2))
case let .Node(_, l1, ky, vy, .Node(.Red, l2, kx2, vx2, r2)):
return .Node(.Red, .Node(.Black, t, kv, vv, l1), ky, vy, .Node(.Black, l2, kx2, vx2, r2))
case let .Node (_, l, ky, vy, r):
return .Node(.Black, t, kv, vv, .Node(.Red, l, ky, vy, r))
default:
return .Leaf
}
}
func is_red (_ t : Tree) -> Bool {
switch t {
case .Node(.Red, _, _, _, _):
return true
default:
return false
}
}
func ins(_ t : Tree, _ kx : UInt64, _ vx : Bool) -> Tree {
switch t {
case .Leaf:
return .Node(.Red, .Leaf, kx, vx, .Leaf)
case let .Node(.Red, a, ky, vy, b):
if kx < ky {
return .Node(.Red, ins(a, kx, vx), ky, vy, b)
} else if ky == kx {
return .Node(.Red, a, kx, vx, b)
} else {
return .Node(.Red, a, ky, vy, ins(b, kx, vx))
}
case let .Node(.Black, a, ky, vy, b):
if kx < ky {
if is_red(a) {
return balance1(ky, vy, b, ins(a, kx, vx))
} else {
return .Node(.Black, ins(a, kx, vx), ky, vy, b)
}
} else if kx == ky {
return .Node(.Black, a, kx, vx, b)
} else {
if is_red(b) {
return balance2(a, ky, vy, ins(b, kx, vx))
} else {
return .Node(.Black, a, ky, vy, ins(b, kx, vx))
}
}
}
}
func set_black (_ n : Tree) -> Tree {
switch n {
case let .Node (_, l, k, v, r):
return .Node (.Black, l, k, v, r)
default:
return n
}
}
func insert (_ t : Tree, _ k : UInt64, _ v : Bool) -> Tree {
if is_red(t) {
return set_black(ins(t, k, v))
} else {
return ins(t, k, v)
}
}
func fold (_ f : (_ k : UInt64, _ v : Bool, _ d : UInt64) -> UInt64, _ n : Tree, _ d : UInt64) -> UInt64 {
switch n {
case .Leaf:
return d
case let .Node(_, l, k, v, r):
return fold(f, r, f(k, v, fold(f, l, d)))
}
}
indirect enum TreeList {
case Nil
case Cons(Tree, TreeList)
}
func mk_map (_ n : UInt64, _ freq : UInt64) -> TreeList {
var i = n
var m : Tree = .Leaf
var r : TreeList = .Nil
while i > 0 {
i = i - 1
m = insert(m, i, (i%10 == 0))
if i % freq == 0 {
r = .Cons(m, r)
}
}
return .Cons(m, r)
}
func my_len (_ n : TreeList) -> UInt64 {
var r : UInt64 = 0
var it : TreeList = n
while true {
switch it {
case let .Cons(.Node (_, _, _, _, _), xs):
r = r + 1
it = xs
case let .Cons(.Leaf, xs):
it = xs
default:
return r
}
}
}
func aux (_ k : UInt64, _ v : Bool, _ r : UInt64) -> UInt64 {
if v {
return r + 1
} else {
return r
}
}
func head (_ m : TreeList) -> Tree {
switch m {
case let .Cons(x, _):
return x
default:
return .Leaf
}
}
var num: UInt64? = 4200000
var freq: UInt64? = 5
if CommandLine.arguments.count >= 3 {
num = UInt64(CommandLine.arguments[1])
freq = UInt64(CommandLine.arguments[2])
}
let m = mk_map(num!, freq!)
let v = fold(aux, head(m), 0)
print(my_len(m), " ", v)
| 22.890909 | 106 | 0.522107 |
7210834be2389e85e9e38ab12f5b9230944197dd | 7,216 | import Foundation
import SourceKittenFramework
public struct ControlStatementRule: ConfigurationProviderRule, AutomaticTestableRule, SubstitutionCorrectableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "control_statement",
name: "Control Statement",
description:
"`if`, `for`, `guard`, `switch`, `while`, and `catch` statements shouldn't unnecessarily wrap their " +
"conditionals or arguments in parentheses.",
kind: .style,
nonTriggeringExamples: [
"if condition {\n",
"if (a, b) == (0, 1) {\n",
"if (a || b) && (c || d) {\n",
"if (min...max).contains(value) {\n",
"if renderGif(data) {\n",
"renderGif(data)\n",
"for item in collection {\n",
"for (key, value) in dictionary {\n",
"for (index, value) in enumerate(array) {\n",
"for var index = 0; index < 42; index++ {\n",
"guard condition else {\n",
"while condition {\n",
"} while condition {\n",
"do { ; } while condition {\n",
"switch foo {\n",
"do {\n} catch let error as NSError {\n}",
"foo().catch(all: true) {}",
"if max(a, b) < c {\n",
"switch (lhs, rhs) {\n"
],
triggeringExamples: [
"↓if (condition) {\n",
"↓if(condition) {\n",
"↓if (condition == endIndex) {\n",
"↓if ((a || b) && (c || d)) {\n",
"↓if ((min...max).contains(value)) {\n",
"↓for (item in collection) {\n",
"↓for (var index = 0; index < 42; index++) {\n",
"↓for(item in collection) {\n",
"↓for(var index = 0; index < 42; index++) {\n",
"↓guard (condition) else {\n",
"↓while (condition) {\n",
"↓while(condition) {\n",
"} ↓while (condition) {\n",
"} ↓while(condition) {\n",
"do { ; } ↓while(condition) {\n",
"do { ; } ↓while (condition) {\n",
"↓switch (foo) {\n",
"do {\n} ↓catch(let error as NSError) {\n}",
"↓if (max(a, b) < c) {\n"
],
corrections: [
"↓if (condition) {\n": "if condition {\n",
"↓if(condition) {\n": "if condition {\n",
"↓if (condition == endIndex) {\n": "if condition == endIndex {\n",
"↓if ((a || b) && (c || d)) {\n": "if (a || b) && (c || d) {\n",
"↓if ((min...max).contains(value)) {\n": "if (min...max).contains(value) {\n",
"↓for (item in collection) {\n": "for item in collection {\n",
"↓for (var index = 0; index < 42; index++) {\n": "for var index = 0; index < 42; index++ {\n",
"↓for(item in collection) {\n": "for item in collection {\n",
"↓for(var index = 0; index < 42; index++) {\n": "for var index = 0; index < 42; index++ {\n",
"↓guard (condition) else {\n": "guard condition else {\n",
"↓while (condition) {\n": "while condition {\n",
"↓while(condition) {\n": "while condition {\n",
"} ↓while (condition) {\n": "} while condition {\n",
"} ↓while(condition) {\n": "} while condition {\n",
"do { ; } ↓while(condition) {\n": "do { ; } while condition {\n",
"do { ; } ↓while (condition) {\n": "do { ; } while condition {\n",
"↓switch (foo) {\n": "switch foo {\n",
"do {\n} ↓catch(let error as NSError) {\n}": "do {\n} catch let error as NSError {\n}",
"↓if (max(a, b) < c) {\n": "if max(a, b) < c {\n"
]
)
public func validate(file: SwiftLintFile) -> [StyleViolation] {
return violationRanges(in: file).map { match -> StyleViolation in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: match.location))
}
}
public func violationRanges(in file: SwiftLintFile) -> [NSRange] {
let statements = ["if", "for", "guard", "switch", "while", "catch"]
let statementPatterns: [String] = statements.map { statement -> String in
let isGuard = statement == "guard"
let isSwitch = statement == "switch"
let elsePattern = isGuard ? "else\\s*" : ""
let clausePattern = isSwitch ? "[^,{]*" : "[^{]*"
return "\(statement)\\s*\\(\(clausePattern)\\)\\s*\(elsePattern)\\{"
}
return statementPatterns.flatMap { pattern -> [NSRange] in
return file.match(pattern: pattern)
.filter { match, syntaxKinds -> Bool in
let matchString = file.contents.substring(from: match.location, length: match.length)
return !isFalsePositive(matchString, syntaxKind: syntaxKinds.first)
}
.map { $0.0 }
.filter { match -> Bool in
let contents = file.contents.bridge()
guard let byteOffset = contents.NSRangeToByteRange(start: match.location, length: 1)?.location,
let outerKind = file.structureDictionary.structures(forByteOffset: byteOffset).last else {
return true
}
return outerKind.expressionKind != .call
}
}
}
public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String) {
var violationString = file.contents.bridge().substring(with: violationRange)
if violationString.contains("(") && violationString.contains(")") {
if let openingIndex = violationString.firstIndex(of: "(") {
let replacement = violationString[violationString.index(before: openingIndex)] == " " ? "" : " "
violationString.replaceSubrange(openingIndex...openingIndex, with: replacement)
}
if let closingIndex = violationString.lastIndex(of: ")" as Character) {
let replacement = violationString[violationString.index(after: closingIndex)] == " " ? "" : " "
violationString.replaceSubrange(closingIndex...closingIndex, with: replacement)
}
}
return (violationRange, violationString)
}
private func isFalsePositive(_ content: String, syntaxKind: SyntaxKind?) -> Bool {
if syntaxKind != .keyword {
return true
}
guard let lastClosingParenthesePosition = content.lastIndex(of: ")") else {
return false
}
var depth = 0
var index = 0
for char in content {
if char == ")" {
if index != lastClosingParenthesePosition && depth == 1 {
return true
}
depth -= 1
} else if char == "(" {
depth += 1
}
index += 1
}
return false
}
}
| 45.961783 | 115 | 0.504157 |
8fda1457aebc96860f1e56dd0de92f8963125985 | 451 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct S<T{let:{class b.protocol P{func f func f:T.C
| 45.1 | 79 | 0.751663 |
62e1474ffdd287c15350410ca3679e8b2e46032a | 553 | //
// DeviceType.swift
// NotificationHub
//
// Created by Yudai.Hirose on 2019/10/06.
// Copyright © 2019 bannzai. All rights reserved.
//
import Foundation
import SwiftUI
enum DeviceType: String, CaseIterable, Identifiable {
// TODO: Add cases
case iPhoneSE = "iPhone SE"
case iPhoneXSMax = "iPhone XS Max"
var id: String { rawValue }
var preview: PreviewDevice { PreviewDevice(rawValue: rawValue) }
var name: String { rawValue }
static var previewDevices: [DeviceType] { [.iPhoneSE, .iPhoneXSMax] }
}
| 23.041667 | 73 | 0.672694 |
28cd81e9fa23734e6c98caa2d32aa94e6e8fed65 | 268 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
struct Favicon {
static func get(for url: URL?) -> URL? {
guard let host = url?.host else { return nil }
return URL(string: "https://api.faviconkit.com/\(host)/144")
}
}
| 24.363636 | 68 | 0.63806 |
0a8f29f8a21b174b03bca335d0812d04c7729edd | 666 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
final class TimerImpl: Timer {
private var timer: Foundation.Timer?
private var fire: (() -> Void)?
init() {}
func invalidate() {
timer?.invalidate()
}
func restart(timeout: Double, repeat repeats: Bool, fire: @escaping () -> Void) {
invalidate()
self.fire = fire
timer = Foundation.Timer.scheduledTimer(timeInterval: timeout,
target: self,
selector: #selector(TimerImpl.timerFired),
userInfo: nil,
repeats: repeats
)
}
@objc private func timerFired() {
fire?()
}
}
| 20.8125 | 85 | 0.566066 |
e91d760d4092000e7500efb4dde3c76b024d6e44 | 665 | //
// CreateSummariesQuery.swift
// ComicsInfoCore
//
// Created by Aleksandar Dinic on 14/02/2021.
// Copyright © 2021 Aleksandar Dinic. All rights reserved.
//
import struct Logging.Logger
import Foundation
public struct CreateSummariesQuery<Summary: ItemSummary>: LoggerProvider {
let summaries: [Summary]
let table: String
let logger: Logger?
var dynamoDBQuery: DynamoDBCreateSummariesQuery<Summary> {
let query = DynamoDBCreateSummariesQuery(summaries: summaries, table: table)
guard let logger = logger else {
return query
}
return log(logger, loggable: query)
}
}
| 23.75 | 84 | 0.675188 |
1198fcb4c6eba14a2ec1e7fc34b442ab87ea3e49 | 5,731 | import PathKit
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case name
case sorting
case projects
case folders
case files
}
// MARK: - Decodable
extension Manifest: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Decoding name
name = try container.decode(String.self, forKey: .name)
// Decoding sorting
let sorting: Sorting
if let sortingRules = try? container.decode([String].self, forKey: .sorting) {
sorting = .init(from: sortingRules)
} else {
sorting = .default
}
self.sorting = sorting
// Decoding workspaceElements
let decodedFolders = (try? container.decode([Folder].self, forKey: .folders)) ?? []
let decodedProjects = (try? container.decode([String].self, forKey: .projects)) ?? []
let decodedFiles = (try? container.decode([String].self, forKey: .files)) ?? []
let foldersProcessingResult = try Self.processFolders(
decodedFolders
)
let projectsProcessingResult = Self.processProjects(
decodedProjects + foldersProcessingResult.projectsToProcess
)
let filesProcessingResult = Self.processFiles(
decodedFiles + foldersProcessingResult.filesToProcess
)
self.workspaceElements = foldersProcessingResult.workspaceElements +
projectsProcessingResult.workspaceElements +
filesProcessingResult.workspaceElements
}
}
// MARK: - Folders
private extension Manifest {
struct FoldersProcessingResult {
var workspaceElements = [WorkspaceElement]()
var projectsToProcess = [String]()
var filesToProcess = [String]()
}
static func processFolders(_ folders: [Folder]) throws -> FoldersProcessingResult {
guard let outputPathString = Self.outputPath else {
throw ManifestDecodingError.manifestOutputPathIsNotSet
}
let outputPath = Path(outputPathString)
var foldersQueue = folders
var result = FoldersProcessingResult()
while let folder = foldersQueue.popLast() {
let location: String
let type: WorkspaceElementType
if folder.isRecursive {
let children = (try? (outputPath + folder.path).children()) ?? []
recursiveFolderLoop: for child in children {
let childRelativePath = folder.path + "/" + child.lastComponent
guard !folder.exclude.contains(child.lastComponentWithoutExtension) else {
continue recursiveFolderLoop
}
if child.extension == "xcodeproj" {
result.projectsToProcess.append(folder.path + "/" + child.lastComponentWithoutExtension)
} else if child.isFile {
result.filesToProcess.append(childRelativePath)
} else if child.isDirectory {
foldersQueue.insert(
.init(
path: childRelativePath,
isRecursive: false,
exclude: []
),
at: 0
)
}
}
continue
} else {
location = folder.path
let folderPackagePath: Path = outputPath + folder.path + "Package.swift"
if folderPackagePath.exists {
type = .package
} else {
type = .folder
}
}
result.workspaceElements.append(
.init(
location: location,
domain: .group,
kind: .fileRef,
type: type
)
)
}
return result
}
}
// MARK: - Projects
private extension Manifest {
struct ProjectsProcessingResult {
var workspaceElements = [WorkspaceElement]()
}
static func processProjects(_ projects: [String]) -> ProjectsProcessingResult {
var result = ProjectsProcessingResult()
for project in projects {
result.workspaceElements.append(
.init(
location: project + ".xcodeproj",
domain: .group,
kind: .fileRef,
type: .project
)
)
}
return result
}
}
// MARK: - Files
private extension Manifest {
struct FilesProcessingResult {
var workspaceElements = [WorkspaceElement]()
}
static let ignoringFilenames = [
".DS_Store"
]
static func processFiles(_ files: [String]) -> FilesProcessingResult {
var result = FilesProcessingResult()
let files = files
.filter { file in
ignoringFilenames
.map { !file.hasSuffix($0) }
.allSatisfy { $0 }
}
for file in files {
result.workspaceElements.append(
.init(
location: file,
domain: .group,
kind: .fileRef,
type: .file
)
)
}
return result
}
}
// MARK: - ManifestDecodingError
public extension Manifest {
enum ManifestDecodingError: Error {
case manifestOutputPathIsNotSet
}
}
| 28.655 | 112 | 0.52975 |
615be8c0e7c613484c474ce9d1aeaf9604a28925 | 2,620 | //
// ContentView.swift
// Einthoven
//
// Created by Yannick Börner on 29.03.21.
//
import SwiftUI
import HealthKit
struct ContentView: View {
@State var serverAddress: String = UserDefaultsProvider.getValueFromUserDefaults(key: "serverAddress") ?? ""
@State var patientReference: String = UserDefaultsProvider.getValueFromUserDefaults(key: "patientReference") ?? ""
var body: some View {
ScrollView(Axis.Set.vertical, showsIndicators: true) {
VStack {
VStack {
Image("1-01-transparent-cropped")
.resizable()
.scaledToFit()
.frame(width: 250, height: 250)
TextField("Server address", text: $serverAddress, onCommit: {
UserDefaultsProvider.setValueInUserDefaults(key: "serverAddress", value: self.serverAddress)
})
.multilineTextAlignment(.center)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Patient reference", text: $patientReference, onCommit: {
UserDefaultsProvider.setValueInUserDefaults(key: "patientReference", value: self.patientReference)
})
.multilineTextAlignment(.center)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
Spacer(minLength: 20)
}.padding()
Button(action: {
HKAuthorizer.authorizeHealthKit(completion: { (success, error) in
let ecgType = HKObjectType.electrocardiogramType()
let anchor = HKAnchorProvider.GetAnchor(forType: ecgType)
//let anchor = HKQueryAnchor.init(fromValue: 0)
HKSynchronizer().Synchronize(type: ecgType, predicate: nil, anchor: anchor, limit: HKObjectQueryNoLimit) { (success) in
if (success) {
print("All records synchronized")
} else {
print("There was an error during synchronization")
}
}
})
}) {
Text("Synchronize ECG records")
}.foregroundColor(.white)
.padding()
.background(Color.accentColor)
.cornerRadius(8)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 39.104478 | 139 | 0.529389 |
de4f2cbbbdb8b708117bbb7bded53dd0000c3b24 | 7,063 | import Foundation
import JSONUtilities
import PathKit
import ProjectSpec
import xcproj
import Yams
extension Project {
public func getProjectBuildSettings(config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if let type = config.type, options.settingPresets.applyProject {
buildSettings += SettingsPresetFile.base.getBuildSettings()
buildSettings += SettingsPresetFile.config(type).getBuildSettings()
}
// apply custom platform version
for platform in Platform.all {
if let version = options.deploymentTarget.version(for: platform) {
buildSettings[platform.deploymentTargetSetting] = version.deploymentTarget
}
}
// Prevent setting presets from overrwriting settings in project xcconfig files
if let configPath = configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
buildSettings += getBuildSettings(settings: settings, config: config)
return buildSettings
}
public func getTargetBuildSettings(target: Target, config: Config) -> BuildSettings {
var buildSettings = BuildSettings()
if options.settingPresets.applyTarget {
buildSettings += SettingsPresetFile.platform(target.platform).getBuildSettings()
buildSettings += SettingsPresetFile.product(target.type).getBuildSettings()
buildSettings += SettingsPresetFile.productPlatform(target.type, target.platform).getBuildSettings()
}
// apply custom platform version
if let version = target.deploymentTarget {
buildSettings[target.platform.deploymentTargetSetting] = version.deploymentTarget
}
// Prevent setting presets from overrwriting settings in target xcconfig files
if let configPath = target.configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
// Prevent setting presets from overrwriting settings in project xcconfig files
if let configPath = configFiles[config.name] {
buildSettings = removeConfigFileSettings(from: buildSettings, configPath: configPath)
}
buildSettings += getBuildSettings(settings: target.settings, config: config)
return buildSettings
}
public func getBuildSettings(settings: Settings, config: Config) -> BuildSettings {
var buildSettings: BuildSettings = [:]
for group in settings.groups {
if let settings = settingGroups[group] {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
buildSettings += settings.buildSettings
for (configVariant, settings) in settings.configSettings {
if config.name.lowercased().contains(configVariant.lowercased()) {
buildSettings += getBuildSettings(settings: settings, config: config)
}
}
return buildSettings
}
// combines all levels of a target's settings: target, target config, project, project config
public func getCombinedBuildSettings(basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> BuildSettings {
var buildSettings: BuildSettings = [:]
if includeProject {
if let configFilePath = configFiles[config.name] {
buildSettings += loadConfigFileBuildSettings(path: configFilePath)
}
buildSettings += getProjectBuildSettings(config: config)
}
if let configFilePath = target.configFiles[config.name] {
buildSettings += loadConfigFileBuildSettings(path: configFilePath)
}
buildSettings += getTargetBuildSettings(target: target, config: config)
return buildSettings
}
public func targetHasBuildSetting(_ setting: String, basePath: Path, target: Target, config: Config, includeProject: Bool = true) -> Bool {
let buildSettings = getCombinedBuildSettings(
basePath: basePath,
target: target,
config: config,
includeProject: includeProject
)
return buildSettings[setting] != nil
}
/// Removes values from build settings if they are defined in an xcconfig file
private func removeConfigFileSettings(from buildSettings: BuildSettings, configPath: String) -> BuildSettings {
var buildSettings = buildSettings
if let configSettings = loadConfigFileBuildSettings(path: configPath) {
for key in configSettings.keys {
// FIXME: Catch platform specifier. e.g. LD_RUNPATH_SEARCH_PATHS[sdk=iphone*]
buildSettings.removeValue(forKey: key)
buildSettings.removeValue(forKey: key.quoted)
}
}
return buildSettings
}
/// Returns cached build settings from a config file
private func loadConfigFileBuildSettings(path: String) -> BuildSettings? {
let configFilePath = basePath + path
if let settings = configFileSettings[configFilePath.string] {
return settings
} else {
guard let configFile = try? XCConfig(path: configFilePath) else { return nil }
let settings = configFile.flattenedBuildSettings()
configFileSettings[configFilePath.string] = settings
return settings
}
}
}
// cached flattened xcconfig file settings
private var configFileSettings: [String: BuildSettings] = [:]
// cached setting preset settings
private var settingPresetSettings: [String: BuildSettings] = [:]
extension SettingsPresetFile {
public func getBuildSettings() -> BuildSettings? {
if let group = settingPresetSettings[path] {
return group
}
let bundlePath = Path(Bundle.main.bundlePath)
let relativePath = Path("SettingPresets/\(path).yml")
var possibleSettingsPaths: [Path] = [
relativePath,
bundlePath + relativePath,
bundlePath + "../share/xcodegen/\(relativePath)",
Path(#file).parent().parent().parent() + relativePath,
]
if let symlink = try? bundlePath.symlinkDestination() {
possibleSettingsPaths = [
symlink + relativePath,
] + possibleSettingsPaths
}
guard let settingsPath = possibleSettingsPaths.first(where: { $0.exists }) else {
switch self {
case .base, .config, .platform:
print("No \"\(name)\" settings found")
case .product, .productPlatform:
break
}
return nil
}
guard let buildSettings = try? loadYamlDictionary(path: settingsPath) else {
print("Error parsing \"\(name)\" settings")
return nil
}
settingPresetSettings[path] = buildSettings
return buildSettings
}
}
| 38.595628 | 143 | 0.651281 |
26efeb969cb951fdbe74498b280bec0f2035a639 | 22,801 | import Ably
import Quick
import Nimble
class RestClientPresence: QuickSpec {
override func spec() {
describe("Presence") {
// RSP3
context("get") {
// RSP3a
xit("should return a PaginatedResult page containing the first page of members") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var disposable = [ARTRealtime]()
defer {
for clientItem in disposable {
clientItem.dispose()
clientItem.close()
}
}
let expectedData = "online"
let expectedPattern = "^user(\\d+)$"
// Load 150 members (2 pages)
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 150, data:expectedData as AnyObject?, options: options)]
waitUntil(timeout: testTimeout) { done in
channel.presence.get { membersPage, error in
expect(error).to(beNil())
let membersPage = membersPage!
expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult<ARTPresenceMessage>.self))
expect(membersPage.items).to(haveCount(100))
let members = membersPage.items
expect(members).to(allPass({ member in
return NSRegularExpression.match(member!.clientId, pattern: expectedPattern)
&& (member!.data as? String) == expectedData
}))
expect(membersPage.hasNext).to(beTrue())
expect(membersPage.isLast).to(beFalse())
membersPage.next { nextPage, error in
expect(error).to(beNil())
let nextPage = nextPage!
expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult<ARTPresenceMessage>.self))
expect(nextPage.items).to(haveCount(50))
let members = nextPage.items
expect(members).to(allPass({ member in
return NSRegularExpression.match(member!.clientId, pattern: expectedPattern)
&& (member!.data as? String) == expectedData
}))
expect(nextPage.hasNext).to(beFalse())
expect(nextPage.isLast).to(beTrue())
done()
}
}
}
}
// RSP3a1
it("limit should support up to 1000 items") {
let client = ARTRest(options: AblyTests.commonAppSetup())
let channel = client.channels.get("test")
let query = ARTPresenceQuery()
expect(query.limit).to(equal(100))
query.limit = 1001
expect{ try channel.presence.get(query, callback: { _, _ in }) }.to(throwError())
query.limit = 1000
expect{ try channel.presence.get(query, callback: { _, _ in }) }.toNot(throwError())
}
// RSP3a2
it("clientId should filter members by the provided clientId") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
let realtime = ARTRealtime(options: options)
defer { realtime.close() }
let realtimeChannel = realtime.channels.get("test")
realtimeChannel.presence.enterClient("ana", data: "mobile")
realtimeChannel.presence.enterClient("john", data: "web")
realtimeChannel.presence.enterClient("casey", data: "mobile")
expect(realtimeChannel.internal.presenceMap.members).toEventually(haveCount(3), timeout: testTimeout)
let query = ARTPresenceQuery()
query.clientId = "john"
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.get(query) { membersPage, error in
expect(error).to(beNil())
expect(membersPage!.items).to(haveCount(1))
let member = membersPage!.items[0]
expect(member.clientId).to(equal("john"))
expect(member.data as? NSObject).to(equal("web" as NSObject?))
done()
}
}.toNot(throwError())
}
}
// RSP3a3
it("connectionId should filter members by the provided connectionId") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var disposable = [ARTRealtime]()
defer {
for clientItem in disposable {
clientItem.dispose()
clientItem.close()
}
}
// One connection
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 6, options: options)]
// Another connection
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 3, startFrom: 7, options: options)]
let query = ARTRealtimePresenceQuery()
// Return all members from last connection (connectionId from the last connection)
query.connectionId = disposable.last!.connection.id!
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.get(query) { membersPage, error in
expect(error).to(beNil())
expect(membersPage!.items).to(haveCount(3))
expect(membersPage!.hasNext).to(beFalse())
expect(membersPage!.isLast).to(beTrue())
expect(membersPage!.items).to(allPass({ member in
let member = member!
return NSRegularExpression.match(member.clientId, pattern: "^user(7|8|9)")
}))
done()
}
}.toNot(throwError())
}
}
}
// RSP4
context("history") {
// RSP4a
it("should return a PaginatedResult page containing the first page of members") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var realtime: ARTRealtime!
defer { realtime.dispose(); realtime.close() }
let expectedData = "online"
let expectedPattern = "^user(\\d+)$"
realtime = AblyTests.addMembersSequentiallyToChannel("test", members: 150, data: expectedData as AnyObject?, options: options)
waitUntil(timeout: testTimeout) { done in
channel.presence.history { membersPage, error in
expect(error).to(beNil())
guard let membersPage = membersPage else {
fail("Page is empty"); done(); return
}
expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult<ARTPresenceMessage>.self))
expect(membersPage.items).to(haveCount(100))
let members = membersPage.items
expect(members).to(allPass({ member in
return NSRegularExpression.match(member!.clientId, pattern: expectedPattern)
&& (member!.data as? String) == expectedData
}))
expect(membersPage.hasNext).to(beTrue())
expect(membersPage.isLast).to(beFalse())
membersPage.next { nextPage, error in
expect(error).to(beNil())
guard let nextPage = nextPage else {
fail("nextPage is empty"); done(); return
}
expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult<ARTPresenceMessage>.self))
expect(nextPage.items).to(haveCount(50))
let members = nextPage.items
expect(members).to(allPass({ member in
return NSRegularExpression.match(member!.clientId, pattern: expectedPattern)
&& (member!.data as? String) == expectedData
}))
expect(nextPage.hasNext).to(beFalse())
expect(nextPage.isLast).to(beTrue())
done()
}
}
}
}
}
// RSP4
context("history") {
// RSP4b
context("query argument") {
// RSP4b2
// Disabled because there's something wrong in the Sandbox.
// More info at https://ably-real-time.slack.com/archives/C030C5YLY/p1614269570000400
xit("direction should change the order of the members") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var disposable = [ARTRealtime]()
defer {
for clientItem in disposable {
clientItem.dispose()
clientItem.close()
}
}
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 10, data:nil, options: options)]
let query = ARTDataQuery()
expect(query.direction).to(equal(ARTQueryDirection.backwards))
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.history(query) { membersPage, error in
expect(error).to(beNil())
let firstMember = membersPage!.items.first!
expect(firstMember.clientId).to(equal("user10"))
let lastMember = membersPage!.items.last!
expect(lastMember.clientId).to(equal("user1"))
done()
}
}.toNot(throwError())
}
query.direction = .forwards
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.history(query) { membersPage, error in
expect(error).to(beNil())
let firstMember = membersPage!.items.first!
expect(firstMember.clientId).to(equal("user1"))
let lastMember = membersPage!.items.last!
expect(lastMember.clientId).to(equal("user10"))
done()
}
}.toNot(throwError())
}
}
}
}
// RSP4
context("history") {
// RSP4b
context("query argument") {
// RSP4b3
it("limit supports up to 1000 members") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var realtime: ARTRealtime!
defer { realtime.dispose(); realtime.close() }
realtime = AblyTests.addMembersSequentiallyToChannel("test", members: 1, options: options)
let query = ARTDataQuery()
expect(query.limit).to(equal(100))
query.limit = 1
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.history(query) { membersPage, error in
expect(error).to(beNil())
expect(membersPage!.items).to(haveCount(1))
expect(membersPage!.hasNext).to(beFalse())
expect(membersPage!.isLast).to(beTrue())
done()
}
}.toNot(throwError())
}
query.limit = 1001
expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in
expect(error._code).to(equal(ARTDataQueryError.limit.rawValue))
})
}
}
// RSP3a3
it("connectionId should filter members by the provided connectionId") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var disposable = [ARTRealtime]()
defer {
for clientItem in disposable {
clientItem.dispose()
clientItem.close()
}
}
// One connection
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 6, options: options)]
// Another connection
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 3, startFrom: 7, options: options)]
let query = ARTRealtimePresenceQuery()
// Return all members from last connection (connectionId from the last connection)
query.connectionId = disposable.last!.connection.id!
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.get(query) { membersPage, error in
expect(error).to(beNil())
expect(membersPage!.items).to(haveCount(3))
expect(membersPage!.hasNext).to(beFalse())
expect(membersPage!.isLast).to(beTrue())
expect(membersPage!.items).to(allPass({ member in
let member = member
return NSRegularExpression.match(member!.clientId, pattern: "^user(7|8|9)")
}))
done()
}
}.toNot(throwError())
}
}
}
// RSP4
context("history") {
// RSP4b
context("query argument") {
// RSP4b1
it("start and end should filter members between those two times") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
var disposable = [ARTRealtime]()
defer {
for clientItem in disposable {
clientItem.dispose()
clientItem.close()
}
}
let query = ARTDataQuery()
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 25, options: options)]
waitUntil(timeout: testTimeout) { done in
client.time { time, error in
expect(error).to(beNil())
query.start = time
done()
}
}
waitUntil(timeout: testTimeout) { done in
delay(1.5) { done() }
}
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 3, options: options)]
waitUntil(timeout: testTimeout) { done in
client.time { time, error in
expect(error).to(beNil())
query.end = time
done()
}
}
disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 10, options: options)]
waitUntil(timeout: testTimeout) { done in
expect {
try channel.presence.history(query) { membersPage, error in
expect(error).to(beNil())
expect(membersPage!.items).to(haveCount(3))
done()
}
}.toNot(throwError())
}
}
// RSP4b1
it("start must be equal to or less than end and is unaffected by the request direction") {
let client = ARTRest(options: AblyTests.commonAppSetup())
let channel = client.channels.get("test")
let query = ARTDataQuery()
query.direction = .backwards
query.end = NSDate() as Date
query.start = query.end!.addingTimeInterval(10.0)
expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in
expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue))
})
query.direction = .forwards
expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in
expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue))
})
}
}
}
// RSP5
it("presence messages retrieved are decoded in the same way that messages are decoded") {
let options = AblyTests.commonAppSetup()
let client = ARTRest(options: options)
let channel = client.channels.get("test")
let expectedData = ["test":1]
waitUntil(timeout: testTimeout) { done in
channel.publish(nil, data: expectedData) { _ in done() }
}
let realtime = ARTRealtime(options: options)
defer { realtime.dispose(); realtime.close() }
waitUntil(timeout: testTimeout) { done in
let partialDone = AblyTests.splitDone(2, done: done)
let channel = realtime.channels.get("test")
channel.presence.enterClient("john", data: expectedData) { _ in
partialDone()
}
channel.presence.subscribe { _ in
channel.presence.unsubscribe()
partialDone()
}
}
typealias Done = () -> Void
func checkReceivedMessage<T: ARTBaseMessage>(_ done: @escaping Done) -> (ARTPaginatedResult<T>?, ARTErrorInfo?) -> Void {
return { membersPage, error in
expect(error).to(beNil())
let member = membersPage!.items[0]
expect(member.data as? NSDictionary).to(equal(expectedData as NSDictionary?))
done()
}
}
var decodeNumberOfCalls = 0
let hook = channel.internal.dataEncoder.testSuite_injectIntoMethod(after: #selector(ARTDataEncoder.decode(_:encoding:))) {
decodeNumberOfCalls += 1
}
defer { hook.remove() }
waitUntil(timeout: testTimeout) { done in
channel.history(checkReceivedMessage(done))
}
waitUntil(timeout: testTimeout) { done in
channel.presence.history(checkReceivedMessage(done))
}
expect(decodeNumberOfCalls).to(equal(2))
}
}
}
}
| 45.510978 | 150 | 0.435025 |
33b2e71139f4559f488e65be8cc18ff32058106c | 3,091 | //
// RegisterViewController.swift
// Artable
//
// Created by Ashraf Ahmed on 27/10/19.
// Copyright © 2019 Shakil Ahammed. All rights reserved.
//
import UIKit
import Firebase
class RegisterViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPassTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var passImg: UIImageView!
@IBOutlet weak var confirmPassImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupPasswordMatch()
}
private func setupPasswordMatch() {
//password match checking
passwordTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
confirmPassTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
if(textField == confirmPassTextField && passwordTextField.text != "") {
if(textField.text == "") {
passImg.isHidden = true
confirmPassImg.isHidden = true
}else {
passImg.isHidden = false
confirmPassImg.isHidden = false
if(textField.text == passwordTextField.text) {
passImg.image = UIImage(named: AppImages.GreenCheck)
confirmPassImg.image = UIImage(named: AppImages.GreenCheck)
}else{
passImg.image = UIImage(named: AppImages.RedCheck)
confirmPassImg.image = UIImage(named: AppImages.RedCheck)
}
}
}else{
passImg.isHidden = true
confirmPassImg.isHidden = true
confirmPassTextField.text = ""
}
}
@IBAction func registerBtnClicked(_ sender: Any) {
activityIndicator.startAnimating()
guard let email = emailTextField.text, email.isNotEmpty, let password = passwordTextField.text, password.isNotEmpty else {return}
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
// ...
if let error = error {
debugPrint(error)
return
}
self.activityIndicator.stopAnimating()
self.dismiss(animated: true, completion: nil)
}
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 33.967033 | 137 | 0.614688 |
edaf4bc182baf7603b35317d613e8d1e2e8beff0 | 661 | import Cocoa
protocol ViewClicked {
func buttonClicked()
}
class PopoverView: NSView, ViewClicked {
var delegate: ViewClicked?
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
let backgroundColor = NSColor.clearColor()
backgroundColor.set()
NSBezierPath.fillRect(dirtyRect)
}
override func rightMouseDown(theEvent: NSEvent) {
delegate?.buttonClicked()
}
override func otherMouseDown(theEvent: NSEvent) {
delegate?.buttonClicked()
}
override func mouseDown(theEvent: NSEvent) {
delegate?.buttonClicked()
}
func buttonClicked() { }
}
| 20.65625 | 53 | 0.664145 |
e9a521353f907b2e22294344290bbf8bf1e94943 | 2,035 | //
// WindowController.swift
// 4DSTEM Explorer
//
// Created by James LeBeau on 12/28/17.
// Copyright © 2017 The LeBeau Group. All rights reserved.
//
import Cocoa
class WindowController : NSWindowController, NSWindowDelegate {
@IBOutlet weak var scaleField:NSTextField?
var lastSelectionTag:Int?
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func windowWillLoad() {
}
override func windowDidLoad() {
self.window?.isReleasedWhenClosed = false
super.windowDidLoad()
self.window?.delegate = self
// window?.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
// window?.titlebarAppearsTransparent = true
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
self.window?.orderOut(self)
return false
}
func updateScale(_ zoom: CGFloat){
scaleField?.takeFloatValueFrom(Float(zoom))
}
@IBAction func export(_ sender:Any){
if sender is NSPopUpButton{
let popup = sender as! NSPopUpButton
let cvc = self.contentViewController as! ViewController
cvc.export(popup)
}
}
@IBAction func changeSelectionMode(_ sender:Any){
if sender is NSSegmentedControl{
let segmented = sender as! NSSegmentedControl
let cvc = self.contentViewController as! ViewController
switch segmented.selectedSegment{
case 0:
cvc.imageView.selectMode = .point
case 1:
cvc.imageView.selectMode = .marquee
// case 2:
// cvc.imageView.selectMode = .marquee
default:
cvc.imageView.selectMode = .point
}
}
}
}
| 22.865169 | 81 | 0.536609 |
690ddf9a2197febeaf33054d88190948e490b3d2 | 362 | //
// DetailView.swift
// SwiftUIListExamples
//
// Created by Hafiz on 04/08/2021.
//
import SwiftUI
struct DetailView: View {
let title: String
var body: some View {
Text(title)
.bold()
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView(title: "Lorem Ipsum")
}
}
| 15.73913 | 45 | 0.616022 |
0ebc2f87e8ccde18e2a574a1a5fb62d75da4f14d | 8,233 | //
// RWMEventKitTests.swift
// RWMRecurrenceRuleTests
//
// Created by Richard W Maddy on 5/21/18.
// Copyright © 2018 Maddysoft. All rights reserved.
//
import XCTest
class RWMEventKitTests: RWMRecurrenceRuleBase {
/*
A - RRULE FREQ=DAILY;INTERVAL=1;UNTIL=20180629T055959Z
B - RRULE FREQ=WEEKLY;INTERVAL=1;UNTIL=20180822T055959Z
C - RRULE FREQ=WEEKLY;INTERVAL=2;UNTIL=20180922T055959Z
D - RRULE FREQ=MONTHLY;INTERVAL=1;UNTIL=20200522T055959Z
E - RRULE FREQ=YEARLY;INTERVAL=1;UNTIL=20230521T180000Z
F - RRULE FREQ=DAILY;INTERVAL=3;UNTIL=20180722T055959Z
G - RRULE FREQ=WEEKLY;INTERVAL=2;UNTIL=20180822T055959Z;BYDAY=SU,WE,SA;WKST=SU
H - RRULE FREQ=MONTHLY;INTERVAL=2;UNTIL=20190622T055959Z;BYMONTHDAY=10,15,20
I - RRULE FREQ=MONTHLY;INTERVAL=3;UNTIL=20190622T055959Z;BYDAY=TU;BYSETPOS=2
J - RRULE FREQ=MONTHLY;INTERVAL=1;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYSETPOS=-1
K - RRULE FREQ=MONTHLY;INTERVAL=1;UNTIL=20190622T055959Z;BYDAY=SU,SA;BYSETPOS=3
L - RRULE FREQ=YEARLY;INTERVAL=2;UNTIL=20230622T055959Z;BYMONTH=9,10,11
M - RRULE FREQ=YEARLY;INTERVAL=1;UNTIL=20190622T055959Z;BYMONTH=5,7;BYDAY=1WE
*/
lazy var start = calendar.date(from: DateComponents(year: 2018, month: 5, day: 21, hour: 9))!
func testA() {
run(rule: "RRULE:FREQ=DAILY;INTERVAL=1;UNTIL=20180602T055959Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-05-22T09:00:00", "2018-05-23T09:00:00", "2018-05-24T09:00:00",
"2018-05-25T09:00:00", "2018-05-26T09:00:00", "2018-05-27T09:00:00", "2018-05-28T09:00:00",
"2018-05-29T09:00:00", "2018-05-30T09:00:00", "2018-05-31T09:00:00", "2018-06-01T09:00:00"]
)
}
func testB() {
run(rule: "RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20180722T055959Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-05-28T09:00:00", "2018-06-04T09:00:00", "2018-06-11T09:00:00",
"2018-06-18T09:00:00", "2018-06-25T09:00:00", "2018-07-02T09:00:00", "2018-07-09T09:00:00",
"2018-07-16T09:00:00"]
)
}
func testC() {
run(rule: "RRULE:FREQ=WEEKLY;INTERVAL=2;UNTIL=20180822T055959Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-06-04T09:00:00", "2018-06-18T09:00:00", "2018-07-02T09:00:00",
"2018-07-16T09:00:00", "2018-07-30T09:00:00", "2018-08-13T09:00:00"]
)
}
func testD() {
run(rule: "RRULE:FREQ=MONTHLY;INTERVAL=1;UNTIL=20190522T055959Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-06-21T09:00:00", "2018-07-21T09:00:00", "2018-08-21T09:00:00",
"2018-09-21T09:00:00", "2018-10-21T09:00:00", "2018-11-21T09:00:00", "2018-12-21T09:00:00",
"2019-01-21T09:00:00", "2019-02-21T09:00:00", "2019-03-21T09:00:00", "2019-04-21T09:00:00",
"2019-05-21T09:00:00"]
)
}
func testE() {
run(rule: "RRULE:FREQ=YEARLY;INTERVAL=1;UNTIL=20230521T180000Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2019-05-21T09:00:00", "2020-05-21T09:00:00", "2021-05-21T09:00:00",
"2022-05-21T09:00:00", "2023-05-21T09:00:00"]
)
}
func testF() {
run(rule: "RRULE:FREQ=DAILY;INTERVAL=3;UNTIL=20180722T055959Z", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-05-24T09:00:00", "2018-05-27T09:00:00", "2018-05-30T09:00:00",
"2018-06-02T09:00:00", "2018-06-05T09:00:00", "2018-06-08T09:00:00", "2018-06-11T09:00:00",
"2018-06-14T09:00:00", "2018-06-17T09:00:00", "2018-06-20T09:00:00", "2018-06-23T09:00:00",
"2018-06-26T09:00:00", "2018-06-29T09:00:00", "2018-07-02T09:00:00", "2018-07-05T09:00:00",
"2018-07-08T09:00:00", "2018-07-11T09:00:00", "2018-07-14T09:00:00", "2018-07-17T09:00:00",
"2018-07-20T09:00:00"]
)
}
func testG() {
run(rule: "RRULE:FREQ=WEEKLY;INTERVAL=2;UNTIL=20180822T055959Z;BYDAY=SU,WE,SA;WKST=SU", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-05-23T09:00:00", "2018-05-26T09:00:00", "2018-05-27T09:00:00",
"2018-06-06T09:00:00", "2018-06-09T09:00:00", "2018-06-10T09:00:00", "2018-06-20T09:00:00", "2018-06-23T09:00:00",
"2018-06-24T09:00:00", "2018-07-04T09:00:00", "2018-07-07T09:00:00", "2018-07-08T09:00:00",
"2018-07-18T09:00:00", "2018-07-21T09:00:00", "2018-07-22T09:00:00", "2018-08-01T09:00:00",
"2018-08-04T09:00:00", "2018-08-05T09:00:00", "2018-08-15T09:00:00", "2018-08-18T09:00:00",
"2018-08-19T09:00:00"]
)
}
func testH() {
run(rule: "RRULE:FREQ=MONTHLY;INTERVAL=2;UNTIL=20190622T055959Z;BYMONTHDAY=10,15,20", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-07-10T09:00:00", "2018-07-15T09:00:00", "2018-07-20T09:00:00",
"2018-09-10T09:00:00", "2018-09-15T09:00:00", "2018-09-20T09:00:00", "2018-11-10T09:00:00",
"2018-11-15T09:00:00", "2018-11-20T09:00:00", "2019-01-10T09:00:00", "2019-01-15T09:00:00",
"2019-01-20T09:00:00", "2019-03-10T09:00:00", "2019-03-15T09:00:00", "2019-03-20T09:00:00",
"2019-05-10T09:00:00", "2019-05-15T09:00:00", "2019-05-20T09:00:00"]
)
}
func testI() {
run(rule: "RRULE:FREQ=MONTHLY;INTERVAL=3;UNTIL=20190622T055959Z;BYDAY=TU;BYSETPOS=2", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-08-14T09:00:00", "2018-11-13T09:00:00", "2019-02-12T09:00:00",
"2019-05-14T09:00:00"]
)
}
func testJ() {
run(rule: "RRULE:FREQ=MONTHLY;INTERVAL=1;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYSETPOS=-1;COUNT=20", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-05-31T09:00:00", "2018-06-30T09:00:00", "2018-07-31T09:00:00",
"2018-08-31T09:00:00", "2018-09-30T09:00:00", "2018-10-31T09:00:00", "2018-11-30T09:00:00",
"2018-12-31T09:00:00", "2019-01-31T09:00:00", "2019-02-28T09:00:00", "2019-03-31T09:00:00",
"2019-04-30T09:00:00", "2019-05-31T09:00:00", "2019-06-30T09:00:00", "2019-07-31T09:00:00",
"2019-08-31T09:00:00", "2019-09-30T09:00:00", "2019-10-31T09:00:00", "2019-11-30T09:00:00"]
)
}
func testK() {
run(rule: "RRULE:FREQ=MONTHLY;INTERVAL=1;UNTIL=20190622T055959Z;BYDAY=SU,SA;BYSETPOS=3", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-06-09T09:00:00", "2018-07-08T09:00:00", "2018-08-11T09:00:00",
"2018-09-08T09:00:00", "2018-10-13T09:00:00", "2018-11-10T09:00:00", "2018-12-08T09:00:00",
"2019-01-12T09:00:00", "2019-02-09T09:00:00", "2019-03-09T09:00:00", "2019-04-13T09:00:00",
"2019-05-11T09:00:00", "2019-06-08T09:00:00"]
)
}
func testL() {
run(rule: "RRULE:FREQ=YEARLY;INTERVAL=2;UNTIL=20230622T055959Z;BYMONTH=9,10,11", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-09-21T09:00:00", "2018-10-21T09:00:00", "2018-11-21T09:00:00",
"2020-09-21T09:00:00", "2020-10-21T09:00:00", "2020-11-21T09:00:00", "2022-09-21T09:00:00",
"2022-10-21T09:00:00", "2022-11-21T09:00:00"]
)
}
func testM() {
run(rule: "RRULE:FREQ=YEARLY;INTERVAL=1;UNTIL=20190622T055959Z;BYMONTH=5,7;BYDAY=1WE", mode: .eventKit, start: start, results:
["2018-05-21T09:00:00", "2018-07-04T09:00:00", "2019-05-01T09:00:00"]
)
}
func testWeekly1() {
// Start 20181117T090000
// Weekly with with exdates.
let start = calendar.date(from: DateComponents(year: 2018, month: 11, day: 17, hour: 9))!
run(rule: "RRULE:FREQ=WEEKLY;COUNT=10", mode: .eventKit, start: start, results:
["2018-11-17T09:00:00", "2018-11-24T09:00:00", "2018-12-01T09:00:00", "2018-12-08T09:00:00",
"2018-12-15T09:00:00", "2018-12-22T09:00:00", "2018-12-29T09:00:00", "2019-01-05T09:00:00",
"2019-01-12T09:00:00", "2019-01-19T09:00:00"]
)
}
}
| 53.810458 | 138 | 0.602454 |
e6982968602eb1dea6a329c91859577f279f3f6d | 294 | // RUN: %target-typecheck-verify-swift -swift-version 5 -solver-enable-operator-designated-types -solver-disable-shrink -disable-constraint-solver-performance-hacks
func test(_ x: Int) -> Int {
return x + nil
// expected-error@-1 {{type of expression is ambiguous without more context}}
}
| 42 | 164 | 0.748299 |
75cb6678b73028b4f385b6a5ebcd3139f1573b9a | 793 | import Foundation
import CoreLocation
@objc(PermissionManagementPlugin) class PermissionManagementPlugin: CDVPlugin {
private let LOG_TAG = "PermissionManagementPlugin"
private var pmanagement: PermissionManagement?
override func pluginInitialize() {
self.pmanagement = PermissionManagement()
super.pluginInitialize()
}
@objc(requestCapturePermission:) func requestCapturePermission(_ command: CDVInvokedUrlCommand) {
let config = command.argument(at: 0) as! [String:Any]
self.pmanagement?.requestCapturePermission(config:config)
let warnings = [String]()
let result: CDVPluginResult
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: warnings.joined(separator: "\n"))
commandDelegate!.send(result, callbackId: command.callbackId)
}
} | 41.736842 | 102 | 0.778058 |
d52f6fb7e9dd349ccaf1435e8b813706168293a3 | 3,165 | //
// UICoordinator.swift
// LibreKitUI
//
// Created by Julian Groen on 01/01/2021.
// Copyright © 2021 Julian Groen. All rights reserved.
//
import SwiftUI
import LoopKit
import LoopKitUI
import LibreKit
class UICoordinator: UINavigationController, CGMManagerOnboarding, CompletionNotifying, UINavigationControllerDelegate {
let cgmManager: LibreCGMManager?
let glucoseUnitObservable: DisplayGlucoseUnitObservable?
let colorPalette: LoopUIColorPalette
weak var cgmManagerOnboardingDelegate: CGMManagerOnboardingDelegate?
weak var completionDelegate: CompletionDelegate?
init(
cgmManager: LibreCGMManager? = nil,
glucoseUnitObservable: DisplayGlucoseUnitObservable? = nil,
colorPalette: LoopUIColorPalette
) {
self.colorPalette = colorPalette
self.glucoseUnitObservable = glucoseUnitObservable
self.cgmManager = cgmManager
super.init(navigationBarClass: UINavigationBar.self, toolbarClass: UIToolbar.self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.prefersLargeTitles = true
delegate = self
}
override func viewWillAppear(_ animated: Bool) {
let controller = viewController(willShow: (cgmManager == nil ? .setup : .settings))
setViewControllers([controller], animated: false)
}
private enum ControllerType: Int, CaseIterable {
case setup
case settings
}
private func viewController(willShow view: ControllerType) -> UIViewController {
switch view {
case .setup:
let model = TransmitterConnectModel()
model.hasCancelled = { [weak self] in
self?.notifyCompletion()
}
model.hasContinued = { [weak self] manager in
self?.setupCompletion(manager)
}
let view = TransmitterConnectView(viewModel: model)
return viewController(rootView: view)
case .settings:
guard let cgmManager = cgmManager, let observable = glucoseUnitObservable else {
fatalError()
}
let model = ManagerSettingsModel(cgmManager: cgmManager, for: observable)
model.hasCompleted = { [weak self] in
self?.notifyCompletion()
}
let view = ManagerSettingsView(viewModel: model)
return viewController(rootView: view)
}
}
private func viewController<Content: View>(rootView: Content) -> DismissibleHostingController {
return DismissibleHostingController(rootView: rootView, colorPalette: colorPalette)
}
private func setupCompletion(_ cgmManager: LibreCGMManager) {
cgmManagerOnboardingDelegate?.cgmManagerOnboarding(didCreateCGMManager: cgmManager)
completionDelegate?.completionNotifyingDidComplete(self)
}
private func notifyCompletion() {
completionDelegate?.completionNotifyingDidComplete(self)
}
}
| 33.315789 | 120 | 0.665087 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.