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
|
---|---|---|---|---|---|
ccee186eb83f41e9ccc08223ea93bfd79808414f | 355 | //
// Reusable.swift
// Pods
//
// Created by 臧金晓 on 14/11/2016.
//
//
import Foundation
public protocol Reusable {
associatedtype Container
static func reuseIdentifier() -> String
static func register(for container: Container)
}
public extension Reusable {
static func reuseIdentifier() -> String {
return "\(self)"
}
}
| 16.136364 | 50 | 0.659155 |
1caac3d88bc0bb12a4c523920ca7a7e251fbc512 | 1,762 | import Foundation
import TSCBasic
import TuistCore
public protocol TargetActionsContentHashing {
func hash(targetActions: [TargetAction]) throws -> String
}
/// `TargetActionsContentHasher`
/// is responsible for computing a unique hash that identifies a list of target actions
public final class TargetActionsContentHasher: TargetActionsContentHashing {
private let contentHasher: ContentHashing
// MARK: - Init
public init(contentHasher: ContentHashing) {
self.contentHasher = contentHasher
}
// MARK: - TargetActionsContentHasher
/// Returns the hash that uniquely identifies an array of target actions
/// The hash takes into consideration the content of the script to execute, the content of input/output files, the name of the tool to execute, the order, the arguments and its name
public func hash(targetActions: [TargetAction]) throws -> String {
var stringsToHash: [String] = []
for targetAction in targetActions {
var pathsToHash: [AbsolutePath] = [targetAction.path ?? ""]
pathsToHash.append(contentsOf: targetAction.inputPaths)
pathsToHash.append(contentsOf: targetAction.inputFileListPaths)
pathsToHash.append(contentsOf: targetAction.outputPaths)
pathsToHash.append(contentsOf: targetAction.outputFileListPaths)
let fileHashes = try pathsToHash.map { try contentHasher.hash(path: $0) }
stringsToHash.append(contentsOf: fileHashes +
[targetAction.name,
targetAction.tool ?? "", // TODO: don't default to ""
targetAction.order.rawValue] +
targetAction.arguments)
}
return try contentHasher.hash(stringsToHash)
}
}
| 41.952381 | 185 | 0.695233 |
9b72ba42b5710ca8306d5722a05e07f963af9cf9 | 486 | //
// ControlsDemoViewController.swift
// LayoutInspectorExample
//
// Created by Igor Savynskyi on 12/25/18.
// Copyright © 2018 Igor Savynskyi. All rights reserved.
//
import UIKit
import LayoutInspector
class ControlsDemoViewController: UIViewController, ChangeAutoTriggerProtocol {
@IBAction private func inspectLayoutAction(_ sender: Any) {
LayoutInspector.shared.showLayout()
}
@IBAction func changeAutoTrigger(_ sender: Any) {
changeAutoTrigger()
}
}
| 22.090909 | 79 | 0.751029 |
6710c31310a6d662cfc9b2774ff8b147b847e46e | 4,335 | //
// UnderlineFocusView.swift
// PagingKit
//
// Copyright (c) 2017 Kazuhiro Hayashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Basic style of focus view
/// - underline height
/// - underline color
public class UnderlineFocusView: UIView {
/// The color of underline
public var underlineColor = UIColor.pk.focusRed {
didSet {
underlineView.backgroundColor = underlineColor
}
}
/// The color of underline
public var underlineHeight = CGFloat(4) {
didSet {
heightConstraint.constant = underlineHeight
}
}
public var underlineWidth: CGFloat? = nil {
didSet {
if let underlineWidth = underlineWidth {
widthConstraint.isActive = true
widthConstraint.constant = underlineWidth
} else {
widthConstraint.isActive = false
}
}
}
public var masksToBounds: Bool {
get { return underlineView.layer.masksToBounds }
set { underlineView.layer.masksToBounds = newValue }
}
public var cornerRadius: CGFloat {
get { return underlineView.layer.cornerRadius }
set { underlineView.layer.cornerRadius = newValue }
}
private let widthConstraint: NSLayoutConstraint
private let heightConstraint: NSLayoutConstraint
private let underlineView = UIView()
required public init?(coder aDecoder: NSCoder) {
widthConstraint = NSLayoutConstraint(
item: underlineView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width, multiplier: 1, constant: 0
)
heightConstraint = NSLayoutConstraint(
item: underlineView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height, multiplier: 1, constant: 0
)
super.init(coder: aDecoder)
setup()
}
override public init(frame: CGRect) {
widthConstraint = NSLayoutConstraint(
item: underlineView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .height, multiplier: 1, constant: underlineHeight
)
heightConstraint = NSLayoutConstraint(
item: underlineView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height, multiplier: 1, constant: underlineHeight
)
super.init(frame: frame)
setup()
}
private func setup() {
addSubview(underlineView)
underlineView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(heightConstraint)
addConstraint(widthConstraint)
widthConstraint.isActive = false
let constraintsA = [.bottom].anchor(from: underlineView, to: self)
let constraintsB = [.width, .centerX].anchor(from: underlineView, to: self)
constraintsB.forEach {
$0.priority = .defaultHigh
$0.isActive = true
}
addConstraints(constraintsA + constraintsB)
underlineView.backgroundColor = underlineColor
}
}
| 33.867188 | 83 | 0.632987 |
8f499b015ccc0e71813fcb8a981f143749d9c0b1 | 3,615 | //
// TableViewSectionProvider.swift
// Flix
//
// Created by DianQK on 04/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
public enum UITableElementKindSection {
case header
case footer
}
public protocol _SectionPartionTableViewProvider: FlixCustomStringConvertible {
var cellType: UITableViewHeaderFooterView.Type { get }
var tableElementKindSection: UITableElementKindSection { get }
func _tableView(_ tableView: UITableView, heightInSection section: Int, node: _Node) -> CGFloat?
func _configureSection(_ tableView: UITableView, view: UITableViewHeaderFooterView, viewInSection section: Int, node: _Node)
func _genteralSectionPartion() -> Observable<_Node?>
}
extension _SectionPartionTableViewProvider {
public func register(_ tableView: UITableView) {
tableView.register(self.cellType, forHeaderFooterViewReuseIdentifier: self._flix_identity)
}
}
public protocol SectionPartionTableViewProvider: _SectionPartionTableViewProvider {
associatedtype Cell: UITableViewHeaderFooterView
associatedtype Value
func tableView(_ tableView: UITableView, heightInSection section: Int, value: Value) -> CGFloat?
func configureSection(_ tableView: UITableView, view: UITableViewHeaderFooterView, viewInSection section: Int, value: Value)
func genteralSection() -> Observable<Value?>
}
extension SectionPartionTableViewProvider {
public var cellType: UITableViewHeaderFooterView.Type { return Cell.self }
public func _configureSection(_ tableView: UITableView, view: UITableViewHeaderFooterView, viewInSection section: Int, node: _Node) {
self.configureSection(tableView, view: view as! Cell, viewInSection: section, value: node._unwarp())
}
public func _genteralSectionPartion() -> Observable<_Node?> {
let providerIdentity = self._flix_identity
return genteralSection().map { $0.map { Node(providerIdentity: providerIdentity, value: $0) } }
}
public func _tableView(_ tableView: UITableView, heightInSection section: Int, node: _Node) -> CGFloat? {
return self.tableView(tableView, heightInSection: section, value: node._unwarp())
}
public func tableView(_ tableView: UITableView, heightInSection section: Int, node: _Node) -> CGFloat? {
return nil
}
}
public protocol _AnimatableSectionPartionProviderable {
func _genteralAnimatableSectionPartion() -> Observable<IdentifiableNode?>
}
public typealias _AnimatableSectionPartionTableViewProvider = _AnimatableSectionPartionProviderable & _SectionPartionTableViewProvider
public protocol AnimatablePartionSectionTableViewProvider: SectionPartionTableViewProvider, _AnimatableSectionPartionProviderable where Value: Equatable, Value: StringIdentifiableType {
func genteralAnimatableSectionPartion() -> Observable<IdentifiableNode?>
}
extension AnimatablePartionSectionTableViewProvider {
public func _genteralAnimatableSectionPartion() -> Observable<IdentifiableNode?> {
return genteralAnimatableSectionPartion()
}
public var identity: String {
return self._flix_identity
}
}
extension AnimatablePartionSectionTableViewProvider {
public func genteralAnimatableSectionPartion() -> Observable<IdentifiableNode?> {
let providerIdentity = self._flix_identity
return genteralSection().map { $0.map { IdentifiableNode(providerIdentity: providerIdentity, valueNode: $0) } }
}
}
| 33.472222 | 185 | 0.751867 |
1c51fcfa9e1d86bda3b9ff0d0721bea466b244df | 1,250 | //
// SplitViewController.swift
// ResinDashboard
//
// Created by Alex Kerney on 2/22/18.
// Copyright © 2018 Alex Kerney. All rights reserved.
//
import UIKit
class SplitViewController: UISplitViewController, UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
navigationItem.leftItemsSupplementBackButton = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return true
}
/*
// 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.
}
*/
}
| 29.761905 | 191 | 0.712 |
3334001ddc2d8f05b53707ed774aa171a56fec7c | 669 | import Flutter
import UIKit
@available(iOS 9.0, *)
public class SwiftActivityRecognitionPlugin: NSObject, FlutterPlugin {
internal let registrar: FlutterPluginRegistrar
private let activityClient = ActivityClient()
private let activityChannel: ActivityChannel
init(registrar: FlutterPluginRegistrar) {
self.registrar = registrar
self.activityChannel = ActivityChannel(activityClient: activityClient)
super.init()
activityChannel.register(on: self)
}
public static func register(with registrar: FlutterPluginRegistrar) {
_ = SwiftActivityRecognitionPlugin(registrar: registrar)
}
}
| 30.409091 | 78 | 0.724963 |
2893f243c74fbe945beb129dd617e55c60b797dc | 261 | //
// SKDocInfo.swift
// Sylvester 😼
//
// Created by Chris Zielinski on 1/28/19.
// Copyright © 2019 Big Z Labs. All rights reserved.
//
import SourceKittenFramework
/// A _SourceKit_ doc info request.
open class SKDocInfo: SKGenericDocInfo<SKEntity> {}
| 20.076923 | 53 | 0.712644 |
6a2e85fc0fb487ceecb1d06b32980d2c16108010 | 2,823 | import Bits
/// Represents information about a single MySQL connection.
final class MySQLConnectionSession {
/// The state of this connection.
var handshakeState: MySQLHandshakeState
/// The state of queries and other functionality on this connection.
var connectionState: MySQLConnectionState
/// The next available sequence ID.
var nextSequenceID: Byte {
defer { incrementSequenceID() }
return sequenceID
}
/// The current sequence ID.
private var sequenceID: Byte
/// Creates a new `MySQLConnectionSession`.
init() {
self.handshakeState = .waiting
self.connectionState = .none
self.sequenceID = 0
}
/// Increments the sequence ID.
func incrementSequenceID() {
sequenceID = sequenceID &+ 1
}
/// Resets the sequence ID.
func resetSequenceID() {
sequenceID = 0
}
}
/// Possible connection states.
enum MySQLHandshakeState {
/// This is a new connection that has not completed the MySQL handshake.
case waiting
/// The handshake has been completed and server capabilities are received.
case complete(MySQLCapabilities)
}
/// Possible states of a handshake-completed connection.
enum MySQLConnectionState {
/// No special state.
/// The connection should parse OK and ERR packets only.
case none
/// Performing a Text Protocol query.
case text(MySQLTextProtocolState)
/// Performing a Statement Protocol query.
case statement(MySQLStatementProtocolState)
}
/// Connection states during a simple query aka Text Protocol.
/// https://dev.mysql.com/doc/internals/en/text-protocol.html
enum MySQLTextProtocolState {
/// 14.6.4 COM_QUERY has been sent, awaiting response.
case waiting
/// parsing column_count * Protocol::ColumnDefinition packets
case columns(columnCount: Int, remaining: Int)
/// parsing One or more ProtocolText::ResultsetRow packets, each containing column_count values
case rows(columnCount: Int, remaining: Int)
}
/// Connection states during a prepared query aka Statement Protocol.
/// https://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html
enum MySQLStatementProtocolState {
/// COM_STMT_PREPARE_OK on success, ERR_Packet otherwise
case waitingPrepare
/// If num_params > 0 more packets will follow:
case params(ok: MySQLComStmtPrepareOK, remaining: Int)
case paramsDone(ok: MySQLComStmtPrepareOK)
/// If num_columns > 0 more packets will follow:
case columns(remaining: Int)
case columnsDone
case waitingExecute
case rowColumns(columns: [MySQLColumnDefinition41], remaining: Int)
case rowColumnsDone(columns: [MySQLColumnDefinition41])
/// ProtocolBinary::ResultsetRow until eof
case rows(columns: [MySQLColumnDefinition41])
}
| 32.448276 | 99 | 0.715551 |
ab7115cec82498526ef8d4f4ac6ca514b2fd629d | 186 | import Foundation
public protocol Solution {
static var title: String { get }
static func part1(_ input: String) -> String
static func part2(_ input: String) -> String
}
| 16.909091 | 48 | 0.682796 |
38d771351b9ee6f29c6fdab728d57aed09485636 | 1,034 | import CoreGraphics
/// An element that dynamically builds its content based on the environment.
///
/// Use this element to build elements whose contents may change depending on the `Environment`.
///
/// ## Example
///
/// EnvironmentReader { environment -> Element in
/// MyElement(
/// foo: environment.foo
/// )
/// }
///
/// - seealso: ProxyElement
/// - seealso: Environment
public struct EnvironmentReader: Element {
/// Return the contents of this element in the given environment.
var elementRepresentation: (Environment) -> Element
public init(elementRepresentation: @escaping (_ environment: Environment) -> Element) {
self.elementRepresentation = elementRepresentation
}
public var content: ElementContent {
return ElementContent { _, environment in
self.elementRepresentation(environment)
}
}
public func backingViewDescription(with context: ViewDescriptionContext) -> ViewDescription? {
return nil
}
}
| 28.722222 | 98 | 0.672147 |
22475f41b1b40c56158c2840c73ae2310e082f35 | 8,735 | //
// OKEntity.swift
// OctopusKit
//
// Created by [email protected] on 2017/10/11.
// Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt)
//
import GameplayKit
public typealias OctopusEntityDelegate = OKEntityDelegate
public typealias OctopusEntity = OKEntity
/// A protocol for types that manage entities, such as `OKScene`.
public protocol OKEntityDelegate: AnyObject {
func entity(_ entity: GKEntity, didAddComponent component: GKComponent)
func entity(_ entity: GKEntity, willRemoveComponent component: GKComponent)
@discardableResult
func entity(_ entity: GKEntity, didSpawn spawnedEntity: GKEntity) -> Bool
func entityDidRequestRemoval(_ entity: GKEntity)
}
/// A collection of components.
///
/// An entity will usually have a visual representation on-screen via a `NodeComponent` node.
///
/// An `OKScene` is also represented by an entity via a `SceneComponent`.
open class OKEntity: GKEntity {
// ℹ️ Also see GKEntity+OctopusKit extensions.
/// Identifies the entity. Can be non-unique and shared with other entities.
///
/// An `OKScene` may search for entities by their name via `entities(withName:)`.
public var name: String?
public weak var delegate: OKEntityDelegate? // CHECK: Should this be `weak`?
/// If `true`, the `OKEntityDelegate` (i.e. the scene) will also call `removeAllComponents()` when this entity is removed. This may be required to allow the entity and all its components to be deinitialized and freed from memory when no longer needed. Default: `false`
///
/// - IMPORTANT: ❕ This flag should *not* be set on the `OKGameCoordinator`'s entity, as it should not be destroyed when removing from a scene, i.e. upon changing scenes.
public var removeAllComponentsWhenRemovedFromScene: Bool = false
/// Indicates whether a scene should check whether it has systems for each of this entity's components that must be updated every frame or turn. Setting `true` may improve performance for entities that are added frequently. Setting `false` may help reduce bugs that result from missing systems.
open var suppressSystemsAvailabilityCheck: Bool = false
open override var description: String {
// CHECK: Improve?
"\(super.description) \"\(self.name ?? "")\""
}
open override var debugDescription: String {
"\(self.description)\(components.count > 0 ? " \(components.count) components = \(components)" : "")"
}
// MARK: - Initializers
// ℹ️ NOTE: These inits are not marked with the `convenience` modifier because we want to set `self.name = name` BEFORE calling `GKEntity` inits, in order to ensure that the log entries for `addComponent` will include the `OKEntity`'s name if it's supplied.
// However, if these were convenience initializers, we would get the error: "'self' used in property access 'name' before 'self.init' call"
/// Creates an entity with the specified name and adds the components in the specified order.
public init(name: String? = nil,
components: [GKComponent] = [])
{
self.name = name
super.init()
for component in components {
self.addComponent(component)
}
}
/// Creates an entity, adding an `NodeComponent` to associate it with the specified node and adds any other components if specified.
///
/// Sets the entity's name to the node's name, if any.
public init(node: SKNode,
components: [GKComponent] = [])
{
// 💬 It may be clearer to use `OKEntity(name:components:)` and explicitly write `NodeComponent` in the list.
self.name = node.name
super.init()
self.addComponent(NodeComponent(node: node))
for component in components {
self.addComponent(component)
}
}
/// Creates an entity and adds an `NodeComponent` associated with the specified node to the entity, optionally adding the node to a specified parent.
public init(name: String? = nil,
node: SKNode,
addToNode parentNode: SKNode? = nil)
{
// CHECK: Will making `name` an optional argument conflict with the signature of `GKEntity(node:addToNode:)` extensions?
self.name = name
super.init()
self.addComponent(NodeComponent(node: node, addToNode: parentNode))
}
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
// MARK: - Components
/// Adds a component to the entity and notifies the delegate, logging a warning if the entity already has another component of the same class, as the new component will replace the existing component.
open override func addComponent(_ component: GKComponent) {
/// 🐛 NOTE: BUG? GameplayKit's default implementation does NOT remove a component from its current entity before adding it to a different entity.
/// So we do that here, because otherwise it may cause unexpected behavior. A component's `entity` property can only point to one entity anyway; the latest.
/// ℹ️ DESIGN: DECIDED: When adding a `RelayComponent<TargetComponentType>`, we should NOT remove any existing component of the same type as the RelayComponent's target.
/// REASON: Components need to operate on their entity; adding a RelayComponent to an entity does NOT and SHOULD NOT set the target component's `entity` property to that entity. So we cannot and SHOULD NOT replace a direct component with a RelayComponent.
/// NOTE: This design decision means that an entity might find 2 components of the same type when checking for them with `GKEntity.componentOrRelay(ofType:)`, e.g. a NodePointerStateComponent and a RelayComponent<NodePointerStateComponent>, so `GKEntity.componentOrRelay(ofType:)` must always return the direct component first.
/// NOTE: Checking the `component.componentType` of a `RelayComponent` will return its `target?.componentType`, so we will use `type(of: component)` instead, to avoid deleting a direct component when a relay to the same component type is added.
#if LOGECSVERBOSE
debugLog("component: \(component), self: \(self)")
#endif
component.entity?.removeComponent(ofType: type(of: component))
// Warn if we already have a component of the same class, as GameplayKit does not allow multiple components of the same type in the same entity.
if let existingComponent = self.component(ofType: type(of: component)) {
/// If we have the **exact component instance** that is being added, just skip it and return.
// TODO: Add test for both these cases.
if existingComponent === component { /// Note the 3 equal-signs: `===`
OctopusKit.logForWarnings("\(self) already has \(component) — Not re-adding")
OctopusKit.logForTips("If you mean to reset the component or call its `didAddToEntity()` again, then remove it manually and re-add.")
return
} else {
OctopusKit.logForWarnings("\(self) replacing \(existingComponent) → \(component)")
// NOTE: BUG? GameplayKit's default implementation does NOT seem to set the about-to-be-replaced component's entity property to `nil`.
// So we manually remove an existing duplicate component here, if any.
self.removeComponent(ofType: type(of: existingComponent))
}
}
super.addComponent(component)
delegate?.entity(self, didAddComponent: component)
}
// MARK: - Removal
/// Requests this entity's `OKEntityDelegate` (i.e. the scene) to remove this entity.
@inlinable
public final func removeFromDelegate() {
self.delegate?.entityDidRequestRemoval(self)
}
deinit {
OctopusKit.logForDeinits("\(self)")
// Give all components a chance to clean up after themselves.
// ⚠️ NOTE: Not doing this may cause a situation where a `deinit`ing component tries to access its `deinit`ed `entity` property in `OKComponent.willRemoveFromEntity()`, causing a `-[OctopusKit.OKEntity retain]: message sent to deallocated instance` exception.
for component in self.components {
self.removeComponent(ofType: type(of: component))
}
}
}
| 49.350282 | 335 | 0.664568 |
bbf42bbdf190eba1e08958df86d5e373d429690d | 4,514 | //
// MultipleLinesChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class MultipleLinesChartViewController: DemoBaseViewController {
@IBOutlet var chartView: LineChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Multiple Lines Chart"
self.options = [.toggleValues,
.toggleFilled,
.toggleCircles,
.toggleCubic,
.toggleStepped,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription.enabled = false
chartView.leftAxis.enabled = false
chartView.rightAxis.drawAxisLineEnabled = false
chartView.xAxis.drawAxisLineEnabled = false
chartView.drawBordersEnabled = false
chartView.setScaleEnabled(true)
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .top
l.orientation = .vertical
l.drawInside = false
// chartView.legend = l
sliderX.value = 20
sliderY.value = 100
slidersValueChanged(nil)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value))
}
// TODO: Refine data creation
func setDataCount(_ count: Int, range: UInt32) {
let colors = ChartColorTemplates.vordiplom()[0...2]
let block: (Int) -> ChartDataEntry = { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let dataSets = (0..<3).map { i -> LineChartDataSet in
let yVals = (0..<count).map(block)
let set = LineChartDataSet(values: yVals, label: "DataSet \(i)")
set.lineWidth = 2.5
set.circleRadius = 4
set.circleHoleRadius = 2
let color = colors[i % colors.count]
set.setColor(color)
set.setCircleColor(color)
return set
}
dataSets[0].lineDashLengths = [5, 5]
dataSets[0].colors = ChartColorTemplates.vordiplom()
dataSets[0].circleColors = ChartColorTemplates.vordiplom()
let data = LineChartData(dataSets: dataSets)
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
chartView.data = data
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleFilled:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawFilledEnabled = !set.drawFilledEnabled
}
chartView.setNeedsDisplay()
case .toggleCircles:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawCirclesEnabled = !set.drawCirclesEnabled
}
chartView.setNeedsDisplay()
case .toggleCubic:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier
}
chartView.setNeedsDisplay()
case .toggleStepped:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .stepped) ? .linear : .stepped
}
chartView.setNeedsDisplay()
default:
super.handleOption(option, forChartView: chartView)
}
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
self.updateChartData()
}
}
| 32.47482 | 78 | 0.557377 |
4b1fbe207a9543525deb06d12162e8f5e41a9644 | 978 | import UIKit
// Error handling - Hata Yakalama
var ekran = "0.0"
enum HesaplamaHatalari:Error{ //Error protokolünü kullanıyoruz
case nanHatasi // nan : Tanımsız, tanımlanamayan hata
case InfHatasi //inf : Sonsuz
}
//hata fırlatmasını istiyorsak throws ekliyoruz. throws : Fırlatmak
func bolme(bolunen:Double, bolen:Double) throws->Double{
guard bolunen != 0 else {
print("Tanımsız Değer")
throw HesaplamaHatalari.nanHatasi
}
guard bolen != 0 else {
print("Inf Hatası")
throw HesaplamaHatalari.InfHatasi
}
return bolunen/bolen
}
//Hatayı throws ile fırlattık burada da yakalama işlemini yapacağız
do {
try bolme(bolunen: 0, bolen: 0)
} catch HesaplamaHatalari.InfHatasi {
ekran = "HATA"
} catch HesaplamaHatalari.nanHatasi{
ekran = "Tanımsız"
}
//not 100 den büyük olamaz
//not negatif olamaz
//bolme(bolunen: 1, bolen: 0) // Inf hatası alınır
//bolme(bolunen: 0, bolen: 0) // nan hatası alırız
| 24.45 | 67 | 0.693252 |
337ad906c03c340ee2fcff97d36e39b01273345b | 729 | import Foundation
import OptimoveSDK
import OptimoveCore
class PlacedOrderEvent: OptimoveEvent {
private let cartItems: [CartItem]
init(_ items: [CartItem]) {
self.cartItems = items
}
var name: String {
return "placed_order"
}
var parameters: [String: Any] {
var params: [String: Any] = [:]
var totalPrice = 0.0
for i in 0..<self.cartItems.count {
let item = self.cartItems[i]
params["item_name_\(i)"] = item.name
params["item_price_\(i)"] = item.price
params["item_image_\(i)"] = item.image
totalPrice += item.price
}
params["total_price"] = totalPrice
return params
}
}
| 23.516129 | 50 | 0.572016 |
8fd621fa1a54054706b03d89c0d26f19adfc42e3 | 3,975 | import Auth0ObjC // Added by Auth0toSPM
// ResponseSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Quick
import Nimble
@testable import Auth0
private let URL = Foundation.URL(string: "https://samples.auth0.com")!
private let JSONData = try! JSONSerialization.data(withJSONObject: ["attr": "value"], options: [])
private func http(_ statusCode: Int, url: Foundation.URL = URL) -> HTTPURLResponse {
return HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: "1.0", headerFields: [:])!
}
class ResponseSpec: QuickSpec {
override func spec() {
describe("successful response") {
it("should handle HTTP 204 responses") {
let response = Response<AuthenticationError>(data: nil, response: http(204), error: nil)
expect(try! response.result()).to(beNil())
}
it("should handle valid JSON") {
let response = Response<AuthenticationError>(data: JSONData, response: http(200), error: nil)
expect(try? response.result()).toNot(beNil())
}
it("should handle string as json for reset password") {
let data = "A simple String".data(using: .utf8)
let response = Response<AuthenticationError>(data: data, response: http(200, url: Foundation.URL(string: "https://samples.auth0.com/dbconnections/change_password")!), error: nil)
expect(try! response.result()).to(beNil())
}
}
describe("failed response") {
it("should fail with code lesser than 200") {
let response = Response<AuthenticationError>(data: nil, response: http(199), error: nil)
expect(try? response.result()).to(beNil())
}
it("should fail with code greater than 200") {
let response = Response<AuthenticationError>(data: nil, response: http(300), error: nil)
expect(try? response.result()).to(beNil())
}
it("should fail with empty HTTP 200 responses") {
let response = Response<AuthenticationError>(data: nil, response: http(200), error: nil)
expect(try? response.result()).to(beNil())
}
it("should fail with invalid JSON") {
let data = "A simple String".data(using: .utf8)
let response = Response<AuthenticationError>(data: data, response: http(200), error: nil)
expect(try? response.result()).to(beNil())
}
it("should fail with NSError") {
let error = NSError(domain: "com.auth0", code: -99999, userInfo: nil)
let response = Response<AuthenticationError>(data: nil, response: http(200), error: error)
expect(try? response.result()).to(beNil())
}
}
}
}
| 43.681319 | 194 | 0.639748 |
094978a610a545cc0d3d9c83b657d08b3a7c6fb9 | 2,359 | /*
* Copyright (c) 2014 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import SceneKit
class Molecules {
class func methaneMolecule() -> SCNNode {
var methaneMolecule = SCNNode()
// 1 Carbon
let carbonNode1 = nodeWithAtom(Atoms.carbonAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, 0, 0))
// 4 Hydrogen
let hydrogenNode1 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(-4, 0, 0))
let hydrogenNode2 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(+4, 0, 0))
let hydrogenNode3 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, -4, 0))
let hydrogenNode4 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, +4, 0))
return methaneMolecule
}
class func ethanolMolecule() -> SCNNode {
var ethanolMolecule = SCNNode()
return ethanolMolecule
}
class func ptfeMolecule() -> SCNNode {
var ptfeMolecule = SCNNode()
return ptfeMolecule
}
class func nodeWithAtom(atom: SCNGeometry, molecule: SCNNode, position: SCNVector3) -> SCNNode {
let node = SCNNode(geometry: atom)
node.position = position
molecule.addChildNode(node)
return node
}
}
| 39.983051 | 121 | 0.74184 |
761decc12c6114f2eb9c9b9c0921ff9c6324835d | 2,089 | //
// AC3_2_TDD_introTests.swift
// AC3.2-TDD_introTests
//
// Created by Annie Tung on 3/28/17.
// Copyright © 2017 Annie Tung. All rights reserved.
//
import XCTest
@testable import AC3_2_TDD_intro
class AC3_2_TDD_introTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func countVowels(_ str: String) -> Int {
return 0
}
func test_VowelCount_AnnieShouldReturnThree() {
let viewController = ViewController()
let testString = "Annie"
let numberOfVowels = viewController.numberVowels(testString)
XCTAssertEqual(numberOfVowels, 3, "Vowel count should be accurate!")//, file: "TDD_IntroTests.swift", line: 34)
// let vowelCount = 3
// let badVowelCount = 3
// XCTAssert(vowelCount == badVowelCount, "We should get an accurate vowel count")
}
func test_CapitalizeFirstLetterInEachWord() {
let viewController = ViewController()
let testString = "this is a string"
let expectedString = "This Is A String"
// this will fail until you write the function for it
let resultString = viewController.capitalizeFirstLetter(testString)
XCTAssertEqual(expectedString, resultString, "First Letter of each word should be capitalized!")
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure { // good way of checking for average performance!
// Put the code you want to measure the time of here.
}
}
}
| 32.138462 | 119 | 0.642413 |
b98daec4189cb16ae096cea8390ff60a71c1a679 | 11,354 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
//
// -----------------------------------------------------
// IMPORTANT: When modifying this file, make sure to
// increment the version number at the very
// bottom of the file to notify users about
// the new SnapshotHelper.swift
// -----------------------------------------------------
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {
Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool) {
if waitForLoadingIndicator {
Snapshot.snapshot(name)
} else {
Snapshot.snapshot(name, timeWaitingForIdle: 0)
}
}
/// - Parameters:
/// - name: The name of the snapshot
/// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait.
func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
Snapshot.snapshot(name, timeWaitingForIdle: timeout)
}
enum SnapshotError: Error, CustomDebugStringConvertible {
case cannotFindSimulatorHomeDirectory
case cannotRunOnPhysicalDevice
var debugDescription: String {
switch self {
case .cannotFindSimulatorHomeDirectory:
return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable."
case .cannotRunOnPhysicalDevice:
return "Can't use Snapshot on a physical device."
}
}
}
@objcMembers
open class Snapshot: NSObject {
static var app: XCUIApplication?
static var waitForAnimations = true
static var cacheDirectory: URL?
static var screenshotsDirectory: URL? {
return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true)
}
open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) {
Snapshot.app = app
Snapshot.waitForAnimations = waitForAnimations
do {
let cacheDir = try getCacheDirectory()
Snapshot.cacheDirectory = cacheDir
setLanguage(app)
setLocale(app)
setLaunchArguments(app)
} catch let error {
NSLog(error.localizedDescription)
}
}
class func setLanguage(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("language.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
NSLog("Couldn't detect/set language...")
}
}
class func setLocale(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = CharacterSet.whitespacesAndNewlines
locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet)
} catch {
NSLog("Couldn't detect/set locale...")
}
if locale.isEmpty && !deviceLanguage.isEmpty {
locale = Locale(identifier: deviceLanguage).identifier
}
if !locale.isEmpty {
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
}
class func setLaunchArguments(_ app: XCUIApplication) {
guard let cacheDirectory = self.cacheDirectory else {
NSLog("CacheDirectory is not set - probably running on a physical device?")
return
}
let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8)
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
NSLog("Couldn't detect/set launch_arguments...")
}
}
open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
if timeout > 0 {
waitForLoadingIndicatorToDisappear(within: timeout)
}
NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work
if Snapshot.waitForAnimations {
sleep(1) // Waiting for the animation to be finished (kind of)
}
#if os(OSX)
guard let app = self.app else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
#else
guard self.app != nil else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
let screenshot = XCUIScreen.main.screenshot()
#if os(iOS)
let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image
#else
let image = screenshot.image
#endif
guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return }
do {
// The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices
let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ")
let range = NSRange(location: 0, length: simulator.count)
simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "")
let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")
try image.pngData()?.write(to: path, options: .atomic)
} catch let error {
NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png")
NSLog(error.localizedDescription)
}
#endif
}
class func fixLandscapeOrientation(image: UIImage) -> UIImage {
if #available(iOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
return renderer.image { context in
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
}
} else {
return image
}
}
class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) {
#if os(tvOS)
return
#endif
guard let app = self.app else {
NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
return
}
let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element
let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator)
_ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout)
}
class func getCacheDirectory() throws -> URL {
let cachePath = "Library/Caches/tools.fastlane"
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
let homeDir = URL(fileURLWithPath: NSHomeDirectory())
return homeDir.appendingPathComponent(cachePath)
#elseif arch(i386) || arch(x86_64)
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
throw SnapshotError.cannotFindSimulatorHomeDirectory
}
let homeDir = URL(fileURLWithPath: simulatorHostHome)
return homeDir.appendingPathComponent(cachePath)
#else
throw SnapshotError.cannotRunOnPhysicalDevice
#endif
}
}
private extension XCUIElementAttributes {
var isNetworkLoadingIndicator: Bool {
if hasAllowListedIdentifier { return false }
let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20)
let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3)
return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize
}
var hasAllowListedIdentifier: Bool {
let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
return allowListedIdentifiers.contains(identifier)
}
func isStatusBar(_ deviceWidth: CGFloat) -> Bool {
if elementType == .statusBar { return true }
guard frame.origin == .zero else { return false }
let oldStatusBarSize = CGSize(width: deviceWidth, height: 20)
let newStatusBarSize = CGSize(width: deviceWidth, height: 44)
return [oldStatusBarSize, newStatusBarSize].contains(frame.size)
}
}
private extension XCUIElementQuery {
var networkLoadingIndicators: XCUIElementQuery {
let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isNetworkLoadingIndicator
}
return self.containing(isNetworkLoadingIndicator)
}
var deviceStatusBars: XCUIElementQuery {
guard let app = Snapshot.app else {
fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
}
let deviceWidth = app.windows.firstMatch.frame.width
let isStatusBar = NSPredicate { (evaluatedObject, _) in
guard let element = evaluatedObject as? XCUIElementAttributes else { return false }
return element.isStatusBar(deviceWidth)
}
return self.containing(isStatusBar)
}
}
private extension CGFloat {
func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool {
return numberA...numberB ~= self
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [1.24]
| 37.596026 | 158 | 0.639775 |
ebd0107a867833913a85a3fc6f0c6dd104f588f1 | 289 | // Swift CLib
// Copyright (c) 2016-2019 Shota Shimazu
// This program is freely distributed under the MIT, see LICENSE for detail.
#if os(Linux)
// Import Glibc on Linux
@_exported import Glibc
#elseif os(OSX)
// Import Darwin on macOS
@_exported import Darwin.C
#endif
| 22.230769 | 76 | 0.702422 |
564cb2204acdf4bbb43de5947483d0e91af1d574 | 2,136 | //
// ComplicationController.swift
// WatchWeather WatchKit Extension
//
// Created by Dareway on 2017/11/2.
// Copyright © 2017年 Pluto. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler([.forward, .backward])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
| 37.473684 | 169 | 0.703652 |
91350d5b34b5ce047516c2edab0dad003edec107 | 8,718 | import Foundation
import AVFoundation
// MARK: FLVVideoCodec
enum FLVVideoCodec: UInt8 {
case SorensonH263 = 2
case Screen1 = 3
case ON2VP6 = 4
case ON2VP6Alpha = 5
case Screen2 = 6
case AVC = 7
case Unknown = 0xFF
var isSupported:Bool {
switch self {
case SorensonH263:
return false
case Screen1:
return false
case ON2VP6:
return false
case ON2VP6Alpha:
return false
case Screen2:
return false
case AVC:
return true
case Unknown:
return false
}
}
}
// MARK: - FLVFrameType
enum FLVFrameType: UInt8 {
case Key = 1
case Inter = 2
case Disposable = 3
case Generated = 4
case Command = 5
}
// MARK: - FLVAVCPacketType
enum FLVAVCPacketType:UInt8 {
case Seq = 0
case Nal = 1
case Eos = 2
}
// MARK: - FLVAACPacketType
enum FLVAACPacketType:UInt8 {
case Seq = 0
case Raw = 1
}
// MARK: - FLVSoundRate
enum FLVSoundRate:UInt8 {
case KHz5_5 = 0
case KHz11 = 1
case KHz22 = 2
case KHz44 = 3
var floatValue:Float64 {
switch self {
case KHz5_5:
return 5500
case KHz11:
return 11025
case KHz22:
return 22050
case KHz44:
return 44100
}
}
}
// MARK: - FLVSoundSize
enum FLVSoundSize:UInt8 {
case Snd8bit = 0
case Snd16bit = 1
}
// MARK: - FLVSoundType
enum FLVSoundType:UInt8 {
case Mono = 0
case Stereo = 1
}
// MARK: - FLVAudioCodec
enum FLVAudioCodec:UInt8 {
case PCM = 0
case ADPCM = 1
case MP3 = 2
case PCMLE = 3
case Nellymoser16K = 4
case Nellymoser8K = 5
case Nellymoser = 6
case G711A = 7
case G711MU = 8
case AAC = 10
case Speex = 11
case MP3_8k = 14
case Unknown = 0xFF
var isSupported:Bool {
switch self {
case PCM:
return false
case ADPCM:
return false
case MP3:
return false
case PCMLE:
return false
case Nellymoser16K:
return false
case Nellymoser8K:
return false
case Nellymoser:
return false
case G711A:
return false
case G711MU:
return false
case AAC:
return true
case Speex:
return false
case MP3_8k:
return false
case Unknown:
return false
}
}
var formatID:AudioFormatID {
switch self {
case PCM:
return kAudioFormatLinearPCM
case MP3:
return kAudioFormatMPEGLayer3
case PCMLE:
return kAudioFormatLinearPCM
case AAC:
return kAudioFormatMPEG4AAC
case MP3_8k:
return kAudioFormatMPEGLayer3
default:
return 0
}
}
var headerSize:Int {
switch self {
case AAC:
return 2
default:
return 1
}
}
}
// MARK: FLVTag
struct FLVTag {
enum TagType:UInt8 {
case Audio = 8
case Video = 9
case Data = 18
var streamId:UInt16 {
switch self {
case .Audio:
return RTMPChunk.audio
case .Video:
return RTMPChunk.video
case .Data:
return 0
}
}
var headerSize:Int {
switch self {
case .Audio:
return 2
case .Video:
return 5
case .Data:
return 0
}
}
func createMessage(streamId: UInt32, timestamp: UInt32, buffer:NSData) -> RTMPMessage {
switch self {
case .Audio:
return RTMPAudioMessage(streamId: streamId, timestamp: timestamp, buffer: buffer)
case .Video:
return RTMPVideoMessage(streamId: streamId, timestamp: timestamp, buffer: buffer)
case .Data:
return RTMPDataMessage(objectEncoding: 0x00)
}
}
}
static let headerSize = 11
var tagType:TagType = .Data
var dataSize:UInt32 = 0
var timestamp:UInt32 = 0
var timestampExtended:UInt8 = 0
var streamId:UInt32 = 0
}
// MARK: CustomStringConvertible
extension FLVTag: CustomStringConvertible {
var description:String {
return Mirror(reflecting: self).description
}
}
// MARK: RTMPRecorder
final class RTMPRecorder: NSObject {
static let defaultVersion:UInt8 = 1
static let headerSize:UInt32 = 13
weak var dispatcher:IEventDispatcher? = nil
private var version:UInt8 = RTMPRecorder.defaultVersion
private var fileHandle:NSFileHandle? = nil
private var audioTimestamp:UInt32 = 0
private var videoTimestamp:UInt32 = 0
private let lockQueue:dispatch_queue_t = dispatch_queue_create(
"com.github.shogo4405.lf.RTMPRecorder.lock", DISPATCH_QUEUE_SERIAL
)
func open(file:String, option:RTMPStream.RecordOption) {
dispatch_async(lockQueue) {
let path:String = RTMPStream.rootPath + file + ".flv"
self.createFileIfNotExists(path)
self.fileHandle = option.createFileHandle(file)
guard let fileHandle:NSFileHandle = self.fileHandle else {
self.dispatcher?.dispatchEventWith(Event.RTMP_STATUS, bubbles: false, data: RTMPStream.Code.RecordFailed.data(path))
return
}
fileHandle.seekToFileOffset(UInt64(RTMPRecorder.headerSize))
self.dispatcher?.dispatchEventWith(Event.RTMP_STATUS, bubbles: false, data: RTMPStream.Code.RecordStart.data(path))
}
}
func close() {
dispatch_async(lockQueue) {
self.audioTimestamp = 0
self.videoTimestamp = 0
self.fileHandle?.closeFile()
self.fileHandle = nil
self.dispatcher?.dispatchEventWith(Event.RTMP_STATUS, bubbles: false, data: RTMPStream.Code.RecordStop.data(""))
}
}
private func createFileIfNotExists(path: String) {
let manager:NSFileManager = NSFileManager.defaultManager()
guard !manager.fileExistsAtPath(path) else {
return
}
do {
let dir:String = (path as NSString).stringByDeletingLastPathComponent
try manager.createDirectoryAtPath(dir, withIntermediateDirectories: true, attributes: nil)
var header:[UInt8] = [0x46, 0x4C, 0x56, version, 0b00000101]
header += UInt32(9).bigEndian.bytes
header += UInt32(0).bigEndian.bytes
manager.createFileAtPath(path, contents: NSData(bytes: &header, length: header.count), attributes: nil)
} catch let error as NSError {
dispatcher?.dispatchEventWith(Event.RTMP_STATUS, bubbles: false, data: RTMPStream.Code.RecordFailed.data(error.description))
}
}
private func appendData(type:UInt8, timestamp:UInt32, payload:[UInt8]) {
var bytes:[UInt8] = [type]
bytes += Array(UInt32(payload.count).bigEndian.bytes[1...3])
bytes += Array(timestamp.bigEndian.bytes[1...3])
bytes += [timestamp.bigEndian.bytes[0]]
bytes += [0, 0, 0]
bytes += payload
bytes += UInt32(payload.count + 11).bigEndian.bytes
let data:NSData = NSData(bytes: bytes, length: bytes.count)
fileHandle?.writeData(data)
}
func onMessage(message: RTMPMessage) {
dispatch_async(lockQueue) {
guard let _:NSFileHandle = self.fileHandle else {
return
}
if let message:RTMPAudioMessage = message as? RTMPAudioMessage {
self.appendData(FLVTag.TagType.Audio.rawValue, timestamp: self.audioTimestamp, payload: message.payload)
self.audioTimestamp += message.timestamp
return
}
if let message:RTMPVideoMessage = message as? RTMPVideoMessage {
self.appendData(FLVTag.TagType.Video.rawValue, timestamp: self.videoTimestamp, payload: message.payload)
self.videoTimestamp += message.timestamp
return
}
if let message:RTMPDataMessage = message as? RTMPDataMessage {
self.appendData(FLVTag.TagType.Data.rawValue, timestamp: 0, payload: message.payload)
return
}
}
}
}
| 28.032154 | 136 | 0.570544 |
569c04e4f46edbd24aa10c23c5f0db4770ecee62 | 3,297 | //
// EditUserProfilePresenter.swift
// My Octocat
//
// Created by Daniele Vitali on 3/20/16.
// Copyright © 2016 Daniele Vitali. All rights reserved.
//
import Foundation
import RxSwift
class EditUserProfilePresenter: BasePresenter, EditUserProfilePresenterContract {
private weak var view: EditUserProfileViewContract!
private let repository: UserProfileRepositoryContract
private var user: User {
return repository.user!
}
private var name: String!
private var location: String?
private var company: String?
private var bio: String?
init(view: EditUserProfileViewContract, repository: UserProfileRepositoryContract) {
self.view = view
self.repository = repository
}
func viewDidLoad() {
if let profile = user.profile {
view.toggleMainLoading(false)
view.enableToolbar(true)
showUserProfile(profile)
} else {
view.toggleMainLoading(true)
view.enableToolbar(false)
repository.getUserProfile()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [unowned self] profile in
self.view.toggleMainLoading(false)
self.view.enableToolbar(true)
self.showUserProfile(profile)
}, onError: { [unowned self] errorType in
let error = errorType as! Error
self.view.toggleMainLoading(false)
self.view.enableToolbar(true)
self.view.showError(error.message)
self.view.dismiss()
}, onCompleted: { () in
}, onDisposed: { () in
}).addDisposableTo(disposeBag)
}
}
private func showUserProfile(profile: Profile) {
name = profile.name
location = profile.location
company = profile.company
bio = profile.bio
view.showUserProfile(profile)
}
func onSaveClick() {
guard name != "" else {
view.showError("Type your name")
return
}
view.toggleMainLoading(true)
repository.saveUserProfile(name, location: location, company: company, bio: bio)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [unowned self] profile in
self.view.dismiss()
}, onError: { [unowned self] errorType in
let error = errorType as! Error
self.view.toggleMainLoading(false)
self.view.showError(error.message)
}, onCompleted: { () in
}, onDisposed: { () in
}).addDisposableTo(disposeBag)
}
func onCancelClick() {
view.dismiss()
}
func onEndEditingName(name: String) {
self.name = name
}
func onEndEditingLocation(location: String) {
self.location = location
}
func onEndEditingCompany(company: String) {
self.company = company
}
func onEndEditingBio(bio: String) {
self.bio = bio
}
} | 30.247706 | 88 | 0.552017 |
8fe43916ee342ebb3d53e250f3b27a930d26fea3 | 1,788 | //
// Main.swift
// Tweaks for Reddit
//
// Created by Michael Rippe on 10/21/19.
// Copyright © 2019 Michael Rippe. All rights reserved.
//
import SwiftUI
import StoreKit
@main
struct RedditweaksApp: App {
// periphery:ignore
@NSApplicationDelegateAdaptor private var appDelegate: RedditweaksAppDelegate
@Environment(\.scenePhase) private var scenePhase
@StateObject private var appState = MainAppState()
var body: some Scene {
WindowGroup {
MainView()
.environmentObject(appState)
.onOpenURL { url in
guard url.absoluteString.starts(with: "rdtwks://") else {
return
}
appState.selectedTab = .liveCommentPreview
}
.accentColor(.redditOrange)
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
DispatchQueue.main.asyncAfter(deadline: .now().advanced(by: .seconds(1))) {
NSApp!.mainWindow!.isMovableByWindowBackground = true
}
default:
return
}
}
}
.defaultAppStorage(Redditweaks.defaults)
.windowStyle(HiddenTitleBarWindowStyle())
}
}
class RedditweaksAppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
SKPaymentQueue.default().add(IAPHelper.shared.transactionPublisher)
}
func applicationWillTerminate(_ notification: Notification) {
SKPaymentQueue.default().remove(IAPHelper.shared.transactionPublisher)
}
}
| 28.83871 | 103 | 0.571588 |
3939b8a56e6d23120ef3d9c25f75ca6f9d35f1de | 2,919 | ////
//// MIT License
////
//// Copyright (c) 2018-2019 Open Zesame (https://github.com/OpenZesame)
////
//// Permission is hereby granted, free of charge, to any person obtaining a copy
//// of this software and associated documentation files (the "Software"), to deal
//// in the Software without restriction, including without limitation the rights
//// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//// copies of the Software, and to permit persons to whom the Software is
//// furnished to do so, subject to the following conditions:
////
//// The above copyright notice and this permission notice shall be included in all
//// copies or substantial portions of the Software.
////
//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//// SOFTWARE.
////
//
//import Foundation
//import RxTest
//import RxCocoa
//import RxSwift
//
///// stolen from: https://github.com/RxSwiftCommunity/RxTestExt/blob/master/RxTestExt/Core/TestScheduler%2BExt.swift
//extension TestScheduler {
//
// /// Builds testable observer for s specific observable sequence, binds it's results and sets up disposal.
// ///
// // This function was copied from RxSwift's example app:
// // https://github.com/ReactiveX/RxSwift/blob/f639ff450487340a18931a7dbe3d5c8a0976be7b/RxExample/RxExample-iOSTests/TestScheduler%2BMarbleTests.swift#L189
// //
// /// - Parameter source: Observable sequence to observe.
// /// - Returns: Observer that records all events for observable sequence.
// public func record<O: ObservableConvertibleType>(_ source: O) -> TestableObserver<O.E> {
// let observer = self.createObserver(O.E.self)
// let disposable = source.asObservable().subscribe(observer)
// self.scheduleAt(100000) {
// disposable.dispose()
// }
// return observer
// }
//
// /// Binds given events to an observer
// ///
// /// Builds a hot observable with predefined events, binds it's result to given observer and sets up disposal.
// ///
// /// - Parameters:
// /// - events: Array of recorded events to emit over the scheduled observable
// /// - target: Observer to bind to
// public func bind<O: ObserverType>(_ events: [Recorded<Event<O.E>>], to target: O) {
// let driver = self.createHotObservable(events)
// let disposable = driver.asObservable().subscribe(target)
// self.scheduleAt(100000) {
// disposable.dispose()
// }
// }
//}
| 45.609375 | 160 | 0.686879 |
6210c027e44fcb40e7c2c2c42c98e54ca4642438 | 696 | //
// ExtendedDataTests.swift
//
// Copyright 2020-2021 Herald Project Contributors
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
@testable import Herald
class ExtendedDataTests: XCTestCase {
func testMultipleSections() throws {
let extendedData = ConcreteExtendedDataV1();
let section1Code = UInt8(0x01);
let section1Value = UInt8(3);
extendedData.addSection(code: section1Code, value: section1Value)
let section2Code = UInt8(0x02);
let section2Value = UInt16(25);
extendedData.addSection(code: section2Code, value: section2Value)
XCTAssertEqual(2, extendedData.getSections().count)
}
}
| 24.857143 | 73 | 0.679598 |
8f4e69d8c9d785d63777d903ad2410b8e28d09db | 416 | //
// AppDelegate.swift
// BitWatch
//
// Created by Mic Pringle on 19/11/2014.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
}
| 18.909091 | 125 | 0.721154 |
16b091ddde2ee33e1e4a277f0030a400b81a6fb9 | 399 | //
// BasicAttributeExtractor.swift
// Graphaello
//
// Created by Mathias Quintero on 12/8/19.
// Copyright © 2019 Mathias Quintero. All rights reserved.
//
import Foundation
struct BasicAttributeExtractor: AttributeExtractor {
func extract(code: SourceCode) throws -> Stage.Extracted.Attribute {
return Stage.Extracted.Attribute(code: code, kind: try code.attribute())
}
}
| 22.166667 | 80 | 0.721805 |
1118e09ad26cb00dbeb51b1cd6c7b23d19e6c050 | 586 | //
// StaticImageResource.swift
// DandaniaResources
//
// Created by Martin Lalev on 23.04.20.
// Copyright © 2020 Martin Lalev. All rights reserved.
//
import Foundation
public class StaticImageResource: ImageResource {
public let id: String
private let image: ImageConvertible?
public init(id: String, for image: ImageConvertible?) {
self.id = id
self.image = image
}
public func load(_ callback: @escaping (ImageConvertible?) -> Void) -> ImageLoaderCancellable? {
callback(self.image)
return nil
}
}
| 21.703704 | 100 | 0.648464 |
140283befc3bcf10ba99e346286a67c431c0345a | 4,941 | import Html
let lifxRemote = baseHtml([
baseHead(title: "Remote Control for LIFX", styles: [.navbar, .projects]),
body([
navbar(),
div([`class`("project-entry")], [
div([style("border-style: solid; border-color: gray; border-width: 2px; padding: 1em;")],
["This project is unmaintained."]),
projectHeader(title: "Remote Control for LIFX",
subtitle: "Control LIFX Lightbulbs from your Mac",
img: "/images/lifx_remote_icon.png"),
aImg("/images/lifx_remote_hero.jpg"),
macAppStore("https://itunes.apple.com/us/app/remote-control-for-lifx/id1182646052"),
p([
b(["Source code"]), " on ",
a([href("https://github.com/Gofake1/Remote-Control-for-LIFX")], ["GitHub"]),
"."
]),
p([
"Remote Control for LIFX is a handy way of controlling your LIFX lightbulbs.",
br,
"It is designed to blend in with the rest of the status bar."
]),
h2(["Support"]),
h4(["How do I use Remote Control for LIFX?"]),
"""
Remote Control for LIFX will automatically find all lightbulbs on \
your local network when it is launched. You can also manually \
rediscover lightbulbs in Preferences.
""",
img([src("/images/lifx_remote_help.png")]),
p([
"""
Remote Control for LIFX puts a menu item in your Mac status menu. \
Your lightbulbs will appear in that status menu. From there you can \
quickly change bulb brightness by dragging the slider, and power by \
clicking the power button. To change the color or view bulb details, \
click the bulb's name to access the HUD.
"""
]),
h4(["Why aren't my lightbulbs discoverable?"]),
"There are a few requirements that need to be met for Remote Control to work:",
ul([
li(["Remote Control requires port 56700 on your Mac"]),
li(["LIFX bulbs require an IPv4 address, and need to be on the same network as your Mac"]),
li(["LIFX Original 1000 bulbs must be on firmware version 2 or higher"]),
li(["Your router must allow UDP broadcast"])
]),
"There are some limitations:",
ul([
li(["Infrared control is not supported"]),
li(["MultiZone lights (e.g. LIFX Z) are not supported"])
]),
h4(["How do I contact the developer?"]),
"Open an issue on ",
a([href("https://github.com/Gofake1/Remote-Control-for-LIFX")], ["GitHub"]),
".",
h2(["Changelog"]),
h4(["Version 1.5.1 - ", span([`class`("project-date")], ["29 Oct. 2017"])]),
ul([
li(["(Fix) Crash when opening Preferences on macOS 10.11"])
]),
h4(["Version 1.5 - ", span([`class`("project-date")], ["26 Oct. 2017"])]),
ul([
li([
"Key bindings", br,
img([src("/images/lifx_remote_key_bindings.png")])
])
]),
h4(["Version 1.4 - ", span([`class`("project-date")], ["21 July 2017"])]),
ul([
li([
"Improved Menu UI", br,
img([src("/images/lifx_remote_1-3_to_1-4.png")])
])
]),
h4(["Version 1.3.1 - ", span([`class`("project-date")], ["18 May 2017"])]),
ul([
li(["HUD color wheel supports dragging"])
]),
h4(["Version 1.3 - ", span([`class`("project-date")], ["5 Feb. 2017"])]),
ul([
li(["Adjust color temperature in the HUD"]),
li(["Choose which groups and devices to show in the menu"]),
li(["Display LIFX bulb IP address"]),
li(["Acknowledge third-party libraries"])
]),
h4(["Version 1.2 - ", span([`class`("project-date")], ["28 Jan. 2017"])]),
ul([
li(["Create 'Groups' of LIFX bulbs"]),
li(["New Preferences window"]),
li(["Refined HUD window"]),
li(["HUD windows now open from the top left instead of top right"]),
li(["Persist state across launches"]),
li(["Disable highlighting on mouseover in menu"])
]),
h4(["Version 1.1 - ", span([`class`("project-date")], ["11 Dec. 2016"])]),
ul([
li(["More reactive interface"]),
li(["HUD color wheel is now a wheel"]),
li(["HUD Wifi status is more intuitive"]),
li(["Click the LIFX bulb's name to access its HUD"]),
li(["Click the color indicator in a menu item to turn the LIFX bulb on/off"])
]),
h4(["Version 1.0 - ", span([`class`("project-date")], ["3 Dec. 2016"])]),
ul([
li(["Discover LIFX bulbs automatically"]),
li(["Manually discover bulbs in Preferences"]),
li(["Change a bulb's brightness from its menu item"]),
li(["Change a bulb's color from its HUD"])
])
]),
footer([
"""
© 2016-2018 David Wu. Mac App Store is a registered trademark of Apple, \
Inc. LIFX is a registered trademark of LiFi Labs, Inc.
"""
])
])
])
| 40.5 | 99 | 0.562032 |
91351e29b75e6f5f2045ec55aa02fdf1cc357c7a | 1,437 | //
// Coverage.swift
// Mendoza
//
// Created by Tomas Camin on 26/02/2019.
//
// https://github.com/llvm-mirror/llvm/blob/master/tools/llvm-cov/CoverageExporterJson.cpp
import Foundation
struct Coverage: Codable {
let version: String
let type: String
let data: [Data]
}
extension Coverage {
struct Data: Codable {
let files: [File]
let functions: [Function]
let totals: Stats
}
}
extension Coverage.Data {
struct File: Codable {
let filename: String
let segments: [[Int]]?
let expansions: [Expansion]?
let summary: Stats?
}
struct Function: Codable {
let name: String?
let count: Int?
let regions: [[Int]]?
let filenames: [String]?
}
struct Stats: Codable {
struct Item: Codable {
let count: Int?
let covered: Int?
let notcovered: Int?
let percent: Int?
}
let lines: Item?
let functions: Item?
let instantiations: Item?
let regions: Item?
}
}
extension Coverage.Data.File {
struct Expansion: Codable {
let sourceRegion: [Int]?
let targetRegions: [[Int]]?
let filenames: [String]?
enum CodingKeys: String, CodingKey {
case sourceRegion = "source_region"
case targetRegions = "target_regions"
case filenames
}
}
}
| 21.132353 | 90 | 0.56785 |
084ccf85597a5145cd196432dacf9bb1fba1c6b5 | 5,146 | //
// GraphStoreAgent.swift
// Ursus Chat
//
// Created by Daniel Clelland on 24/11/20.
// Copyright © 2020 Protonome. All rights reserved.
//
import Foundation
import Alamofire
import UrsusHTTP
extension Client {
public func graphStoreAgent(ship: Ship, state: GraphStoreAgent.State = .init()) -> GraphStoreAgent {
return agent(ship: ship, app: "graph-store", state: state)
}
}
public class GraphStoreAgent: Agent<GraphStoreAgent.State, GraphStoreAgent.Request> {
public struct State: AgentState {
public var graphs: Graphs
public var graphKeys: Set<String>
public init(graphs: Graphs = .init(), graphKeys: Set<String> = .init()) {
self.graphs = graphs
self.graphKeys = graphKeys
}
}
public enum Request: AgentRequest { }
@discardableResult public func keysSubscribeRequest(handler: @escaping (SubscribeEvent<Result<SubscribeResponse, Error>>) -> Void) -> DataRequest {
return subscribeRequest(path: "/keys", handler: handler)
}
@discardableResult public func updatesSubscribeRequest(handler: @escaping (SubscribeEvent<Result<SubscribeResponse, Error>>) -> Void) -> DataRequest {
return subscribeRequest(path: "/updates", handler: handler)
}
#warning("TODO: Finish GraphStoreAgent")
// private storeAction(action: any): Promise<any> {
// return this.action('graph-store', 'graph-update', action)
// }
// addGraph(ship: Patp, name: string, graph: any, mark: any) {
// return this.storeAction({
// 'add-graph': {
// resource: { ship, name },
// graph,
// mark
// }
// });
// }
public func getKeys() -> DataRequest {
return scryRequest(path: "/keys")
}
public func getTags() -> DataRequest {
return scryRequest(path: "/tags")
}
public func getTagQueries() -> DataRequest {
return scryRequest(path: "/tag-queries")
}
public func getGraph(ship: Ship, resource: Resource) -> DataRequest {
return scryRequest(path: "/graph/\(Ship.Prefixless(ship))/\(resource.description)")
}
public func getGraphSubset(ship: Ship, resource: Resource, start: String, end: String) -> DataRequest {
return scryRequest(path: "/graph-subset/\(Ship.Prefixless(ship))/\(resource.description)/\(end)/\(start)")
}
public func getNode(ship: Ship, resource: Resource, index: Index) -> DataRequest {
// const idx = index.split('/').map(numToUd).join('/');
return scryRequest(path: "/node/\(Ship.Prefixless(ship))/\(resource.description)\(index)")
}
}
extension GraphStoreAgent {
public enum SubscribeResponse: Decodable {
case graphUpdate(GraphUpdate)
enum CodingKeys: String, CodingKey {
case graphUpdate = "graph-update"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch Set(container.allKeys) {
case [.graphUpdate]:
self = .graphUpdate(try container.decode(GraphUpdate.self, forKey: .graphUpdate))
default:
throw DecodingError.dataCorruptedError(type(of: self), at: decoder.codingPath, in: container)
}
}
}
}
/*
import BaseApi from './base';
import { StoreState } from '../store/type';
import { Patp, Path, PatpNoSig } from '~/types/noun';
import _ from 'lodash';
import {makeResource, resourceFromPath} from '../lib/group';
import {GroupPolicy, Enc, Post, NodeMap, Content} from '~/types';
import { numToUd, unixToDa } from '~/logic/lib/util';
export const createBlankNodeWithChildPost = (
parentIndex: string = '',
childIndex: string = '',
contents: Content[]
) => {
const date = unixToDa(Date.now()).toString();
const nodeIndex = parentIndex + '/' + date;
const childGraph = {};
childGraph[childIndex] = {
post: {
author: `~${window.ship}`,
index: nodeIndex + '/' + childIndex,
'time-sent': Date.now(),
contents,
hash: null,
signatures: []
},
children: { empty: null }
};
return {
post: {
author: `~${window.ship}`,
index: nodeIndex,
'time-sent': Date.now(),
contents: [],
hash: null,
signatures: []
},
children: {
graph: childGraph
}
};
};
export const createPost = (
contents: Content[],
parentIndex: string = '',
childIndex:string = 'DATE_PLACEHOLDER'
) => {
if (childIndex === 'DATE_PLACEHOLDER') {
childIndex = unixToDa(Date.now()).toString();
}
return {
author: `~${window.ship}`,
index: parentIndex + '/' + childIndex,
'time-sent': Date.now(),
contents,
hash: null,
signatures: []
};
};
function moduleToMark(mod: string): string | undefined {
if(mod === 'link') {
return 'graph-validator-link';
}
if(mod === 'publish') {
return 'graph-validator-publish';
}
return undefined;
}
*/
| 27.518717 | 154 | 0.600078 |
11333ab02c5c8031151af7a8c955ffeeecbee0a6 | 3,173 | //
// LeftNodeTableViewCell.swift
// V2ex-Swift
//
// Created by huangfeng on 1/23/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class LeftNodeTableViewCell: UITableViewCell {
var nodeImageView: UIImageView = UIImageView()
var nodeNameLabel: UILabel = {
let label = UILabel()
label.font = v2Font(16)
return label
}()
var panel = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup()->Void{
self.selectionStyle = .none
self.backgroundColor = UIColor.clear
self.contentView.addSubview(panel)
panel.addSubview(self.nodeImageView)
panel.addSubview(self.nodeNameLabel)
panel.snp.makeConstraints{ (make) -> Void in
make.left.top.right.equalTo(self.contentView)
make.height.equalTo(55)
}
self.nodeImageView.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(panel)
make.left.equalTo(panel).offset(20)
make.width.height.equalTo(25)
}
self.nodeNameLabel.snp.makeConstraints{ (make) -> Void in
make.left.equalTo(self.nodeImageView.snp.right).offset(20)
make.centerY.equalTo(self.nodeImageView)
}
self.themeChangedHandler = {[weak self] (style) -> Void in
self?.configureColor()
}
}
func configureColor(){
self.panel.backgroundColor = V2EXColor.colors.v2_LeftNodeBackgroundColor
self.nodeImageView.tintColor = V2EXColor.colors.v2_LeftNodeTintColor
self.nodeNameLabel.textColor = V2EXColor.colors.v2_LeftNodeTintColor
}
}
class LeftNotifictionCell : LeftNodeTableViewCell{
var notifictionCountLabel:UILabel = {
let label = UILabel()
label.font = v2Font(10)
label.textColor = UIColor.white
label.layer.cornerRadius = 7
label.layer.masksToBounds = true
label.backgroundColor = V2EXColor.colors.v2_NoticePointColor
return label
}()
override func setup() {
super.setup()
self.nodeNameLabel.text = NSLocalizedString("notifications")
self.contentView.addSubview(self.notifictionCountLabel)
self.notifictionCountLabel.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.nodeNameLabel)
make.left.equalTo(self.nodeNameLabel.snp.right).offset(5)
make.height.equalTo(14)
}
self.kvoController.observe(V2User.sharedInstance, keyPath: "notificationCount", options: [.initial,.new]) { [weak self](cell, clien, change) -> Void in
if V2User.sharedInstance.notificationCount > 0 {
self?.notifictionCountLabel.text = " \(V2User.sharedInstance.notificationCount) "
}
else{
self?.notifictionCountLabel.text = ""
}
}
}
}
| 33.052083 | 160 | 0.624015 |
bf68c3f1415b90b712fc5b0fbd3c320d13509615 | 163 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ScryfallModelTests.allTests),
]
}
#endif
| 16.3 | 46 | 0.680982 |
fb3a6f54712b41a5c77c82536e900a53412d47f9 | 3,465 | // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t -enable-experimental-concurrency
// SAFE_NOTREC: Begin completions, 2 items
// SAFE_NOTREC-DAG: Keyword[self]/CurrNominal: self[#SafelyIsolatedCls#];
// SAFE_NOTREC-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: method()[' async'][#Void#];
// SAFE_NOTREC: End completions
// UNSAFE_NOTREC: Begin completions, 2 items
// UNSAFE_NOTREC-DAG: Keyword[self]/CurrNominal: self[#UnsafelyIsolatedCls#];
// UNSAFE_NOTREC-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: method()[' async'][#Void#];
// UNSAFE_NOTREC: End completions
// SAFE_OK: Begin completions, 2 items
// SAFE_OK-DAG: Keyword[self]/CurrNominal: self[#SafelyIsolatedCls#];
// SAFE_OK-DAG: Decl[InstanceMethod]/CurrNominal: method()[' async'][#Void#];
// SAFE_OK: End completions
// UNSAFE_OK: Begin completions, 2 items
// UNSAFE_OK-DAG: Keyword[self]/CurrNominal: self[#UnsafelyIsolatedCls#];
// UNSAFE_OK-DAG: Decl[InstanceMethod]/CurrNominal: method()[' async'][#Void#];
// UNSAFE_OK: End completions
// UNSAFE_OK_SYNC: Begin completions, 2 items
// UNSAFE_OK_SYNC-DAG: Keyword[self]/CurrNominal: self[#UnsafelyIsolatedCls#];
// UNSAFE_OK_SYNC-DAG: Decl[InstanceMethod]/CurrNominal: method()[#Void#];
// UNSAFE_OK_SYNC: End completions
@globalActor
actor MyGlobalActor {
static let shared = MyGlobalActor()
}
@MyGlobalActor(unsafe)
class UnsafelyIsolatedCls {
func method()
}
@MyGlobalActor
class SafelyIsolatedCls {
func method()
}
class TestNormal {
func testSync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) {
s.#^IN_METHOD_SYNC_SAFE?check=SAFE_NOTREC^#
u.#^IN_METHOD_SYNC_UNSAFE?check=UNSAFE_OK_SYNC^#
}
func testAsync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) async {
s.#^IN_METHOD_ASYNC_SAFE?check=SAFE_OK^#
u.#^IN_METHOD_ASYNC_UNSAFE?check=UNSAFE_OK^#
}
}
func testSync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) {
s.#^IN_FUNC_SYNC_SAFE?check=SAFE_NOTREC^#
u.#^IN_FUNC_SYNC_UNSAFE?check=UNSAFE_OK_SYNC^#
}
func testAsync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) async {
s.#^IN_FUNC_ASYNC_SAFE?check=SAFE_OK^#
u.#^IN_FUNC_ASYNC_UNSAFE?check=UNSAFE_OK^#
}
func testClosure(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) {
func receiverSync(fn: () -> Void) {}
func receiverAsync(fn: () async -> Void) {}
receiverSync {
dummy;
s.#^IN_CLOSURE_SYNC_SAFE?check=SAFE_NOTREC^#
u.#^IN_CLOSURE_SYNC_UNSAFE?check=UNSAFE_OK_SYNC^#
}
receiverAsync {
dummy;
s.#^IN_CLOSURE_ASYNC_SAFE?check=SAFE_OK^#
u.#^IN_CLOSURE_ASYNC_UNSAFE?check=UNSAFE_OK^#
}
}
actor TestActor {
func test(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) {
s.#^IN_ACTOR_SYNC_SAFE?check=SAFE_NOTREC^#
u.#^IN_ACTOR_SYNC_UNSAFE?check=UNSAFE_NOTREC^#
}
func testAsync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) async {
s.#^IN_ACTOR_ASYNC_SAFE?check=SAFE_OK^#
u.#^IN_ACTOR_ASYNC_UNSAFE?check=UNSAFE_OK^#
}
}
@MainActor
class TestMainActorIsolated {
func test(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) {
s.#^IN_GLOBALACTOR_SYNC_SAFE?check=SAFE_NOTREC^#
u.#^IN_GLOBALACTOR_SYNC_UNSAFE?check=UNSAFE_NOTREC^#
}
func testAsync(s: SafelyIsolatedCls, u: UnsafelyIsolatedCls) async {
s.#^IN_GLOBALACTOR_ASYNC_SAFE?check=SAFE_OK^#
u.#^IN_GLOBALACTOR_ASYNC_UNSAFE?check=UNSAFE_OK^#
}
}
| 33.317308 | 158 | 0.731025 |
bf74a482e295bc4677dd6b92ec019778908bea46 | 851 | //
// URL+Sunlit.swift
// Sunlit
//
// Created by Jonathan Hays on 5/27/20.
// Copyright © 2020 Micro.blog, LLC. All rights reserved.
//
import Foundation
extension URL {
static func createTempFile() -> URL {
let documentsURL = self.documentsDirectory()
let filename = self.generateUniqueFilename(myFileName: "SunlitTempFile-")
let completeURL = URL(fileURLWithPath: filename, relativeTo: documentsURL)
return completeURL
}
static func generateUniqueFilename (myFileName: String) -> String {
let guid = ProcessInfo.processInfo.globallyUniqueString
let uniqueFileName = ("\(myFileName)_\(guid)")
return uniqueFileName
}
static func documentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
| 25.029412 | 84 | 0.73443 |
e09c6b44047d8d275f7caba9b7a1e334ea1f1fea | 2,626 | //
// SimpleCircleButtonBuilder.swift
// BoomMenuButton
//
// Created by Nightonke on 2017/4/28.
// Copyright © 2017 Nightonke. All rights reserved.
//
public class SimpleCircleButtonBuilder: BoomButtonBuilder {
/// The radius (in points) of the circular (or square) button.
///
/// **Synchronicity:** Changing this property from builder will synchronically affect the corresponding boom-button, even the boom-button has been shown on the screen.
///
/// The default value is **40**.
public var radius: CGFloat = 40 {
didSet {
if radius == oldValue {
return
}
button?.radius = radius
button?.resetButtonLayer()
button?.resetShadow()
if button?.lastStateEnum == .normal {
button?.toNormalButton()
} else if button?.lastStateEnum == .highlighted {
button?.toHighlightedButton()
} else if button?.lastStateEnum == .unable {
button?.toUnableButton()
}
button?.rotateAnchorPointInitialized = false
button?.setRotateAnchorPoints()
}
}
/// Whether the boom-button is in a circular shape. If not, then the simple-circle-button looks like a simple-square-button. Only after the 'round' property is false does the corner-radius property work.
///
/// **Synchronicity:** Changing this property from builder will synchronically affect the corresponding boom-button, even the boom-button has been shown on the screen.
///
/// The default value is **true**.
public var round = true {
didSet {
if round == oldValue {
return
}
button?.round = round
button?.resetButtonLayer()
button?.resetShadow()
if button?.lastStateEnum == .normal {
button?.toNormalButton()
} else if button?.lastStateEnum == .highlighted {
button?.toHighlightedButton()
} else if button?.lastStateEnum == .unable {
button?.toUnableButton()
}
}
}
// MARK: - Initialize
public override init() {
super.init()
shadowPathRect = CGRect.init(x: 2, y: 2, width: radius + radius - 4, height: radius + radius - 4)
}
override func build() -> SimpleCircleButton {
let button = SimpleCircleButton.init(builder: self)
self.button = button
return button
}
override func type() -> ButtonEnum {
return .simpleCircle
}
}
| 34.103896 | 207 | 0.579589 |
ab76b4b6fb056dd04702d5c90e4db51c943691d6 | 2,299 | #if !os(macOS)
import Foundation
import UIKit
private var HKPictureInPicureControllerImplKey: UInt8 = 0
/// HKPictureInPicureController protocol default implementation.
public extension HKPictureInPicureController where Self: UIViewController {
var isPictureInPictureActive: Bool {
impl.isPictureInPictureActive
}
var pictureInPictureSize: CGSize {
get {
impl.pictureInPictureSize
}
set {
impl.pictureInPictureSize = newValue
}
}
var pictureInPicturePosition: HKPictureInPicureControllerPosition {
get {
impl.pictureInPicturePosition
}
set {
impl.pictureInPicturePosition = newValue
}
}
var pictureInPictureMargin: CGFloat {
get {
impl.pictureInPictureMargin
}
set {
impl.pictureInPictureMargin = newValue
}
}
var pictureInPictureCornerRadius: CGFloat {
get {
impl.pictureInPictureCornerRadius
}
set {
impl.pictureInPictureCornerRadius = newValue
}
}
var pictureInPictureAnimationDuration: TimeInterval {
get {
impl.pictureInPictureAnimationDuration
}
set {
impl.pictureInPictureAnimationDuration = newValue
}
}
private var impl: HKPictureInPicureControllerImpl {
get {
guard let object = objc_getAssociatedObject(self, &HKPictureInPicureControllerImplKey) as? HKPictureInPicureControllerImpl else {
let impl = HKPictureInPicureControllerImpl(self)
objc_setAssociatedObject(self, &HKPictureInPicureControllerImplKey, impl, .OBJC_ASSOCIATION_RETAIN)
return impl
}
return object
}
set {
objc_setAssociatedObject(self, &HKPictureInPicureControllerImplKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
func startPictureInPicture() {
guard !impl.isPictureInPictureActive else {
return
}
impl.startPictureInPicture()
}
func stopPictureInPicture() {
guard impl.isPictureInPictureActive else {
return
}
impl.stopPictureInPicture()
}
}
#endif
| 26.425287 | 141 | 0.626359 |
ed2f2725a6b01ea289d3391cff9d05db7940b66a | 1,065 | //
// AtomicContainer.swift
// VCoreTests
//
// Created by Vakhtang Kontridze on 17.05.22.
//
import Foundation
// MARK: - Atomic Container
final class AtomicContainer<Value> where Value: Hashable {
// MARK: Properties
private let dispatchSemaphore: DispatchSemaphore = .init(value: 1)
private var storage: [Value]
// MARK: Initializers
init() {
self.storage = []
}
// MARK: Methods
subscript(index: Int) -> Value {
get {
dispatchSemaphore.wait()
defer { dispatchSemaphore.signal() }
return storage[index]
}
set {
dispatchSemaphore.wait()
defer { dispatchSemaphore.signal() }
storage[index] = newValue
}
}
func append(_ element: Value) {
dispatchSemaphore.wait()
defer { dispatchSemaphore.signal() }
storage.append(element)
}
func allElements() -> [Value] {
dispatchSemaphore.wait()
defer { dispatchSemaphore.signal() }
return storage
}
}
| 20.480769 | 70 | 0.579343 |
e0b6100d4f0d8434de6aa8af2dcb10e39a199211 | 35,444 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Backend.swift
//
// Created by Joshua Liebowitz on 8/2/21.
import Foundation
typealias SubscriberAttributeDict = [String: SubscriberAttribute]
typealias BackendCustomerInfoResponseHandler = (CustomerInfo?, Error?) -> Void
typealias IntroEligibilityResponseHandler = ([String: IntroEligibility], Error?) -> Void
typealias OfferingsResponseHandler = ([String: Any]?, Error?) -> Void
typealias OfferSigningResponseHandler = (String?, String?, UUID?, Int?, Error?) -> Void
typealias PostRequestResponseHandler = (Error?) -> Void
typealias IdentifyResponseHandler = (CustomerInfo?, Bool, Error?) -> Void
// swiftlint:disable type_body_length file_length
class Backend {
static let RCSuccessfullySyncedKey: NSError.UserInfoKey = "rc_successfullySynced"
static let RCAttributeErrorsKey = "attribute_errors"
static let RCAttributeErrorsResponseKey = "attributes_error_response"
private let httpClient: HTTPClient
private let apiKey: String
// callbackQueue controls access to callbackCaches
private let callbackQueue = DispatchQueue(label: "Backend callbackQueue")
private var offeringsCallbacksCache: [String: [OfferingsResponseHandler]]
private var customerInfoCallbacksCache: [String: [BackendCustomerInfoResponseHandler]]
private var createAliasCallbacksCache: [String: [PostRequestResponseHandler?]]
private var identifyCallbacksCache: [String: [IdentifyResponseHandler]]
private var authHeaders: [String: String] { return ["Authorization": "Bearer \(self.apiKey)"] }
convenience init(apiKey: String,
systemInfo: SystemInfo,
eTagManager: ETagManager,
operationDispatcher: OperationDispatcher) {
let httpClient = HTTPClient(systemInfo: systemInfo, eTagManager: eTagManager)
self.init(httpClient: httpClient, apiKey: apiKey)
}
required init(httpClient: HTTPClient, apiKey: String) {
self.httpClient = httpClient
self.apiKey = apiKey
self.offeringsCallbacksCache = [:]
self.customerInfoCallbacksCache = [:]
self.createAliasCallbacksCache = [:]
self.identifyCallbacksCache = [:]
}
func createAlias(appUserID: String, newAppUserID: String, completion: PostRequestResponseHandler?) {
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion?(ErrorUtils.missingAppUserIDError())
return
}
let cacheKey = appUserID + newAppUserID
if add(createAliasCallback: completion, key: cacheKey) == .addedToExistingInFlightList {
return
}
Logger.user(Strings.identity.creating_alias(userA: appUserID, userB: newAppUserID))
httpClient.performPOSTRequest(serially: true,
path: "/subscribers/\(appUserID)/alias",
requestBody: ["new_app_user_id": newAppUserID],
headers: authHeaders) { statusCode, response, error in
for callback in self.getCreateAliasCallbacksAndClearCache(forKey: cacheKey) {
self.handle(response: response, statusCode: statusCode, maybeError: error, completion: callback)
}
}
}
func clearCaches() {
httpClient.clearCaches()
}
// swiftlint:disable:next function_parameter_count
func post(receiptData: Data,
appUserID: String,
isRestore: Bool,
productInfo: ProductInfo?,
presentedOfferingIdentifier offeringIdentifier: String?,
observerMode: Bool,
subscriberAttributes subscriberAttributesByKey: SubscriberAttributeDict?,
completion: @escaping BackendCustomerInfoResponseHandler) {
let fetchToken = receiptData.asFetchToken
var body: [String: Any] = [
"fetch_token": fetchToken,
"app_user_id": appUserID,
"is_restore": isRestore,
"observer_mode": observerMode
]
let cacheKey =
"""
\(appUserID)-\(isRestore)-\(fetchToken)-\(productInfo?.cacheKey ?? "")
-\(offeringIdentifier ?? "")-\(observerMode)-\(subscriberAttributesByKey?.debugDescription ?? "")"
"""
if add(callback: completion, key: cacheKey) == .addedToExistingInFlightList {
return
}
if let productInfo = productInfo {
body.merge(productInfo.asDictionary()) { _, new in new }
}
if let subscriberAttributesByKey = subscriberAttributesByKey {
let attributesInBackendFormat = subscriberAttributesToDict(subscriberAttributes: subscriberAttributesByKey)
body["attributes"] = attributesInBackendFormat
}
if let offeringIdentifier = offeringIdentifier {
body["presented_offering_identifier"] = offeringIdentifier
}
httpClient.performPOSTRequest(serially: true,
path: "/receipts",
requestBody: body,
headers: authHeaders) { statusCode, response, error in
let callbacks = self.getCustomerInfoCallbacksAndClearCache(forKey: cacheKey)
for callback in callbacks {
self.handle(customerInfoResponse: response,
statusCode: statusCode,
maybeError: error,
completion: callback)
}
}
}
func getSubscriberData(appUserID: String, completion: @escaping BackendCustomerInfoResponseHandler) {
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion(nil, ErrorUtils.missingAppUserIDError())
return
}
let path = "/subscribers/\(appUserID)"
if add(callback: completion, key: path) == .addedToExistingInFlightList {
return
}
httpClient.performGETRequest(serially: true,
path: path,
headers: authHeaders) { [weak self] (statusCode, response, error) in
guard let self = self else {
return
}
for completion in self.getCustomerInfoCallbacksAndClearCache(forKey: path) {
self.handle(customerInfoResponse: response,
statusCode: statusCode,
maybeError: error,
completion: completion)
}
}
}
// swiftlint:disable:next function_parameter_count function_body_length
func post(offerIdForSigning offerIdentifier: String,
productIdentifier: String,
subscriptionGroup: String,
receiptData: Data,
appUserID: String,
completion: @escaping OfferSigningResponseHandler) {
let fetchToken = receiptData.asFetchToken
let requestBody: [String: Any] = ["app_user_id": appUserID,
"fetch_token": fetchToken,
"generate_offers": [
["offer_id": offerIdentifier,
"product_id": productIdentifier,
"subscription_group": subscriptionGroup
]
]]
self.httpClient.performPOSTRequest(serially: true,
path: "/offers",
requestBody: requestBody,
headers: authHeaders) { statusCode, maybeResponse, maybeError in
if let error = maybeError {
completion(nil, nil, nil, nil, ErrorUtils.networkError(withUnderlyingError: error))
return
}
guard statusCode < HTTPStatusCodes.redirect.rawValue else {
let backendCode = BackendErrorCode(maybeCode: maybeResponse?["code"])
let backendMessage = maybeResponse?["message"] as? String
let error = ErrorUtils.backendError(withBackendCode: backendCode, backendMessage: backendMessage)
completion(nil, nil, nil, nil, error)
return
}
guard let response = maybeResponse else {
let subErrorCode = UnexpectedBackendResponseSubErrorCode.postOfferEmptyResponse
let error = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode)
Logger.debug(Strings.backendError.offerings_empty_response)
completion(nil, nil, nil, nil, error)
return
}
guard let offers = response["offers"] as? [[String: Any]] else {
let subErrorCode = UnexpectedBackendResponseSubErrorCode.postOfferIdBadResponse
let error = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode,
extraContext: response.stringRepresentation)
Logger.debug(Strings.backendError.offerings_response_json_error(response: response))
completion(nil, nil, nil, nil, error)
return
}
guard offers.count > 0 else {
let subErrorCode = UnexpectedBackendResponseSubErrorCode.postOfferIdMissingOffersInResponse
let error = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode)
Logger.debug(Strings.backendError.no_offerings_response_json(response: response))
completion(nil, nil, nil, nil, error)
return
}
let offer = offers[0]
if let signatureError = offer["signature_error"] as? [String: Any] {
let backendCode = BackendErrorCode(maybeCode: signatureError["code"])
let backendMessage = signatureError["message"] as? String
let error = ErrorUtils.backendError(withBackendCode: backendCode, backendMessage: backendMessage)
completion(nil, nil, nil, nil, error)
return
} else if let signatureData = offer["signature_data"] as? [String: Any] {
let signature = signatureData["signature"] as? String
let keyIdentifier = offer["key_id"] as? String
let nonceString = signatureData["nonce"] as? String
let maybeNonce = nonceString.flatMap { UUID(uuidString: $0) }
let timestamp = signatureData["timestamp"] as? Int
completion(signature, keyIdentifier, maybeNonce, timestamp, nil)
return
} else {
Logger.error(Strings.backendError.signature_error(maybeSignatureDataString: offer["signature_data"]))
let subErrorCode = UnexpectedBackendResponseSubErrorCode.postOfferIdSignature
let signatureError = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode)
completion(nil, nil, nil, nil, signatureError)
return
}
}
}
func post(attributionData: [String: Any],
network: AttributionNetwork,
appUserID: String,
completion: PostRequestResponseHandler?) {
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion?(ErrorUtils.missingAppUserIDError())
return
}
let path = "/subscribers/\(appUserID)/attribution"
let body: [String: Any] = ["network": network.rawValue, "data": attributionData]
httpClient.performPOSTRequest(serially: true,
path: path,
requestBody: body,
headers: authHeaders) { statusCode, response, error in
self.handle(response: response, statusCode: statusCode, maybeError: error, completion: completion)
}
}
func post(subscriberAttributes: SubscriberAttributeDict,
appUserID: String,
completion: PostRequestResponseHandler?) {
guard subscriberAttributes.count > 0 else {
Logger.warn(Strings.attribution.empty_subscriber_attributes)
completion?(ErrorCode.emptySubscriberAttributes)
return
}
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion?(ErrorUtils.missingAppUserIDError())
return
}
let path = "/subscribers/\(appUserID)/attributes"
let attributesInBackendFormat = subscriberAttributesToDict(subscriberAttributes: subscriberAttributes)
httpClient.performPOSTRequest(serially: true,
path: path,
requestBody: ["attributes": attributesInBackendFormat],
headers: authHeaders) { statusCode, response, error in
self.handleSubscriberAttributesResult(statusCode: statusCode,
response: response,
maybeError: error,
completion: completion)
}
}
func logIn(currentAppUserID: String,
newAppUserID: String,
completion: @escaping IdentifyResponseHandler) {
let cacheKey = currentAppUserID + newAppUserID
if add(identifyCallback: completion, key: cacheKey) == .addedToExistingInFlightList {
return
}
let requestBody = ["app_user_id": currentAppUserID, "new_app_user_id": newAppUserID]
httpClient.performPOSTRequest(serially: true,
path: "/subscribers/identify",
requestBody: requestBody,
headers: authHeaders) { statusCode, response, error in
for callback in self.getIdentifyCallbacksAndClearCache(forKey: cacheKey) {
self.handleLogin(maybeResponse: response,
statusCode: statusCode,
maybeError: error,
completion: callback)
}
}
}
func getOfferings(appUserID: String, completion: @escaping OfferingsResponseHandler) {
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion(nil, ErrorUtils.missingAppUserIDError())
return
}
let path = "/subscribers/\(appUserID)/offerings"
if add(callback: completion, key: path) == .addedToExistingInFlightList {
return
}
httpClient.performGETRequest(serially: true,
path: path,
headers: authHeaders) { [weak self] (statusCode, maybeResponse, maybeError) in
guard let self = self else {
Logger.debug(Strings.backendError.backend_deallocated)
return
}
if maybeError == nil && statusCode < HTTPStatusCodes.redirect.rawValue {
for callback in self.getOfferingsCallbacksAndClearCache(forKey: path) {
callback(maybeResponse, nil)
}
return
}
let errorForCallbacks: Error
if let error = maybeError {
errorForCallbacks = ErrorUtils.networkError(withUnderlyingError: error)
} else if statusCode >= HTTPStatusCodes.redirect.rawValue {
let backendCode = BackendErrorCode(maybeCode: maybeResponse?["code"])
let backendMessage = maybeResponse?["message"] as? String
errorForCallbacks = ErrorUtils.backendError(withBackendCode: backendCode,
backendMessage: backendMessage)
} else {
let subErrorCode = UnexpectedBackendResponseSubErrorCode.getOfferUnexpectedResponse
errorForCallbacks = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode)
}
let responseString = maybeResponse?.debugDescription
Logger.error(Strings.backendError.unknown_get_offerings_error(statusCode: statusCode,
maybeResponseString: responseString))
for callback in self.getOfferingsCallbacksAndClearCache(forKey: path) {
callback(nil, errorForCallbacks)
}
}
}
func fetchIntroEligibility(appUserID: String,
receiptData: Data,
productIdentifiers: [String],
completion: @escaping IntroEligibilityResponseHandler) {
guard productIdentifiers.count > 0 else {
completion([:], nil)
return
}
if receiptData.count == 0 {
if self.httpClient.systemInfo.isSandbox {
Logger.appleWarning(Strings.receipt.no_sandbox_receipt_intro_eligibility)
}
var eligibilities: [String: IntroEligibility] = [:]
for productID in productIdentifiers {
eligibilities[productID] = IntroEligibility(eligibilityStatus: .unknown)
}
completion(eligibilities, nil)
return
}
// Closure we can use for both missing appUserID as well as server error where we have an unknown
// eligibility status.
let unknownEligibilityClosure: () -> [String: IntroEligibility] = {
let unknownEligibilities = [IntroEligibility](repeating: IntroEligibility(eligibilityStatus: .unknown),
count: productIdentifiers.count)
let productIdentifiersToEligibility = zip(productIdentifiers, unknownEligibilities)
return Dictionary(uniqueKeysWithValues: productIdentifiersToEligibility)
}
guard let appUserID = try? escapedAppUserID(appUserID: appUserID) else {
completion(unknownEligibilityClosure(), ErrorUtils.missingAppUserIDError())
return
}
let fetchToken = receiptData.asFetchToken
let path = "/subscribers/\(appUserID)/intro_eligibility"
let body: [String: Any] = ["product_identifiers": productIdentifiers,
"fetch_token": fetchToken]
httpClient.performPOSTRequest(serially: true,
path: path,
requestBody: body,
headers: authHeaders) { statusCode, maybeResponse, error in
let eligibilityResponse = IntroEligibilityResponse(maybeResponse: maybeResponse,
statusCode: statusCode,
error: error,
productIdentifiers: productIdentifiers,
unknownEligibilityClosure: unknownEligibilityClosure,
completion: completion)
self.handleIntroEligibility(response: eligibilityResponse)
}
}
}
private extension Backend {
enum CallbackCacheStatus {
// When an array exists in the cache for a particular path, we add to it and return this value.
case addedToExistingInFlightList
// When an array doesn't yet exist in the cache for a particular path, we create one, add to it
// and return this value.
case firstCallbackAddedToList
}
func handleIntroEligibility(response: IntroEligibilityResponse) {
var eligibilitiesByProductIdentifier = response.maybeResponse
if response.statusCode >= HTTPStatusCodes.redirect.rawValue || response.error != nil {
eligibilitiesByProductIdentifier = [:]
}
guard let eligibilitiesByProductIdentifier = eligibilitiesByProductIdentifier else {
response.completion(response.unknownEligibilityClosure(), nil)
return
}
var eligibilities: [String: IntroEligibility] = [:]
for productID in response.productIdentifiers {
let status: IntroEligibilityStatus
if let eligibility = eligibilitiesByProductIdentifier[productID] as? Bool {
status = eligibility ? .eligible : .ineligible
} else {
status = .unknown
}
eligibilities[productID] = IntroEligibility(eligibilityStatus: status)
}
response.completion(eligibilities, nil)
}
func handleLogin(maybeResponse: [String: Any]?,
statusCode: Int,
maybeError: Error?,
completion: IdentifyResponseHandler) {
if let error = maybeError {
completion(nil, false, ErrorUtils.networkError(withUnderlyingError: error))
return
}
guard let response = maybeResponse else {
let subErrorCode = UnexpectedBackendResponseSubErrorCode.loginMissingResponse
let responseError = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode)
completion(nil, false, responseError)
return
}
if statusCode > HTTPStatusCodes.redirect.rawValue {
let backendCode = BackendErrorCode(maybeCode: response["code"])
let backendMessage = response["message"] as? String
let responsError = ErrorUtils.backendError(withBackendCode: backendCode, backendMessage: backendMessage)
completion(nil, false, ErrorUtils.networkError(withUnderlyingError: responsError))
return
}
do {
let customerInfo = try parseCustomerInfo(fromMaybeResponse: maybeResponse)
let created = statusCode == HTTPStatusCodes.createdSuccess.rawValue
Logger.user(Strings.identity.login_success)
completion(customerInfo, created, nil)
} catch let customerInfoError {
Logger.error(Strings.backendError.customer_info_instantiation_error(maybeResponse: response))
let extraContext = "statusCode: \(statusCode)"
let subErrorCode = UnexpectedBackendResponseSubErrorCode
.loginResponseDecoding
.addingUnderlyingError(customerInfoError)
let responseError = ErrorUtils.unexpectedBackendResponse(withSubError: subErrorCode,
extraContext: extraContext)
completion(nil, false, responseError)
}
}
func attributesUserInfoFromResponse(response: [String: Any], statusCode: Int) -> [String: Any] {
var resultDict: [String: Any] = [:]
let isInternalServerError = statusCode >= HTTPStatusCodes.internalServerError.rawValue
let isNotFoundError = statusCode == HTTPStatusCodes.notFoundError.rawValue
let successfullySynced = !(isInternalServerError || isNotFoundError)
resultDict[Backend.RCSuccessfullySyncedKey as String] = successfullySynced
let hasAttributesResponseContainerKey = (response[Backend.RCAttributeErrorsResponseKey] != nil)
let attributesResponseDict = hasAttributesResponseContainerKey
? response[Backend.RCAttributeErrorsResponseKey]
: response
if let attributesResponseDict = attributesResponseDict as? [String: Any],
let attributesErrors = attributesResponseDict[Backend.RCAttributeErrorsKey] {
resultDict[Backend.RCAttributeErrorsKey] = attributesErrors
}
return resultDict
}
func handleSubscriberAttributesResult(statusCode: Int,
response: [String: Any]?,
maybeError: Error?,
completion: PostRequestResponseHandler?) {
guard let completion = completion else {
return
}
if let error = maybeError {
completion(ErrorUtils.networkError(withUnderlyingError: error))
return
}
let responseError: Error?
if let response = response, statusCode > HTTPStatusCodes.redirect.rawValue {
let extraUserInfo = attributesUserInfoFromResponse(response: response, statusCode: statusCode)
let backendErrorCode = BackendErrorCode(maybeCode: response["code"])
responseError = ErrorUtils.backendError(withBackendCode: backendErrorCode,
backendMessage: response["message"] as? String,
extraUserInfo: extraUserInfo as [NSError.UserInfoKey: Any])
} else {
responseError = nil
}
completion(responseError)
}
func handle(response: [String: Any]?,
statusCode: Int,
maybeError: Error?,
completion: PostRequestResponseHandler?) {
if let error = maybeError {
completion?(ErrorUtils.networkError(withUnderlyingError: error))
return
}
guard statusCode <= HTTPStatusCodes.redirect.rawValue else {
let backendErrorCode = BackendErrorCode(maybeCode: response?["code"])
let message = response?["message"] as? String
let responseError = ErrorUtils.backendError(withBackendCode: backendErrorCode, backendMessage: message)
completion?(responseError)
return
}
completion?(nil)
}
func parseCustomerInfo(fromMaybeResponse maybeResponse: [String: Any]?) throws -> CustomerInfo {
guard let customerJson = maybeResponse else {
throw UnexpectedBackendResponseSubErrorCode.customerInfoResponseMalformed
}
do {
return try CustomerInfo(data: customerJson)
} catch {
let parsingError = UnexpectedBackendResponseSubErrorCode.customerInfoResponseParsing
let subError = parsingError.addingUnderlyingError(error,
extraContext: customerJson.stringRepresentation)
throw subError
}
}
// swiftlint:disable:next function_body_length
func handle(customerInfoResponse maybeResponse: [String: Any]?,
statusCode: Int,
maybeError: Error?,
file: String = #fileID,
function: String = #function,
line: UInt = #line,
completion: BackendCustomerInfoResponseHandler) {
if let error = maybeError {
completion(nil, ErrorUtils.networkError(withUnderlyingError: error,
fileName: file, functionName: function, line: line))
return
}
let isErrorStatusCode = statusCode >= HTTPStatusCodes.redirect.rawValue
let maybeCustomerInfoError: Error?
let maybeCustomerInfo: CustomerInfo?
if !isErrorStatusCode {
// Only attempt to parse a response if we don't have an error status code from the backend.
do {
maybeCustomerInfo = try parseCustomerInfo(fromMaybeResponse: maybeResponse)
maybeCustomerInfoError = nil
} catch let customerInfoError {
maybeCustomerInfo = nil
maybeCustomerInfoError = customerInfoError
}
} else {
maybeCustomerInfoError = nil
maybeCustomerInfo = nil
}
if !isErrorStatusCode && maybeCustomerInfo == nil {
let extraContext = "statusCode: \(statusCode), json:\(maybeResponse.debugDescription)"
completion(nil, ErrorUtils.unexpectedBackendResponse(withSubError: maybeCustomerInfoError,
extraContext: extraContext,
fileName: file, functionName: function, line: line))
return
}
let subscriberAttributesErrorInfo = attributesUserInfoFromResponse(response: maybeResponse ?? [:],
statusCode: statusCode)
let hasError = (isErrorStatusCode
|| subscriberAttributesErrorInfo[Backend.RCAttributeErrorsKey] != nil
|| maybeCustomerInfoError != nil)
guard !hasError else {
let finishable = statusCode < HTTPStatusCodes.internalServerError.rawValue
var extraUserInfo = [ErrorDetails.finishableKey: finishable] as [String: Any]
extraUserInfo.merge(subscriberAttributesErrorInfo) { _, new in new }
let backendErrorCode = BackendErrorCode(maybeCode: maybeResponse?["code"])
let message = maybeResponse?["message"] as? String
var responseError = ErrorUtils.backendError(withBackendCode: backendErrorCode,
backendMessage: message,
extraUserInfo: extraUserInfo as [NSError.UserInfoKey: Any])
if let maybeCustomerInfoError = maybeCustomerInfoError {
responseError = maybeCustomerInfoError
.addingUnderlyingError(responseError, extraContext: maybeResponse?.stringRepresentation)
}
completion(maybeCustomerInfo, responseError)
return
}
completion(maybeCustomerInfo, nil)
}
func escapedAppUserID(appUserID: String) throws -> String {
let trimmedAndEscapedAppUserID = appUserID
.trimmingCharacters(in: .whitespacesAndNewlines)
.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
guard trimmedAndEscapedAppUserID.count > 0 else {
Logger.warn("appUserID is empty")
throw ErrorUtils.missingAppUserIDError()
}
return trimmedAndEscapedAppUserID
}
func subscriberAttributesToDict(subscriberAttributes: SubscriberAttributeDict) -> [String: Any] {
var attributesByKey: [String: Any] = [:]
for (key, value) in subscriberAttributes {
attributesByKey[key] = value.asBackendDictionary()
}
return attributesByKey
}
func userInfoAttributes(response: [String: Any], statusCode: Int) -> [String: Any] {
var resultDict: [String: Any] = [:]
let isInternalServerError = statusCode >= HTTPStatusCodes.internalServerError.rawValue
let isNotFoundError = statusCode == HTTPStatusCodes.notFoundError.rawValue
let successfullySynced = !(isInternalServerError || isNotFoundError)
resultDict[Backend.RCSuccessfullySyncedKey as String] = successfullySynced
let attributesResponse = (response[Backend.RCAttributeErrorsResponseKey] as? [String: Any]) ?? response
resultDict[Backend.RCAttributeErrorsKey] = attributesResponse[Backend.RCAttributeErrorsKey]
return resultDict
}
// MARK: Callback cache management
func add(callback: @escaping BackendCustomerInfoResponseHandler, key: String) -> CallbackCacheStatus {
return callbackQueue.sync { [self] in
var callbacksForKey = customerInfoCallbacksCache[key] ?? []
let cacheStatus: CallbackCacheStatus = !callbacksForKey.isEmpty
? .addedToExistingInFlightList
: .firstCallbackAddedToList
callbacksForKey.append(callback)
customerInfoCallbacksCache[key] = callbacksForKey
return cacheStatus
}
}
func add(callback: @escaping OfferingsResponseHandler, key: String) -> CallbackCacheStatus {
return callbackQueue.sync { [self] in
var callbacksForKey = offeringsCallbacksCache[key] ?? []
let cacheStatus: CallbackCacheStatus = !callbacksForKey.isEmpty
? .addedToExistingInFlightList
: .firstCallbackAddedToList
callbacksForKey.append(callback)
offeringsCallbacksCache[key] = callbacksForKey
return cacheStatus
}
}
func add(createAliasCallback: PostRequestResponseHandler?, key: String) -> CallbackCacheStatus {
return callbackQueue.sync { [self] in
var callbacksForKey = createAliasCallbacksCache[key] ?? []
let cacheStatus: CallbackCacheStatus = !callbacksForKey.isEmpty
? .addedToExistingInFlightList
: .firstCallbackAddedToList
callbacksForKey.append(createAliasCallback)
createAliasCallbacksCache[key] = callbacksForKey
return cacheStatus
}
}
func add(identifyCallback: @escaping IdentifyResponseHandler, key: String) -> CallbackCacheStatus {
return callbackQueue.sync { [self] in
var callbacksForKey = identifyCallbacksCache[key] ?? []
let cacheStatus: CallbackCacheStatus = !callbacksForKey.isEmpty
? .addedToExistingInFlightList
: .firstCallbackAddedToList
callbacksForKey.append(identifyCallback)
identifyCallbacksCache[key] = callbacksForKey
return cacheStatus
}
}
func getOfferingsCallbacksAndClearCache(forKey key: String) -> [OfferingsResponseHandler] {
return callbackQueue.sync { [self] in
let callbacks = offeringsCallbacksCache.removeValue(forKey: key)
assert(callbacks != nil)
return callbacks ?? []
}
}
func getCustomerInfoCallbacksAndClearCache(forKey key: String) -> [BackendCustomerInfoResponseHandler] {
return callbackQueue.sync { [self] in
let callbacks = customerInfoCallbacksCache.removeValue(forKey: key)
assert(callbacks != nil)
return callbacks ?? []
}
}
func getCreateAliasCallbacksAndClearCache(forKey key: String) -> [PostRequestResponseHandler?] {
return callbackQueue.sync { [self] in
let callbacks = createAliasCallbacksCache.removeValue(forKey: key)
assert(callbacks != nil)
return callbacks ?? []
}
}
func getIdentifyCallbacksAndClearCache(forKey key: String) -> [IdentifyResponseHandler] {
return callbackQueue.sync { [self] in
let callbacks = identifyCallbacksCache.removeValue(forKey: key)
assert(callbacks != nil)
return callbacks ?? []
}
}
}
// swiftlint:enable type_body_length file_length
| 44.809102 | 119 | 0.603769 |
e5165d6c0680889ebc34e6b5922bd6f8bbda7bde | 1,827 | //
// SZMentionHelper.swift
// SZMentionsSwift
//
// Created by Steve Zweier on 2/1/16.
// Copyright © 2016 Steven Zweier. All rights reserved.
//
internal extension Array where Element: SZMention {
/**
@brief returns the mention being edited (if a mention is being edited)
@param range: the range to look for a mention
@return SZMention?: the mention being edited (if one exists)
*/
func mentionBeingEdited(atRange range: NSRange) -> SZMention? {
return filter{ NSIntersectionRange(range, $0.mentionRange).length > 0 ||
(range.location + range.length) > $0.mentionRange.location &&
(range.location + range.length) < ($0.mentionRange.location + $0.mentionRange.length) }.first
}
/**
@brief adjusts the positioning of mentions that exist after the range where text was edited
@param range: the range where text was changed
@param text: the text that was changed
@param mentions: the list of current mentions
*/
func adjustMentions(forTextChangeAtRange range: NSRange, text: String) {
let rangeAdjustment = text.utf16.count - range.length
mentionsAfterTextEntry(range).forEach { mention in
mention.mentionRange = NSRange(
location: mention.mentionRange.location + rangeAdjustment,
length: mention.mentionRange.length)
}
}
/**
@brief Determines what mentions exist after a given range
@param range: the range where text was changed
@param mentionsList: the list of current mentions
@return [SZMention]: list of mentions that exist after the provided range
*/
private func mentionsAfterTextEntry(_ range: NSRange) -> [SZMention] {
return filter{ $0.mentionRange.location >= range.location + range.length }
}
}
| 39.717391 | 105 | 0.675424 |
e58bf0fa9ce5604fe1c84e3f0d5c8266e4eeac4f | 488 | //
// AWSDKError_Proxy.swift
// AWError
//
// Copyright © 2016 VMware, Inc. All rights reserved. This product is protected
// by copyright and intellectual property laws in the United States and other
// countries as well as by international treaties. VMware products are covered
// by one or more patents listed at http://www.vmware.com/go/patents.
//
import Foundation
public extension AWError.SDK {
enum Proxy {
}
}
public extension AWError.SDK.Proxy {
} | 23.238095 | 80 | 0.711066 |
8a0ac4798cff3579d5206ec7ccef9406d1a501ed | 3,296 | //
// LoaderViewController.swift
// Vouch365
//
// Created by Veer Suthar on 4/29/17.
// Copyright © 2017 Veer Suthar. All rights reserved.
//
import UIKit
class LoaderViewController: UIViewController {
@IBOutlet weak var imageview: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
/* imageview.animationImages = [
UIImage(named: "GIF-01.jpg")!,
UIImage(named: "GIF-02.jpg")!,
UIImage(named: "GIF-03.jpg")!,
UIImage(named: "GIF-03.jpg")!,
UIImage(named: "GIF-04.jpg")!,
UIImage(named: "GIF-05.jpg")!,
UIImage(named: "GIF-06.jpg")!,
UIImage(named: "GIF-07.jpg")!,
UIImage(named: "GIF-08.jpg")!,
UIImage(named: "GIF-09.jpg")!,
UIImage(named: "GIF-10.jpg")!,
UIImage(named: "GIF-11.jpg")!,
UIImage(named: "GIF-12.jpg")!,
UIImage(named: "GIF-13.jpg")!,
UIImage(named: "GIF-14.jpg")!,
UIImage(named: "GIF-15.jpg")!,
UIImage(named: "GIF-16.jpg")!,
UIImage(named: "GIF-17.jpg")!,
UIImage(named: "GIF-18.jpg")!,
UIImage(named: "GIF-19.jpg")!,
UIImage(named: "GIF-20.jpg")!,
UIImage(named: "GIF-21.jpg")!,
UIImage(named: "GIF-22.jpg")!,
UIImage(named: "GIF-23.jpg")!,
UIImage(named: "GIF-24.jpg")!,
UIImage(named: "GIF-25.jpg")!,
UIImage(named: "GIF-26.jpg")!,
UIImage(named: "GIF-27.jpg")!,
UIImage(named: "GIF-28.jpg")!,
UIImage(named: "GIF-29.jpg")!,
UIImage(named: "GIF-30.jpg")!,
UIImage(named: "GIF-31.jpg")!,
UIImage(named: "GIF-32.jpg")!,
UIImage(named: "GIF-33.jpg")!,
UIImage(named: "GIF-34.jpg")!,
UIImage(named: "GIF-35.jpg")!,
UIImage(named: "GIF-36.jpg")!,
UIImage(named: "GIF-37.jpg")!,
UIImage(named: "GIF-38.jpg")!,
UIImage(named: "GIF-39.jpg")!,
UIImage(named: "GIF-40.jpg")!,
UIImage(named: "GIF-41.jpg")!,
UIImage(named: "GIF-42.jpg")!,
UIImage(named: "GIF-43.jpg")!,
UIImage(named: "GIF-44.jpg")!,
UIImage(named: "GIF-45.jpg")!,
UIImage(named: "GIF-46.jpg")!,
UIImage(named: "GIF-47.jpg")!,
UIImage(named: "GIF-48.jpg")!]
imageview.animationDuration = 2.5
imageview.animationRepeatCount = 1
imageview.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.animationDidFinish()
}*/
self.animationDidFinish()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func animationDidFinish() {
if let viewController = UIStoryboard(name: "Main-Pso", bundle: nil).instantiateViewController(withIdentifier: "TabBarController") as? UIViewController {
self.present(viewController, animated: true, completion: nil)
}
//Bootstrapper.initializeAfterLoading()
}
/*
// 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.
}
*/
}
| 31.09434 | 153 | 0.611347 |
9ce370cf299886a50fa872fdd9fbbfe240484e65 | 803 | //
// ServiceError.swift
// ChuckFacts
//
// Created by Calebe Emerick on 02/03/2018.
// Copyright © 2018 Stone Pagamentos. All rights reserved.
//
import Foundation
enum ServiceError: Error {
case JSONParse(JSONParseError)
case badRequest(BadRequestError)
case connection(InternetConnectionError)
case `internalServer`
}
extension ServiceError: Equatable {
static func ==(lhs: ServiceError, rhs: ServiceError) -> Bool {
switch (lhs, rhs) {
case (let .JSONParse(error), let .JSONParse(error2)):
return error == error2
case (let .badRequest(error), let .badRequest(error2)):
return error == error2
case (let .connection(error), let .connection(error2)):
return error == error2
case (.internalServer, .internalServer):
return true
default:
return false
}
}
}
| 22.305556 | 63 | 0.709838 |
38e9623dc4a788dddd06b0f1d5a9232a229bf9c6 | 2,099 | import Foundation
public extension AnyCharacteristic {
static func isConfigured(
_ value: Enums.IsConfigured = .notconfigured,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Is Configured",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.isConfigured(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func isConfigured(
_ value: Enums.IsConfigured = .notconfigured,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Is Configured",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.IsConfigured> {
GenericCharacteristic<Enums.IsConfigured>(
type: .isConfigured,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| 33.854839 | 67 | 0.586946 |
f4376de526415aa1ce3a5404d277af915096a65a | 377 | //
// HTTP.swift
// ServicesAndVIPER
//
// Created by Tibor Bödecs on 2019. 09. 25..
// Copyright © 2019. Tibor Bödecs. All rights reserved.
//
import Foundation
enum HTTP {
enum Method: String {
case get
//...
}
enum Error: LocalizedError {
case invalidResponse
case statusCode(Int)
case unknown(Swift.Error)
}
}
| 16.391304 | 56 | 0.591512 |
90406d4e7e8098eeb1c5035820832a07d0a6c2e0 | 257 | //
// InitDate+CoreDataClass.swift
// iShop
//
// Created by Chris Filiatrault on 23/7/20.
// Copyright © 2020 Chris Filiatrault. All rights reserved.
//
//
import Foundation
import CoreData
@objc(InitDate)
public class InitDate: NSManagedObject {
}
| 15.117647 | 60 | 0.719844 |
229a8fc5fbd94b9b2b3e2f104842c55c85dacf70 | 9,251 | //
// Socket.swift
// Socket.swift
//
// Created by Orkhan Alikhanov on 7/3/17.
// Copyright © 2017 BiAtoms. All rights reserved.
//
import Foundation
public typealias FileDescriptor = Int32
public typealias Byte = UInt8
public typealias Port = in_port_t
public typealias SocketAddress = sockaddr
public typealias TimeValue = timeval
open class Socket {
public let fileDescriptor: FileDescriptor
open var tls: TLS?
required public init(with fileDescriptor: FileDescriptor) {
self.fileDescriptor = fileDescriptor
}
required public init(_ family: Family, type: Type = .stream, protocol: Protocol = .tcp) throws {
self.fileDescriptor = try ing { socket(family.rawValue, type.rawValue, `protocol`.rawValue) }
}
open func close() {
//Dont close after an error. see http://man7.org/linux/man-pages/man2/close.2.html#NOTES
//TODO: Handle error on close
tls?.close()
_ = OS.close(fileDescriptor)
}
open func read() throws -> Byte {
var byte: Byte = 0
_ = try read(&byte, size: 1)
return byte
}
open func read(_ buffer: UnsafeMutableRawPointer, size: Int) throws -> Int {
if let tls = tls {
return try tls.read(buffer, size: size)
}
let received = try ing { recv(fileDescriptor, buffer, size, 0) }
return received
}
/// Writes all `length` of the `buffer` into the socket by calling
/// write(_:size:) in a loop.
///
/// - Parameters:
/// - buffer: Raw pointer to the buffer.
/// - length: Length of the buffer to be written.
/// - Throws: `Socket.Error` holding `errno`
open func write(_ buffer: UnsafeRawPointer, length: Int) throws {
var totalWritten = 0
while totalWritten < length {
let written = try write(buffer + totalWritten, size: length - totalWritten)
totalWritten += written
}
}
/// Writes bytes to socket
///
/// - Parameters:
/// - buffer: Raw pointer to the buffer.
/// - size: Maximum number of bytes to write.
/// - Returns: Number of written bytes.
/// - Throws: `Socket.Error` holding `errno`
open func write(_ buffer: UnsafeRawPointer, size: Int) throws -> Int {
if let ssl = tls {
return try ssl.write(buffer, size: size)
}
let written = OS.write(fileDescriptor, buffer, size)
if written <= 0 { //see http://man7.org/linux/man-pages/man2/write.2.html#RETURN_VALUE
throw Error(errno: errno)
}
return written
}
open func set<T>(option: Option<T>, _ value: T) throws {
// setsockopt expects at least Int32 structure, meaning 4 bytes at least.
// When the `value` variable is Bool, MemoryLayout<Bool>.size returns 1 and
// bytes in memory are garbage except one of them. (eg. [0, 241, 49, 19], first indicates false)
// Passing a pointer to `value` variable and size of Int32 (which is 4) into setsockopt
// would be equal to always passing true since although the byte sequance [0, 241, 49, 19] of `value`
// variable is false as Bool, it is non-zero as an Int32.
// We avoid it by explicitly checking whether T is Bool and passing Int32 0 or 1.
let size = value is Bool ? MemoryLayout<Int32>.size : MemoryLayout<T>.size
var state: Any = value is Bool ? (value as! Bool == true ? 1 : 0) : value
try ing { setsockopt(fileDescriptor, SOL_SOCKET, option.rawValue, &state, socklen_t(size)) }
}
open func bind(port: Port, address: String? = nil) throws {
try bind(address: SocketAddress(port: port, address: address))
}
open func bind(address: SocketAddress) throws {
var addr = address
try ing { OS.bind(fileDescriptor, &addr, socklen_t(MemoryLayout<SocketAddress>.size)) }
}
open func connect(port: Port, address: String? = nil) throws {
try connect(address: SocketAddress(port: port, address: address))
}
open func connect(address: SocketAddress) throws {
var addr = address
try ing { OS.connect(fileDescriptor, &addr, socklen_t(MemoryLayout<SocketAddress>.size)) }
}
open func listen(backlog: Int32 = SOMAXCONN) throws {
try ing { OS.listen(fileDescriptor, backlog) }
}
open func accept() throws -> Self {
var addrlen: socklen_t = 0, addr = sockaddr()
let client = try ing { OS.accept(fileDescriptor, &addr, &addrlen) }
return type(of: self).init(with: client)
}
public struct WaitOption: OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) { self.rawValue = rawValue }
public static let read = WaitOption(rawValue: POLLIN)
public static let write = WaitOption(rawValue: POLLOUT)
}
/// Wating for socket to become ready to perform I/O.
///
/// - Parameters:
/// - option: `option` to wait for. The option can be masked.
/// - timeout: Number of seconds to wait at most.
/// - retryOnInterrupt: If enabled, will retry polling when EINTR error happens.
/// - Returns: Boolean indicating availability of `option`, false means timeout.
/// - Throws: Socket.Error holding `errno`
open func wait(for option: WaitOption, timeout: TimeInterval, retryOnInterrupt: Bool = true) throws -> Bool {
var fd = pollfd() //swift zeroes out memory of any struct. no need to memset 0
fd.fd = fileDescriptor
fd.events = Int16(option.rawValue)
var rc: Int32 = 0
repeat {
rc = poll(&fd, 1, Int32(timeout * 1000))
} while retryOnInterrupt && rc == -1 && errno == EINTR //retry on interrupt
//-1 will throw error, 0 means timeout, otherwise success
return try ing { rc } != 0
}
/// Resolves domain into connectable addresses.
///
/// - Parameters:
/// - host: The hostname to dns lookup.
/// - port: The port for SocketAddress.
/// - Returns: An array of connectable addresses
/// - Throws: Domain name not resolved
open func addresses(for host: String, port: Port) throws -> [SocketAddress] {
var hints = addrinfo()
//TODO: set correct values of current socket
hints.ai_family = Family.inet.rawValue
hints.ai_socktype = Type.stream.rawValue
hints.ai_protocol = Protocol.tcp.rawValue
var addrs: UnsafeMutablePointer<addrinfo>?
if getaddrinfo(host, String(port), &hints, &addrs) != 0 {
// unable to resolve
throw Error(errno: 11) //TODO: fix this thing
}
defer { freeaddrinfo(addrs) }
var result: [SocketAddress] = []
for addr in sequence(first: addrs!, next: { $0.pointee.ai_next }) {
result.append(addr.pointee.ai_addr.pointee)
}
assert(!result.isEmpty)
return result
}
open func startTls(_ config: TLS.Configuration) throws {
tls = try TLS(self.fileDescriptor, config)
try tls?.handshake()
}
/// Returns the local port number to which the socket is bound.
///
/// - Returns: Local port to which the socket is bound.
open func port() throws -> Port {
var address = sockaddr_in()
var len = socklen_t(MemoryLayout.size(ofValue: address))
let ptr = UnsafeMutableRawPointer(&address).assumingMemoryBound(to: sockaddr.self)
try ing { getsockname(fileDescriptor, ptr, &len) }
return Port(address.sin_port.bigEndian)
}
}
extension Socket {
open class func tcpListening(port: Port, address: String? = nil, maxPendingConnection: Int32 = SOMAXCONN) throws -> Self {
let socket = try self.init(.inet)
try socket.set(option: .reuseAddress, true)
try socket.bind(port: port, address: address)
try socket.listen(backlog: maxPendingConnection)
return socket
}
}
extension Socket {
open func write(_ bytes: [Byte]) throws {
try self.write(bytes, length: bytes.count)
}
}
extension SocketAddress {
public init(port: Port, address: String? = nil) {
var addr = sockaddr_in() //no need to memset 0. Swift does it
#if !os(Linux)
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.stride)
#endif
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
if let address = address {
let r = inet_pton(AF_INET, address, &addr.sin_addr)
assert(r == 1, "\(address) is not converted.")
}
self = withUnsafePointer(to: &addr) {
UnsafePointer<SocketAddress>(OpaquePointer($0)).pointee
}
}
}
extension TimeValue {
public init(seconds: Int, milliseconds: Int = 0, microseconds: Int = 0) {
#if !os(Linux)
let microseconds = Int32(microseconds)
let milliseconds = Int32(milliseconds)
#endif
self.init(tv_sec: seconds, tv_usec: microseconds + milliseconds * 1000)
}
}
| 35.856589 | 126 | 0.611285 |
9ceaeb4ef4c11ffe355908e0a6a4dbfe8128edba | 787 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//406. Queue Reconstruction by Height
//Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
//Note:
//The number of people is less than 1,100.
//Example
//Input:
//[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
//Output:
//[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
//class Solution {
// func reconstructQueue(_ people: [[Int]]) -> [[Int]] {
// }
//}
// Time Is Money | 39.35 | 299 | 0.677255 |
f5af4a584461d2a67a6a71a3d48cb8bdc5458c64 | 13,287 | // Polyline.swift
//
// Copyright (c) 2015 Raphaël Mor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreLocation
// MARK: - Public Classes -
/// This class can be used for :
///
/// - Encoding an [CLLocation] or a [CLLocationCoordinate2D] to a polyline String
/// - Decoding a polyline String to an [CLLocation] or a [CLLocationCoordinate2D]
/// - Encoding / Decoding associated levels
///
/// it is aims to produce the same results as google's iOS sdk not as the online
/// tool which is fuzzy when it comes to rounding values
///
/// it is based on google's algorithm that can be found here :
///
/// :see: https://developers.google.com/maps/documentation/utilities/polylinealgorithm
public struct Polyline {
/// The array of coordinates (nil if polyline cannot be decoded)
public let coordinates: [CLLocationCoordinate2D]?
/// The encoded polyline
public let encodedPolyline: String
/// The array of levels (nil if cannot be decoded, or is not provided)
public let levels: [UInt32]?
/// The encoded levels (nil if cannot be encoded, or is not provided)
public let encodedLevels: String?
/// The array of location (computed from coordinates)
public var locations: [CLLocation]? {
return self.coordinates.map(toLocations)
}
// MARK: - Public Methods -
/// This designated initializer encodes a `[CLLocationCoordinate2D]`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter levels: The optional `Array` of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(coordinates: [CLLocationCoordinate2D], levels: [UInt32]? = nil, precision: Double = 1e5) {
self.coordinates = coordinates
self.levels = levels
encodedPolyline = encodeCoordinates(coordinates, precision: precision)
encodedLevels = levels.map(encodeLevels)
}
/// This designated initializer decodes a polyline `String`
///
/// - parameter encodedPolyline: The polyline that you want to decode
/// - parameter encodedLevels: The levels that you want to decode (default: `nil`)
/// - parameter precision: The precision used for decoding (default: `1e5`)
public init(encodedPolyline: String, encodedLevels: String? = nil, precision: Double = 1e5) {
self.encodedPolyline = encodedPolyline
self.encodedLevels = encodedLevels
coordinates = decodePolyline(encodedPolyline, precision: precision)
levels = self.encodedLevels.flatMap(decodeLevels)
}
/// This init encodes a `[CLLocation]`
///
/// - parameter locations: The `Array` of `CLLocation` that you want to encode
/// - parameter levels: The optional array of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(locations: [CLLocation], levels: [UInt32]? = nil, precision: Double = 1e5) {
let coordinates = toCoordinates(locations)
self.init(coordinates: coordinates, levels: levels, precision:precision)
}
}
// MARK: - Public Functions -
/// This function encodes an `[CLLocationCoordinate2D]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter precision: The precision used to encode coordinates (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeCoordinates(_ coordinates: [CLLocationCoordinate2D], precision: Double = 1e5) -> String {
var previousCoordinate = IntegerCoordinates(0, 0)
var encodedPolyline = ""
for coordinate in coordinates {
let intLatitude = Int(round(coordinate.latitude * precision))
let intLongitude = Int(round(coordinate.longitude * precision))
let coordinatesDifference = (intLatitude - previousCoordinate.latitude, intLongitude - previousCoordinate.longitude)
encodedPolyline += encodeCoordinate(coordinatesDifference)
previousCoordinate = (intLatitude,intLongitude)
}
return encodedPolyline
}
/// This function encodes an `[CLLocation]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocation` that you want to encode
/// - parameter precision: The precision used to encode locations (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeLocations(_ locations: [CLLocation], precision: Double = 1e5) -> String {
return encodeCoordinates(toCoordinates(locations), precision: precision)
}
/// This function encodes an `[UInt32]` to a `String`
///
/// - parameter levels: The `Array` of `UInt32` levels that you want to encode
///
/// - returns: A `String` representing the encoded Levels
public func encodeLevels(_ levels: [UInt32]) -> String {
return levels.reduce("") {
$0 + encodeLevel($1)
}
}
/// This function decodes a `String` to a `[CLLocationCoordinate2D]?`
///
/// - parameter encodedPolyline: `String` representing the encoded Polyline
/// - parameter precision: The precision used to decode coordinates (default: `1e5`)
///
/// - returns: A `[CLLocationCoordinate2D]` representing the decoded polyline if valid, `nil` otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocationCoordinate2D]? {
let data = encodedPolyline.data(using: String.Encoding.utf8)!
let byteArray = unsafeBitCast((data as NSData).bytes, to: UnsafePointer<Int8>.self)
let length = Int(data.count)
var position = Int(0)
var decodedCoordinates = [CLLocationCoordinate2D]()
var lat = 0.0
var lon = 0.0
while position < length {
do {
let resultingLat = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lat += resultingLat
let resultingLon = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lon += resultingLon
} catch {
return nil
}
decodedCoordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
return decodedCoordinates
}
/// This function decodes a String to a [CLLocation]?
///
/// - parameter encodedPolyline: String representing the encoded Polyline
/// - parameter precision: The precision used to decode locations (default: 1e5)
///
/// - returns: A [CLLocation] representing the decoded polyline if valid, nil otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocation]? {
return decodePolyline(encodedPolyline, precision: precision).map(toLocations)
}
/// This function decodes a `String` to an `[UInt32]`
///
/// - parameter encodedLevels: The `String` representing the levels to decode
///
/// - returns: A `[UInt32]` representing the decoded Levels if the `String` is valid, `nil` otherwise
public func decodeLevels(_ encodedLevels: String) -> [UInt32]? {
var remainingLevels = encodedLevels.unicodeScalars
var decodedLevels = [UInt32]()
while remainingLevels.count > 0 {
do {
let chunk = try extractNextChunk(&remainingLevels)
let level = decodeLevel(chunk)
decodedLevels.append(level)
} catch {
return nil
}
}
return decodedLevels
}
// MARK: - Private -
// MARK: Encode Coordinate
private func encodeCoordinate(_ locationCoordinate: IntegerCoordinates) -> String {
let latitudeString = encodeSingleComponent(locationCoordinate.latitude)
let longitudeString = encodeSingleComponent(locationCoordinate.longitude)
return latitudeString + longitudeString
}
private func encodeSingleComponent(_ value: Int) -> String {
var intValue = value
if intValue < 0 {
intValue = intValue << 1
intValue = ~intValue
} else {
intValue = intValue << 1
}
return encodeFiveBitComponents(intValue)
}
// MARK: Encode Levels
private func encodeLevel(_ level: UInt32) -> String {
return encodeFiveBitComponents(Int(level))
}
private func encodeFiveBitComponents(_ value: Int) -> String {
var remainingComponents = value
var fiveBitComponent = 0
var returnString = String()
repeat {
fiveBitComponent = remainingComponents & 0x1F
if remainingComponents >= 0x20 {
fiveBitComponent |= 0x20
}
fiveBitComponent += 63
let char = UnicodeScalar(fiveBitComponent)!
returnString.append(String(char))
remainingComponents = remainingComponents >> 5
} while (remainingComponents != 0)
return returnString
}
// MARK: Decode Coordinate
// We use a byte array (UnsafePointer<Int8>) here for performance reasons. Check with swift 2 if we can
// go back to using [Int8]
private func decodeSingleCoordinate(byteArray: UnsafePointer<Int8>, length: Int, position: inout Int, precision: Double = 1e5) throws -> Double {
guard position < length else { throw PolylineError.singleCoordinateDecodingError }
let bitMask = Int8(0x1F)
var coordinate: Int32 = 0
var currentChar: Int8
var componentCounter: Int32 = 0
var component: Int32 = 0
repeat {
currentChar = byteArray[position] - 63
component = Int32(currentChar & bitMask)
coordinate |= (component << (5*componentCounter))
position += 1
componentCounter += 1
} while ((currentChar & 0x20) == 0x20) && (position < length) && (componentCounter < 6)
if (componentCounter == 6) && ((currentChar & 0x20) == 0x20) {
throw PolylineError.singleCoordinateDecodingError
}
if (coordinate & 0x01) == 0x01 {
coordinate = ~(coordinate >> 1)
} else {
coordinate = coordinate >> 1
}
return Double(coordinate) / precision
}
// MARK: Decode Levels
private func extractNextChunk(_ encodedString: inout String.UnicodeScalarView) throws -> String {
var currentIndex = encodedString.startIndex
while currentIndex != encodedString.endIndex {
let currentCharacterValue = Int32(encodedString[currentIndex].value)
if isSeparator(currentCharacterValue) {
let extractedScalars = encodedString[encodedString.startIndex...currentIndex]
encodedString = encodedString[encodedString.index(after: currentIndex)..<encodedString.endIndex]
return String(extractedScalars)
}
currentIndex = encodedString.index(after: currentIndex)
}
throw PolylineError.chunkExtractingError
}
private func decodeLevel(_ encodedLevel: String) -> UInt32 {
let scalarArray = [] + encodedLevel.unicodeScalars
return UInt32(agregateScalarArray(scalarArray))
}
private func agregateScalarArray(_ scalars: [UnicodeScalar]) -> Int32 {
let lastValue = Int32(scalars.last!.value)
let fiveBitComponents: [Int32] = scalars.map { scalar in
let value = Int32(scalar.value)
if value != lastValue {
return (value - 63) ^ 0x20
} else {
return value - 63
}
}
return Array(fiveBitComponents.reversed()).reduce(0) { ($0 << 5 ) | $1 }
}
// MARK: Utilities
enum PolylineError: Error {
case singleCoordinateDecodingError
case chunkExtractingError
}
private func toCoordinates(_ locations: [CLLocation]) -> [CLLocationCoordinate2D] {
return locations.map {location in location.coordinate}
}
private func toLocations(_ coordinates: [CLLocationCoordinate2D]) -> [CLLocation] {
return coordinates.map { coordinate in
CLLocation(latitude:coordinate.latitude, longitude:coordinate.longitude)
}
}
private func isSeparator(_ value: Int32) -> Bool {
return (value - 63) & 0x20 != 0x20
}
private typealias IntegerCoordinates = (latitude: Int, longitude: Int)
| 35.244032 | 145 | 0.681719 |
ffe85ff58e3322dc42202d3cbb538314cc084753 | 15,355 | //
// Appointment.swift
// HealthSoftware
//
// Generated from FHIR 3.0.1.11917 (http://hl7.org/fhir/StructureDefinition/Appointment)
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
A booking of a healthcare event among patient(s), practitioner(s), related person(s) and/or device(s) for a specific
date/time. This may result in one or more Encounter(s).
*/
open class Appointment: DomainResource {
override open class var resourceType: ResourceType { return .appointment }
/// External Ids for this item
public var identifier: [Identifier]?
/// The overall status of the Appointment. Each of the participants has their own participation status which
/// indicates their involvement in the process, however this status indicates the shared status.
public var status: FHIRPrimitive<AppointmentStatus>
/// A broad categorisation of the service that is to be performed during this appointment
public var serviceCategory: CodeableConcept?
/// The specific service that is to be performed during this appointment
public var serviceType: [CodeableConcept]?
/// The specialty of a practitioner that would be required to perform the service requested in this appointment
public var specialty: [CodeableConcept]?
/// The style of appointment or patient that has been booked in the slot (not service type)
public var appointmentType: CodeableConcept?
/// Reason this appointment is scheduled
public var reason: [CodeableConcept]?
/// Reason the appointment is to takes place (resource)
public var indication: [Reference]?
/// Used to make informed decisions if needing to re-prioritize
public var priority: FHIRPrimitive<FHIRUnsignedInteger>?
/// Shown on a subject line in a meeting request, or appointment list
public var description_fhir: FHIRPrimitive<FHIRString>?
/// Additional information to support the appointment
public var supportingInformation: [Reference]?
/// When appointment is to take place
public var start: FHIRPrimitive<Instant>?
/// When appointment is to conclude
public var end: FHIRPrimitive<Instant>?
/// Can be less than start/end (e.g. estimate)
public var minutesDuration: FHIRPrimitive<FHIRPositiveInteger>?
/// The slots that this appointment is filling
public var slot: [Reference]?
/// The date that this appointment was initially created
public var created: FHIRPrimitive<DateTime>?
/// Additional comments
public var comment: FHIRPrimitive<FHIRString>?
/// The ReferralRequest provided as information to allocate to the Encounter
public var incomingReferral: [Reference]?
/// Participants involved in appointment
public var participant: [AppointmentParticipant]
/// Potential date/time interval(s) requested to allocate the appointment within
public var requestedPeriod: [Period]?
/// Designated initializer taking all required properties
public init(participant: [AppointmentParticipant], status: FHIRPrimitive<AppointmentStatus>) {
self.participant = participant
self.status = status
super.init()
}
/// Convenience initializer
public convenience init(
appointmentType: CodeableConcept? = nil,
comment: FHIRPrimitive<FHIRString>? = nil,
contained: [ResourceProxy]? = nil,
created: FHIRPrimitive<DateTime>? = nil,
description_fhir: FHIRPrimitive<FHIRString>? = nil,
end: FHIRPrimitive<Instant>? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
identifier: [Identifier]? = nil,
implicitRules: FHIRPrimitive<FHIRURI>? = nil,
incomingReferral: [Reference]? = nil,
indication: [Reference]? = nil,
language: FHIRPrimitive<FHIRString>? = nil,
meta: Meta? = nil,
minutesDuration: FHIRPrimitive<FHIRPositiveInteger>? = nil,
modifierExtension: [Extension]? = nil,
participant: [AppointmentParticipant],
priority: FHIRPrimitive<FHIRUnsignedInteger>? = nil,
reason: [CodeableConcept]? = nil,
requestedPeriod: [Period]? = nil,
serviceCategory: CodeableConcept? = nil,
serviceType: [CodeableConcept]? = nil,
slot: [Reference]? = nil,
specialty: [CodeableConcept]? = nil,
start: FHIRPrimitive<Instant>? = nil,
status: FHIRPrimitive<AppointmentStatus>,
supportingInformation: [Reference]? = nil,
text: Narrative? = nil)
{
self.init(participant: participant, status: status)
self.appointmentType = appointmentType
self.comment = comment
self.contained = contained
self.created = created
self.description_fhir = description_fhir
self.end = end
self.`extension` = `extension`
self.id = id
self.identifier = identifier
self.implicitRules = implicitRules
self.incomingReferral = incomingReferral
self.indication = indication
self.language = language
self.meta = meta
self.minutesDuration = minutesDuration
self.modifierExtension = modifierExtension
self.priority = priority
self.reason = reason
self.requestedPeriod = requestedPeriod
self.serviceCategory = serviceCategory
self.serviceType = serviceType
self.slot = slot
self.specialty = specialty
self.start = start
self.supportingInformation = supportingInformation
self.text = text
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case appointmentType
case comment; case _comment
case created; case _created
case description_fhir = "description"; case _description_fhir = "_description"
case end; case _end
case identifier
case incomingReferral
case indication
case minutesDuration; case _minutesDuration
case participant
case priority; case _priority
case reason
case requestedPeriod
case serviceCategory
case serviceType
case slot
case specialty
case start; case _start
case status; case _status
case supportingInformation
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.appointmentType = try CodeableConcept(from: _container, forKeyIfPresent: .appointmentType)
self.comment = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .comment, auxiliaryKey: ._comment)
self.created = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .created, auxiliaryKey: ._created)
self.description_fhir = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .description_fhir, auxiliaryKey: ._description_fhir)
self.end = try FHIRPrimitive<Instant>(from: _container, forKeyIfPresent: .end, auxiliaryKey: ._end)
self.identifier = try [Identifier](from: _container, forKeyIfPresent: .identifier)
self.incomingReferral = try [Reference](from: _container, forKeyIfPresent: .incomingReferral)
self.indication = try [Reference](from: _container, forKeyIfPresent: .indication)
self.minutesDuration = try FHIRPrimitive<FHIRPositiveInteger>(from: _container, forKeyIfPresent: .minutesDuration, auxiliaryKey: ._minutesDuration)
self.participant = try [AppointmentParticipant](from: _container, forKey: .participant)
self.priority = try FHIRPrimitive<FHIRUnsignedInteger>(from: _container, forKeyIfPresent: .priority, auxiliaryKey: ._priority)
self.reason = try [CodeableConcept](from: _container, forKeyIfPresent: .reason)
self.requestedPeriod = try [Period](from: _container, forKeyIfPresent: .requestedPeriod)
self.serviceCategory = try CodeableConcept(from: _container, forKeyIfPresent: .serviceCategory)
self.serviceType = try [CodeableConcept](from: _container, forKeyIfPresent: .serviceType)
self.slot = try [Reference](from: _container, forKeyIfPresent: .slot)
self.specialty = try [CodeableConcept](from: _container, forKeyIfPresent: .specialty)
self.start = try FHIRPrimitive<Instant>(from: _container, forKeyIfPresent: .start, auxiliaryKey: ._start)
self.status = try FHIRPrimitive<AppointmentStatus>(from: _container, forKey: .status, auxiliaryKey: ._status)
self.supportingInformation = try [Reference](from: _container, forKeyIfPresent: .supportingInformation)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try appointmentType?.encode(on: &_container, forKey: .appointmentType)
try comment?.encode(on: &_container, forKey: .comment, auxiliaryKey: ._comment)
try created?.encode(on: &_container, forKey: .created, auxiliaryKey: ._created)
try description_fhir?.encode(on: &_container, forKey: .description_fhir, auxiliaryKey: ._description_fhir)
try end?.encode(on: &_container, forKey: .end, auxiliaryKey: ._end)
try identifier?.encode(on: &_container, forKey: .identifier)
try incomingReferral?.encode(on: &_container, forKey: .incomingReferral)
try indication?.encode(on: &_container, forKey: .indication)
try minutesDuration?.encode(on: &_container, forKey: .minutesDuration, auxiliaryKey: ._minutesDuration)
try participant.encode(on: &_container, forKey: .participant)
try priority?.encode(on: &_container, forKey: .priority, auxiliaryKey: ._priority)
try reason?.encode(on: &_container, forKey: .reason)
try requestedPeriod?.encode(on: &_container, forKey: .requestedPeriod)
try serviceCategory?.encode(on: &_container, forKey: .serviceCategory)
try serviceType?.encode(on: &_container, forKey: .serviceType)
try slot?.encode(on: &_container, forKey: .slot)
try specialty?.encode(on: &_container, forKey: .specialty)
try start?.encode(on: &_container, forKey: .start, auxiliaryKey: ._start)
try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status)
try supportingInformation?.encode(on: &_container, forKey: .supportingInformation)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? Appointment else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return appointmentType == _other.appointmentType
&& comment == _other.comment
&& created == _other.created
&& description_fhir == _other.description_fhir
&& end == _other.end
&& identifier == _other.identifier
&& incomingReferral == _other.incomingReferral
&& indication == _other.indication
&& minutesDuration == _other.minutesDuration
&& participant == _other.participant
&& priority == _other.priority
&& reason == _other.reason
&& requestedPeriod == _other.requestedPeriod
&& serviceCategory == _other.serviceCategory
&& serviceType == _other.serviceType
&& slot == _other.slot
&& specialty == _other.specialty
&& start == _other.start
&& status == _other.status
&& supportingInformation == _other.supportingInformation
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(appointmentType)
hasher.combine(comment)
hasher.combine(created)
hasher.combine(description_fhir)
hasher.combine(end)
hasher.combine(identifier)
hasher.combine(incomingReferral)
hasher.combine(indication)
hasher.combine(minutesDuration)
hasher.combine(participant)
hasher.combine(priority)
hasher.combine(reason)
hasher.combine(requestedPeriod)
hasher.combine(serviceCategory)
hasher.combine(serviceType)
hasher.combine(slot)
hasher.combine(specialty)
hasher.combine(start)
hasher.combine(status)
hasher.combine(supportingInformation)
}
}
/**
Participants involved in appointment.
List of participants involved in the appointment.
*/
open class AppointmentParticipant: BackboneElement {
/// Role of participant in the appointment
public var type: [CodeableConcept]?
/// Person, Location/HealthcareService or Device
public var actor: Reference?
/// Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet
/// to discuss the results for a specific patient, and the patient is not required to be present.
public var required: FHIRPrimitive<ParticipantRequired>?
/// Participation status of the actor.
public var status: FHIRPrimitive<ParticipationStatus>
/// Designated initializer taking all required properties
public init(status: FHIRPrimitive<ParticipationStatus>) {
self.status = status
super.init()
}
/// Convenience initializer
public convenience init(
actor: Reference? = nil,
`extension`: [Extension]? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
modifierExtension: [Extension]? = nil,
required: FHIRPrimitive<ParticipantRequired>? = nil,
status: FHIRPrimitive<ParticipationStatus>,
type: [CodeableConcept]? = nil)
{
self.init(status: status)
self.actor = actor
self.`extension` = `extension`
self.id = id
self.modifierExtension = modifierExtension
self.required = required
self.type = type
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case actor
case required; case _required
case status; case _status
case type
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.actor = try Reference(from: _container, forKeyIfPresent: .actor)
self.required = try FHIRPrimitive<ParticipantRequired>(from: _container, forKeyIfPresent: .required, auxiliaryKey: ._required)
self.status = try FHIRPrimitive<ParticipationStatus>(from: _container, forKey: .status, auxiliaryKey: ._status)
self.type = try [CodeableConcept](from: _container, forKeyIfPresent: .type)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try actor?.encode(on: &_container, forKey: .actor)
try required?.encode(on: &_container, forKey: .required, auxiliaryKey: ._required)
try status.encode(on: &_container, forKey: .status, auxiliaryKey: ._status)
try type?.encode(on: &_container, forKey: .type)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? AppointmentParticipant else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return actor == _other.actor
&& required == _other.required
&& status == _other.status
&& type == _other.type
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(actor)
hasher.combine(required)
hasher.combine(status)
hasher.combine(type)
}
}
| 38.775253 | 149 | 0.74041 |
8f70fea08f6f45111ca8167c866bdd09bbf0ae5b | 1,413 | //
// LumiaUITests.swift
// LumiaUITests
//
// Created by xiAo_Ju on 2019/12/31.
// Copyright © 2019 黄伯驹. All rights reserved.
//
import XCTest
class LumiaUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.113636 | 182 | 0.649682 |
bb7010cca4e220186c8485ec203791bf9c36e80f | 643 | //
// UIViewController+Errors.swift
// SampleFeediOS
//
// Created by Danny Sung on 02/01/2020.
// Copyright © 2020 Sung Heroes. All rights reserved.
//
import UIKit
public extension UIViewController {
func present(error: Error, completion: @escaping ()->Void = { }) {
let alertVC = UIAlertController(title: "Error", message: "\(error.localizedDescription)", preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .cancel) { (_) in
completion()
}
alertVC.addAction(dismissAction)
self.present(alertVC, animated: true)
}
}
| 26.791667 | 121 | 0.62986 |
f424eff912e7615cc64bc9905fe555bb2929ecfc | 4,163 | // Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialButtons_Theming
import MaterialComponents.MaterialContainerScheme
import MaterialComponents.MaterialTypography
class ButtonsDynamicTypeExample: UIViewController {
@objc var containerScheme = MDCContainerScheme()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = containerScheme.colorScheme.backgroundColor
let flatButtonStatic = MDCButton()
flatButtonStatic.applyContainedTheme(withScheme: containerScheme)
flatButtonStatic.setTitle("Static", for: UIControl.State())
flatButtonStatic.sizeToFit()
flatButtonStatic.translatesAutoresizingMaskIntoConstraints = false
flatButtonStatic.addTarget(self, action: #selector(tap), for: .touchUpInside)
view.addSubview(flatButtonStatic)
let flatButtonDynamic = MDCButton()
flatButtonDynamic.applyContainedTheme(withScheme: containerScheme)
let buttonFont = containerScheme.typographyScheme.button.mdc_scaledFont(for: view)
flatButtonDynamic.setTitleFont(buttonFont, for: .normal)
flatButtonDynamic.mdc_adjustsFontForContentSizeCategory = true
flatButtonDynamic.setTitle("Dynamic", for: UIControl.State())
flatButtonDynamic.sizeToFit()
flatButtonDynamic.translatesAutoresizingMaskIntoConstraints = false
flatButtonDynamic.addTarget(self, action: #selector(tap), for: .touchUpInside)
view.addSubview(flatButtonDynamic)
let flatButtonDynamicLegacy = MDCButton()
flatButtonDynamicLegacy.applyContainedTheme(withScheme: containerScheme)
let legacyButtonFont = MDCTypographyScheme(defaults: .material201804).button
flatButtonDynamicLegacy.setTitleFont(legacyButtonFont, for: .normal)
flatButtonDynamicLegacy.setTitle("Dynamic (legacy)", for: UIControl.State())
flatButtonDynamicLegacy.sizeToFit()
flatButtonDynamicLegacy.translatesAutoresizingMaskIntoConstraints = false
flatButtonDynamicLegacy.addTarget(self, action: #selector(tap), for: .touchUpInside)
flatButtonDynamicLegacy.mdc_adjustsFontForContentSizeCategory = true
flatButtonDynamicLegacy.adjustsFontForContentSizeCategoryWhenScaledFontIsUnavailable = true
view.addSubview(flatButtonDynamicLegacy)
let views = [
"flatStatic": flatButtonStatic,
"flatDynamic": flatButtonDynamic,
"flatDynamicLegacy": flatButtonDynamicLegacy,
]
centerView(view: flatButtonDynamic, onView: self.view)
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat:
"V:[flatStatic]-40-[flatDynamic]-40-[flatDynamicLegacy]",
options: .alignAllCenterX, metrics: nil, views: views))
}
// MARK: Private
func centerView(view: UIView, onView: UIView) {
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerX,
relatedBy: .equal,
toItem: onView,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0))
onView.addConstraint(NSLayoutConstraint(
item: view,
attribute: .centerY,
relatedBy: .equal,
toItem: onView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
}
@objc func tap(_ sender: Any) {
print("\(type(of: sender)) was tapped.")
}
}
// MARK: Catalog by conventions
extension ButtonsDynamicTypeExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Buttons", "Buttons (DynamicType)"],
"primaryDemo": false,
"presentable": false,
]
}
}
| 36.517544 | 95 | 0.750901 |
03e9254b1e86eb66956b05e6c3d41caf391c1842 | 1,204 | import Fluent
import Foundation
import Vapor
final class Admin: Content {
typealias ID = idType
public static var idKey: IDKey { return \.id }
var id: ID?
var userId: User.ID
var createdAt: Date?
var updatedAt: Date?
enum CodingKeys: String, CodingKey
{
case id = "id"
case userId = "user_id"
case createdAt = "created_At"
case updatedAt = "updated_At"
}
public static var createdAtKey: TimestampKey { return \.createdAt }
public static var updatedAtKey: TimestampKey { return \.updatedAt }
var user: Parent<Admin, User> {
return parent(\Admin.userId)
}
init(user: User) throws {
self.userId = try user.requireID()
}
}
extension Admin: Model{}
extension Admin: DatabaseModel {
static func prepare(on connection: Admin.Database.Connection) ->
Future<Void> {
return Database.create(self, on: connection) { builder in
try addProperties(to: builder)
builder.reference(from: \Admin.userId, to: \User.id, onDelete: ._setNull)
}
}
}
extension Admin: Migration {}
extension Admin: Parameter {}
| 22.716981 | 89 | 0.615449 |
c153fa38eb2a7b971d885bed7d61a8259ff11fd9 | 665 | //
// StringExtension.swift
// hseProject_1
//
// Created by Ildar on 9/20/20.
// Copyright © 2020 Ildar Nigmetzyanov. All rights reserved.
//
import Foundation
extension String {
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
| 27.708333 | 66 | 0.669173 |
23c295434676b06b5c55127dc7dbe9dd5fdc4852 | 277 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{{enum b:a{let e:a}protocol a{let e:c}protocol c
| 34.625 | 87 | 0.740072 |
d600be9e3e9cf30a269ee3563b673ac94484a5cc | 2,097 | /*
Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import AST
class ParserPostfixOperatorExpressionTests: XCTestCase {
func testPostfixOperator() {
let testOps = [
// regular operators
"/",
"-",
"+",
"--",
"++",
"+=",
"=-",
"==",
"!*",
"*<",
"<>",
"<!>",
">?>?>",
"&|^~?",
">>>!!>>",
// dot operators
"..",
"...",
".......................",
"../",
"...++",
"..--"
]
for testOp in testOps {
let testCode = "foo\(testOp)"
parseExpressionAndTest(testCode, testCode, testClosure: { expr in
guard let postfixOpExpr = expr as? PostfixOperatorExpression else {
XCTFail("Failed in getting a postfix operator expression")
return
}
XCTAssertEqual(postfixOpExpr.postfixOperator, testOp)
XCTAssertTrue(postfixOpExpr.postfixExpression is IdentifierExpression)
})
}
}
func testSourceRange() {
let testExprs: [(testString: String, expectedEndColumn: Int)] = [
("foo/", 5),
("foo<>", 6),
("foo...", 7),
]
for t in testExprs {
parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn))
})
}
}
static var allTests = [
("testPostfixOperator", testPostfixOperator),
("testSourceRange", testSourceRange),
]
}
| 26.2125 | 85 | 0.593228 |
38159c5edb430229e23e626ba9fc3f93ebae75ad | 1,452 | //
// RxTextStorageDelegateProxy.swift
// RxCocoa
//
// Created by Segii Shulga on 12/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
open class RxTextStorageDelegateProxy
: DelegateProxy<NSTextStorage, NSTextStorageDelegate>
, DelegateProxyType
, NSTextStorageDelegate {
/// Typed parent object.
public weak private(set) var textStorage: NSTextStorage?
/// - parameter parentObject: Parent object for delegate proxy.
public init(parentObject: NSTextStorage) {
self.textStorage = parentObject
super.init(parentObject: parentObject, delegateProxy: RxTextStorageDelegateProxy.self)
}
// Register known implementations
public static func registerKnownImplementations() {
self.register { RxTextStorageDelegateProxy(parentObject: $0) }
}
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: NSTextStorageDelegate?, to object: ParentObject) {
object.delegate = delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> NSTextStorageDelegate? {
return object.delegate
}
}
#endif
| 31.565217 | 105 | 0.65427 |
110aae07e8aa760ee2c7b61696734f2b7fd0b058 | 567 | //
// AppDelegate.swift
// Shop
//
// Created by 任一杰 on 2020/12/14.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = RYJTabBarController()
window?.makeKeyAndVisible()
return true
}
}
| 21.807692 | 145 | 0.703704 |
efaa52f34d20fcef1b34a7ba0dada83ecc630e2c | 535 | //
// File.swift
//
//
// Created by Monika Gorkani on 6/26/20.
//
import Foundation
extension FileManager {
func listFiles(path: String) -> [URL] {
let baseurl: URL = URL(fileURLWithPath: path)
var urls = [URL]()
enumerator(atPath: path)?.forEach({ (e) in
guard let s = e as? String else { return }
let relativeURL = URL(fileURLWithPath: s, relativeTo: baseurl)
let url = relativeURL.absoluteURL
urls.append(url)
})
return urls
}
}
| 23.26087 | 74 | 0.568224 |
21993b7adf4a65ea1e2fe679068ba672d96a360a | 241 | @objc(AudioFilter)
class AudioFilter: NSObject {
@objc(multiply:withB:withResolver:withRejecter:)
func multiply(a: Float, b: Float, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
resolve(a*b)
}
}
| 26.777778 | 108 | 0.717842 |
219e1a94e54a5406add8f484bf7c59350f2a9dd9 | 5,822 | //
// SearchViewModel.swift
// iOSEngineerCodeCheck
//
// Created by Akihiro Matsuyama on 2021/10/22.
// Copyright © 2021 YUMEMI Inc. All rights reserved.
//
import Foundation
class SearchViewModel: NSObject {
//MARK: - STATE ステータス
enum State {
case busy // 準備中
case ready // 準備完了
case error // エラー発生
}
public var state: ((State) -> Void)?
final class Repo {
var lang = ""
var stars = ""
var watchers = ""
var forks = ""
var issues = ""
var title = ""
var imageUrl = ""
var ownerName = ""
var repoName = ""
var desc = ""
var lastUpdate = ""
}
var repos:[Repo] = []
var tappedCellIndex = 0
let apiManager = ApiManager.singleton
func searchText(_ text: String) {
state?(.busy) // 通信開始(通信中)
// API送信する
self.apiManager.searchRepository(text,
success: { [weak self] (response) in
guard let self = self else { // SearchViewModelのself
AKLog(level: .FATAL, message: "[self] FatalError")
fatalError()
}
self.repos.removeAll()
for row in response.items {
let re = Repo()
if let lang = row.language {
re.lang = lang
} else {
re.lang = "None"
}
if let fullName = row.fullName {
re.title = fullName
} else {
re.title = "Title None"
}
if let desc = row.description {
if desc.count < 100 { // 説明文が100文字超えていたら省略
re.desc = desc
} else {
re.desc = "\(desc.prefix(100))..."
}
} else {
re.desc = "None"
}
re.stars = "\(row.stargazersCount ?? 0) stars"
re.watchers = "\(row.watchersCount ?? 0) watchers"
re.forks = "\(row.forksCount ?? 0) forks"
re.issues = "\(row.openIssuesCount ?? 0) open issues"
re.imageUrl = row.owner?.avatarUrl ?? "NoImage"
re.ownerName = row.owner?.login ?? "None"
re.repoName = row.name ?? "None"
re.lastUpdate = self.timeLag(row.pushedAt)
self.repos.append(re)
}
self.state?(.ready) // 通信完了
},
failure: { [weak self] (error) in
AKLog(level: .ERROR, message: "[API] userUpdate: failure:\(error.localizedDescription)")
self?.state?(.error) // エラー表示
}
)
}
private func timeLag(_ updatedAt: String?) -> String {
let now = Date()
let formatter = ISO8601DateFormatter()
guard let updated = updatedAt,
let date = formatter.date(from: updated) else {
return "None"
}
let text = "Updated " + timeSpanText(timeSpan: now.timeIntervalSince(date))
return text
}
private func timeSpanText(timeSpan: TimeInterval) -> String {
let span = Int(timeSpan) // 秒
let seconds = 0
let minutes = 60
let hours = minutes * 60
let days = hours * 24
let years = days * 365
switch span {
case seconds ..< hours: // 0秒〜60分
let text = String(span / minutes)
return "\(text) minutes ago"
case hours ..< days: // 1時間〜24時間
let text = String(span / hours)
return "\(text) hours ago"
case days ..< years: // 1日〜365日
let text = String(span / days)
return "\(text) days ago"
default: // 1年〜
let text = String(span / years)
return "\(text) years ago"
}
}
}
| 41 | 132 | 0.318619 |
f7e599993c04c62cec488313cf9f3b66d80b8866 | 5,152 | /*
* AnyPlace: A free and open Indoor Navigation Service with superb accuracy!
*
* Anyplace is a first-of-a-kind indoor information service offering GPS-less
* localization, navigation and search inside buildings using ordinary smartphones.
*
* Author(s): Artem Nikitin
*
* Supervisor: Demetrios Zeinalipour-Yazti
*
* URL: http://anyplace.cs.ucy.ac.cy
* Contact: [email protected]
*
* Copyright (c) 2015, Data Management Systems Lab (DMSL), University of Cyprus.
* 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 NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
import UIKit
class ArchitectController: UIViewController, UIWebViewDelegate {
private let TAG = "ArchitectController: "
private let BUID = "buid"
private let FLOOR_NUMBER = "floor_number"
private let SEGUE_IDENTIFIER_LOGGER_CONTROLLER = "showLoggerController"
private let indexURL: NSURL! = NSBundle.mainBundle().URLForResource("index", withExtension: "html", subdirectory: "Architect-Website")!
struct RequestFromJavaScript {
enum RequestType: CustomStringConvertible {
case ShowLogger
var description: String {
switch self {
case .ShowLogger: return "iOS: showLoggerController: "
}
}
static func fromString(s: String) -> RequestType? {
if s == "iOS: showLoggerController: "{
return RequestType.ShowLogger
}
return nil
}
static var key: String { return "request_type" }
}
static let data_key = "data"
let type: RequestType
let data: String?
init(type: RequestType, data: String?) {
self.type = type
self.data = data
}
static func fromString(s: String?) -> RequestFromJavaScript? {
guard let request = s else { return nil }
guard let json = StringToJSON(request) else { return nil }
guard let typeField = json[RequestType.key] else { return nil }
guard let type = RequestType.fromString(typeField as! String) else { return nil }
switch type {
case .ShowLogger:
let data = JSONToString(json[data_key]!)
return RequestFromJavaScript(type: type, data: data)
default: return nil
}
}
}
@IBOutlet weak var webView: UIWebView! {
didSet{
webView.loadRequest(NSURLRequest(URL: indexURL))
}
}
private var buid: String!
private var floorNum: String!
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print(TAG + "shouldStartLoadWithRequest")
print(request.URL?.description)
if let request = RequestFromJavaScript.fromString(request.URL?.description) {
switch request.type {
case .ShowLogger:
let json = StringToJSON(request.data!)!
buid = (json[BUID]! as! String)
floorNum = (json[FLOOR_NUMBER]! as! String)
performSegueWithIdentifier(SEGUE_IDENTIFIER_LOGGER_CONTROLLER, sender: nil)
}
return false
}
return true
}
func webViewDidStartLoad(webView: UIWebView) {
print(TAG + "webViewDidStartLoad")
}
func webViewDidFinishLoad(webView: UIWebView) {
print(TAG + "webViewDidFinishLoad")
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print(TAG + "didFailLoadWithError: \(error)")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let loggerViewController = segue.destinationViewController as? LoggerController {
assert(buid != nil && floorNum != nil)
loggerViewController.buid = buid
loggerViewController.floorNum = floorNum
}
}
}
| 35.287671 | 139 | 0.634899 |
e0c5bf4fa49b1a1d6f7b510787c40f69ae4a9d05 | 9,893 | //
// Annotation.swift
// Excerptor
//
// Created by Chen Guo on 6/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Foundation
import AppKit
class Annotation {
enum AnnotationType {
case highlight
case strikeout
case underline
case note
case text
case freeText
case unrecognized
init(string: String) {
switch string {
case "Highlight", SKNHighlightString, SKNMarkUpString:
self = .highlight
case "Strikeout", SKNStrikeOutString:
self = .strikeout
case "Underline", SKNUnderlineString:
self = .underline
case "Note", SKNNoteString:
self = .note
case "Text", SKNTextString:
self = .text
case "FreeText", SKNFreeTextString:
self = .freeText
default:
self = .unrecognized
}
}
func string() -> String {
switch self {
case .highlight: return "Highlight"
case .strikeout: return "Strikeout"
case .underline: return "Underline"
case .note: return "Note"
case .text: return "Text"
case .freeText: return "FreeText"
case .unrecognized: return "Unrecognized"
}
}
}
let annotationText: String?
let noteText: String?
var annotationOrNoteText: String { return annotationText ?? noteText! }
let annotationType: AnnotationType
let markupColor: NSColor?
let author: String?
let date: Date?
let pageIndex: Int
let pdfFileID: FileID
let pdfFileName: String
init(annotationText: String?, noteText: String?, annotationType: AnnotationType, markupColor: NSColor?, author: String?, date: Date?, pageIndex: Int, pdfFileID: FileID, pdfFileName: String) {
self.annotationText = annotationText
self.noteText = noteText
self.annotationType = annotationType
self.markupColor = markupColor
self.author = author
self.date = date
self.pageIndex = pageIndex
self.pdfFileID = pdfFileID
self.pdfFileName = pdfFileName
}
// swiftlint:disable function_body_length
func writeToFileWith(_ annotationFileTemplate: FileTemplate) {
let annotationDNtpUuidLinkGetter = { () -> String in
if let annotationDNtpUuidTypeLink = AnnotationLink(annotation: self)?.getDNtpUuidTypeLink()?.string {
return annotationDNtpUuidTypeLink
} else {
if let annotationiFilePathTypeLink = AnnotationLink(annotation: self)?.getFilePathTypeLink()?.string {
notifyPDFFileNotFoundInDNtpWith(self.pdfFileID.getFilePath(), replacingPlaceholder: Preferences.AnnotationPlaceholders.AnnotationLink_FilePathType)
return annotationiFilePathTypeLink
} else {
exitWithError("Fail to get annotation link")
}
}
}
let annotationFilePathLinkGetter = { () -> String in
if let annotationFilePathTypeLink = AnnotationLink(annotation: self)?.getFilePathTypeLink()?.string {
return annotationFilePathTypeLink
} else {
exitWithError("Fail to get annotation file path link")
}
}
/* Xcode think this is too complex ..., so I rewrite all keys and values as separate variables.
let propertyGettersByPlaceholder: [String: () -> String] = [
Preferences.AnnotationPlaceholders.AnnotationText: { self.annotationText ?? "" },
Preferences.AnnotationPlaceholders.NoteText: { self.noteText ?? "" },
Preferences.AnnotationPlaceholders.Type: { self.annotationType.string() },
Preferences.AnnotationPlaceholders.Color: { self.markupColor?.hexDescription ?? "NO COLOR" },
Preferences.AnnotationPlaceholders.Author: { self.author ?? "NO AUTHOR" },
Preferences.AnnotationPlaceholders.AnnotationDate: { (self.date ?? NSDate()).ISO8601String() },
Preferences.AnnotationPlaceholders.ExportDate: { NSDate().ISO8601String() },
Preferences.CommonPlaceholders.Page: { "\(self.pageIndex + 1)" },
Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType: { () -> String in
if let dntpUuidLink = self.pdfFileID.getDNtpUuidFileID()?.urlString {
return dntpUuidLink
} else {
notifyPDFFileNotFoundInDNtpWith(self.pdfFileID.getFilePath(), replacingPlaceholder: Preferences.CommonPlaceholders.PDFFileLink_FilePathType)
return self.pdfFileID.getFilePathFileID().urlString
}
},
Preferences.CommonPlaceholders.PDFFileLink_FilePathType: { self.pdfFileID.getFilePathFileID().urlString },
Preferences.CommonPlaceholders.PDFFilePath: { self.pdfFileID.getFilePath() },
Preferences.CommonPlaceholders.PDFFileName: { self.pdfFileName },
Preferences.CommonPlaceholders.PDFFileName_NoExtension: { self.pdfFileName.stringByDeletingPathExtension },
Preferences.AnnotationPlaceholders.AnnotationLink_DEVONthinkUUIDType: annotationDNtpUuidLinkGetter,
Preferences.AnnotationPlaceholders.AnnotationLink_FilePathType: annotationFilePathLinkGetter,
Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID: { self.pdfFileID.getDNtpUuid() ?? "NOT FOUND" }
]
*/
let pap_AnnotationText = Preferences.AnnotationPlaceholders.AnnotationText
let pap_AnnotationText_Getter = { self.annotationText ?? "" }
let pap_NoteText = Preferences.AnnotationPlaceholders.NoteText
let pap_NoteText_Getter = { self.noteText ?? "" }
let pap_Type = Preferences.AnnotationPlaceholders.annotationType
let pap_Type_Getter = { self.annotationType.string() }
let pap_Color = Preferences.AnnotationPlaceholders.Color
let pap_Color_Getter = { self.markupColor?.hexDescription ?? "NO COLOR" }
let pap_Author = Preferences.AnnotationPlaceholders.Author
let pap_Author_Getter = { self.author ?? "NO AUTHOR" }
let pap_AnnotationDate = Preferences.AnnotationPlaceholders.AnnotationDate
let pap_AnnotationDate_Getter = { (self.date ?? Date()).ISO8601String() }
let pap_ExportDate = Preferences.AnnotationPlaceholders.ExportDate
let pap_ExportDate_Getter = { Date().ISO8601String() }
let pap_Page = Preferences.CommonPlaceholders.Page
let pap_Page_Getter = { "\(self.pageIndex + 1)" }
let pap_PDFFileLink_DEVONthinkUUIDType = Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType
let pap_PDFFileLink_DEVONthinkUUIDType_Getter = { () -> String in
if let dntpUuidLink = self.pdfFileID.getDNtpUuidFileID()?.urlString {
return dntpUuidLink
} else {
notifyPDFFileNotFoundInDNtpWith(self.pdfFileID.getFilePath(), replacingPlaceholder: Preferences.CommonPlaceholders.PDFFileLink_FilePathType)
return self.pdfFileID.getFilePathFileID().urlString
}
}
let pap_PDFFileLink_FilePathType = Preferences.CommonPlaceholders.PDFFileLink_FilePathType
let pap_PDFFileLink_FilePathType_Getter : () -> String = { self.pdfFileID.getFilePathFileID().urlString }
let pap_PDFFilePath = Preferences.CommonPlaceholders.PDFFilePath
let pap_PDFFilePath_Getter : () -> String = { self.pdfFileID.getFilePath() }
let pap_PDFFileName = Preferences.CommonPlaceholders.PDFFileName
let pap_PDFFileName_Getter : () -> String = { self.pdfFileName }
let pap_PDFFileName_NoExtension = Preferences.CommonPlaceholders.PDFFileName_NoExtension
let pap_PDFFileName_NoExtension_Getter : () -> String = { NSURL(fileURLWithPath: self.pdfFileName).deletingPathExtension!.lastPathComponent }
let pap_AnnotationLink_DEVONthinkUUIDType = Preferences.AnnotationPlaceholders.AnnotationLink_DEVONthinkUUIDType
let pap_AnnotationLink_DEVONthinkUUIDType_Getter : () -> String = annotationDNtpUuidLinkGetter
let pap_AnnotationLink_FilePathType = Preferences.AnnotationPlaceholders.AnnotationLink_FilePathType
let pap_AnnotationLink_FilePathType_Getter : () -> String = annotationFilePathLinkGetter
let pap_PDFFileDEVONthinkUUID = Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID
let pap_PDFFileDEVONthinkUUID_Getter : () -> String = { self.pdfFileID.getDNtpUuid() ?? "NOT FOUND" }
let propertyGettersByPlaceholder: [String: () -> String] = [
pap_AnnotationText: pap_AnnotationText_Getter,
pap_NoteText: pap_NoteText_Getter,
pap_Type: pap_Type_Getter,
pap_Color: pap_Color_Getter,
pap_Author: pap_Author_Getter,
pap_AnnotationDate: pap_AnnotationDate_Getter,
pap_ExportDate: pap_ExportDate_Getter,
pap_Page: pap_Page_Getter,
pap_PDFFileLink_DEVONthinkUUIDType: pap_PDFFileLink_DEVONthinkUUIDType_Getter,
pap_PDFFileLink_FilePathType: pap_PDFFileLink_FilePathType_Getter,
pap_PDFFilePath: pap_PDFFilePath_Getter,
pap_PDFFileName: pap_PDFFileName_Getter,
pap_PDFFileName_NoExtension: pap_PDFFileName_NoExtension_Getter,
pap_AnnotationLink_DEVONthinkUUIDType: pap_AnnotationLink_DEVONthinkUUIDType_Getter,
pap_AnnotationLink_FilePathType: pap_AnnotationLink_FilePathType_Getter,
pap_PDFFileDEVONthinkUUID: pap_PDFFileDEVONthinkUUID_Getter
]
annotationFileTemplate.writeToFileWithPropertyGettersDictionary(propertyGettersByPlaceholder)
}
// swiftlint:enable function_body_length
}
| 51.526042 | 195 | 0.681189 |
fbd8c6753e08f5505c47caef9fe3850717138f3c | 9,922 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
A Config object that setups Facebook specific configuration parameters.
*/
open class FacebookConfig: Config {
/**
Init a Facebook configuration.
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
:param: clientSecret OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
:param: scopes an array of scopes the app is asking access to.
:param: accountId this unique id is used by AccountManager to identify the OAuth2 client.
:param: isOpenIDConnect to identify if fetching id information is required.
*/
public init(clientId: String, clientSecret: String, scopes: [String], accountId: String? = nil, isOpenIDConnect: Bool = false) {
super.init(base: "",
authzEndpoint: "https://www.facebook.com/dialog/oauth",
redirectURL: "fb\(clientId)://authorize/",
accessTokenEndpoint: "https://graph.facebook.com/oauth/access_token",
clientId: clientId,
refreshTokenEndpoint: "https://graph.facebook.com/oauth/access_token",
revokeTokenEndpoint: "https://www.facebook.com/me/permissions",
isOpenIDConnect: isOpenIDConnect,
userInfoEndpoint: isOpenIDConnect ? "https://graph.facebook.com/v2.10/me" : nil,
scopes: scopes,
clientSecret: clientSecret,
accountId: accountId)
// Add openIdConnect scope
if self.isOpenIDConnect {
if self.scopes[0].range(of: "public_profile") == nil {
self.scopes[0] = self.scopes[0] + ", public_profile"
}
}
}
}
/**
A Config object that setups Google specific configuration parameters.
*/
open class GoogleConfig: Config {
/**
Init a Google configuration.
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
:param: scopes an array of scopes the app is asking access to.
:param: accountId this unique id is used by AccountManager to identify the OAuth2 client.
:param: isOpenIDConnect to identify if fetching id information is required.
*/
public init(clientId: String, scopes: [String], audienceId: String? = nil, accountId: String? = nil, isOpenIDConnect: Bool = false) {
let bundleString = Bundle.main.bundleIdentifier ?? "google"
super.init(base: "https://accounts.google.com",
authzEndpoint: "o/oauth2/v2/auth",
redirectURL: "\(bundleString):/oauth2Callback",
accessTokenEndpoint: "o/oauth2/token",
clientId: clientId,
audienceId: audienceId,
refreshTokenEndpoint: "o/oauth2/token",
revokeTokenEndpoint: "o/oauth2/revoke",
isOpenIDConnect: isOpenIDConnect,
userInfoEndpoint: isOpenIDConnect ? "https://www.googleapis.com/plus/v1/people/me/openIdConnect" : nil,
scopes: scopes,
accountId: accountId
)
// Add openIdConnect scope
if self.isOpenIDConnect {
self.scopes += ["openid", "email", "profile"]
}
}
}
/**
A Config object that setups Keycloak specific configuration parameters.
*/
open class KeycloakConfig: Config {
/**
Init a Keycloak configuration.
:param: clientId OAuth2 credentials an unique string that is generated in the OAuth2 provider Developers Console.
:param: host to identify where the Keycloak server located.
:param: realm to identify which realm to use. A realm group a set of application/OAuth2 client together.
:param: isOpenIDConnect to identify if fetching id information is required.
*/
public init(clientId: String, clientSecret: String, host: String, realm: String? = nil, isOpenIDConnect: Bool = false) {
let bundleString = Bundle.main.bundleIdentifier ?? "keycloak"
let defaulRealmName = String(format: "%@-realm", clientId)
let realm = realm ?? defaulRealmName
super.init(
base: "\(host)/auth",
authzEndpoint: "realms/\(realm)/protocol/openid-connect/auth",
redirectURL: "\(bundleString):/oauth2Callback",
accessTokenEndpoint: "realms/\(realm)/protocol/openid-connect/token",
clientId: clientId,
refreshTokenEndpoint: "realms/\(realm)/protocol/openid-connect/token",
revokeTokenEndpoint: "realms/\(realm)/protocol/openid-connect/logout",
isOpenIDConnect: isOpenIDConnect,
clientSecret: clientSecret
)
// Add openIdConnect scope
if self.isOpenIDConnect {
self.scopes += ["openid", "email", "profile"]
}
}
}
/**
An account manager used to instantiate, store and retrieve OAuth2 modules.
*/
open class AccountManager {
/// List of OAuth2 modules available for a given app. Each module is linked to an OAuth2Session which securely store the tokens.
var modules: [String: OAuth2Module]
init() {
self.modules = [String: OAuth2Module]()
}
/// access a shared instance of an account manager
open class var sharedInstance: AccountManager {
struct Singleton {
static let instance = AccountManager()
}
return Singleton.instance
}
/**
Instantiate an OAuth2 Module using the configuration object passed in and adds it to the account manager. It uses the OAuth2Session account_id as the name that this module will be stored in.
:param: config the configuration object to use to setup an OAuth2 module.
:param: moduleClass the type of the OAuth2 module to instantiate.
:param: session the type of session the module uses
:returns: the OAuth2 module
*/
open class func addAccountWith(config: Config, moduleClass: OAuth2Module.Type, session: OAuth2Session? = nil) -> OAuth2Module {
var myModule: OAuth2Module
if let session = session {
myModule = moduleClass.init(config: config, session: session)
} else {
myModule = moduleClass.init(config: config)
}
// TODO check accountId is unique in modules list
sharedInstance.modules[myModule.oauth2Session.accountId] = myModule
return myModule
}
/**
Removes an OAuth2 module
:param: name the name that the OAuth2 module was bound to.
:param: config the configuration object to use to setup an OAuth2 module.
:param: moduleClass the type of the OAuth2 module to instantiate.
:returns: the OAuth2module or nil if not found
*/
open class func removeAccountWith(name: String) -> OAuth2Module? {
return sharedInstance.modules.removeValue(forKey: name)
}
/**
Retrieves an OAuth2 module by a name
:param: name the name that the OAuth2 module was bound to.
:returns: the OAuth2module or nil if not found.
*/
open class func getAccountBy(name: String) -> OAuth2Module? {
return sharedInstance.modules[name]
}
/**
Retrieves a list of OAuth2 modules bound to specific clientId.
:param: clientId the client id that the oauth2 module was bound to.
:returns: the OAuth2module or nil if not found.
*/
open class func getAccountsBy(clientId: String) -> [OAuth2Module] {
let modules: [OAuth2Module] = [OAuth2Module](sharedInstance.modules.values)
return modules.filter {$0.config.clientId == clientId }
}
/**
Retrieves an OAuth2 module by using a configuration object.
:param: config the Config object that this oauth2 module was used to instantiate.
:returns: the OAuth2module or nil if not found.
*/
open class func getAccountBy(config: Config) -> OAuth2Module? {
if config.accountId != nil {
return sharedInstance.modules[config.accountId!]
} else {
let modules = getAccountsBy(clientId: config.clientId)
if modules.count > 0 {
return modules[0]
} else {
return nil
}
}
}
/**
Convenient method to retrieve a Facebook OAuth2 module.
:param: config a Facebook configuration object. See FacebookConfig.
:returns: a Facebook OAuth2 module.
*/
open class func addFacebookAccount(config: FacebookConfig) -> FacebookOAuth2Module {
return addAccountWith(config: config, moduleClass: FacebookOAuth2Module.self) as! FacebookOAuth2Module
}
/**
Convenient method to retrieve a Google OAuth2 module ready to be used.
:param: config a google configuration object. See GoogleConfig.
:returns: a google OAuth2 module.
*/
open class func addGoogleAccount(config: GoogleConfig) -> OAuth2Module {
return addAccountWith(config: config, moduleClass: OAuth2Module.self)
}
/**
Convenient method to retrieve a Keycloak OAuth2 module ready to be used.
:param: config a Keycloak configuration object. See KeycloakConfig.
:returns: a Keycloak OAuth2 module.
*/
open class func addKeycloakAccount(config: KeycloakConfig) -> KeycloakOAuth2Module {
return addAccountWith(config: config, moduleClass: KeycloakOAuth2Module.self) as! KeycloakOAuth2Module
}
}
| 39.52988 | 194 | 0.676477 |
4b0a0bc6b266220834b4ca171282fd85e2ba0e0d | 11,079 | //
// Code turning Forth source into compiled program for VM.
//
import Foundation
// We do not want to treat "+" and "-" as Int as they are valid Forth words.
extension String {
func toForthInt() -> Int? {
if self == "+" || self == "-" {
return nil
}
return self.toInt()
}
}
// An entry in the Forth dictionary.
// Either a special form, evaluated at compile time, or a regular word, evaluated at runtime.
struct Definition {
enum Body {
case SpecialForm
case Regular(phrase: CompiledPhrase)
}
let name: String
let body: Body
}
// The Forth dictionary. We use a growing array rather than a Swift dictionary to mimic Forth
// classical implementation and ease implementation of the MARKER word.
class Dictionary {
var content = [Definition]()
func append(def: Definition) {
content.append(def)
}
func appendPhrase(name: String, phrase: [Instruction]) {
content.append(Definition(name: name, body: .Regular(phrase: CompiledPhrase(instructions: phrase))))
}
func appendSpecialForm(name: String) {
content.append(Definition(name: name, body: .SpecialForm))
}
subscript(name: String) -> Definition? {
for var i = content.count - 1; i >= 0; i-- {
if content[i].name == name {
return content[i]
}
}
return nil
}
func isSpecialForm(name: String) -> Bool {
if let def = self[name] {
switch def.body {
case .SpecialForm:
return true
default:
return false
}
}
return false
}
}
// Helper class for incrementally compiling a phrase.
class PhraseBuilder {
var phrase = [Instruction]()
var forwardBranchCount = 0
var nextAddress : CompiledPhrase.Address {
return phrase.count
}
func appendInstruction(insn: Instruction) -> CompiledPhrase.Address {
phrase += [insn]
return phrase.count - 1
}
func appendForwardBranch(condition: Instruction.BranchCondition) -> CompiledPhrase.Address {
++forwardBranchCount
phrase += [.Branch(condition, nil)]
return phrase.count - 1
}
func patchBranchAt(address: CompiledPhrase.Address, withTarget target: CompiledPhrase.Address) {
assert(forwardBranchCount > 0, "unexpected patching")
--forwardBranchCount
switch phrase[address] {
case let .Branch(condition, nil):
phrase[address] = .Branch(condition, target)
default:
assert(false, "patching non-branch instruction")
}
}
func getAndReset() -> CompiledPhrase {
assert(forwardBranchCount == 0, "phrase has unpatched instructions")
let result = phrase
phrase = [Instruction]()
return CompiledPhrase(instructions: result)
}
}
// The compiler entry point and heart.
class Compiler : ErrorRaiser {
enum DefinitionState : Printable {
case None
case WaitingName
case CompilingBody(String)
var isDefining : Bool {
switch self {
case .None:
return false
default:
return true
}
}
var name : String? {
switch self {
case .CompilingBody(let name):
return name
default:
return nil
}
}
var description : String {
switch self {
case .None:
return ".None"
case .CompilingBody(let name):
return ".CompilingBody(\(name))"
case .WaitingName:
return ".WaitingName"
}
}
}
var definitionState = DefinitionState.None
var dictionary = Dictionary()
var phraseBeingCompiled = PhraseBuilder()
var ifCompilerHelper : IfCompilerHelper!
var loopCompilerHelper : LoopCompilerHelper!
override init() {
super.init()
ifCompilerHelper = IfCompilerHelper(compiler: self)
loopCompilerHelper = LoopCompilerHelper(compiler: self)
// Register all primitives.
// TODO: Compiler hangs when turning this into a loop over an array
// containing the primitives.
dictionary.appendPhrase("+", phrase: [.Add])
dictionary.appendPhrase("-", phrase: [.Sub])
dictionary.appendPhrase("*", phrase: [.Mul])
dictionary.appendPhrase("/", phrase: [.Div])
dictionary.appendPhrase(".", phrase: [.Dot])
dictionary.appendPhrase("EMIT", phrase: [.Emit])
dictionary.appendPhrase("I", phrase: [.PushControlStackTop])
// Register all special forms.
dictionary.appendSpecialForm(":")
dictionary.appendSpecialForm(";")
dictionary.appendSpecialForm("IF")
dictionary.appendSpecialForm("THEN")
dictionary.appendSpecialForm("ELSE")
dictionary.appendSpecialForm("DO")
dictionary.appendSpecialForm("LOOP")
}
override func resetAfterError() {
definitionState = DefinitionState.None
ifCompilerHelper = IfCompilerHelper(compiler: self)
loopCompilerHelper = LoopCompilerHelper(compiler: self)
phraseBeingCompiled = PhraseBuilder()
}
var isCompiling : Bool {
return ifCompilerHelper.isCompiling || loopCompilerHelper.isCompiling ||
definitionState.isDefining
}
// Transform source string into compiled phrase. Return phrase on success
// or nil on error.
func compile(input: String) -> CompiledPhrase? {
let tokens = splitInBlankSeparatedWords(input)
for token in tokens {
debug(.Compiler, "Processing token: \(token) definitionState: \(definitionState)")
switch definitionState {
case .WaitingName:
if token.toForthInt() != nil || dictionary.isSpecialForm(token) {
error("word expected after ':' (parsed \(token))")
return nil
}
definitionState = .CompilingBody(token)
default:
if !compileToken(token) {
return nil
}
}
}
return isCompiling ? CompiledPhrase() : phraseBeingCompiled.getAndReset()
}
// Compile single token into phraseBeingCompiled. Return true on success.
func compileToken(token: String) -> Bool {
if let n = token.toForthInt() {
phraseBeingCompiled.appendInstruction(.PushConstant(n))
} else if let def = dictionary[token] {
switch def.body {
case .SpecialForm:
let success = compileSpecialForm(token)
if !success {
return false
}
case .Regular(let phrase):
phraseBeingCompiled.appendInstruction(.Call(name: token, phrase))
}
} else {
error("unknown word \(token)")
return false
}
return true
}
// Deal with words evaluated at compile-time. Return true on
// success.
// TODO: The initial idea was to associate Body.SpecialForm with a closure.
// However, this triggers lots of weird behavior from the Swift compiler so
// use the special form name for the time being.
func compileSpecialForm(name: String) -> Bool {
var success = true
switch (name) {
case ":":
definitionState = .WaitingName
case ";":
if let name = definitionState.name {
if ifCompilerHelper.isCompiling {
error("unterminated IF in definition")
success = false
} else if loopCompilerHelper.isCompiling {
// TODO: Change message or logic if LoopCompilerHelper extended for other kinds of loops.
error("unterminated DO in definition")
success = false
} else {
dictionary.append(Definition(name: name, body: .Regular(phrase: phraseBeingCompiled.getAndReset())))
definitionState = .None
}
} else {
error("unexpected ;")
success = false
}
case "IF":
success = ifCompilerHelper.onIf()
case "THEN":
success = ifCompilerHelper.onThen()
case "ELSE":
success = ifCompilerHelper.onElse()
case "DO":
success = loopCompilerHelper.onDo()
case "LOOP":
success = loopCompilerHelper.onLoop()
default:
assert(false, "bad special form")
}
return success
}
}
// Abstract base class for helper classes Compiler delegate to.
class AbstractCompilerHelper {
init(compiler: Compiler) {
self.compiler = compiler
}
var isCompiling : Bool {
return false
}
unowned let compiler: Compiler
}
// Handle compilation of IF [ELSE] THEN special forms.
class IfCompilerHelper : AbstractCompilerHelper {
override var isCompiling : Bool {
return !stack.isEmpty
}
func onIf() -> Bool {
stack.push(compiler.phraseBeingCompiled.appendForwardBranch(.IfZero))
return true
}
func onElse() -> Bool {
if stack.isEmpty {
compiler.error("ELSE without IF")
return false
}
let ifAddress = stack.pop()
let elseAddress = compiler.phraseBeingCompiled.appendForwardBranch(.Always)
compiler.phraseBeingCompiled.patchBranchAt(ifAddress, withTarget: compiler.phraseBeingCompiled.nextAddress)
stack.push(elseAddress)
return true
}
func onThen() -> Bool {
if stack.isEmpty {
compiler.error("THEN without IF")
return false
}
let target = compiler.phraseBeingCompiled.appendInstruction(.Nop) // ensure there is an insn at jump target
let ifAddress = stack.pop()
compiler.phraseBeingCompiled.patchBranchAt(ifAddress, withTarget: target)
return true
}
let stack = ForthStack<CompiledPhrase.Address>()
}
// Handle compilation of DO LOOP.
class LoopCompilerHelper : AbstractCompilerHelper {
override var isCompiling : Bool {
return !stack.isEmpty
}
func onDo() -> Bool {
compiler.phraseBeingCompiled.appendInstruction(.Do)
stack.push(compiler.phraseBeingCompiled.nextAddress)
return true
}
func onLoop() -> Bool {
if stack.isEmpty {
compiler.error("LOOP without DO")
return false
}
let doAddress = stack.pop()
compiler.phraseBeingCompiled.appendInstruction(.Loop(doAddress))
return true
}
let stack = ForthStack<CompiledPhrase.Address>()
} | 31.208451 | 120 | 0.583446 |
28a6d137695542d0a8d44c941eb9a562faa2145a | 2,122 |
// Copyright (c) 2016, Yuji
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
// Created by yuuji on 9/27/16.
// Copyright © 2016 yuuji. All rights reserved.
//
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
import CKit
import Dispatch
import struct Foundation.Data
import struct Foundation.Date
extension ConvenientPointer {
var mmapData: Data {
return Data(bytesNoCopy: UnsafeMutableRawPointer(self.pointer), count: self.size, deallocator: .unmap)
}
}
public protocol Cache {
func read() -> Data?
mutating func update()
}
| 39.296296 | 110 | 0.748822 |
f96a600bdddd0ed3e6cb457fd23fc208c3c50c58 | 5,728 | //
// IngredientListViewController.swift
// Reciplease
//
// Created by MacBook DS on 03/08/2019.
// Copyright © 2019 Djilali Sakkar. All rights reserved.
//
import UIKit
class IngredientListViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var ingredientTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - Properties
var ingredients = [String]()
let edamamService = EdamamService()
var recipes: Edamam?
let userDefault = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
ingredients = userDefault.updateIngredientList()
tableView.tableFooterView = UIView(frame: CGRect.zero)
addButton.layer.cornerRadius = 10
clearButton.layer.cornerRadius = 10
searchButton.layer.cornerRadius = 10
tableView.reloadData()
}
// MARK: - Actions
@IBAction func didTapAddIngredient(_ sender: Any) {
addIngredient()
//tableView.reloadData()
}
@IBAction func didTapClearIngredientList(_ sender: Any) {
ingredients.removeAll()
UserDefaults.standard.set(ingredients, forKey: "myIngredients")
tableView.reloadData()
}
@IBAction func didTapSearchRecipes(_ sender: Any) {
if ingredients.isEmpty {
presentAlert(with: "Please, type an ingredient")
} else {
searchRecipes()
}
}
// MARK: - Methods
/// Method for adding an ingredient in the list before the search
private func addIngredient() {
guard let ingredient = ingredientTextField.text, ingredientTextField.text?.isEmptyOrWhitespace() == false else {
presentAlert(with: "Please, type an ingredient")
return
}
ingredients.append(ingredient)
let indexPath = IndexPath(row: ingredients.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
ingredientTextField.text = ""
UserDefaults.standard.set(ingredients, forKey: "myIngredients")
view.endEditing(true)
}
private func toggleActivityIndicator(shown: Bool) {
searchButton.isHidden = shown
clearButton.isHidden = shown
activityIndicator.isHidden = !shown
}
/// Method for search recipes
func searchRecipes() {
toggleActivityIndicator(shown: true)
edamamService.getRecipes(ingredients: ingredients) { (success, recipes) in
DispatchQueue.main.async {
if success {
self.toggleActivityIndicator(shown: false)
guard let recipes = recipes else {return}
self.recipes = recipes
print(recipes)
guard !recipes.hits.isEmpty else {
self.presentAlert(with: "No recipes found with these ingredients")
return
}
self.performSegue(withIdentifier: "recipeListSegue", sender: self)
} else {
self.presentAlert(with: "Please, check your connexion")
self.toggleActivityIndicator(shown: false)
}
}
}
}
/// Method to go to the recipe list page
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "recipeListSegue" {
if let recipes = recipes {
if let successVC = segue.destination as? RecipeListTableViewController {
successVC.recipes = recipes
}
}
}
}
}
// MARK: - DataSource and Delegate extension
extension IngredientListViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredients.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath)
let ingredient = ingredients[indexPath.row]
cell.textLabel?.text = "\(ingredient)"
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
ingredients.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
UserDefaults.standard.set(ingredients, forKey: "myIngredients")
tableView.endUpdates()
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "Add some ingredients"
label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
label.textAlignment = .center
label.textColor = .darkGray
return label
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return ingredients.isEmpty ? 200 : 0
}
}
| 33.893491 | 121 | 0.619413 |
50ed54a227fd62159793a1df15a35cdcea9919e2 | 794 | //
// PreworkUITestsLaunchTests.swift
// PreworkUITests
//
// Created by Abhi Neti on 12/21/21.
//
import XCTest
class PreworkUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24.060606 | 88 | 0.671285 |
f8522257e1e714bce1ca9853f3cf8e1d05fa5427 | 1,464 | // Copyright © 2018 Stormbird PTE. LTD.
import XCTest
@testable import AlphaWallet
import Foundation
class TokensDataStoreTest: XCTestCase {
private let storage = FakeTokensDataStore()
private let token = TokenObject(
contract: AlphaWallet.Address.make(),
server: .main,
value: "0",
type: .erc20
)
override func setUp() {
storage.add(tokens: [token])
}
// We make a call to update token in datastore to store the updated balance after an async call to fetch the balance over the web. Token in the datastore might have been deleted when the web call is completed. Make sure this doesn't crash
func testUpdateDeletedTokensDoNotCrash() {
storage.delete(tokens: [token])
XCTAssertNoThrow(storage.update(token: token, action: .value(1)))
}
// Ensure this works:
// 1. Copy contract address for a token to delete (actually hide).
// 2. Swipe to hide the token.
// 3. Manually add that token back (add custom token screen)
// 4. Swipe to hide that token.
// 5. BOOM.
func testHideContractTwiceDoesNotCrash() {
let contract = AlphaWallet.Address(string: "0x66F08Ca6892017A45Da6FB792a8E946FcBE3d865")!
storage.add(hiddenContracts: [HiddenContract(contractAddress: contract, server: .ropsten)])
XCTAssertNoThrow(storage.add(hiddenContracts: [HiddenContract(contractAddress: contract, server: .ropsten)]))
}
}
| 38.526316 | 242 | 0.687158 |
edb795a6df13b37f99733dc1d6dd1de34ffe95e3 | 28,258 | // Copyright 2018-2019 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://www.apache.org/licenses/LICENSE-2.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.
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment
// -- Generated Code; do not edit --
//
// BatchModelDefaultInstances.swift
// BatchModel
//
import Foundation
public extension ArrayProperties {
/**
Default instance of the ArrayProperties structure.
*/
public static let __default: BatchModel.ArrayProperties = {
let defaultInstance = BatchModel.ArrayProperties(
size: nil)
return defaultInstance
}()
}
public extension ArrayPropertiesDetail {
/**
Default instance of the ArrayPropertiesDetail structure.
*/
public static let __default: BatchModel.ArrayPropertiesDetail = {
let defaultInstance = BatchModel.ArrayPropertiesDetail(
index: nil,
size: nil,
statusSummary: nil)
return defaultInstance
}()
}
public extension ArrayPropertiesSummary {
/**
Default instance of the ArrayPropertiesSummary structure.
*/
public static let __default: BatchModel.ArrayPropertiesSummary = {
let defaultInstance = BatchModel.ArrayPropertiesSummary(
index: nil,
size: nil)
return defaultInstance
}()
}
public extension AttemptContainerDetail {
/**
Default instance of the AttemptContainerDetail structure.
*/
public static let __default: BatchModel.AttemptContainerDetail = {
let defaultInstance = BatchModel.AttemptContainerDetail(
containerInstanceArn: nil,
exitCode: nil,
logStreamName: nil,
networkInterfaces: nil,
reason: nil,
taskArn: nil)
return defaultInstance
}()
}
public extension AttemptDetail {
/**
Default instance of the AttemptDetail structure.
*/
public static let __default: BatchModel.AttemptDetail = {
let defaultInstance = BatchModel.AttemptDetail(
container: nil,
startedAt: nil,
statusReason: nil,
stoppedAt: nil)
return defaultInstance
}()
}
public extension CancelJobRequest {
/**
Default instance of the CancelJobRequest structure.
*/
public static let __default: BatchModel.CancelJobRequest = {
let defaultInstance = BatchModel.CancelJobRequest(
jobId: "value",
reason: "value")
return defaultInstance
}()
}
public extension CancelJobResponse {
/**
Default instance of the CancelJobResponse structure.
*/
public static let __default: BatchModel.CancelJobResponse = {
let defaultInstance = BatchModel.CancelJobResponse()
return defaultInstance
}()
}
public extension ClientException {
/**
Default instance of the ClientException structure.
*/
public static let __default: BatchModel.ClientException = {
let defaultInstance = BatchModel.ClientException(
message: nil)
return defaultInstance
}()
}
public extension ComputeEnvironmentDetail {
/**
Default instance of the ComputeEnvironmentDetail structure.
*/
public static let __default: BatchModel.ComputeEnvironmentDetail = {
let defaultInstance = BatchModel.ComputeEnvironmentDetail(
computeEnvironmentArn: "value",
computeEnvironmentName: "value",
computeResources: nil,
ecsClusterArn: "value",
serviceRole: nil,
state: nil,
status: nil,
statusReason: nil,
type: nil)
return defaultInstance
}()
}
public extension ComputeEnvironmentOrder {
/**
Default instance of the ComputeEnvironmentOrder structure.
*/
public static let __default: BatchModel.ComputeEnvironmentOrder = {
let defaultInstance = BatchModel.ComputeEnvironmentOrder(
computeEnvironment: "value",
order: 0)
return defaultInstance
}()
}
public extension ComputeResource {
/**
Default instance of the ComputeResource structure.
*/
public static let __default: BatchModel.ComputeResource = {
let defaultInstance = BatchModel.ComputeResource(
bidPercentage: nil,
desiredvCpus: nil,
ec2KeyPair: nil,
imageId: nil,
instanceRole: "value",
instanceTypes: [],
launchTemplate: nil,
maxvCpus: 0,
minvCpus: 0,
placementGroup: nil,
securityGroupIds: nil,
spotIamFleetRole: nil,
subnets: [],
tags: nil,
type: .__default)
return defaultInstance
}()
}
public extension ComputeResourceUpdate {
/**
Default instance of the ComputeResourceUpdate structure.
*/
public static let __default: BatchModel.ComputeResourceUpdate = {
let defaultInstance = BatchModel.ComputeResourceUpdate(
desiredvCpus: nil,
maxvCpus: nil,
minvCpus: nil)
return defaultInstance
}()
}
public extension ContainerDetail {
/**
Default instance of the ContainerDetail structure.
*/
public static let __default: BatchModel.ContainerDetail = {
let defaultInstance = BatchModel.ContainerDetail(
command: nil,
containerInstanceArn: nil,
environment: nil,
exitCode: nil,
image: nil,
instanceType: nil,
jobRoleArn: nil,
logStreamName: nil,
memory: nil,
mountPoints: nil,
networkInterfaces: nil,
privileged: nil,
readonlyRootFilesystem: nil,
reason: nil,
resourceRequirements: nil,
taskArn: nil,
ulimits: nil,
user: nil,
vcpus: nil,
volumes: nil)
return defaultInstance
}()
}
public extension ContainerOverrides {
/**
Default instance of the ContainerOverrides structure.
*/
public static let __default: BatchModel.ContainerOverrides = {
let defaultInstance = BatchModel.ContainerOverrides(
command: nil,
environment: nil,
instanceType: nil,
memory: nil,
resourceRequirements: nil,
vcpus: nil)
return defaultInstance
}()
}
public extension ContainerProperties {
/**
Default instance of the ContainerProperties structure.
*/
public static let __default: BatchModel.ContainerProperties = {
let defaultInstance = BatchModel.ContainerProperties(
command: nil,
environment: nil,
image: nil,
instanceType: nil,
jobRoleArn: nil,
memory: nil,
mountPoints: nil,
privileged: nil,
readonlyRootFilesystem: nil,
resourceRequirements: nil,
ulimits: nil,
user: nil,
vcpus: nil,
volumes: nil)
return defaultInstance
}()
}
public extension ContainerSummary {
/**
Default instance of the ContainerSummary structure.
*/
public static let __default: BatchModel.ContainerSummary = {
let defaultInstance = BatchModel.ContainerSummary(
exitCode: nil,
reason: nil)
return defaultInstance
}()
}
public extension CreateComputeEnvironmentRequest {
/**
Default instance of the CreateComputeEnvironmentRequest structure.
*/
public static let __default: BatchModel.CreateComputeEnvironmentRequest = {
let defaultInstance = BatchModel.CreateComputeEnvironmentRequest(
computeEnvironmentName: "value",
computeResources: nil,
serviceRole: "value",
state: nil,
type: .__default)
return defaultInstance
}()
}
public extension CreateComputeEnvironmentResponse {
/**
Default instance of the CreateComputeEnvironmentResponse structure.
*/
public static let __default: BatchModel.CreateComputeEnvironmentResponse = {
let defaultInstance = BatchModel.CreateComputeEnvironmentResponse(
computeEnvironmentArn: nil,
computeEnvironmentName: nil)
return defaultInstance
}()
}
public extension CreateJobQueueRequest {
/**
Default instance of the CreateJobQueueRequest structure.
*/
public static let __default: BatchModel.CreateJobQueueRequest = {
let defaultInstance = BatchModel.CreateJobQueueRequest(
computeEnvironmentOrder: [],
jobQueueName: "value",
priority: 0,
state: nil)
return defaultInstance
}()
}
public extension CreateJobQueueResponse {
/**
Default instance of the CreateJobQueueResponse structure.
*/
public static let __default: BatchModel.CreateJobQueueResponse = {
let defaultInstance = BatchModel.CreateJobQueueResponse(
jobQueueArn: "value",
jobQueueName: "value")
return defaultInstance
}()
}
public extension DeleteComputeEnvironmentRequest {
/**
Default instance of the DeleteComputeEnvironmentRequest structure.
*/
public static let __default: BatchModel.DeleteComputeEnvironmentRequest = {
let defaultInstance = BatchModel.DeleteComputeEnvironmentRequest(
computeEnvironment: "value")
return defaultInstance
}()
}
public extension DeleteComputeEnvironmentResponse {
/**
Default instance of the DeleteComputeEnvironmentResponse structure.
*/
public static let __default: BatchModel.DeleteComputeEnvironmentResponse = {
let defaultInstance = BatchModel.DeleteComputeEnvironmentResponse()
return defaultInstance
}()
}
public extension DeleteJobQueueRequest {
/**
Default instance of the DeleteJobQueueRequest structure.
*/
public static let __default: BatchModel.DeleteJobQueueRequest = {
let defaultInstance = BatchModel.DeleteJobQueueRequest(
jobQueue: "value")
return defaultInstance
}()
}
public extension DeleteJobQueueResponse {
/**
Default instance of the DeleteJobQueueResponse structure.
*/
public static let __default: BatchModel.DeleteJobQueueResponse = {
let defaultInstance = BatchModel.DeleteJobQueueResponse()
return defaultInstance
}()
}
public extension DeregisterJobDefinitionRequest {
/**
Default instance of the DeregisterJobDefinitionRequest structure.
*/
public static let __default: BatchModel.DeregisterJobDefinitionRequest = {
let defaultInstance = BatchModel.DeregisterJobDefinitionRequest(
jobDefinition: "value")
return defaultInstance
}()
}
public extension DeregisterJobDefinitionResponse {
/**
Default instance of the DeregisterJobDefinitionResponse structure.
*/
public static let __default: BatchModel.DeregisterJobDefinitionResponse = {
let defaultInstance = BatchModel.DeregisterJobDefinitionResponse()
return defaultInstance
}()
}
public extension DescribeComputeEnvironmentsRequest {
/**
Default instance of the DescribeComputeEnvironmentsRequest structure.
*/
public static let __default: BatchModel.DescribeComputeEnvironmentsRequest = {
let defaultInstance = BatchModel.DescribeComputeEnvironmentsRequest(
computeEnvironments: nil,
maxResults: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension DescribeComputeEnvironmentsResponse {
/**
Default instance of the DescribeComputeEnvironmentsResponse structure.
*/
public static let __default: BatchModel.DescribeComputeEnvironmentsResponse = {
let defaultInstance = BatchModel.DescribeComputeEnvironmentsResponse(
computeEnvironments: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension DescribeJobDefinitionsRequest {
/**
Default instance of the DescribeJobDefinitionsRequest structure.
*/
public static let __default: BatchModel.DescribeJobDefinitionsRequest = {
let defaultInstance = BatchModel.DescribeJobDefinitionsRequest(
jobDefinitionName: nil,
jobDefinitions: nil,
maxResults: nil,
nextToken: nil,
status: nil)
return defaultInstance
}()
}
public extension DescribeJobDefinitionsResponse {
/**
Default instance of the DescribeJobDefinitionsResponse structure.
*/
public static let __default: BatchModel.DescribeJobDefinitionsResponse = {
let defaultInstance = BatchModel.DescribeJobDefinitionsResponse(
jobDefinitions: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension DescribeJobQueuesRequest {
/**
Default instance of the DescribeJobQueuesRequest structure.
*/
public static let __default: BatchModel.DescribeJobQueuesRequest = {
let defaultInstance = BatchModel.DescribeJobQueuesRequest(
jobQueues: nil,
maxResults: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension DescribeJobQueuesResponse {
/**
Default instance of the DescribeJobQueuesResponse structure.
*/
public static let __default: BatchModel.DescribeJobQueuesResponse = {
let defaultInstance = BatchModel.DescribeJobQueuesResponse(
jobQueues: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension DescribeJobsRequest {
/**
Default instance of the DescribeJobsRequest structure.
*/
public static let __default: BatchModel.DescribeJobsRequest = {
let defaultInstance = BatchModel.DescribeJobsRequest(
jobs: [])
return defaultInstance
}()
}
public extension DescribeJobsResponse {
/**
Default instance of the DescribeJobsResponse structure.
*/
public static let __default: BatchModel.DescribeJobsResponse = {
let defaultInstance = BatchModel.DescribeJobsResponse(
jobs: nil)
return defaultInstance
}()
}
public extension Host {
/**
Default instance of the Host structure.
*/
public static let __default: BatchModel.Host = {
let defaultInstance = BatchModel.Host(
sourcePath: nil)
return defaultInstance
}()
}
public extension JobDefinition {
/**
Default instance of the JobDefinition structure.
*/
public static let __default: BatchModel.JobDefinition = {
let defaultInstance = BatchModel.JobDefinition(
containerProperties: nil,
jobDefinitionArn: "value",
jobDefinitionName: "value",
nodeProperties: nil,
parameters: nil,
retryStrategy: nil,
revision: 0,
status: nil,
timeout: nil,
type: "value")
return defaultInstance
}()
}
public extension JobDependency {
/**
Default instance of the JobDependency structure.
*/
public static let __default: BatchModel.JobDependency = {
let defaultInstance = BatchModel.JobDependency(
jobId: nil,
type: nil)
return defaultInstance
}()
}
public extension JobDetail {
/**
Default instance of the JobDetail structure.
*/
public static let __default: BatchModel.JobDetail = {
let defaultInstance = BatchModel.JobDetail(
arrayProperties: nil,
attempts: nil,
container: nil,
createdAt: nil,
dependsOn: nil,
jobDefinition: "value",
jobId: "value",
jobName: "value",
jobQueue: "value",
nodeDetails: nil,
nodeProperties: nil,
parameters: nil,
retryStrategy: nil,
startedAt: 0,
status: .__default,
statusReason: nil,
stoppedAt: nil,
timeout: nil)
return defaultInstance
}()
}
public extension JobQueueDetail {
/**
Default instance of the JobQueueDetail structure.
*/
public static let __default: BatchModel.JobQueueDetail = {
let defaultInstance = BatchModel.JobQueueDetail(
computeEnvironmentOrder: [],
jobQueueArn: "value",
jobQueueName: "value",
priority: 0,
state: .__default,
status: nil,
statusReason: nil)
return defaultInstance
}()
}
public extension JobSummary {
/**
Default instance of the JobSummary structure.
*/
public static let __default: BatchModel.JobSummary = {
let defaultInstance = BatchModel.JobSummary(
arrayProperties: nil,
container: nil,
createdAt: nil,
jobId: "value",
jobName: "value",
nodeProperties: nil,
startedAt: nil,
status: nil,
statusReason: nil,
stoppedAt: nil)
return defaultInstance
}()
}
public extension JobTimeout {
/**
Default instance of the JobTimeout structure.
*/
public static let __default: BatchModel.JobTimeout = {
let defaultInstance = BatchModel.JobTimeout(
attemptDurationSeconds: nil)
return defaultInstance
}()
}
public extension KeyValuePair {
/**
Default instance of the KeyValuePair structure.
*/
public static let __default: BatchModel.KeyValuePair = {
let defaultInstance = BatchModel.KeyValuePair(
name: nil,
value: nil)
return defaultInstance
}()
}
public extension LaunchTemplateSpecification {
/**
Default instance of the LaunchTemplateSpecification structure.
*/
public static let __default: BatchModel.LaunchTemplateSpecification = {
let defaultInstance = BatchModel.LaunchTemplateSpecification(
launchTemplateId: nil,
launchTemplateName: nil,
version: nil)
return defaultInstance
}()
}
public extension ListJobsRequest {
/**
Default instance of the ListJobsRequest structure.
*/
public static let __default: BatchModel.ListJobsRequest = {
let defaultInstance = BatchModel.ListJobsRequest(
arrayJobId: nil,
jobQueue: nil,
jobStatus: nil,
maxResults: nil,
multiNodeJobId: nil,
nextToken: nil)
return defaultInstance
}()
}
public extension ListJobsResponse {
/**
Default instance of the ListJobsResponse structure.
*/
public static let __default: BatchModel.ListJobsResponse = {
let defaultInstance = BatchModel.ListJobsResponse(
jobSummaryList: [],
nextToken: nil)
return defaultInstance
}()
}
public extension MountPoint {
/**
Default instance of the MountPoint structure.
*/
public static let __default: BatchModel.MountPoint = {
let defaultInstance = BatchModel.MountPoint(
containerPath: nil,
readOnly: nil,
sourceVolume: nil)
return defaultInstance
}()
}
public extension NetworkInterface {
/**
Default instance of the NetworkInterface structure.
*/
public static let __default: BatchModel.NetworkInterface = {
let defaultInstance = BatchModel.NetworkInterface(
attachmentId: nil,
ipv6Address: nil,
privateIpv4Address: nil)
return defaultInstance
}()
}
public extension NodeDetails {
/**
Default instance of the NodeDetails structure.
*/
public static let __default: BatchModel.NodeDetails = {
let defaultInstance = BatchModel.NodeDetails(
isMainNode: nil,
nodeIndex: nil)
return defaultInstance
}()
}
public extension NodeOverrides {
/**
Default instance of the NodeOverrides structure.
*/
public static let __default: BatchModel.NodeOverrides = {
let defaultInstance = BatchModel.NodeOverrides(
nodePropertyOverrides: nil,
numNodes: nil)
return defaultInstance
}()
}
public extension NodeProperties {
/**
Default instance of the NodeProperties structure.
*/
public static let __default: BatchModel.NodeProperties = {
let defaultInstance = BatchModel.NodeProperties(
mainNode: 0,
nodeRangeProperties: [],
numNodes: 0)
return defaultInstance
}()
}
public extension NodePropertiesSummary {
/**
Default instance of the NodePropertiesSummary structure.
*/
public static let __default: BatchModel.NodePropertiesSummary = {
let defaultInstance = BatchModel.NodePropertiesSummary(
isMainNode: nil,
nodeIndex: nil,
numNodes: nil)
return defaultInstance
}()
}
public extension NodePropertyOverride {
/**
Default instance of the NodePropertyOverride structure.
*/
public static let __default: BatchModel.NodePropertyOverride = {
let defaultInstance = BatchModel.NodePropertyOverride(
containerOverrides: nil,
targetNodes: "value")
return defaultInstance
}()
}
public extension NodeRangeProperty {
/**
Default instance of the NodeRangeProperty structure.
*/
public static let __default: BatchModel.NodeRangeProperty = {
let defaultInstance = BatchModel.NodeRangeProperty(
container: nil,
targetNodes: "value")
return defaultInstance
}()
}
public extension RegisterJobDefinitionRequest {
/**
Default instance of the RegisterJobDefinitionRequest structure.
*/
public static let __default: BatchModel.RegisterJobDefinitionRequest = {
let defaultInstance = BatchModel.RegisterJobDefinitionRequest(
containerProperties: nil,
jobDefinitionName: "value",
nodeProperties: nil,
parameters: nil,
retryStrategy: nil,
timeout: nil,
type: .__default)
return defaultInstance
}()
}
public extension RegisterJobDefinitionResponse {
/**
Default instance of the RegisterJobDefinitionResponse structure.
*/
public static let __default: BatchModel.RegisterJobDefinitionResponse = {
let defaultInstance = BatchModel.RegisterJobDefinitionResponse(
jobDefinitionArn: "value",
jobDefinitionName: "value",
revision: 0)
return defaultInstance
}()
}
public extension ResourceRequirement {
/**
Default instance of the ResourceRequirement structure.
*/
public static let __default: BatchModel.ResourceRequirement = {
let defaultInstance = BatchModel.ResourceRequirement(
type: .__default,
value: "value")
return defaultInstance
}()
}
public extension RetryStrategy {
/**
Default instance of the RetryStrategy structure.
*/
public static let __default: BatchModel.RetryStrategy = {
let defaultInstance = BatchModel.RetryStrategy(
attempts: nil)
return defaultInstance
}()
}
public extension ServerException {
/**
Default instance of the ServerException structure.
*/
public static let __default: BatchModel.ServerException = {
let defaultInstance = BatchModel.ServerException(
message: nil)
return defaultInstance
}()
}
public extension SubmitJobRequest {
/**
Default instance of the SubmitJobRequest structure.
*/
public static let __default: BatchModel.SubmitJobRequest = {
let defaultInstance = BatchModel.SubmitJobRequest(
arrayProperties: nil,
containerOverrides: nil,
dependsOn: nil,
jobDefinition: "value",
jobName: "value",
jobQueue: "value",
nodeOverrides: nil,
parameters: nil,
retryStrategy: nil,
timeout: nil)
return defaultInstance
}()
}
public extension SubmitJobResponse {
/**
Default instance of the SubmitJobResponse structure.
*/
public static let __default: BatchModel.SubmitJobResponse = {
let defaultInstance = BatchModel.SubmitJobResponse(
jobId: "value",
jobName: "value")
return defaultInstance
}()
}
public extension TerminateJobRequest {
/**
Default instance of the TerminateJobRequest structure.
*/
public static let __default: BatchModel.TerminateJobRequest = {
let defaultInstance = BatchModel.TerminateJobRequest(
jobId: "value",
reason: "value")
return defaultInstance
}()
}
public extension TerminateJobResponse {
/**
Default instance of the TerminateJobResponse structure.
*/
public static let __default: BatchModel.TerminateJobResponse = {
let defaultInstance = BatchModel.TerminateJobResponse()
return defaultInstance
}()
}
public extension Ulimit {
/**
Default instance of the Ulimit structure.
*/
public static let __default: BatchModel.Ulimit = {
let defaultInstance = BatchModel.Ulimit(
hardLimit: 0,
name: "value",
softLimit: 0)
return defaultInstance
}()
}
public extension UpdateComputeEnvironmentRequest {
/**
Default instance of the UpdateComputeEnvironmentRequest structure.
*/
public static let __default: BatchModel.UpdateComputeEnvironmentRequest = {
let defaultInstance = BatchModel.UpdateComputeEnvironmentRequest(
computeEnvironment: "value",
computeResources: nil,
serviceRole: nil,
state: nil)
return defaultInstance
}()
}
public extension UpdateComputeEnvironmentResponse {
/**
Default instance of the UpdateComputeEnvironmentResponse structure.
*/
public static let __default: BatchModel.UpdateComputeEnvironmentResponse = {
let defaultInstance = BatchModel.UpdateComputeEnvironmentResponse(
computeEnvironmentArn: nil,
computeEnvironmentName: nil)
return defaultInstance
}()
}
public extension UpdateJobQueueRequest {
/**
Default instance of the UpdateJobQueueRequest structure.
*/
public static let __default: BatchModel.UpdateJobQueueRequest = {
let defaultInstance = BatchModel.UpdateJobQueueRequest(
computeEnvironmentOrder: nil,
jobQueue: "value",
priority: nil,
state: nil)
return defaultInstance
}()
}
public extension UpdateJobQueueResponse {
/**
Default instance of the UpdateJobQueueResponse structure.
*/
public static let __default: BatchModel.UpdateJobQueueResponse = {
let defaultInstance = BatchModel.UpdateJobQueueResponse(
jobQueueArn: nil,
jobQueueName: nil)
return defaultInstance
}()
}
public extension Volume {
/**
Default instance of the Volume structure.
*/
public static let __default: BatchModel.Volume = {
let defaultInstance = BatchModel.Volume(
host: nil,
name: nil)
return defaultInstance
}()
}
| 27.622678 | 99 | 0.641624 |
d79584700df7dcf748ce05cf977a7b045a16cf53 | 7,440 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import libetpan
public struct MimeType {
public let type: String
public let subtype: String
public init(type: String, subtype: String) {
self.type = type.lowercased()
self.subtype = subtype.lowercased()
}
}
extension MimeType: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(31 &* type.hash &+ subtype.hash)
}
}
public func == (lhs: MimeType, rhs: MimeType) -> Bool {
return lhs.type == rhs.type && lhs.subtype == rhs.subtype
}
extension MimeType: CustomStringConvertible {
public var description: String { return "\(type)/\(subtype)" }
}
public extension MimeType {
static var applicationJavascript: MimeType { return MimeType(type: "application", subtype: "javascript") }
static var applicationOctetStream: MimeType { return MimeType(type: "application", subtype: "octet-stream") }
static var applicationOgg: MimeType { return MimeType(type: "application", subtype: "ogg") }
static var applicationPdf: MimeType { return MimeType(type: "application", subtype: "pdf") }
static var applicationXhtml: MimeType { return MimeType(type: "application", subtype: "xhtml+xml") }
static var applicationFlash: MimeType { return MimeType(type: "application", subtype: "x-shockwave-flash") }
static var applicationJson: MimeType { return MimeType(type: "application", subtype: "json") }
static var applicationXml: MimeType { return MimeType(type: "application", subtype: "xml") }
static var applicationZip: MimeType { return MimeType(type: "application", subtype: "zip") }
static var audioMpeg: MimeType { return MimeType(type: "audio", subtype: "mpeg") }
static var audioMp3: MimeType { return MimeType(type: "audio", subtype: "mp3") }
static var audioWma: MimeType { return MimeType(type: "audio", subtype: "x-ms-wma") }
static var audioWav: MimeType { return MimeType(type: "audio", subtype: "x-wav") }
static var imageGif: MimeType { return MimeType(type: "image", subtype: "jpeg") }
static var imageJpeg: MimeType { return MimeType(type: "image", subtype: "jpeg") }
static var imagePng: MimeType { return MimeType(type: "image", subtype: "jpeg") }
static var imageTiff: MimeType { return MimeType(type: "image", subtype: "jpeg") }
static var imageIcon: MimeType { return MimeType(type: "image", subtype: "x-icon") }
static var imageSvg: MimeType { return MimeType(type: "image", subtype: "svg+xml") }
static var multipartMixed: MimeType { return MimeType(type: "multipart", subtype: "mixed") }
static var multipartAlternative: MimeType { return MimeType(type: "multipart", subtype: "alternative") }
static var multipartRelated: MimeType { return MimeType(type: "multipart", subtype: "related") }
static var textCss: MimeType { return MimeType(type: "text", subtype: "css") }
static var textCsv: MimeType { return MimeType(type: "text", subtype: "csv") }
static var textHtml: MimeType { return MimeType(type: "text", subtype: "html") }
static var textJavascript: MimeType { return MimeType(type: "text", subtype: "javascript") }
static var textPlain: MimeType { return MimeType(type: "text", subtype: "plain") }
static var textXml: MimeType { return MimeType(type: "text", subtype: "xml") }
static var videoMpeg: MimeType { return MimeType(type: "video", subtype: "mpeg") }
static var videoMp4: MimeType { return MimeType(type: "video", subtype: "mp4") }
static var videoQuicktime: MimeType { return MimeType(type: "video", subtype: "quicktime") }
static var videoWmv: MimeType { return MimeType(type: "video", subtype: "x-ms-wmv") }
static var videoAvi: MimeType { return MimeType(type: "video", subtype: "x-msvideo") }
static var videoFlv: MimeType { return MimeType(type: "video", subtype: "x-flv") }
static var videoWebm: MimeType { return MimeType(type: "video", subtype: "webm") }
}
// MARK: IMAP Parsing
extension mailimap_media_basic {
var parse: MimeType? {
let subtype = String(cString: med_subtype).lowercased()
switch Int(med_type) {
case MAILIMAP_MEDIA_BASIC_APPLICATION: return MimeType(type: "application", subtype: subtype)
case MAILIMAP_MEDIA_BASIC_AUDIO: return MimeType(type: "audio", subtype: subtype)
case MAILIMAP_MEDIA_BASIC_IMAGE: return MimeType(type: "image", subtype: subtype)
case MAILIMAP_MEDIA_BASIC_MESSAGE: return MimeType(type: "message", subtype: subtype)
case MAILIMAP_MEDIA_BASIC_VIDEO: return MimeType(type: "video", subtype: subtype)
case MAILIMAP_MEDIA_BASIC_OTHER: return String.fromUTF8CString(med_basic_type).map { MimeType(type: $0, subtype: subtype) }
default: return nil
}
}
}
// MARK: IMF Parsing
extension mailmime_content {
var parse: MimeType {
let type: String = ct_type?.pointee.parse ?? "unknown"
let subtype = String.fromUTF8CString(ct_subtype)?.lowercased() ?? "unknown"
return MimeType(type: type, subtype: subtype)
}
}
extension mailmime_type {
var parse: String? {
switch Int(tp_type) {
case MAILMIME_TYPE_DISCRETE_TYPE: return tp_data.tp_discrete_type?.pointee.parse
case MAILMIME_TYPE_COMPOSITE_TYPE: return tp_data.tp_composite_type?.pointee.parse
default: return nil
}
}
}
extension mailmime_composite_type {
var parse: String? {
switch Int(ct_type) {
case MAILMIME_COMPOSITE_TYPE_MESSAGE: return "message"
case MAILMIME_COMPOSITE_TYPE_MULTIPART: return "multipart"
case MAILMIME_COMPOSITE_TYPE_EXTENSION: return String.fromUTF8CString(ct_token)?.lowercased()
default: return nil
}
}
}
extension mailmime_discrete_type {
var parse: String? {
switch Int(dt_type) {
case MAILMIME_DISCRETE_TYPE_TEXT: return "text"
case MAILMIME_DISCRETE_TYPE_IMAGE: return "image"
case MAILMIME_DISCRETE_TYPE_AUDIO: return "audio"
case MAILMIME_DISCRETE_TYPE_VIDEO: return "video"
case MAILMIME_DISCRETE_TYPE_APPLICATION: return "application"
case MAILMIME_DISCRETE_TYPE_EXTENSION: return String.fromUTF8CString(dt_extension)?.lowercased()
default: return nil
}
}
}
| 47.388535 | 131 | 0.704704 |
67a455ec2697674f64a0e9af2616d089acb5c6cd | 2,369 | import Foundation
import PathKit
@testable import xcodeproj
import XCTest
final class PBXProjIntegrationTests: XCTestCase {
func test_init_initializesTheProjCorrectly() {
let data = try! Data(contentsOf: fixturePath().url)
let decoder = XcodeprojPropertyListDecoder()
let proj = try? decoder.decode(PBXProj.self, from: data)
XCTAssertNotNil(proj)
if let proj = proj {
assert(proj: proj)
}
}
func test_write() {
testWrite(from: fixturePath(),
initModel: { path -> PBXProj? in
let data = try! Data(contentsOf: path.url)
let decoder = XcodeprojPropertyListDecoder()
return try? decoder.decode(PBXProj.self, from: data)
},
modify: { $0 })
}
private func fixturePath() -> Path {
let path = fixturesPath() + "iOS/Project.xcodeproj/project.pbxproj"
return path
}
private func assert(proj: PBXProj) {
XCTAssertEqual(proj.archiveVersion, 1)
XCTAssertEqual(proj.objectVersion, 46)
XCTAssertEqual(proj.classes.count, 0)
XCTAssertEqual(proj.objects.buildFiles.count, 11)
XCTAssertEqual(proj.objects.aggregateTargets.count, 0)
XCTAssertEqual(proj.objects.containerItemProxies.count, 1)
XCTAssertEqual(proj.objects.copyFilesBuildPhases.count, 1)
XCTAssertEqual(proj.objects.groups.count, 6)
XCTAssertEqual(proj.objects.configurationLists.count, 3)
XCTAssertEqual(proj.objects.buildConfigurations.count, 6)
XCTAssertEqual(proj.objects.variantGroups.count, 2)
XCTAssertEqual(proj.objects.targetDependencies.count, 1)
XCTAssertEqual(proj.objects.sourcesBuildPhases.count, 2)
XCTAssertEqual(proj.objects.shellScriptBuildPhases.count, 1)
XCTAssertEqual(proj.objects.resourcesBuildPhases.count, 2)
XCTAssertEqual(proj.objects.frameworksBuildPhases.count, 2)
XCTAssertEqual(proj.objects.headersBuildPhases.count, 1)
XCTAssertEqual(proj.objects.nativeTargets.count, 2)
XCTAssertEqual(proj.objects.fileReferences.count, 15)
XCTAssertEqual(proj.objects.buildRules.count, 1)
XCTAssertEqual(proj.objects.versionGroups.count, 1)
XCTAssertEqual(proj.objects.projects.count, 1)
}
}
| 41.561404 | 75 | 0.671169 |
abafaafd0f4a3790373a745a71ab4fdad9ce5f4e | 27 |
let espGitVersion = ""
| 5.4 | 23 | 0.592593 |
fe70ccdfbcd0531a5e404e6ebacc3704f9b9836e | 3,371 | //
// TimeUnit+Double.swift
//
// Created by Chris Scalcucci on 4/20/20.
//
import Foundation
public extension Double {
func nanoseconds(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return self
case .microseconds:
return us2ns(self)
case .milliseconds:
return ms2ns(self)
case .seconds:
return s2ns(self)
case .minutes:
return min2ns(self)
case .hours:
return hr2ns(self)
case .days:
return d2ns(self)
}
}
func microseconds(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2us(self)
case .microseconds:
return self
case .milliseconds:
return ms2us(self)
case .seconds:
return s2us(self)
case .minutes:
return min2us(self)
case .hours:
return hr2us(self)
case .days:
return d2us(self)
}
}
func milliseconds(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2ms(self)
case .microseconds:
return us2ms(self)
case .milliseconds:
return self
case .seconds:
return s2ms(self)
case .minutes:
return min2ms(self)
case .hours:
return hr2ms(self)
case .days:
return d2ms(self)
}
}
func seconds(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2s(self)
case .microseconds:
return us2s(self)
case .milliseconds:
return ms2s(self)
case .seconds:
return self
case .minutes:
return min2s(self)
case .hours:
return hr2s(self)
case .days:
return d2s(self)
}
}
func minutes(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2min(self)
case .microseconds:
return us2min(self)
case .milliseconds:
return ms2min(self)
case .seconds:
return s2min(self)
case .minutes:
return self
case .hours:
return hr2min(self)
case .days:
return d2min(self)
}
}
func hours(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2hr(self)
case .microseconds:
return us2hr(self)
case .milliseconds:
return ms2hr(self)
case .seconds:
return s2hr(self)
case .minutes:
return min2hr(self)
case .hours:
return self
case .days:
return d2hr(self)
}
}
func days(from: TimeUnit) -> Double {
switch from {
case .nanoseconds:
return ns2d(self)
case .microseconds:
return us2d(self)
case .milliseconds:
return ms2d(self)
case .seconds:
return s2d(self)
case .minutes:
return min2d(self)
case .hours:
return hr2d(self)
case .days:
return self
}
}
}
| 23.409722 | 49 | 0.491842 |
2906a9da57fc60623fbcbaa4bdc7563ba52aa652 | 1,228 | //
// tippyUITests.swift
// tippyUITests
//
// Created by Bhavesh on 12/23/17.
// Copyright © 2017 Bhavesh. All rights reserved.
//
import XCTest
class tippyUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.189189 | 182 | 0.659609 |
03d11987d9d61b1081881727214b2b1fabe919ce | 537 | //
// ViewController.swift
// MCDynamicGridLayout
//
// Created by Mohonish Chakraborty on 06/30/2016.
// Copyright (c) 2016 Mohonish Chakraborty. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.48 | 80 | 0.687151 |
61ca4ccba1bab418eb5f6f2313606d5c8885216d | 1,841 | //
// LocalRankTask.swift
// PegaXPool
//
// Created by thailinh on 1/10/19.
// Copyright © 2019 thailinh. All rights reserved.
//
import Foundation
class LocalRankTask: BaseWokerOperationTask {
var listRanks = [RankingModel]()
init(_id: TaskID, data : [RankingModel]) {
super.init(_id: _id)
self.listRanks = data
}
override func main() {
let beginTime = Timestamp.getTimeStamp()
if PoolConstants.Debug.debugTask {print(" Task Begin id : \(String(describing: self.id)) ",beginTime)}
if isCancelled {
if PoolConstants.Debug.debugTask {print(" Task Cancel id : \(String(describing: self.id))")}
self.taskProtocol?.fail(task: self, isValid: false)
return
}
let timestamp = Timestamp()
if isCancelled {
return
}
guard self.listRanks.count > 0 else {
if PoolConstants.Debug.debugLog{ print( "list rankings is nil" )}
self.taskProtocol?.fail(task: self, isValid: false)
return
}
if isCancelled {
self.taskProtocol?.fail(task: self, isValid: false)
return
}
LocalDatabase.shareInstance.updateRanks(ranks: self.listRanks)
// LocalDatabase.shareInstance.deleteOverCapacity()
if PoolConstants.Debug.debugLog{ print( "add ranks success call ranking" )}
self.taskProtocol?.needRanking()
// check xem da du action de rank chua.
let endTime = Timestamp.getTimeStamp()
let duration = TimeInterval(endTime)! - TimeInterval(beginTime)!
if PoolConstants.Debug.debugTask {print(" Task Complete id : \(String(describing: self.id)) : ",endTime ,"\t DURATION = \(duration) ms")}
self.taskProtocol?.complete(taskID: self.id)
}
}
| 36.098039 | 146 | 0.614883 |
727f8bd6eb7a1b6835703bdf3ac54b147b3219b3 | 403 | //
// LicenseViewController.swift
// GradePoint
//
// Created by Luis Padron on 6/23/17.
// Copyright © 2017 Luis Padron. All rights reserved.
//
import UIKit
class LicenseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .never
}
}
}
| 19.190476 | 62 | 0.632754 |
dd126d55b533473ab933d1a177c6d369c68f5b56 | 165 | //
// Created by Dmitriy Stupivtsev on 10/05/2019.
//
import UIKit
// sourcery: AutoMockable
protocol ControllerFactory {
func create() -> UIViewController
}
| 15 | 48 | 0.715152 |
39bd57dc40320ae7a0bc1af8e3ca275bf28caac6 | 197 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to Literals.playground.
//
| 49.25 | 190 | 0.791878 |
ac1a8872a293ab5fe7e162a77b1475a2b3f382c5 | 1,815 | import Foundation
import UIKit
import RealmSwift
protocol HomeViewModelDelegate: class {
func handleApiError(error: Error)
}
final class HomeViewModel {
var myTrendings: [Trending] = []
var myChannels: [Channel] = []
weak var delegate: HomeViewModelDelegate?
// Mark : - Load Data From API
func loadDataTrending(completion: @escaping (Bool) -> Void) {
ApiManager.Snippet.getTrendingData { [weak self] result in
guard let this = self else { return }
switch result {
case .success(let trendingResult):
this.myTrendings.append(contentsOf: trendingResult.myTrending)
completion(true)
case .failure(let error):
this.delegate?.handleApiError(error: error)
completion(false)
}
}
}
func loadDataChannel(completion: @escaping (Bool) -> Void) {
ApiManager.Snippet.getChannelData { [weak self] result in
guard let this = self else { return }
switch result {
case .success(let channelResult):
this.myChannels.append(contentsOf: channelResult.myChannel)
completion(true)
case .failure(let error):
this.delegate?.handleApiError(error: error)
completion(false)
}
}
}
}
extension HomeViewModel {
func numberOfItemsTrending(in section: Int) -> Int {
return myTrendings.count
}
func getTrending(with indexPath: IndexPath) -> Trending {
return myTrendings[indexPath.row]
}
func numberOfItemsChannel(in section: Int) -> Int {
return myChannels.count
}
func getChannel(with indexPath: IndexPath) -> Channel {
return myChannels[indexPath.row]
}
}
| 28.809524 | 78 | 0.609366 |
bb696a7cbb6e77fc30ae2a100684462f3195b91c | 1,456 | extension NatAvatar {
/**
Size is a enum that represents size values for NatAvatar component.
These are all sizes allowed for a NatAvatar:
- standard
- semi
- semiX
- medium
- largeXXX
- Requires:
It's necessary to configure the Design System with a theme or fatalError will be raised.
DesignSystem().configure(with: AvailableTheme)
*/
public enum Size: CaseIterable {
case standard
case semi
case semiX
case medium
case largeXXX
}
}
extension NatAvatar.Size {
var value: CGFloat {
switch self {
case .standard:
return getTokenFromTheme(\.sizeStandard)
case .semi:
return getTokenFromTheme(\.sizeSemi)
case .semiX:
return getTokenFromTheme(\.sizeSemiX)
case .medium:
return getTokenFromTheme(\.sizeMedium)
case .largeXXX:
return getTokenFromTheme(\.sizeLargeXXX)
}
}
var font: UIFont {
switch self {
case .standard:
return NatFonts.font(ofSize: .caption)
case .semi:
return NatFonts.font(ofSize: .body2)
case .semiX:
return NatFonts.font(ofSize: .heading6)
case .medium:
return NatFonts.font(ofSize: .heading5)
case .largeXXX:
return NatFonts.font(ofSize: .heading3)
}
}
}
| 25.103448 | 93 | 0.570742 |
7acfd1a2b525940519aab8539698b8cfd529c885 | 476 | //
// UIColorExtension.swift
// Template
//
// Created by Georg on 02.01.2020.
// Copyright © 2020 Georg. All rights reserved.
//
import UIKit
extension UIColor {
public static var random: UIColor {
let max = CGFloat(UInt32.max)
let red = CGFloat(arc4random()) / max
let green = CGFloat(arc4random()) / max
let blue = CGFloat(arc4random()) / max
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| 22.666667 | 70 | 0.609244 |
339b4a6b8e0a9b0af05dcccbb3934b92bf7195a5 | 520 | //
// UIColor-Extension.swift
// NewsFrameworkDemo
//
// Created by Mazy on 2017/7/25.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r : CGFloat, g : CGFloat, b : CGFloat) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
}
| 24.761905 | 133 | 0.634615 |
2f1d60b81f3dbe009d2229af253c53e5cb08830e | 660 | //
// ModelErrorResponse.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
import AnyCodable
public struct ModelErrorResponse: Codable, Hashable {
/** The error description */
public var errors: [String]?
public init(errors: [String]? = nil) {
self.errors = errors
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case errors
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(errors, forKey: .errors)
}
}
| 21.290323 | 67 | 0.675758 |
67dc6d7f76cf39b9428f8b9624dae0a62da43d0d | 2,779 | //
// ALPushNotificationHandler.swift
// ApplozicSwift
//
// Created by Mukesh Thawani on 04/05/17.
// Copyright © 2017 Applozic. All rights reserved.
//
import ApplozicCore
import Foundation
public class ALKPushNotificationHandler: Localizable {
public static let shared = ALKPushNotificationHandler()
var configuration: ALKConfiguration!
public func dataConnectionNotificationHandlerWith(_ configuration: ALKConfiguration) {
self.configuration = configuration
// No need to add removeObserver() as it is present in pushAssist.
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "showNotificationAndLaunchChat"), object: nil, queue: nil, using: { [weak self] notification in
print("launch chat push notification received")
let (notifData, msg) = NotificationHelper().notificationInfo(notification)
guard
let weakSelf = self,
let notificationData = notifData,
let message = msg
else { return }
guard let userInfo = notification.userInfo as? [String: Any], let state = userInfo["updateUI"] as? NSNumber else { return }
switch state {
case NSNumber(value: APP_STATE_ACTIVE.rawValue):
guard !NotificationHelper().isNotificationForActiveThread(notificationData) else { return }
// TODO: FIX HERE. USE conversationId also.
guard !configuration.isInAppNotificationBannerDisabled else { return }
ALUtilityClass.thirdDisplayNotificationTS(
message,
andForContactId: notificationData.userId,
withGroupId: notificationData.groupId,
completionHandler: {
_ in
weakSelf.launchIndividualChatWith(notificationData: notificationData)
}
)
default:
weakSelf.launchIndividualChatWith(notificationData: notificationData)
}
})
}
func launchIndividualChatWith(notificationData: NotificationHelper.NotificationData) {
guard !NotificationHelper().isApplozicVCAtTop() else {
NotificationHelper().handleNotificationTap(notificationData)
return
}
let topVC = ALPushAssist().topViewController
let listVC = NotificationHelper().getConversationVCToLaunch(notification: notificationData, configuration: configuration)
let nav = ALKBaseNavigationViewController(rootViewController: listVC)
nav.modalTransitionStyle = .crossDissolve
nav.modalPresentationStyle = .fullScreen
topVC?.present(nav, animated: true, completion: nil)
}
}
| 43.421875 | 181 | 0.657431 |
f54e15b76a332f1b7a3dd95d3bc8246916775f6b | 3,337 | //**********************************************************************************************************************
//
// View+onKey.swift
// Adds key press support to a SwiftUI view
// Copyright ©2020 Peter Baumgartner. All rights reserved.
//
//**********************************************************************************************************************
#if os(macOS)
import SwiftUI
import AppKit
//----------------------------------------------------------------------------------------------------------------------
public struct BXKeyEventView : NSViewRepresentable
{
/// Handler closures
var onKeyDown:(NSEvent)->Void
var onKeyUp:(NSEvent)->Void
var onModifiersChanged:(NSEvent)->Void
/// AppKit helper view that performs keyboard handling
public class KeyView : NSView
{
var onKeyDown:(NSEvent)->Void = { _ in }
var onKeyUp:(NSEvent)->Void = { _ in }
var onModifiersChanged:(NSEvent)->Void = { _ in }
// Set this helper view as initialFirstResponder, so that we can restore it when textfields resign
override public func viewDidMoveToWindow()
{
guard let window = self.window else { return }
window.initialFirstResponder = self
window.makeFirstResponder(self)
window.makeKey()
}
override public var acceptsFirstResponder:Bool
{
true
}
// Keyboard event handling
override public func keyDown(with event:NSEvent)
{
self.onKeyDown(event)
}
override public func keyUp(with event:NSEvent)
{
self.onKeyUp(event)
}
override public func flagsChanged(with event:NSEvent)
{
self.onModifiersChanged(event)
}
}
// Create helper view
public func makeNSView(context:Context) -> KeyView
{
let view = KeyView(frame:.zero)
view.onKeyDown = self.onKeyDown
view.onKeyUp = self.onKeyUp
return view
}
public func updateNSView(_ keyView:KeyView, context:Context)
{
}
}
//----------------------------------------------------------------------------------------------------------------------
public extension View
{
/// Adds a keyDown handler to a view
func onKeyDown(action:@escaping (NSEvent)->Void) -> some View
{
return self.background(
BXKeyEventView(onKeyDown:action, onKeyUp:{ _ in }, onModifiersChanged:{ _ in })
)
}
/// Adds a keyUp handler to a view
func onKeyUp(action:@escaping (NSEvent)->Void) -> some View
{
return self.background(
BXKeyEventView(onKeyDown:{ _ in }, onKeyUp:action, onModifiersChanged:{ _ in })
)
}
/// Adds a keyUp handler to a view
func onModifiersChanged(action:@escaping (NSEvent)->Void) -> some View
{
return self.background(
BXKeyEventView(onKeyDown:{ _ in }, onKeyUp:{ _ in }, onModifiersChanged:action)
)
}
/// Adds a keyDown/Up handlers to a view
func onKey(down:@escaping (NSEvent)->Void = { _ in }, up:@escaping (NSEvent)->Void = { _ in }, modifiers:@escaping (NSEvent)->Void = { _ in }) -> some View
{
return self.background(
BXKeyEventView(onKeyDown:down, onKeyUp:up, onModifiersChanged:modifiers)
)
}
}
//----------------------------------------------------------------------------------------------------------------------
#endif
| 25.090226 | 156 | 0.531915 |
3a8970e32423311e78bf67c50cb6bfd11dce327d | 6,759 | //
// LonaLogic.swift
// LonaStudio
//
// Created by devin_abbott on 3/10/18.
// Copyright © 2018 Devin Abbott. All rights reserved.
//
import Foundation
protocol TestingHello {}
private let comparatorMapping: [String: LonaOperator] = [
"equal to": .eq,
"not equal to": .neq,
"greater than": .gt,
"greater than or equal to": .gte,
"less than": .lt,
"less than or equal to": .lte
]
enum LonaOperator: String {
case eq = "=="
case neq = "!="
case gt = ">"
case gte = ">="
case lt = "<"
case lte = "<="
init?(comparator: CSValue) {
if let op = comparatorMapping[comparator.data.stringValue] {
self.init(rawValue: op.rawValue)
} else {
self.init(rawValue: "==")
}
}
func comparator() -> CSValue {
guard let result = comparatorMapping.first(where: { $0.value == self }) else { return CSUndefinedValue }
return CSValue(type: CSComparatorType, data: result.key.toData())
}
}
struct AssignmentExpressionNode {
var assignee: LonaExpression
var content: LonaExpression
enum Keys: String {
case assignee
case content
}
func toData() -> CSData {
return .Object([
Keys.assignee.rawValue: assignee.toData(),
Keys.content.rawValue: content.toData()
])
}
}
struct IfExpressionNode {
var condition: LonaExpression
var body: [LonaExpression]
enum Keys: String {
case condition
case body
}
func toData() -> CSData {
return .Object([
Keys.condition.rawValue: condition.toData(),
Keys.body.rawValue: body.toData()
])
}
}
struct VariableDeclarationNode {
var identifier: LonaExpression
var content: LonaExpression
enum Keys: String {
case identifier = "id"
case content
}
func toData() -> CSData {
return .Object([
Keys.identifier.rawValue: identifier.toData(),
Keys.content.rawValue: content.toData()
])
}
}
struct BinaryExpressionNode {
var left: LonaExpression
var op: LonaExpression
var right: LonaExpression
enum Keys: String {
case left
case op
case right
}
func toData() -> CSData {
return .Object([
Keys.left.rawValue: left.toData(),
Keys.op.rawValue: op.toData(),
Keys.right.rawValue: right.toData()
])
}
}
indirect enum LonaExpression: CSDataSerializable, CSDataDeserializable {
case assignmentExpression(AssignmentExpressionNode)
case ifExpression(IfExpressionNode)
case variableDeclarationExpression(VariableDeclarationNode)
case binaryExpression(BinaryExpressionNode)
case memberExpression([LonaExpression])
case identifierExpression(String)
case literalExpression(CSValue)
case placeholderExpression
enum ExpressionType: String, CSDataSerializable {
case assignmentExpression = "AssignExpr"
case ifExpression = "IfExpr"
case variableDeclarationExpression = "VarDeclExpr"
case binaryExpression = "BinExpr"
case literalExpression = "LitExpr"
func toData() -> CSData {
return self.rawValue.toData()
}
init?(_ data: CSData) {
self.init(rawValue: data.stringValue)
}
}
init(_ data: CSData) {
if let value = data.string {
self = .identifierExpression(value)
} else if let value = data.array {
self = .memberExpression(value.map({ expression in LonaExpression(expression) }))
} else if let type = ExpressionType(data.get(key: "type")) {
switch type {
case .assignmentExpression:
let content = AssignmentExpressionNode(
assignee: LonaExpression(data.get(key: AssignmentExpressionNode.Keys.assignee.rawValue)),
content: LonaExpression(data.get(key: AssignmentExpressionNode.Keys.content.rawValue)))
self = .assignmentExpression(content)
case .ifExpression:
let content = IfExpressionNode(
condition: LonaExpression(data.get(key: IfExpressionNode.Keys.condition.rawValue)),
body: data.get(key: IfExpressionNode.Keys.body.rawValue).arrayValue.map({ LonaExpression($0) }))
self = .ifExpression(content)
case .variableDeclarationExpression:
let content = VariableDeclarationNode(
identifier: LonaExpression(data.get(key: VariableDeclarationNode.Keys.identifier.rawValue)),
content: LonaExpression(data.get(key: VariableDeclarationNode.Keys.content.rawValue)))
self = .variableDeclarationExpression(content)
case .binaryExpression:
let content = BinaryExpressionNode(
left: LonaExpression(data.get(key: BinaryExpressionNode.Keys.left.rawValue)),
op: LonaExpression(data.get(key: BinaryExpressionNode.Keys.op.rawValue)),
right: LonaExpression(data.get(key: BinaryExpressionNode.Keys.right.rawValue)))
self = .binaryExpression(content)
case .literalExpression:
self = .literalExpression(CSValue(data.get(key: "value"), expand: true))
}
} else {
self = .placeholderExpression
}
}
func toData() -> CSData {
switch self {
case .assignmentExpression(let node):
return CSData.Object([
"type": ExpressionType.assignmentExpression.toData()
]).merge(node.toData())
case .ifExpression(let node):
return CSData.Object([
"type": ExpressionType.ifExpression.toData()
]).merge(node.toData())
case .variableDeclarationExpression(let node):
return CSData.Object([
"type": ExpressionType.variableDeclarationExpression.toData()
]).merge(node.toData())
case .binaryExpression(let node):
return CSData.Object([
"type": ExpressionType.binaryExpression.toData()
]).merge(node.toData())
case .memberExpression(let path):
return path.toData()
case .identifierExpression(let identifier):
return identifier.toData()
case .literalExpression(let value):
return CSData.Object([
"type": ExpressionType.literalExpression.toData(),
"value": value.toData(compact: true)])
case .placeholderExpression:
return CSData.Null
}
}
}
| 32.339713 | 116 | 0.602012 |
71b622127e78051eeb1e49fbed1f0757aabf973f | 3,195 | //
// UIViewController+ShorthandAlerts.swift
//
// Created by Ayden P on 2017-07-31.
// Copyright © 2017 Ayden P. All rights reserved.
//
import UIKit
extension UIViewController {
/// Show an alert on the view controller.
func showAlert(title: String? = nil, message: String? = nil, preferredStyle: UIAlertControllerStyle = .alert, actions: [UIAlertAction] = [.ok], completion: (() -> Void)? = nil) {
if !Thread.isMainThread {
DispatchQueue.main.async {
self.showAlert(title: title, message: message, preferredStyle: preferredStyle, actions: actions, completion: completion)
}
return
}
let alert = UIAlertController.createAlert(title: title, message: message, preferredStyle: preferredStyle, actions: actions, completion: completion)
present(alert, animated: true, completion: completion)
}
/// Show an alert on the view controller.
func showAlert(title: String? = nil, message: String? = nil, preferredStyle: UIAlertControllerStyle = .alert, action: UIAlertAction, completion: (() -> Void)? = nil) {
showAlert(title: title, message: message, preferredStyle: preferredStyle, actions: [action], completion: completion)
}
}
extension UIAlertController {
static func createAlert(title: String? = nil, message: String? = nil, preferredStyle: UIAlertControllerStyle = .alert, actions: [UIAlertAction] = [.ok], completion: (() -> Void)? = nil) -> UIAlertController {
let alert = self.init(title: title, message: message, preferredStyle: preferredStyle)
actions.forEach({ alert.addAction($0) })
return alert
}
}
// Extend UIAlertAction to have quick and Swift-like initializers
extension UIAlertAction {
static func cancel(_ title: String = "Cancel", handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return UIAlertAction(title: title, style: .cancel, handler: handler)
}
static func ok(handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return self.cancel("OK", handler: handler)
}
static func dismiss(handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return self.cancel("Dismiss", handler: handler)
}
static func normal(_ title: String, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return UIAlertAction(title: title, style: .default, handler: handler)
}
static func destructive(_ title: String, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return UIAlertAction(title: title, style: .destructive, handler: handler)
}
static func delete(handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return UIAlertAction(title: "Delete", style: .destructive, handler: handler)
}
// Allow being accessed as properties:
static var cancel: UIAlertAction {
return .cancel()
}
static var ok: UIAlertAction {
return .ok()
}
static var dismiss: UIAlertAction {
return .dismiss()
}
static var delete: UIAlertAction {
return .delete()
}
}
| 36.724138 | 212 | 0.645383 |
56cc9f43bd735d913d66f153782c21b44e110760 | 6,221 | //
// LoginPageComponent.swift
// MoveeComponents
//
// Created by Hazal Eroglu on 18.11.2020.
//
import UIKit
public typealias AuthenticationCompletionBlock = (AuthenticationRequest) -> Void
public class LoginPageComponent: DataBasedComponentView<LoginPageComponentData> {
private var authenticationListener: AuthenticationCompletionBlock?
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [logoImageView, emailInputView, passwordInputView, skipAndForgotPasswordStackView, loginButton, registerStackView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill
stackView.distribution = .fill
stackView.axis = .vertical
stackView.backgroundColor = .clear
return stackView
}()
private lazy var skipAndForgotPasswordStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [skipButton, forgotPasswordButton])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill
stackView.distribution = .fill
stackView.axis = .horizontal
stackView.backgroundColor = .clear
return stackView
}()
private lazy var registerStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [registerInfoTitleLabel, registerButton])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill
stackView.distribution = .fill
stackView.axis = .horizontal
stackView.backgroundColor = .clear
return stackView
}()
private lazy var logoImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
return imageView
}()
private lazy var emailInputView: TitleWithInputComponent = {
let emailInputView = TitleWithInputComponent()
emailInputView.translatesAutoresizingMaskIntoConstraints = false
return emailInputView
}()
private lazy var passwordInputView: TitleWithInputComponent = {
let passwordInputView = TitleWithInputComponent()
passwordInputView.translatesAutoresizingMaskIntoConstraints = false
return passwordInputView
}()
private lazy var skipButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: .skipButtonAction, for: .touchUpInside)
return button
}()
private lazy var forgotPasswordButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: .forgotPasswordButtonAction, for: .touchUpInside)
return button
}()
private lazy var loginButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: .forgotPasswordButtonAction, for: .touchUpInside)
return button
}()
private lazy var registerInfoTitleLabel: CommonLabelComponent = {
let label = CommonLabelComponent()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var registerButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
@objc fileprivate func skipButtonAction(sender: UIButton) {
}
@objc fileprivate func forgotPasswordButtonAction(sender: UIButton) {
}
@objc fileprivate func loginButtonAction(sender: UIButton) {
guard let emailInputText = emailInputView.returnInputText(),
let passwordInputText = passwordInputView.returnInputText()
else { return }
authenticationListener?(AuthenticationRequest(username: emailInputText, password: passwordInputText))
}
@objc fileprivate func registerButtonAction(sender: UIButton) {
}
public func listenLoginButtonAction(completion: @escaping AuthenticationCompletionBlock) {
authenticationListener = completion
}
public override func addMajorViews() {
super.addMajorViews()
addSubview(mainStackView)
setupConstraints()
}
private func setupConstraints(){
NSLayoutConstraint.activate([
mainStackView.topAnchor.constraint(equalTo: topAnchor),
mainStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
mainStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
mainStackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
public override func loadDataIntoViews() {
super.loadDataIntoViews()
guard let data = returnData() else {return}
logoImageView.image = data.logoImage
emailInputView.setData(data: data.emailInputComponent)
passwordInputView.setData(data: data.passwordInputComponent)
skipButton.setTitle(data.skipButtonTitle, for: .normal)
forgotPasswordButton.setTitle(data.forgotPasswordTitle, for: .normal)
loginButton.setTitle(data.loginButtonTitle, for: .normal)
registerInfoTitleLabel.setLabelData(data: data.registerInfoTitleLabel)
registerButton.setTitle(data.registerButtonTitle, for: .normal)
}
}
fileprivate extension Selector {
static let skipButtonAction = #selector(LoginPageComponent.skipButtonAction)
static let forgotPasswordButtonAction = #selector(LoginPageComponent.forgotPasswordButtonAction)
static let loginButtonAction = #selector(LoginPageComponent.loginButtonAction)
static let registerButtonAction = #selector(LoginPageComponent.registerButtonAction)
}
public class AuthenticationRequest: Codable {
let username: String
let password: String
init(username: String,
password: String) {
self.username = username
self.password = password
}
}
| 36.594118 | 169 | 0.703906 |
3abb93eb04ca2e92f6e6de49f532f46d7a47e11b | 962 | //
// BikRTests.swift
// BikRTests
//
// Created by Josafá Filho on 7/3/16.
// Copyright © 2016 Josafá Filho. All rights reserved.
//
import XCTest
@testable import BikR
class BikRTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.628898 |
2fe7a0aae74a7510c80fbd2988d85f8b1cf4fd81 | 704 | //
// Currency.swift
// Currency Converter
//
// Created by Giovanny Orozco on 12/12/16.
// Copyright © 2016 Giovanny Orozco. All rights reserved.
//
import Foundation
class Currency {
let symbol: String
let value: Float
var quantity: Float = 1
var accumulatedValue: Float {
return value * quantity
}
var inverted: Float {
return quantity / value
}
init(dictionary: (key: String, value: Float)) {
self.symbol = dictionary.key
self.value = dictionary.value
}
}
extension Currency : CustomStringConvertible {
var description: String {
return "Currency: { symbol: \(symbol), value: \(value) }"
}
}
| 19.555556 | 65 | 0.615057 |
165716e918e0374df2d41afe4baf63bef21e5923 | 2,198 | //
// Copyright (c) 2020 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
//-------------------------------------------------------------------------------------------------------------------------------------------------
class Cards2Cell: UICollectionViewCell {
@IBOutlet var viewBackground: UIView!
@IBOutlet var viewCard: UIView!
@IBOutlet var imageCard: UIImageView!
@IBOutlet var labelCardNumber: UILabel!
@IBOutlet var labelName: UILabel!
@IBOutlet var labelExpiryDate: UILabel!
//---------------------------------------------------------------------------------------------------------------------------------------------
override func awakeFromNib() {
super.awakeFromNib()
viewCard.layer.borderWidth = 1
viewCard.layer.borderColor = AppColor.Border.cgColor
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func bindData(index: IndexPath, data: [String: String]) {
guard let card_number = data["card_number"] else { return }
guard let name = data["name"] else { return }
guard let expiry_date = data["expiry_date"] else { return }
labelCardNumber.text = card_number
labelName.text = name
labelExpiryDate.text = expiry_date
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func setCell(isSelected: Bool) {
viewBackground.backgroundColor = isSelected ? UIColor.systemBackground : UIColor.tertiarySystemFill
viewBackground.layer.borderWidth = isSelected ? 1 : 0
viewBackground.layer.borderColor = isSelected ? AppColor.Border.cgColor : UIColor.clear.cgColor
}
}
| 40.703704 | 147 | 0.556415 |
1edd2bc35cefbad383e52183fc1a96096f86683f | 3,201 | //
// Refresher.swift
// Matters
//
// Created by John on 2019/1/13.
// Copyright © 2019 ElegantMoya. All rights reserved.
//
import UIKit
import PullToRefreshKit
public class Refresher: UIView, RefreshableHeader {
private let circleLayer = CAShapeLayer()
private let strokeColor = UIColor(red: 221.0/255.0, green: 221.0/255.0, blue: 221.0/255.0, alpha: 1.0)
public var adjustOffset: CGFloat = 0
override init(frame: CGRect) {
super.init(frame: frame)
setUpCircleLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
circleLayer.position = CGPoint(x: bounds.width/2, y: bounds.height/2 + 14)
}
func setUpCircleLayer() {
let bezierPath = UIBezierPath(arcCenter: CGPoint(x: 11, y: 11),
radius: 11.0,
startAngle: -CGFloat.pi/2,
endAngle: CGFloat.pi/2.0 * 3.0,
clockwise: true)
circleLayer.path = bezierPath.cgPath
circleLayer.strokeColor = strokeColor.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeStart = 0
circleLayer.strokeEnd = 0
circleLayer.lineWidth = 3.0
circleLayer.lineCap = CAShapeLayerLineCap.round
circleLayer.bounds = CGRect(x: 0, y: 0, width: 22, height: 22)
circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.addSublayer(circleLayer)
}
public func adjustOffsetForHeader() -> CGFloat {
return adjustOffset
}
// MARK: - RefreshableHeader -
public func heightForHeader() -> CGFloat {
return 88
}
public func heightForFireRefreshing() -> CGFloat {
return 60.0
}
public func heightForRefreshingState() -> CGFloat {
return 60.0
}
public func percentUpdateDuringScrolling(_ percent: CGFloat) {
let adjustPercent = max(min(1.0, percent), 0.0)
circleLayer.strokeEnd = 0.75 * adjustPercent
}
public func didBeginRefreshingState() {
circleLayer.strokeEnd = 0.75
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.toValue = NSNumber(value: Double.pi * 2.0)
rotateAnimation.duration = 1
rotateAnimation.isCumulative = true
rotateAnimation.repeatCount = 10000000
rotateAnimation.isRemovedOnCompletion = false
circleLayer.add(rotateAnimation, forKey: "rotate")
}
public func didBeginHideAnimation(_ result: RefreshResult) {
transitionWithOutAnimation {
circleLayer.strokeEnd = 0
}
circleLayer.removeAllAnimations()
}
public func didCompleteHideAnimation(_ result: RefreshResult) {
transitionWithOutAnimation {
circleLayer.strokeEnd = 0
}
}
func transitionWithOutAnimation(_ clousre:() -> Void) {
CATransaction.begin()
CATransaction.setDisableActions(true)
clousre()
CATransaction.commit()
}
}
| 31.07767 | 106 | 0.624492 |
db269473558cd6f1e1e1dca499017046040f2ab7 | 1,214 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Object containing result information that was returned by the query used to create this log entry. Only returned with
logs of type `query`.
*/
public struct LogQueryResponseResultDocuments: Decodable {
public var results: [LogQueryResponseResultDocumentsResult]?
/**
The number of results returned in the query associate with this log.
*/
public var count: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case results = "results"
case count = "count"
}
}
| 31.128205 | 118 | 0.724053 |
9183e90d33d5bb2a49be8c840ab07a4308a3ff34 | 1,130 | // Factory Pattern
// Factory pattern can come in handy when you want to reduce the dependency of a class
// on other classes. On the other hand, it encapsulates the object creation process
// and users can simply pass in parameters to a generic factory class without knowing
// how the objects are actually being created. Also it gives you a clean code.
protocol Human {
var name : String {get set}
func run()
func eat()
func sleep()
}
class Soldier: Human {
//...
}
class Civilian: Human {
//...
}
enum HumanType {
case soldier
case civilian
}
class HumanFactory {
static let shared = HumanFactory()
func getHuman(type: HumanType, name: String) -> Human {
switch type {
case .soldier:
return Soldier(soldierName: name)
case .civilian:
return Civilian(civilianName: name)
}
}
}
let soldier = HumanFactory.shared.getHuman(type: .soldier, name: "Jay")
soldier.sleep()
//soldider Jay is sleeping
let civilian = HumanFactory.shared.getHuman(type: .civilian, name: "Saman")
civilian.run()
//Saman is running
| 24.565217 | 86 | 0.661947 |
9c838d2cc6dd623c88ba073b49f018695bfab346 | 686 | // swift-tools-version:5.4
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "InstrumentationMiddleware",
platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)],
products: [
.library(name: "InstrumentationMiddleware", targets: ["InstrumentationMiddleware"])
],
dependencies: [
.package(url: "https://github.com/SwiftRex/SwiftRex.git", from: "0.8.8")
],
targets: [
.target(
name: "InstrumentationMiddleware",
dependencies: [.product(name: "CombineRex", package: "SwiftRex")]
)
]
)
| 31.181818 | 96 | 0.637026 |
140e6f9b9eac54bfec3a5fc6551eeb0668a63415 | 12,017 | // swiftlint:disable force_unwrapping
import Prelude
import Result
import XCTest
@testable import Kickstarter_Framework
@testable import KsApi
@testable import Library
@testable import LiveStream
internal final class ProjectPamphletContentViewControllerTests: TestCase {
fileprivate var cosmicSurgery: Project!
override func setUp() {
super.setUp()
let deadline = self.dateType.init().timeIntervalSince1970 + 60.0 * 60.0 * 24.0 * 14.0
let launchedAt = self.dateType.init().timeIntervalSince1970 - 60.0 * 60.0 * 24.0 * 14.0
let project = Project.cosmicSurgery
|> Project.lens.photo.full .~ ""
|> (Project.lens.creator.avatar..User.Avatar.lens.small) .~ ""
|> Project.lens.dates.deadline .~ deadline
|> Project.lens.dates.launchedAt .~ launchedAt
self.cosmicSurgery = project
AppEnvironment.pushEnvironment(
config: .template |> Config.lens.countryCode .~ self.cosmicSurgery.country.countryCode,
mainBundle: Bundle.framework
)
UIView.setAnimationsEnabled(false)
}
override func tearDown() {
AppEnvironment.popEnvironment()
UIView.setAnimationsEnabled(true)
super.tearDown()
}
func testNonBacker_LiveProject() {
let project = self.cosmicSurgery
|> Project.lens.state .~ .live
|> Project.lens.stats.pledged .~ (self.cosmicSurgery.stats.goal * 3/4)
combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in
withEnvironment(language: language, locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = device == .pad ? 2_300 : 2_200
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)")
}
}
}
func testNonBacker_SuccessfulProject() {
let deadline = self.dateType.init().addingTimeInterval(-100).timeIntervalSince1970
let project = self.cosmicSurgery
|> Project.lens.dates.stateChangedAt .~ deadline
|> Project.lens.dates.deadline .~ deadline
|> Project.lens.state .~ .successful
Language.allLanguages.forEach { language in
withEnvironment(language: language, locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: .phone4_7inch, orientation: .portrait, child: vc)
parent.view.frame.size.height = 1_750
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)", tolerance: 0.0001)
}
}
}
func testBacker_LiveProject() {
let endsAt = AppEnvironment.current.dateType.init()
.addingTimeInterval(60*60*24*3)
.timeIntervalSince1970
let project = self.cosmicSurgery
|> Project.lens.rewards %~ { rewards in
[
rewards[0]
|> Reward.lens.startsAt .~ 0
|> Reward.lens.endsAt .~ endsAt,
rewards[2]
|> Reward.lens.startsAt .~ 0
|> Reward.lens.endsAt .~ 0
]
}
|> Project.lens.state .~ .live
|> Project.lens.stats.pledged .~ (self.cosmicSurgery.stats.goal * 3/4)
|> Project.lens.personalization.isBacking .~ true
|> Project.lens.personalization.backing %~~ { _, project in
.template
|> Backing.lens.amount .~ (project.rewards.first!.minimum + 5)
|> Backing.lens.rewardId .~ project.rewards.first?.id
|> Backing.lens.reward .~ project.rewards.first
}
combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in
withEnvironment(language: language, locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = device == .pad ? 1_600 : 1_350
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)", tolerance: 0.0001)
}
}
}
func testBacker_LiveProject_NoReward() {
let project = self.cosmicSurgery
|> Project.lens.rewards %~ { rewards in [rewards[0]] }
|> Project.lens.state .~ .live
|> Project.lens.personalization.isBacking .~ true
|> Project.lens.personalization.backing %~~ { _, project in
.template
|> Backing.lens.amount .~ 5
|> Backing.lens.rewardId .~ nil
|> Backing.lens.reward .~ nil
}
Language.allLanguages.forEach { language in
withEnvironment(
apiService: MockService(fetchProjectResponse: project),
language: language,
locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: .phone4_7inch, orientation: .portrait, child: vc)
parent.view.frame.size.height = 1_200
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)", tolerance: 0.0001)
}
}
}
func testBacker_SuccessfulProject() {
let deadline = self.dateType.init().addingTimeInterval(-100).timeIntervalSince1970
let backing = .template
|> Backing.lens.amount .~ (self.cosmicSurgery.rewards.first!.minimum + 5)
|> Backing.lens.rewardId .~ self.cosmicSurgery.rewards.first?.id
|> Backing.lens.reward .~ self.cosmicSurgery.rewards.first
let project = self.cosmicSurgery
|> Project.lens.rewards %~ { rewards in [rewards[0], rewards[2]] }
|> Project.lens.dates.stateChangedAt .~ deadline
|> Project.lens.dates.deadline .~ deadline
|> Project.lens.state .~ .successful
|> Project.lens.personalization.isBacking .~ true
|> Project.lens.personalization.backing .~ backing
combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in
withEnvironment(language: language, locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = device == .pad ? 1_600 : 1_350
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)", tolerance: 0.0001)
}
}
}
func testBackerOfSoldOutReward() {
let soldOutReward = self.cosmicSurgery.rewards.filter { $0.remaining == 0 }.first!
let project = self.cosmicSurgery
|> Project.lens.rewards .~ [soldOutReward]
|> Project.lens.state .~ .live
|> Project.lens.stats.pledged .~ (self.cosmicSurgery.stats.goal * 3/4)
|> Project.lens.personalization.isBacking .~ true
|> Project.lens.personalization.backing %~~ { _, project in
.template
|> Backing.lens.amount .~ (project.rewards.first!.minimum + 5)
|> Backing.lens.rewardId .~ project.rewards.first?.id
|> Backing.lens.reward .~ project.rewards.first
}
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: .phone4_7inch, orientation: .portrait, child: vc)
parent.view.frame.size.height = 1_000
FBSnapshotVerifyView(vc.view, tolerance: 0.0001)
}
func testFailedProject() {
let project = self.cosmicSurgery
|> Project.lens.dates.stateChangedAt .~ 1234567890.0
|> Project.lens.state .~ .failed
Language.allLanguages.forEach { language in
withEnvironment(language: language, locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: .phone4_7inch, orientation: .portrait, child: vc)
parent.view.frame.size.height = 1_700
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)", tolerance: 0.0001)
}
}
}
func testMinimalProjectRendering() {
let project = self.cosmicSurgery!
[Device.phone4_7inch, Device.pad].forEach { device in
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(
device: device, orientation: .portrait, child: vc, handleAppearanceTransition: false
)
parent.beginAppearanceTransition(true, animated: true)
FBSnapshotVerifyView(vc.view, identifier: "device_\(device)")
}
}
func testMinimalAndFullProjectOverlap() {
let project = self.cosmicSurgery!
withEnvironment(apiService: MockService(fetchProjectResponse: project)) {
[Device.phone4_7inch, Device.pad].forEach { device in
let minimal = ProjectPamphletViewController.configuredWith(
projectOrParam: .left(project), refTag: nil
)
let (minimalParent, _) = traitControllers(
device: device, orientation: .portrait, child: minimal, handleAppearanceTransition: false
)
let full = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (fullParent, _) = traitControllers(
device: device, orientation: .portrait, child: full, handleAppearanceTransition: false
)
minimalParent.beginAppearanceTransition(true, animated: true)
fullParent.beginAppearanceTransition(true, animated: true)
fullParent.endAppearanceTransition()
let snapshotView = UIView(frame: fullParent.view.frame)
fullParent.view.alpha = 0.5
minimalParent.view.alpha = 0.5
snapshotView.addSubview(fullParent.view)
snapshotView.addSubview(minimalParent.view)
self.scheduler.advance()
FBSnapshotVerifyView(snapshotView, identifier: "device_\(device)")
}
}
}
func testNonBacker_LiveProject_WithLiveStreams() {
let currentlyLiveStream = .template
|> LiveStreamEvent.lens.id .~ 1
|> LiveStreamEvent.lens.liveNow .~ true
let futureLiveStream = .template
|> LiveStreamEvent.lens.id .~ 2
|> LiveStreamEvent.lens.liveNow .~ false
|> LiveStreamEvent.lens.startDate .~ MockDate().addingTimeInterval(60 * 60 * 24 * 2).date
let pastLiveStream = .template
|> LiveStreamEvent.lens.id .~ 3
|> LiveStreamEvent.lens.liveNow .~ false
|> LiveStreamEvent.lens.startDate .~ MockDate().addingTimeInterval(-60 * 60 * 12).date
let project = self.cosmicSurgery
|> Project.lens.state .~ .live
|> Project.lens.rewards .~ []
let envelope = LiveStreamEventsEnvelope(numberOfLiveStreams: 3,
liveStreamEvents: [
currentlyLiveStream,
futureLiveStream,
pastLiveStream])
let liveService = MockLiveStreamService(fetchEventsForProjectResult: Result(envelope))
let apiService = MockService(fetchProjectResponse: project)
combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in
withEnvironment(
apiService: apiService,
language: language,
liveStreamService: liveService,
locale: .init(identifier: language.rawValue)) {
let vc = ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: nil)
let (parent, _) = traitControllers(device: device, orientation: .portrait, child: vc)
parent.view.frame.size.height = device == .pad ? 1_044 : 800
self.scheduler.advance()
FBSnapshotVerifyView(vc.view, identifier: "lang_\(language)_device_\(device)", tolerance: 0.0001)
}
}
}
}
| 40.325503 | 108 | 0.674045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.