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
|
---|---|---|---|---|---|
619964b4a0a7d727c1dd117fcc2b2c3b602230c4 | 5,820 | //
// Copyright © 2020 Optimize Fitness Inc.
// Licensed under the MIT license
// https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE
//
import Foundation
import UIKit
open class ImageButtonCardCellModel: BaseListCellModel {
fileprivate static let labelMargin: CGFloat = 15
public var numberOfLines = 0
public var selectedImageColor: UIColor?
public var selectedBackgroundColor: UIColor?
public var directionalLayoutMargins = NSDirectionalEdgeInsets(
top: 8,
leading: 16,
bottom: 8,
trailing: 16
)
public var contentMode: UIView.ContentMode = .scaleAspectFit
public var imageColor: UIColor?
public var matchHeightToText: NSAttributedString?
public let attributedText: NSAttributedString
public let selectedAttributedText: NSAttributedString
public let image: UIImage
public let imageSize: CGSize
public let isSelected: Bool
public var borderWidth: CGFloat = 1.0
public var borderRadius: CGFloat = 8.0
public var borderColor: UIColor?
public var maxTextWidth: CGFloat = 600
public init(
identifier: String,
attributedText: NSAttributedString,
selectedAttributedText: NSAttributedString,
image: UIImage,
imageSize: CGSize,
isSelected: Bool
) {
self.attributedText = attributedText
self.selectedAttributedText = selectedAttributedText
self.image = image
self.imageSize = imageSize
self.isSelected = isSelected
super.init(identifier: identifier)
}
// MARK: - BaseListCellModel
override open func identical(to model: ListCellModel) -> Bool {
guard let model = model as? Self, super.identical(to: model) else { return false }
return numberOfLines == model.numberOfLines
&& attributedText == model.attributedText
&& selectedAttributedText == model.selectedAttributedText
&& selectedImageColor == model.selectedImageColor
&& selectedBackgroundColor == model.selectedBackgroundColor
&& contentMode == model.contentMode
&& imageColor == model.imageColor
&& image == model.image
&& imageSize == model.imageSize
&& borderWidth == model.borderWidth
&& borderRadius == model.borderRadius
&& borderColor == model.borderColor
&& maxTextWidth == model.maxTextWidth
&& isSelected == model.isSelected
&& matchHeightToText == model.matchHeightToText
&& directionalLayoutMargins == model.directionalLayoutMargins
}
}
public final class ImageButtonCardCell: BaseListCell<ImageButtonCardCellModel> {
private let buttonContainerView = UIView()
private let label: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
return label
}()
private let imageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
private let imageWidthConstraint: NSLayoutConstraint
private let imageHeightConstraint: NSLayoutConstraint
override public init(frame: CGRect) {
self.imageWidthConstraint = imageView.widthAnchor.constraint(equalToConstant: 0)
self.imageHeightConstraint = imageView.heightAnchor.constraint(equalToConstant: 0)
super.init(frame: frame)
contentView.addSubview(buttonContainerView)
buttonContainerView.addSubview(label)
buttonContainerView.addSubview(imageView)
setupConstraints()
}
override public func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
override public func bind(model: ImageButtonCardCellModel, sizing: Bool) {
super.bind(model: model, sizing: sizing)
label.numberOfLines = model.numberOfLines
label.attributedText = model.isSelected ? model.selectedAttributedText : model.attributedText
imageWidthConstraint.constant = model.imageSize.width
imageHeightConstraint.constant = model.imageSize.height
contentView.directionalLayoutMargins = model.directionalLayoutMargins
guard !sizing else { return }
buttonContainerView.layer.borderWidth = model.borderWidth
buttonContainerView.layer.cornerRadius = model.borderRadius
buttonContainerView.layer.borderColor = model.borderColor?.cgColor
imageView.contentMode = model.contentMode
imageView.tintColor = model.isSelected ? model.selectedImageColor : model.imageColor
imageView.image = model.image.withRenderingMode(.alwaysTemplate)
buttonContainerView.backgroundColor = model.isSelected ? model.selectedBackgroundColor : nil
}
}
// MARK: - Constraints
extension ImageButtonCardCell {
private func setupConstraints() {
buttonContainerView.anchorTo(layoutGuide: contentView.layoutMarginsGuide)
imageView.bottomAnchor
.constraint(
equalTo: label.topAnchor,
constant: -ImageButtonCardCellModel.labelMargin
)
.isActive = true
imageView.topAnchor
.constraint(
equalTo: buttonContainerView.topAnchor,
constant: ImageButtonCardCellModel.labelMargin
)
.isActive = true
imageView.centerXAnchor.constraint(equalTo: buttonContainerView.centerXAnchor).isActive = true
label.leadingAnchor
.constraint(
equalTo: buttonContainerView.leadingAnchor,
constant: ImageButtonCardCellModel.labelMargin
)
.isActive = true
label.trailingAnchor
.constraint(
equalTo: buttonContainerView.trailingAnchor,
constant: -ImageButtonCardCellModel.labelMargin
)
.isActive = true
label.bottomAnchor
.constraint(
equalTo: buttonContainerView.bottomAnchor,
constant: -ImageButtonCardCellModel.labelMargin
)
.isActive = true
imageWidthConstraint.isActive = true
imageHeightConstraint.isActive = true
buttonContainerView.shouldTranslateAutoresizingMaskIntoConstraints(false)
contentView.shouldTranslateAutoresizingMaskIntoConstraints(false)
}
}
| 31.122995 | 98 | 0.742784 |
e935440980072b50593f2a48ce12949b34991ee8 | 8,017 | /*
* Copyright @ 2017-present Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public typealias AnimationCompletion = (Bool) -> Void
public protocol PiPViewCoordinatorDelegate: class {
func exitPictureInPicture()
}
/// Coordinates the view state of a specified view to allow
/// to be presented in full screen or in a custom Picture in Picture mode.
/// This object will also provide the drag and tap interactions of the view
/// when is presented in Picure in Picture mode.
public class PiPViewCoordinator {
/// Limits the boundries of view position on screen when minimized
public var dragBoundInsets: UIEdgeInsets = UIEdgeInsets(top: 25,
left: 5,
bottom: 5,
right: 5) {
didSet {
dragController.insets = dragBoundInsets
}
}
/// The size ratio of the view when in PiP mode
public var pipSizeRatio: CGFloat = {
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
switch deviceIdiom {
case .pad:
return 0.25
case .phone:
return 0.33
default:
return 0.25
}
}()
public weak var delegate: PiPViewCoordinatorDelegate?
private(set) var isInPiP: Bool = false // true if view is in PiP mode
private(set) var view: UIView
private var currentBounds: CGRect = CGRect.zero
private var tapGestureRecognizer: UITapGestureRecognizer?
private var exitPiPButton: UIButton?
private let dragController: DragGestureController = DragGestureController()
public init(withView view: UIView) {
self.view = view
}
/// Configure the view to be always on top of all the contents
/// of the provided parent view.
/// If a parentView is not provided it will try to use the main window
public func configureAsStickyView(withParentView parentView: UIView? = nil) {
guard
let parentView = parentView ?? UIApplication.shared.keyWindow
else { return }
parentView.addSubview(view)
currentBounds = parentView.bounds
view.frame = currentBounds
view.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
}
/// Show view with fade in animation
public func show(completion: AnimationCompletion? = nil) {
if view.isHidden || view.alpha < 1 {
view.isHidden = false
view.alpha = 0
animateTransition(animations: { [weak self] in
self?.view.alpha = 1
}, completion: completion)
}
}
/// Hide view with fade out animation
public func hide(completion: AnimationCompletion? = nil) {
if view.isHidden || view.alpha > 0 {
animateTransition(animations: { [weak self] in
self?.view.alpha = 0
self?.view.isHidden = true
}, completion: completion)
}
}
/// Resize view to and change state to custom PictureInPicture mode
/// This will resize view, add a gesture to enable user to "drag" view
/// around screen, and add a button of top of the view to be able to exit mode
public func enterPictureInPicture() {
isInPiP = true
animateViewChange()
dragController.startDragListener(inView: view)
dragController.insets = dragBoundInsets
// add single tap gesture recognition for displaying exit PiP UI
let exitSelector = #selector(toggleExitPiP)
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: exitSelector)
self.tapGestureRecognizer = tapGestureRecognizer
view.addGestureRecognizer(tapGestureRecognizer)
}
/// Exit Picture in picture mode, this will resize view, remove
/// exit pip button, and disable the drag gesture
@objc public func exitPictureInPicture() {
isInPiP = false
animateViewChange()
dragController.stopDragListener()
// hide PiP UI
exitPiPButton?.removeFromSuperview()
exitPiPButton = nil
// remove gesture
let exitSelector = #selector(toggleExitPiP)
tapGestureRecognizer?.removeTarget(self, action: exitSelector)
tapGestureRecognizer = nil
delegate?.exitPictureInPicture()
}
/// Reset view to provide bounds, use this method on rotation or
/// screen size changes
public func resetBounds(bounds: CGRect) {
currentBounds = bounds
exitPictureInPicture()
}
/// Stop the dragging gesture of the root view
public func stopDragGesture() {
dragController.stopDragListener()
}
/// Customize the presentation of exit pip button
open func configureExitPiPButton(target: Any,
action: Selector) -> UIButton {
let buttonImage = UIImage.init(named: "image-resize",
in: Bundle(for: type(of: self)),
compatibleWith: nil)
let button = UIButton(type: .custom)
let size: CGSize = CGSize(width: 44, height: 44)
button.setImage(buttonImage, for: .normal)
button.backgroundColor = .gray
button.layer.cornerRadius = size.width / 2
button.frame = CGRect(origin: CGPoint.zero, size: size)
button.center = view.convert(view.center, from: view.superview)
button.addTarget(target, action: action, for: .touchUpInside)
return button
}
// MARK: - Interactions
@objc private func toggleExitPiP() {
if exitPiPButton == nil {
// show button
let exitSelector = #selector(exitPictureInPicture)
let button = configureExitPiPButton(target: self,
action: exitSelector)
view.addSubview(button)
exitPiPButton = button
} else {
// hide button
exitPiPButton?.removeFromSuperview()
exitPiPButton = nil
}
}
// MARK: - Size calculation
private func animateViewChange() {
UIView.animate(withDuration: 0.25) {
self.view.frame = self.changeViewRect()
self.view.setNeedsLayout()
}
}
private func changeViewRect() -> CGRect {
let bounds = currentBounds
guard isInPiP else {
return bounds
}
// resize to suggested ratio and position to the bottom right
let adjustedBounds = UIEdgeInsetsInsetRect(bounds, dragBoundInsets)
let size = CGSize(width: bounds.size.width * pipSizeRatio,
height: bounds.size.height * pipSizeRatio)
let x: CGFloat = adjustedBounds.maxX - size.width
let y: CGFloat = adjustedBounds.maxY - size.height
return CGRect(x: x, y: y, width: size.width, height: size.height)
}
// MARK: - Animation helpers
private func animateTransition(animations: @escaping () -> Void,
completion: AnimationCompletion?) {
UIView.animate(withDuration: 0.1,
delay: 0,
options: .beginFromCurrentState,
animations: animations,
completion: completion)
}
}
| 35.631111 | 82 | 0.610702 |
228e7fb81ed7ff1185035a95594f171e3941fdbe | 1,498 | import XCTest
import Foundation
@testable import Emulator6502
final class AndZpTests: XCTestCase {
func testAndZp() {
print("debug: testAndZp")
let pins = Pins()
let testValue1:UInt8 = 0x26
let testValue2:UInt8 = 0x1c
let memory = TestHelper.initMemory(pins)
let memStore:UInt16 = 0x003c
// First OP after reset is op
memory[TestHelper.RES_ADDR] = TestHelper.ANDZp
memory[TestHelper.RES_ADDR&+1] = UInt8(memStore & 0xff) // low byte
memory[TestHelper.RES_ADDR&+2] = TestHelper.NOP
memory[memStore] = testValue2
let cpu = CPU6502(pins)
cpu.reset()
TestHelper.startupSequence(cpu: cpu, pins: pins, mem: memory)
cpu.a.value = testValue1 // Set the accumulator
// Next instruction should be op at RESET address
XCTAssertEqual(pins.address.value, TestHelper.RES_ADDR)
XCTAssertEqual(pins.data.value, TestHelper.ANDZp)
print("debug: perform AND Zp")
// decode OP - fetch ADL
TestHelper.cycle(cpu, pins: pins, mem: memory)
XCTAssertEqual(cpu.ir.value, TestHelper.ANDZp)
XCTAssertEqual(pins.data.value, UInt8(memStore & 0xff))
// Save ADL - fetch arg
TestHelper.cycle(cpu, pins: pins, mem: memory)
XCTAssertEqual(pins.data.value, testValue2)
// And arg to A
TestHelper.cycle(cpu, pins: pins, mem: memory)
XCTAssertEqual(cpu.a.value, testValue1 & testValue2)
// Decode NOP
TestHelper.cycle(cpu, pins: pins, mem: memory)
XCTAssertEqual(cpu.ir.value, TestHelper.NOP)
}
}
| 32.565217 | 71 | 0.698932 |
d9b51ffe0bf244a1958fdd9b0c6a81ee06a40cf0 | 2,801 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
extension Queries {
/// User-configurable options for the `AutoRestUrlTestService.ArrayStringSsvValid` operation.
public struct ArrayStringSsvValidOptions: RequestOptions {
/// an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the ssv-array format
public let arrayQuery: [String]?
/// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// Highly recommended for correlating client-side activites with requests received by the server.
public let clientRequestId: String?
/// A token used to make a best-effort attempt at canceling a request.
public let cancellationToken: CancellationToken?
/// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
public var dispatchQueue: DispatchQueue?
/// A `PipelineContext` object to associate with the request.
public var context: PipelineContext?
/// Initialize a `ArrayStringSsvValidOptions` structure.
/// - Parameters:
/// - arrayQuery: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the ssv-array format
/// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// - cancellationToken: A token used to make a best-effort attempt at canceling a request.
/// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
/// - context: A `PipelineContext` object to associate with the request.
public init(
arrayQuery: [String]? = nil,
clientRequestId: String? = nil,
cancellationToken: CancellationToken? = nil,
dispatchQueue: DispatchQueue? = nil,
context: PipelineContext? = nil
) {
self.arrayQuery = arrayQuery
self.clientRequestId = clientRequestId
self.cancellationToken = cancellationToken
self.dispatchQueue = dispatchQueue
self.context = context
}
}
}
| 47.474576 | 131 | 0.638343 |
1a621eb36a1b3b42e81f562ace979efc724564f5 | 442 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct c<T where g:a{class B{let n={enum a{enum l
| 44.2 | 78 | 0.746606 |
8f3d9f41170084d7e2a01e654efb68e60c8253e6 | 3,961 | //
// PeriodicosTableTableViewController.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 22/1/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
/*
V 1.1: muestra una lista con los periódicos
v 1.3: Ejercicio: mostrar los periódicos deportivos
*/
import UIKit
class PeriodicosTableViewController: UITableViewController {
struct MainStoryboard {
struct TableViewCellIdentifiers {
// Used for normal items and the add item cell.
static let listItemCell = "Cell"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// para que se desplace la tableView hacia abajo y no aparezca ajustada al Top
self.tableView.contentInset = UIEdgeInsetsMake(30, 0, 0, 0);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Periodico.totalPeriodicos()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listItemCell, forIndexPath: indexPath) as UITableViewCell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// pongo primero los generalistas
if (indexPath.row < Periodico.totalPeriodicos(TipoPeriodico.Generalista)){
if let periodico = Periodico(tipo: TipoPeriodico.Generalista,periodico: indexPath.row) {
cell.textLabel?.text = periodico.nombre()
}
}
else { // deportivos
if let periodico = Periodico(tipo: TipoPeriodico.Deportivo, periodico: indexPath.row - Periodico.totalPeriodicos(TipoPeriodico.Generalista)) {
cell.textLabel?.text = periodico.nombre()
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| 35.684685 | 157 | 0.682151 |
bb8a9b3d8872e4d95ccda13efa23c4d842d2e2ce | 536 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// InMageDiskSignatureExclusionOptionsProtocol is guest disk signature based disk exclusion option when doing enable
// protection of virtual machine in InMage provider.
public protocol InMageDiskSignatureExclusionOptionsProtocol : Codable {
var diskSignature: String? { get set }
}
| 48.727273 | 117 | 0.785448 |
238f3b59c19c8c3652a0f2df36a348110b3ed9cb | 15,204 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: unittest_swift_reserved_ext.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protos/unittest_swift_reserved_ext.proto - test proto
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// Test Swift reserved words used as enum or message names
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct SwiftReservedTestExt2 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
#if swift(>=5.5) && canImport(_Concurrency)
extension SwiftReservedTestExt2: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Extension support defined in unittest_swift_reserved_ext.proto.
// MARK: - Extension Properties
// Swift Extensions on the exteneded Messages to add easy access to the declared
// extension fields. The names are based on the extension field name from the proto
// declaration. To avoid naming collisions, the names are prefixed with the name of
// the scope where the extend directive occurs.
extension ProtobufUnittest_SwiftReservedTest.TypeMessage {
/// Will get _p added because it has no package/swift prefix to scope and
/// would otherwise be a problem when added to the message.
var debugDescription_p: Bool {
get {return getExtensionValue(ext: Extensions_debugDescription) ?? false}
set {setExtensionValue(ext: Extensions_debugDescription, value: newValue)}
}
/// Returns true if extension `Extensions_debugDescription`
/// has been explicitly set.
var hasDebugDescription_p: Bool {
return hasExtensionValue(ext: Extensions_debugDescription)
}
/// Clears the value of extension `Extensions_debugDescription`.
/// Subsequent reads from it will return its default value.
mutating func clearDebugDescription_p() {
clearExtensionValue(ext: Extensions_debugDescription)
}
/// These will get _p added for the same reasoning.
var `as`: Bool {
get {return getExtensionValue(ext: Extensions_as) ?? false}
set {setExtensionValue(ext: Extensions_as, value: newValue)}
}
/// Returns true if extension `Extensions_as`
/// has been explicitly set.
var hasAs: Bool {
return hasExtensionValue(ext: Extensions_as)
}
/// Clears the value of extension `Extensions_as`.
/// Subsequent reads from it will return its default value.
mutating func clearAs() {
clearExtensionValue(ext: Extensions_as)
}
var `var`: Bool {
get {return getExtensionValue(ext: Extensions_var) ?? false}
set {setExtensionValue(ext: Extensions_var, value: newValue)}
}
/// Returns true if extension `Extensions_var`
/// has been explicitly set.
var hasVar: Bool {
return hasExtensionValue(ext: Extensions_var)
}
/// Clears the value of extension `Extensions_var`.
/// Subsequent reads from it will return its default value.
mutating func clearVar() {
clearExtensionValue(ext: Extensions_var)
}
var `try`: Bool {
get {return getExtensionValue(ext: Extensions_try) ?? false}
set {setExtensionValue(ext: Extensions_try, value: newValue)}
}
/// Returns true if extension `Extensions_try`
/// has been explicitly set.
var hasTry: Bool {
return hasExtensionValue(ext: Extensions_try)
}
/// Clears the value of extension `Extensions_try`.
/// Subsequent reads from it will return its default value.
mutating func clearTry() {
clearExtensionValue(ext: Extensions_try)
}
var `do`: Bool {
get {return getExtensionValue(ext: Extensions_do) ?? false}
set {setExtensionValue(ext: Extensions_do, value: newValue)}
}
/// Returns true if extension `Extensions_do`
/// has been explicitly set.
var hasDo: Bool {
return hasExtensionValue(ext: Extensions_do)
}
/// Clears the value of extension `Extensions_do`.
/// Subsequent reads from it will return its default value.
mutating func clearDo() {
clearExtensionValue(ext: Extensions_do)
}
var `nil`: Bool {
get {return getExtensionValue(ext: Extensions_nil) ?? false}
set {setExtensionValue(ext: Extensions_nil, value: newValue)}
}
/// Returns true if extension `Extensions_nil`
/// has been explicitly set.
var hasNil: Bool {
return hasExtensionValue(ext: Extensions_nil)
}
/// Clears the value of extension `Extensions_nil`.
/// Subsequent reads from it will return its default value.
mutating func clearNil() {
clearExtensionValue(ext: Extensions_nil)
}
var SwiftReservedTestExt2_hashValue: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.hashValue_`
/// has been explicitly set.
var hasSwiftReservedTestExt2_hashValue: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.hashValue_`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_hashValue() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.hashValue_)
}
/// Reserved words, since these end up in the "enum Extensions", they
/// can't just be get their names, and sanitation kicks.
var SwiftReservedTestExt2_as: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.as) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.as, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.as`
/// has been explicitly set.
var hasSwiftReservedTestExt2_as: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.as)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.as`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_as() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.as)
}
var SwiftReservedTestExt2_var: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.var) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.var, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.var`
/// has been explicitly set.
var hasSwiftReservedTestExt2_var: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.var)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.var`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_var() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.var)
}
var SwiftReservedTestExt2_try: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.try) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.try, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.try`
/// has been explicitly set.
var hasSwiftReservedTestExt2_try: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.try)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.try`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_try() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.try)
}
var SwiftReservedTestExt2_do: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.do) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.do, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.do`
/// has been explicitly set.
var hasSwiftReservedTestExt2_do: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.do)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.do`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_do() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.do)
}
var SwiftReservedTestExt2_nil: Bool {
get {return getExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil) ?? false}
set {setExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil, value: newValue)}
}
/// Returns true if extension `SwiftReservedTestExt2.Extensions.nil`
/// has been explicitly set.
var hasSwiftReservedTestExt2_nil: Bool {
return hasExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil)
}
/// Clears the value of extension `SwiftReservedTestExt2.Extensions.nil`.
/// Subsequent reads from it will return its default value.
mutating func clearSwiftReservedTestExt2_nil() {
clearExtensionValue(ext: SwiftReservedTestExt2.Extensions.nil)
}
}
// MARK: - File's ExtensionMap: UnittestSwiftReservedExt_Extensions
/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by
/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed
/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create
/// a larger `SwiftProtobuf.SimpleExtensionMap`.
let UnittestSwiftReservedExt_Extensions: SwiftProtobuf.SimpleExtensionMap = [
Extensions_debugDescription,
Extensions_as,
Extensions_var,
Extensions_try,
Extensions_do,
Extensions_nil,
SwiftReservedTestExt2.Extensions.hashValue_,
SwiftReservedTestExt2.Extensions.as,
SwiftReservedTestExt2.Extensions.var,
SwiftReservedTestExt2.Extensions.try,
SwiftReservedTestExt2.Extensions.do,
SwiftReservedTestExt2.Extensions.nil
]
// Extension Objects - The only reason these might be needed is when manually
// constructing a `SimpleExtensionMap`, otherwise, use the above _Extension Properties_
// accessors for the extension fields on the messages directly.
/// Will get _p added because it has no package/swift prefix to scope and
/// would otherwise be a problem when added to the message.
let Extensions_debugDescription = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1000,
fieldName: "debugDescription"
)
/// These will get _p added for the same reasoning.
let Extensions_as = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1012,
fieldName: "as"
)
let Extensions_var = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1013,
fieldName: "var"
)
let Extensions_try = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1014,
fieldName: "try"
)
let Extensions_do = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1015,
fieldName: "do"
)
let Extensions_nil = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1016,
fieldName: "nil"
)
extension SwiftReservedTestExt2 {
enum Extensions {
static let hashValue_ = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1001,
fieldName: "SwiftReservedTestExt2.hashValue"
)
/// Reserved words, since these end up in the "enum Extensions", they
/// can't just be get their names, and sanitation kicks.
static let `as` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1022,
fieldName: "SwiftReservedTestExt2.as"
)
static let `var` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1023,
fieldName: "SwiftReservedTestExt2.var"
)
static let `try` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1024,
fieldName: "SwiftReservedTestExt2.try"
)
static let `do` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1025,
fieldName: "SwiftReservedTestExt2.do"
)
static let `nil` = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_SwiftReservedTest.TypeMessage>(
_protobuf_fieldNumber: 1026,
fieldName: "SwiftReservedTestExt2.nil"
)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
extension SwiftReservedTestExt2: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = "SwiftReservedTestExt2"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: SwiftReservedTestExt2, rhs: SwiftReservedTestExt2) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 41.654795 | 179 | 0.763812 |
1caf8d9cea86448d7fb117f888b6e56c4eecbac9 | 2,941 | //
// DayListController.swift
// ImageDocker
//
// Created by Kelvin Wong on 2018/10/19.
// Copyright © 2018年 nonamecat. All rights reserved.
//
import Cocoa
class DayListController : NSObject {
var onClick: ((_ day:String) -> Void)? = nil
var days:[String] = []
var lastSelectedRow:Int? {
didSet {
if lastSelectedRow != nil {
let day:String = self.days[lastSelectedRow!]
if onClick != nil {
onClick!(day)
}
}
}
}
}
extension DayListController : NSTableViewDelegate {
// return view for requested column.
func tableView(_ tableView: NSTableView,
viewFor tableColumn: NSTableColumn?,
row: Int) -> NSView? {
if row > (self.days.count - 1) {
return nil
}
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.groupingSize = 3
let info:String = self.days[row]
//print(info)
var value = ""
//var tip: String? = nil
if let id = tableColumn?.identifier {
switch id {
case NSUserInterfaceItemIdentifier("day"):
value = info
default:
break
}
let colView = tableView.makeView(withIdentifier: id, owner: nil) as! NSTableCellView
colView.textField?.stringValue = value;
colView.textField?.lineBreakMode = .byWordWrapping
// if row == tableView.selectedRow {
// lastSelectedRow = row
// } else {
// lastSelectedRow = nil
// }
return colView
}
return nil
}
func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) {
//guard let tableView = tableView as? CustomTableView else { return }
// rowView.backgroundColor = row % 2 == 1
// ? NSColor.white
// : NSColor.lightGray
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
lastSelectedRow = row
return true
}
func tableView(_ tableView:NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
let myCustomView = CustomRowView()
return myCustomView
}
}
extension DayListController : NSTableViewDataSource {
/// table size is one row per image in the images array
func numberOfRows(in tableView: NSTableView) -> Int {
return self.days.count
}
// table sorting by column contents
func tableView(_ tableView: NSTableView,
sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
}
}
| 29.41 | 96 | 0.538252 |
0aee70c45134d242f7bce7007493ac85447b7a8c | 559 | import RxSwift
import RxCocoa
import Action
import Presentations
class StubPresentingViewModel<Presenter: AnyObject>: PresentingViewModel {
let isActive = BehaviorRelay(value: true)
weak var presenter: Presenter?
let context = BehaviorRelay<Bool?>(value: nil)
private(set) lazy var presentViewModel: Action<Bool, StubViewModel> = makePresentAction { [unowned self] animated -> DismissablePresentationContext<StubViewModel> in
self.context.accept(animated)
return DismissablePresentationContext.stub()
}
}
| 27.95 | 169 | 0.745975 |
9c40112b369638e4e31292d81a84033a6dc5cb29 | 981 | //
// ViewController.swift
// Segues
//
// Created by Jay Clark on 2/23/18.
// Copyright © 2018 Jay Clark. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
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.
}
@IBAction func buttonPressed(_ sender: Any) {
performSegue(withIdentifier: "goToSecondScreen", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToSecondScreen" {
let destinationVC = segue.destination as! SecondViewController
destinationVC.textPassedOver = textField.text
}
}
}
| 24.525 | 80 | 0.644241 |
2f8f0d5dc7546b687e2375a449f60008831674ee | 751 | //
// HasOnlyReadOnly.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct HasOnlyReadOnly: Codable, Hashable {
public private(set) var bar: String?
public private(set) var foo: String?
public init(bar: String? = nil, foo: String? = nil) {
self.bar = bar
self.foo = foo
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case bar
case foo
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(bar, forKey: .bar)
try container.encodeIfPresent(foo, forKey: .foo)
}
}
| 21.457143 | 67 | 0.652463 |
d9d2f4fe074bf73c5ef0069163d1417dab0d5a93 | 1,912 | //
// ProximityManager.swift
// Beiwe
//
// Created by Keary Griffin on 4/2/16.
// Copyright © 2016 Rocketfarm Studios. All rights reserved.
//
import Foundation
import PromiseKit
class ProximityManager : DataServiceProtocol {
let storeType = "proximity";
let headers = ["timestamp", "event"]
var store: DataStorage?;
@objc func proximityStateDidChange(_ notification: Notification){
// The stage did change: plugged, unplugged, full charge...
var data: [String] = [ ];
data.append(String(Int64(Date().timeIntervalSince1970 * 1000)));
data.append(UIDevice.current.proximityState ? "NearUser" : "NotNearUser");
self.store?.store(data);
self.store?.flush();
}
func initCollecting() -> Bool {
store = DataStorageManager.sharedInstance.createStore(storeType, headers: headers);
return true;
}
func startCollecting() {
log.info("Turning \(storeType) collection on");
UIDevice.current.isProximityMonitoringEnabled = true;
NotificationCenter.default.addObserver(self, selector: #selector(self.proximityStateDidChange), name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil)
AppEventManager.sharedInstance.logAppEvent(event: "proximity_on", msg: "Proximity collection on")
}
func pauseCollecting() {
log.info("Pausing \(storeType) collection");
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceProximityStateDidChange, object:nil)
store!.flush();
AppEventManager.sharedInstance.logAppEvent(event: "proximity_off", msg: "Proximity collection off")
}
func finishCollecting() -> Promise<Void> {
log.info("Finish collecting \(storeType) collection");
pauseCollecting();
store = nil;
return DataStorageManager.sharedInstance.closeStore(storeType);
}
}
| 36.769231 | 175 | 0.6909 |
d917613bf9d11c97ada550f42128af992a635ee3 | 3,646 | //
// CoronavirusTrackerTests.swift
// CoronavirusTrackerTests
//
// Created by Александр Федоров on 25.04.2020.
// Copyright © 2020 Personal. All rights reserved.
//
import XCTest
@testable import CoronavirusTracker
final class CoronavirusTrackerTests: XCTestCase {
private var webservice = WebService()
private var dateFormatter = DateFormatter()
override func setUpWithError() throws {
webservice = WebService()
dateFormatter.dateFormat = "M/dd/yy"
}
func testCountryStatsRequest() throws {
let expectation = self.expectation(description: "load country stats")
let url = URL(string: "https://corona.lmao.ninja/v2/countries/ru")!
let resource = Resource<CountryStats>(url: url) { (data) -> CountryStats? in
return try? JSONDecoder().decode(CountryStats.self, from: data)
}
let result = CountryStats(country: "Russia", cases: 0, todayCases: 0, deaths: 0, todayDeaths: 0, recovered: 0)
var countryStats: CountryStats?
webservice.load(resource) { stats in
countryStats = stats
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(countryStats?.country, result.country)
}
func testParseDateString() {
let date = dateFormatter.date(from: "4/25/20")!
let result = DateHelper.dateString(date: date)
XCTAssertEqual("4/25/20", result)
}
func testParseDate() {
let date = dateFormatter.date(from: "4/25/20")
let result = DateHelper.date(dateString: "4/25/20")
XCTAssertEqual(date, result)
}
func testDayBeforeToday() {
let yesterdayDateString = "4/25/20"
let yesterdayDate = dateFormatter.date(from: yesterdayDateString)!
let result = DateHelper.dayBeforToday(count: 1)!
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .day))
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .month))
XCTAssertTrue(Calendar.current.isDate(yesterdayDate, equalTo: result, toGranularity: .year))
}
func testPositiveTrend() {
let cases = [
"4/24/20": 10,
"4/25/20": 20]
let timeline = HistoryData.Timeline(cases: cases,
deaths: [:],
recovered: [:])
let history = HistoryData(country: "", timeline: timeline)
let stats = CountryStats(country: "",
cases: 0,
todayCases: 15,
deaths: 0,
todayDeaths: 0,
recovered: 0)
let result = TrendHelper.calculateTrend(history, stats)
XCTAssertEqual(result, "📈")
}
func testNegativeTrend() {
let cases = [
"4/24/20": 10,
"4/25/20": 20]
let timeline = HistoryData.Timeline(cases: cases,
deaths: [:],
recovered: [:])
let history = HistoryData(country: "", timeline: timeline)
let stats = CountryStats(country: "",
cases: 0,
todayCases: 5,
deaths: 0,
todayDeaths: 0,
recovered: 0)
let result = TrendHelper.calculateTrend(history, stats)
XCTAssertEqual(result, "📉")
}
}
| 33.759259 | 118 | 0.554032 |
5bd1266f82adc228aa5f40f0ed78970a5d655323 | 2,885 | //
// P6_FlaredEllipse.swift
// Fabula
//
// Created by jasu on 2021/09/06.
// Copyright (c) 2021 jasu All rights reserved.
//
import SwiftUI
public struct P6_FlaredEllipse: View {
let spacing: CGFloat = 20
public init() {}
public var body: some View {
HStack(spacing: spacing) {
VStack(spacing: spacing) {
getView("1")
getView("2")
}
HStack(spacing: spacing) {
VStack(spacing: spacing) {
getView("3")
getView("4")
}
getView("5")
}
}
.padding(.vertical, spacing * 3)
.padding(.horizontal, spacing)
}
private func getView(_ text: String) -> some View {
FlaredEllipse {
Text(text)
.font(.title2)
.foregroundColor(Color.fabulaFore1)
}
}
}
fileprivate
struct FlaredEllipse<Content>: View where Content: View {
var backgroundColor: Color = Color(hex: 0x232834).opacity(0.8)
var intensity: CGFloat = 0.5
var gradient = Gradient(colors: [
Color.white,
Color(hex: 0xA85F89),
Color(hex: 0xA85F89).opacity(0)
])
@ViewBuilder var content: () -> Content
var body: some View {
ZStack {
Ellipse()
.fill(backgroundColor)
.overlay(
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
LinearGradient(gradient: gradient, startPoint: .topLeading, endPoint: .bottomTrailing)
.mask(
Ellipse()
)
.opacity(0.12)
LinearGradient(gradient: gradient, startPoint: .topLeading, endPoint: .bottomTrailing)
.mask(
Ellipse()
.strokeBorder(lineWidth: 1)
)
.opacity(0.6)
}
.mask(
LinearGradient(gradient: Gradient(colors: [
Color.black,
Color.black.opacity(0),
Color.black.opacity(0)
]), startPoint: .topLeading, endPoint: .bottomTrailing)
)
}
.opacity(intensity)
)
content()
}
}
}
struct P6_FlaredEllipse_Previews: PreviewProvider {
static var previews: some View {
P6_FlaredEllipse().preferredColorScheme(.dark)
}
}
| 30.368421 | 114 | 0.431196 |
5d86f25716a5962f0eb5fec11a94128cf934c8f6 | 2,457 | //
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
/// core.v1.PersistentVolumeStatus
///
import Foundation
public extension core.v1 {
///
/// PersistentVolumeStatus is the current status of a persistent volume.
///
struct PersistentVolumeStatus: KubernetesResource {
///
/// A human-readable message indicating details about why the volume is in this state.
///
public var message: String?
///
/// Phase indicates if a volume is available, bound to a claim, or released by a claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#phase
///
public var phase: String?
///
/// Reason is a brief CamelCase string that describes any failure and is meant for machine parsing and tidy display in the CLI.
///
public var reason: String?
///
/// Default memberwise initializer
///
public init(
message: String? = nil,
phase: String? = nil,
reason: String? = nil
) {
self.message = message
self.phase = phase
self.reason = reason
}
}
}
///
/// Codable conformance
///
public extension core.v1.PersistentVolumeStatus {
private enum CodingKeys: String, CodingKey {
case message = "message"
case phase = "phase"
case reason = "reason"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.message = try container.decodeIfPresent(String.self, forKey: .message)
self.phase = try container.decodeIfPresent(String.self, forKey: .phase)
self.reason = try container.decodeIfPresent(String.self, forKey: .reason)
}
func encode(to encoder: Encoder) throws {
var encodingContainer = encoder.container(keyedBy: CodingKeys.self)
try encodingContainer.encode(message, forKey: .message)
try encodingContainer.encode(phase, forKey: .phase)
try encodingContainer.encode(reason, forKey: .reason)
}
}
| 28.905882 | 169 | 0.722426 |
f784541785e2fd6fdbdbf6e88e7a672dfb5bc81c | 2,345 | //
// SwitchCell.swift
// Model2App
//
// Created by Karol Kulesza on 7/12/18.
// Copyright © 2018 Q Mobile { http://Q-Mobile.IT }
//
//
// 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
/**
* Property cell with a switch control for presenting boolean property values
*/
open class SwitchCell : PropertyCell<Bool> {
// MARK: -
// MARK: Properties & Constants
/// Switch control for presenting boolean property values
open var switchControl: UISwitch!
// MARK: -
// MARK: Initializers & Deinitializers
deinit {
switchControl.removeTarget(self, action: nil, for: .valueChanged)
}
// MARK: -
// MARK: BaseCell Methods
override open func addViews() {
super.addViews()
switchControl = UISwitch()
switchControl.addTarget(self, action: #selector(switchChanged), for: .valueChanged)
accessoryView = switchControl
editingAccessoryView = accessoryView
}
override open func update() {
super.update()
switchControl.isOn = value ?? false
switchControl.isEnabled = isInEditMode
}
// MARK: -
// MARK: Action Methods
@objc func switchChanged() {
valueChanged?(switchControl?.isOn ?? false)
}
}
| 31.266667 | 91 | 0.681876 |
5b522fcda6da8c16f828429ffd4b056c205eb480 | 2,668 | //
// Publisher.swift
// CEPCombine
//
// Created by Isaac Douglas on 19/09/19.
// Copyright © 2019 Isaac Douglas. All rights reserved.
//
import Foundation
import Combine
extension Publisher {
private func pairwise() -> Publishers.Map<Publishers.Filter<Self>, (Output, Output)> {
var previous: Output? = nil
let pair = self
.filter({ element in
if previous == nil {
previous = element
return false
} else {
return true
}
})
.map({ element -> (Output, Output) in
defer { previous = element }
return (previous!, element)
})
return pair
}
public func followedBy(predicate: @escaping (Self.Output, Self.Output) -> Bool) -> Publishers.Filter<Publishers.Map<Publishers.Filter<Self>, (Self.Output, Self.Output)>> {
return pairwise().filter(predicate)
}
public func subscribe(completion: @escaping ((Self.Output) -> Void)) {
_ = self
.receive(on: RunLoop.main)
.sink(receiveCompletion: { _ in }, receiveValue: completion)
}
public func merge<T: Publisher>(with stream: T, completion: @escaping ((Self.Output, T.Output) -> Void)) where T.Failure == Self.Failure {
let first = self
.map({ $0 as Any })
let second = stream
.map({ $0 as Any })
first
.merge(with: second)
.collect(2)
.subscribe(completion: { values in
guard
let f = values.first(where: { $0 is Self.Output }).map({ $0 as! Self.Output }),
let s = values.first(where: { $0 is T.Output }).map({ $0 as! T.Output })
else { return }
completion(f, s)
})
}
public func duplicate(_ count: Int = 2) -> [Self] {
return (0 ..< count)
.map({ _ in self })
}
public func group<T: Sequence, Key: Hashable>(by keyForValue: @escaping ((T.Element) throws -> Key)) -> Publishers.Map<Self, [[T.Element]]> where T == Self.Output {
return self
.map({ values -> [[T.Element]] in
let dictionary = try! Dictionary(grouping: values, by: keyForValue)
return dictionary.map({ $0.value })
})
}
public func order<T: Sequence>(by: @escaping ((T.Element, T.Element) -> Bool)) -> Publishers.Map<Self, [T.Element]> where T == Self.Output {
return self
.map({ $0.sorted(by: by) })
}
}
| 33.35 | 175 | 0.514993 |
dd9ad8f4bb53600b97667f866ca353802df20e2e | 10,661 | //
// The MIT License (MIT)
//
// Copyright © 2019 NoodleOfDeath. All rights reserved.
// NoodleOfDeath
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
/// Specifications for a `FileExplorerTableViewCell` delegate.
@objc
public protocol FileExplorerTableViewCellDelegate: class {
/// Called when a table view cell is tapped by the user.
@objc optional
func didRecognize(singleTapGesture: UITapGestureRecognizer, in cell: FileExplorerTableViewCell)
/// Called when a table view cell is double tapped by the user.
@objc optional
func didRecognize(doubleTapGesture: UITapGestureRecognizer, in cell: FileExplorerTableViewCell)
/// Called when a table view cell is pressed and held by the user.
@objc optional
func didRecognize(longPressGesture: UILongPressGestureRecognizer, in cell: FileExplorerTableViewCell)
}
/// Custom table view cell to be displayed by a file explorer.
/// Usually displays file/directory name.
@objc
open class FileExplorerTableViewCell: UITableViewCell {
// MARK: - Instance Properties
/// Delegate fileExplorer object.
open weak var delegate: FileExplorerTableViewCellDelegate?
/// Edge insets of this cell.
open var edgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: -10.0, right: -10.0)
/// Main image of this cell.
open var iconImage: UIImage? {
didSet { drawIcon() }
}
/// Image view tint color of this cell.
open var iconTintColor: UIColor = .black {
didSet { drawIcon() }
}
/// Image view alpha of this cell.
open var iconAlpha: CGFloat = 1.0 {
didSet { drawIcon() }
}
open var iconShadow: NSShadow? {
didSet { drawIcon() }
}
/// Title of this cell.
open var title: String? {
get { return titleLabel.text }
set { titleLabel.text = newValue }
}
/// Secondary title of this cell.
open var secondaryTitle: String? {
get { return secondaryTitleLabel.text }
set { secondaryTitleLabel.text = newValue }
}
/// Subtitle of this table view cell.
/// Usually displays file size/file count.
open var leftSubtitle: String? {
get { return leftSubtitleLabel.text }
set { leftSubtitleLabel.text = newValue }
}
/// Subsubtitle of this table view cell.
/// Usually displays the date modified.
open var rightSubtitle: String? {
get { return rightSubtitleLabel.text }
set { rightSubtitleLabel.text = newValue }
}
/// Displays the info accessory button.
open var displayInfoAccessory: Bool = false {
didSet { layoutIfNeeded() }
}
/// Color of the title label of this table view cell.
open var titleColor: UIColor = .black {
didSet { titleLabel.textColor = titleColor }
}
/// Select gesture recognizer of this table view cell.
open lazy var singleTapGesture: UITapGestureRecognizer = {
let gesture =
UITapGestureRecognizer(target: self,
action: #selector(didRecognize(singleTapGesture:)))
gesture.numberOfTapsRequired = 1
gesture.delegate = self
return gesture
}()
/// Double tap gesture recognizer of this table view cell.
open lazy var doubleTapGesture: UITapGestureRecognizer = {
let gesture =
UITapGestureRecognizer(target: self,
action: #selector(didRecognize(doubleTapGesture:)))
gesture.numberOfTapsRequired = 2
gesture.delegate = self
return gesture
}()
/// Long press gesture recognizer of this table view cell.
open lazy var longPressGesture: UILongPressGestureRecognizer = {
let gesture =
UILongPressGestureRecognizer(target: self,
action: #selector(didRecognize(longPressGesture:)))
gesture.minimumPressDuration = 0.3
gesture.delegate = self
return gesture
}()
// MARK: - UI Components
/// Bar button item view of this table view cell.
open var barButtonItem: UIBarButtonItem {
return UIBarButtonItem(customView: accessoryView ?? UIView())
}
/// Stack view of this table view cell.
fileprivate lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.spacing = 10.0
return stackView
}()
/// Custom image view of this table view cell.
fileprivate lazy var iconView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
/// Center view of this table view cell.
fileprivate lazy var mainContentView: UIView = {
let view = UIStackView()
view.axis = .vertical
view.addArrangedSubview(titleView)
view.addArrangedSubview(subtitleView)
return view
}()
/// Title view of this cell.
fileprivate lazy var titleView: UIView = {
let view = UIStackView()
view.addArrangedSubview(titleLabel)
view.addArrangedSubview(secondaryTitleLabel)
return view
}()
/// Meta view of this cell.
fileprivate lazy var subtitleView: UIView = {
let view = UIStackView()
view.addArrangedSubview(leftSubtitleLabel)
view.addArrangedSubview(rightSubtitleLabel)
return view
}()
/// Title label of this cell.
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.adjustsFontSizeToFitWidth = true
label.lineBreakMode = .byTruncatingMiddle
return label
}()
/// Secondary title label of this cell.
fileprivate lazy var secondaryTitleLabel: UILabel = {
let label = UILabel()
label.adjustsFontSizeToFitWidth = true
label.lineBreakMode = .byTruncatingMiddle
return label
}()
/// Subtitle label of this cell.
fileprivate lazy var leftSubtitleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: UIFont.systemFontSize * 0.75)
return label
}()
/// Subsubtitle label of this cell.
fileprivate lazy var rightSubtitleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.font = .systemFont(ofSize: UIFont.systemFontSize * 0.75)
return label
}()
// MARK: - UIView Methods
override open func draw(_ rect: CGRect) {
super.draw(rect)
addGestureRecognizer(singleTapGesture)
addGestureRecognizer(doubleTapGesture)
addGestureRecognizer(longPressGesture)
contentView.addSubview(stackView)
stackView.snp.makeConstraints { (dims) in
dims.top.equalTo(contentView)
dims.left.equalTo(contentView).offset(15.0)
dims.bottom.equalTo(contentView)
dims.right.equalTo(contentView).offset(-15.0)
}
stackView.addArrangedSubview(iconView)
iconView.snp.makeConstraints { (dims) in
dims.width.equalTo(iconImage != nil ? 40.0 : 0.0)
}
stackView.addArrangedSubview(mainContentView)
}
override open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return
gestureRecognizer == singleTapGesture &&
(otherGestureRecognizer == doubleTapGesture || otherGestureRecognizer == longPressGesture)
}
override open func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if editing {
removeGestureRecognizer(singleTapGesture)
removeGestureRecognizer(doubleTapGesture)
removeGestureRecognizer(longPressGesture)
} else {
addGestureRecognizer(singleTapGesture)
addGestureRecognizer(doubleTapGesture)
addGestureRecognizer(longPressGesture)
}
}
}
// MARK: - Event Handler Methods
extension FileExplorerTableViewCell {
@objc
/// Called when a double tap gesture is recognized by this cell.
///
/// - Parameters:
/// - doubleTapGesture: The long press gesture recognizer.
fileprivate func didRecognize(singleTapGesture: UITapGestureRecognizer) {
delegate?.didRecognize?(singleTapGesture: doubleTapGesture, in: self)
}
@objc
/// Called when a double tap gesture is recognized by this cell.
///
/// - Parameters:
/// - doubleTapGesture: The long press gesture recognizer.
fileprivate func didRecognize(doubleTapGesture: UITapGestureRecognizer) {
delegate?.didRecognize?(doubleTapGesture: doubleTapGesture, in: self)
}
@objc
/// Called when a long press gesture is recognized by this cell.
///
/// - Parameters:
/// - longPressGesture: The long press gesture recognizer.
fileprivate func didRecognize(longPressGesture: UILongPressGestureRecognizer) {
delegate?.didRecognize?(longPressGesture: longPressGesture, in: self)
}
}
// MARK: - Instance Methods
extension FileExplorerTableViewCell {
fileprivate func drawIcon() {
var attributes = [UIImage.CGAttribute: Any]()
attributes[.tintColor] = iconTintColor
attributes[.alpha] = iconAlpha
attributes[.shadow] = iconShadow
iconView.image = iconImage?.with(attributes: attributes)
}
}
| 34.060703 | 160 | 0.653597 |
48982387046d5849c536f3a202250eb1b242a6f5 | 1,278 | import UIKit
extension UIColor
{
convenience init(rgba: String)
{
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
let alpha: CGFloat = 1.0
if rgba.hasPrefix("#")
{
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue)
{
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
}
else
{
print("scan hex error, your string should be a hex string of 7 chars. ie: #ebb100")
}
}
else
{
print("invalid rgb string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
class func adjustValue(color: UIColor, percentage: CGFloat = 1.5) -> UIColor
{
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return UIColor(hue: h, saturation: s, brightness: (b * percentage), alpha: a)
}
} | 26.081633 | 91 | 0.579812 |
eb55ce6f5a3aae57054d47449260f31c943dfada | 2,855 | //
// BWDiplayText.swift
// Bike 2 Work
//
// Created by Douglas Barreto on 1/27/16.
// Copyright © 2016 Douglas Mendes. All rights reserved.
//
import Foundation
import UIKit
public class BWDiplayTextBikeToWorkOption : BWDisplayText
{
// public static let hourStartName = "$hourStart";
// public static let hourEndName = "$hourEnd";
// public static let temperatureStartName = "$temperatureStart";
// public static let temperatureEndName = "$temperatureEnd";
// public static let humidityStartName = "$humidityStart";
// public static let humidityEndName = "$humidityEnd";
private let userSettings:UserSettings;
override init(title: String, rawText: String) {
userSettings = UserSettings.sharedInstance;
super.init(title: title, rawText:rawText);
}
override public func updateText() ->NSMutableAttributedString
{
let hToBike = userSettings.hourToBike;
let humidity = userSettings.humidity;
let temperature = userSettings.temperature;
var tempPlainText = NSMutableAttributedString(string: stringText);
var tempTitle = NSMutableAttributedString(string: titleAttInfo.text);
displayText = NSMutableAttributedString();
StringHelper.replaceVariableNameToLinkString(
kHourStartName,
valueToAdd: hToBike.getStartHoursFormated(),
attString: &tempPlainText);
StringHelper.replaceVariableNameToLinkString(
kHourEndName,
valueToAdd:hToBike.getEndHoursFormated(),
attString: &tempPlainText);
StringHelper.replaceVariableNameToLinkString(
kTemperatureStartName,
valueToAdd: temperature.start.getGraus(),
attString: &tempPlainText);
StringHelper.replaceVariableNameToLinkString(
kTemperatureEndName,
valueToAdd: temperature.end.getGraus(),
attString: &tempPlainText);
StringHelper.replaceVariableNameToLinkString(
kHumidityStartName,
valueToAdd: humidity.getStartHumidityFormated(),
attString: &tempPlainText);
StringHelper.replaceVariableNameToLinkString(
kHumidityEndName,
valueToAdd: humidity.getEndtHumidityFormated(),
attString: &tempPlainText);
StringHelper.addAtributeTo(
string: &tempPlainText,
attributes: textAttInfo.getAttributes());
StringHelper.addAtributeTo(
string: &tempTitle,
attributes: titleAttInfo.getAttributes());
displayText.appendAttributedString(tempTitle);
displayText.appendAttributedString(tempPlainText);
return displayText;
}
} | 34.39759 | 77 | 0.647636 |
c12989aa5411d34ea64199132df4d2f3848d03ad | 405 | //
// Cornucopia – (C) Dr. Lauer Information Technology
//
#if !os(Linux)
import Foundation
extension URL: _CornucopiaCoreStorageBackend {
public func object<T: Decodable>(for key: String) -> T? {
self.CC_queryExtendedAttribute(for: key)
}
public func set<T: Encodable>(_ value: T?, for key: String) {
self.CC_storeAsExtendedAttribute(item: value, for: key)
}
}
#endif
| 22.5 | 65 | 0.671605 |
019bc2fa9641a9ddabc711b4dea082c21a72e67b | 2,029 | import Foundation
import UIKit
struct DeviceEnvironment {
private let stableIDKey = "com.Statsig.InternalStore.stableIDKey"
var deviceOS: String = "iOS"
var sdkType: String = "ios-client"
var sdkVersion: String = "1.7.1"
var sessionID: String? { UUID().uuidString }
var systemVersion: String { UIDevice.current.systemVersion }
var systemName: String { UIDevice.current.systemName }
var language: String { Locale.preferredLanguages[0] }
var locale: String { Locale.current.identifier }
var appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
var appIdentifier = Bundle.main.bundleIdentifier
var deviceModel: String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
return simulatorModelIdentifier
}
var sysinfo = utsname()
uname(&sysinfo)
if let deviceModel = String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii) {
return deviceModel.trimmingCharacters(in: .controlCharacters)
} else {
return UIDevice.current.model
}
}
func getStableID(_ overrideStableID: String? = nil) -> String {
let stableID = overrideStableID ?? UserDefaults.standard.string(forKey: stableIDKey) ?? UUID().uuidString
UserDefaults.standard.setValue(stableID, forKey: stableIDKey)
return stableID
}
func get(_ overrideStableID: String? = nil) -> [String: String?] {
return [
"appIdentifier": appIdentifier,
"appVersion": appVersion,
"deviceModel": deviceModel,
"deviceOS": deviceOS,
"language": language,
"locale": locale,
"sdkType": sdkType,
"sdkVersion": sdkVersion,
"sessionID": sessionID,
"stableID": getStableID(overrideStableID),
"systemVersion": systemVersion,
"systemName": systemName
]
}
}
| 36.890909 | 119 | 0.644653 |
891ec8ddb265dffa5b274938d9c2ab784d38aabf | 1,197 | //
// Message.swift
// programmeerproject
//
// Created by Ayanna Colden on 12/01/2017.
// Copyright © 2017 Ayanna Colden. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class Message: NSObject {
var fromId: String?
var text: String?
var timestamp: NSNumber?
var toId: String?
var imageUrl: String?
var imageHeight: NSNumber?
var imageWidth: NSNumber?
var imagePicked: UIImage?
var videoUrl: String?
func chatPartnerId() -> String? {
return fromId == FIRAuth.auth()?.currentUser?.uid ? toId : fromId
}
init(dictionary: [String: AnyObject]) {
super.init()
fromId = dictionary["fromId"] as? String
text = dictionary["text"] as? String
timestamp = dictionary["timestamp"] as? NSNumber
toId = dictionary["toId"] as? String
imageUrl = dictionary["imageUrl"] as? String
imageHeight = dictionary["imageHeight"] as? NSNumber
imageWidth = dictionary["imageWidth"] as? NSNumber
imagePicked = dictionary["imagePicked"] as? UIImage
videoUrl = dictionary["videoUrl"] as? String
}
}
| 24.428571 | 73 | 0.619883 |
cc12077ae2d48ce646d8d978414c44d4c8efedf8 | 6,310 | //
// ListViewController.swift
// Rocket.Chat
//
// Created by Vladimir Boyko on 14/09/2019.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import UIKit
import SwiftyJSON
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
struct Item {
let name: String
let price: Double
}
let items: Array<Item> = [Item(name: "Блин с ветчиной", price: 120) ,Item(name: "Грибной крем-суп", price: 300) , Item(name: "Апельсиновый сок", price: 80), Item(name: "Пицца Маргарита", price: 500),Item(name:"Картофель фри", price: 125) , Item(name: "Куриная котлета", price: 150)]
@IBOutlet var sumLabel: UILabel?
@IBOutlet var tableView: UITableView?
@IBAction func buttonClicked() {
let activityView = UIActivityIndicatorView(style: .whiteLarge)
activityView.center = self.view.center
activityView.startAnimating()
self.view.addSubview(activityView)
let selection = tableView?.visibleCells.map({ (cell) -> String in
let text = cell.textLabel?.text ?? ""
if cell.isHighlighted == true {
return text
}
return ""
}).filter({$0.count > 0 })
let text = "Были выбраны: \(selection?.joined(separator: ", ") ?? "") Итого: \(sumLabel!.text!)"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ListReady"), object: self, userInfo: ["text": text])
let json: [String: Any] = ["addresses": [],
"deviceId": "test_device_id",
"deviceType": 1]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://89.208.84.235:31080/api/v1/session")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("32852185-988b-4de6-8df3-7dd340942cf0", forHTTPHeaderField: "FPSID")
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
guard let sum = sumLabel!.text?.components(separatedBy: " ")[0], let cur = Double(sum) else {return}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
let json: [String: Any] = [ "amount": cur,
"currencyCode": 810,
"description": "test description",
"number": JSON(responseJSON)["data"].rawString()!,
"payer": "ab0ae25f2dfb1832961f051e0050087fd9d76885",
"recipient": "3c63a8ea371fa1c582cb6f158f8c8be7cf17cba5"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://89.208.84.235:31080/api/v1/invoice")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("32852185-988b-4de6-8df3-7dd340942cf0", forHTTPHeaderField: "FPSID")
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
let session = URLSession(configuration: sessionConfig)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
DispatchQueue.main.async {
activityView.stopAnimating()
self.dismiss(animated: true, completion: nil)
}
}
}
task.resume()
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
view.isOpaque = false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
cell.textLabel?.text = items[indexPath.item].name
cell.detailTextLabel?.text = String(items[indexPath.item].price)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.isHighlighted = !(tableView.cellForRow(at: indexPath)?.isHighlighted ?? true)
if let title = sumLabel!.text?.components(separatedBy: " ")[0], let cur = Double(title) {
sumLabel!.text = "\(cur + items[indexPath.item].price) ₽"
}
}
}
| 41.513158 | 286 | 0.56767 |
7130f972efbfcee6e37854f08803fadef0d90a1c | 1,600 | //
// NEOAsset.swift
// O3
//
// Created by Apisit Toompakdee on 1/23/18.
// Copyright © 2018 drei. All rights reserved.
//
import UIKit
import NeoSwift
import Cache
enum AssetType: Int, Codable {
case nativeAsset = 0
case nep5Token
}
extension TransferableAsset {
var formattedBalanceString: String {
let amountFormatter = NumberFormatter()
amountFormatter.minimumFractionDigits = self.decimal
amountFormatter.numberStyle = .decimal
amountFormatter.locale = Locale.current
amountFormatter.usesGroupingSeparator = true
return String(format: "%@", amountFormatter.string(from: NSDecimalNumber(decimal: self.balance))!)
}
}
struct TransferableAsset: Codable {
var assetID: String!
var name: String!
var symbol: String!
var assetType: AssetType! = AssetType.nativeAsset //default to this
var decimal: Int!
var balance: Decimal! = 0.0
}
extension TransferableAsset {
static func NEO() -> TransferableAsset {
return TransferableAsset(
assetID: NeoSwift.AssetId.neoAssetId.rawValue,
name: "NEO",
symbol: "NEO",
assetType: AssetType.nativeAsset,
decimal: 0,
balance: Decimal(O3Cache.neoBalance()))
}
static func GAS() -> TransferableAsset {
return TransferableAsset(
assetID: NeoSwift.AssetId.gasAssetId.rawValue,
name: "GAS",
symbol: "GAS",
assetType: AssetType.nativeAsset,
decimal: 8,
balance: Decimal(O3Cache.gasBalance()))
}
}
| 26.666667 | 106 | 0.643125 |
ab337979a857b350a37b6eaf358a6d1d12d760c9 | 4,325 | //
// AATransitioningDelegate.swift
// uchain
//
// Created by Fxxx on 2018/11/14.
// Copyright © 2018 Fxxx. All rights reserved.
//
import UIKit
public class AATransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
private var isPresented = true
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresented = true
return self
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresented = false
return self
}
// public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// return self
// }
//
// public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// return self
// }
}
//extension AATransitioningDelegate: UIViewControllerInteractiveTransitioning {
// public func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
//
// }
//}
extension AATransitioningDelegate: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresented {
animationForPresented(using: transitionContext)
} else {
animationForDissmissed(using: transitionContext)
}
}
func animationForPresented(using transitionContext: UIViewControllerContextTransitioning) {
let toView = transitionContext.view(forKey: .to)!
transitionContext.containerView.addSubview(toView)
let toCtr = transitionContext.viewController(forKey: .to) as! AAPhotoBrowser
let originalView = toCtr.delegate.photo(of: toCtr.selectedIndex, with: toCtr).originalView
guard originalView != nil else {
transitionContext.completeTransition(true)
return
}
let blackView = UIView.init(frame: UIScreen.main.bounds)
blackView.backgroundColor = UIColor.black
transitionContext.containerView.addSubview(blackView)
let newRect = originalView!.convert(originalView!.bounds, to: nil)
let imageView = UIImageView.init(frame: newRect)
imageView.image = originalView?.image!
imageView.contentMode = originalView!.contentMode
transitionContext.containerView.addSubview(imageView)
UIView.animate(withDuration: toCtr.presentDuration, animations: {
imageView.frame = UIScreen.main.bounds
imageView.contentMode = .scaleAspectFit
}) { (finish) in
imageView.removeFromSuperview()
blackView.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
func animationForDissmissed(using transitionContext: UIViewControllerContextTransitioning) {
let fromCtr = transitionContext.viewController(forKey: .from) as! AAPhotoBrowser
let originalView = fromCtr.delegate.photo(of: fromCtr.selectedIndex, with: fromCtr).originalView
guard originalView != nil else {
transitionContext.completeTransition(true)
return
}
let cell = fromCtr.collectionView.cellForItem(at: IndexPath.init(item: fromCtr.selectedIndex, section: 0)) as! AAPhotoCell
let showView = cell.imageView!
transitionContext.containerView.addSubview(showView)
let newRect = originalView!.convert(originalView!.bounds, to: nil)
UIView.animate(withDuration: fromCtr.dissmissDuration, animations: {
showView.frame = newRect
fromCtr.view.backgroundColor = UIColor.clear
}) { (finish) in
transitionContext.completeTransition(true)
}
}
}
| 36.965812 | 177 | 0.684624 |
618f07d5e92993d26f3fa86c435b881d025e77ca | 6,605 | //
// ThemeManager.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-04-12.
//
// ---------------------------------------------------------------------------
//
// © 2014-2020 1024jp
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AppKit
@objc protocol ThemeHolder: AnyObject {
func changeTheme(_ sender: AnyObject?)
}
// MARK: -
final class ThemeManager: SettingFileManaging {
typealias Setting = Theme
// MARK: Public Properties
static let shared = ThemeManager()
// MARK: Setting File Managing Properties
static let directoryName: String = "Themes"
let filePathExtensions: [String] = DocumentType.theme.extensions
let settingFileType: SettingFileType = .theme
private(set) var settingNames: [String] = []
private(set) var bundledSettingNames: [String] = []
var cachedSettings: [String: Setting] = [:]
// MARK: -
// MARK: Lifecycle
private init() {
// cache bundled setting names
self.bundledSettingNames = Bundle.main.urls(forResourcesWithExtension: self.filePathExtension, subdirectory: Self.directoryName)!
.map { self.settingName(from: $0) }
.sorted(options: [.localized, .caseInsensitive])
// cache user setting names
self.checkUserSettings()
}
// MARK: Public Methods
/// default setting by taking the appearance state into consideration
var defaultSettingName: String {
let defaultSettingName = DefaultSettings.defaults[.theme] as! String
let forDark = self.usesDarkAppearance
return self.equivalentSettingName(to: defaultSettingName, forDark: forDark)!
}
/// user default setting by taking the appearance state into consideration
var userDefaultSettingName: String {
let settingName = UserDefaults.standard[.theme]!
if UserDefaults.standard[.pinsThemeAppearance] || NSAppKitVersion.current <= .macOS10_13 {
return settingName
}
if let equivalentSettingName = self.equivalentSettingName(to: settingName, forDark: self.usesDarkAppearance) {
return equivalentSettingName
}
guard self.settingNames.contains(settingName) else { return self.defaultSettingName }
return settingName
}
/// save setting file
func save(setting: Setting, name: String, completionHandler: @escaping (() -> Void) = {}) throws {
// create directory to save in user domain if not yet exist
try self.prepareUserSettingDirectory()
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(setting)
let fileURL = self.preparedURLForUserSetting(name: name)
try data.write(to: fileURL, options: .atomic)
self.cachedSettings[name] = setting
self.updateCache { [weak self] in
self?.notifySettingUpdate(oldName: name, newName: name)
completionHandler()
}
}
/// create a new untitled setting
func createUntitledSetting(completionHandler: @escaping ((_ settingName: String) -> Void) = { _ in }) throws {
let name = self.savableSettingName(for: "Untitled".localized)
try self.save(setting: Setting(), name: name) {
completionHandler(name)
}
}
/// return whether given setting name is dark theme
func isDark(name: String) -> Bool {
return name.range(of: "(Dark)", options: [.anchored, .backwards]) != nil
}
/// return setting name of dark/light version of given one if any exists
func equivalentSettingName(to name: String, forDark: Bool) -> String? {
let baseName: String
if let range = name.range(of: "^.+(?= \\((?:Dark|Light)\\)$)", options: .regularExpression) {
baseName = String(name[range])
} else {
baseName = name
}
let settingName = baseName + " " + (forDark ? "(Dark)" : "(Light)")
if self.settingNames.contains(settingName) {
return settingName
}
if !forDark, self.settingNames.contains(baseName) {
return baseName
}
return nil
}
// MARK: Setting File Managing
/// load setting from the file at given URL
func loadSetting(at fileURL: URL) throws -> Setting {
return try Theme.theme(contentsOf: fileURL)
}
/// load settings in the user domain
func checkUserSettings() {
// get user setting names if exists
let userSettingNames = self.userSettingFileURLs
.map { self.settingName(from: $0) }
.sorted(options: [.localized, .caseInsensitive])
self.settingNames = (self.bundledSettingNames + userSettingNames).unique
// reset user default if not found
if let userSetting = UserDefaults.standard[.theme],
!self.settingNames.contains(userSetting)
{
UserDefaults.standard.restore(key: .theme)
}
}
// MARK: Private Methods
/// Whether user prefers using dark mode window.
private var usesDarkAppearance: Bool {
switch UserDefaults.standard[.documentAppearance] {
case .default:
guard #available(macOS 10.14, *) else { return false }
// -> NSApperance.current doesn't return the latest appearance when the system appearance
// was changed after the app launch (macOS 10.14).
return NSApp.effectiveAppearance.isDark
case .light:
return false
case .dark:
return true
}
}
}
| 29.886878 | 137 | 0.595458 |
142fe2ccb929dea9c5e6d02e167802a5df956f86 | 269 | public extension Svg {
static var crosshair: Svg {
.icon([
Circle(cx: 12, cy: 12, r: 10),
Line(x1: 22, y1: 12, x2: 18, y2: 12),
Line(x1: 6, y1: 12, x2: 2, y2: 12),
Line(x1: 12, y1: 6, x2: 12, y2: 2),
Line(x1: 12, y1: 22, x2: 12, y2: 18),
])
}
}
| 22.416667 | 40 | 0.505576 |
db5ce27801a946861da19bcbca3acac2b0e12fc3 | 5,393 | import Foundation
import Marketcloud
//Manages the Cart and the objects in the cart when retrieved from the server
open class Cart {
open static var lastCart:NSDictionary? = nil
open static var products = [Product]()
open static var cartId:Int = -1
open static func elabCartItems() {
// print("Starting elabCartItems")
// print("Before crash : lastCart is \(lastCart)")
let cartDataItems:NSDictionary = (lastCart!["data"]! as! NSDictionary)
let cartItems:NSArray = cartDataItems["items"] as! NSArray
//let cartItems:NSArray = (lastCart!.value(forKey: "data") as! NSDictionary).value(forKey: "items") as! NSArray
//let cartId:Int = (cart.value(forKey: "data") as! NSDictionary).value(forKey: "id") as! Int
let itemsCount:Int = cartItems.count
for i in 0 ..< itemsCount {
let temp:NSDictionary = cartItems[i] as! NSDictionary
guard temp.value(forKey: "id") != nil else {
continue
}
let tempId:Int = temp.value(forKey: "id") as! Int
temp.value(forKey: "description")
var tempDescription:String = "No description available"
if (temp.value(forKey: "description") != nil) {
tempDescription = temp["description"]! as! String
}
guard temp.value(forKey: "name") != nil else {
continue
}
let tempName:String = temp.value(forKey: "name") as! String
var tempImages = [String]()
if (temp.value(forKey: "images") == nil) {
} else {
tempImages = temp["images"]! as! [String]
}
var hasVariants:Bool = false
if (temp.value(forKey: "has_variants") != nil) {
hasVariants = temp.value(forKey: "has_variants") as! Bool
}
guard temp.value(forKey: "price") != nil else {
continue
}
let tempPrice:Double = temp["price"]! as! Double
guard temp.value(forKey: "quantity") != nil else {
continue
}
let quantity:Int = temp.value(forKey: "quantity") as! Int
let product = Product(id: tempId, description: tempDescription, name: tempName, images: tempImages, price: tempPrice, quantity: quantity, hasVariants: hasVariants)
products.append(product)
}
// print("Products in cart")
// dump(products)
}
//sets a new cart (or an updated one)
open static func refreshCart(_ cart:NSDictionary) {
// print("Refreshing cart. New Cart is :")
// print(cart)
lastCart = cart;
products.removeAll()
guard (lastCart!["id"] != nil) else {
cartId = (lastCart!["data"]! as! NSDictionary)["id"] as! Int
elabCartItems()
return
}
cartId = lastCart!["id"] as! Int
elabCartItems()
}
//get a cart from the server
open static func getCart() {
lastCart = (MarketcloudMain.getMcloud()?.getCart())!
guard (lastCart!["errors"] == nil) else {
print("users had no cart. Creating one...")
lastCart = (MarketcloudMain.getMcloud()?.createEmptyCart())!
let cartDatas:NSDictionary = lastCart!["data"]! as! NSDictionary
cartId = cartDatas["id"] as! Int
// print("cart id is \(cartId)")
return
}
let cartDatas:NSDictionary = lastCart!["data"]! as! NSDictionary
cartId = cartDatas["id"] as! Int
// print("cart id is \(cartId)")
// print("Calling elabCartItems")
// print("But first, let me call lastCart!")
elabCartItems()
}
//calculates the total from the items in the cart
open static func calcTotal() -> Double {
// print("calc Total")
let itemsTotal = products.count
// print("Items total is \(itemsTotal)")
var total:Double = 0
for i in 0 ..< itemsTotal {
total += (products[i].price! * Double(products[i].quantity!))
}
return total
}
/*
generates a text with a recap of all the items in cart
*/
open static func generateTextRecap() -> String {
var ret:String = ""
let itemsTotal = products.count
for i in 0 ..< itemsTotal {
ret += "Item: \(products[i].name!) - Quantity \(products[i].quantity!)\n"
ret += "price: \(products[i].price! * Double(products[i].quantity!))\n\n"
}
return ret
}
//empties the cart (server-side)
open static func emptyCart() {
var itemArray = [Any]()
let itemsTotal = products.count
for i in 0 ..< itemsTotal {
if(products[i].hasVariants!) {
itemArray.append(["product_id":products[i].id!,"variant_id":1])
} else {
itemArray.append(["product_id":products[i].id!])
}
}
let newCart = MarketcloudMain.getMcloud()?.removeFromCart(Cart.cartId, data: itemArray)
refreshCart(newCart!)
}
}
| 35.715232 | 175 | 0.533655 |
dec3703c608e2aa50c4fd51cac04cfc4b8b88f97 | 117 | import XCTest
import RocketTests
var tests = [XCTestCaseEntry]()
tests += RocketTests.__allTests()
XCTMain(tests)
| 13 | 33 | 0.769231 |
1cbed5de5d5617ed562e589167874eca83be41e2 | 172 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ProfilePlaceholderViewTests.allTests),
]
}
#endif
| 17.2 | 55 | 0.697674 |
7a8594e95ad4ef8687d46e76027750361db78ffb | 8,358 | //
// YYTTagView.swift
// YouTag
//
// Created by Youstanzr Alqattan on 3/12/20.
// Copyright © 2020 Youstanzr Alqattan. All rights reserved.
//
import UIKit
protocol YYTTagViewDelegate: class {
func tagsListChanged(newTagsList: NSMutableArray)
}
class YYTTagView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, UIGestureRecognizerDelegate {
weak var yytdelegate: YYTTagViewDelegate?
var addTagPlaceHolder: String!
var isAddEnabled: Bool!
var isDeleteEnabled: Bool!
var tagsList: NSMutableArray! {
didSet {
print(selectedTagList)
selectedTagList.removeAllObjects()
print(selectedTagList)
}
}
var selectedTagList = NSMutableArray()
var isEditing: Bool = false
init(frame: CGRect, tagsList: NSMutableArray, isAddEnabled: Bool, isMultiSelection: Bool, isDeleteEnabled: Bool) {
super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
self.register(YYTTagCell.self, forCellWithReuseIdentifier: "TagCell")
self.delegate = self
self.dataSource = self
self.layer.cornerRadius = 5
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.lightGray.cgColor
self.backgroundColor = UIColor.clear
self.allowsMultipleSelection = isMultiSelection
self.isAddEnabled = isAddEnabled
self.isDeleteEnabled = isDeleteEnabled
self.tagsList = tagsList
let tap = UITapGestureRecognizer(target: self, action: #selector(UIView.endEditing(_:)))
tap.cancelsTouchesInView = false
self.addGestureRecognizer(tap)
if isDeleteEnabled {
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
lpgr.minimumPressDuration = 0.5
lpgr.delegate = self
self.addGestureRecognizer(lpgr)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func removeTag(at index: Int) {
if isAddEnabled {
self.selectedTagList.remove(tagsList.object(at: index - 1))
self.tagsList.removeObject(at: index - 1)
} else {
self.selectedTagList.remove(tagsList.object(at: index))
self.tagsList.removeObject(at: index)
}
yytdelegate?.tagsListChanged(newTagsList: self.tagsList)
self.reloadData()
}
func removeAllTags() {
self.tagsList.removeAllObjects()
self.selectedTagList.removeAllObjects()
yytdelegate?.tagsListChanged(newTagsList: self.tagsList)
self.reloadData()
}
func deselectAllTags() {
guard let selectedItems = indexPathsForSelectedItems else { return }
for indexPath in selectedItems { collectionView(self, didDeselectItemAt: indexPath) }
self.selectedTagList.removeAllObjects()
}
// MARK: Long Press Gesture Recognizer
@objc func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != .began {
return
}
let p = gestureReconizer.location(in: self)
let indexPath = self.indexPathForItem(at: p)
//check if the long press was into the collection view or the cells
if let index = indexPath {
if !isAddEnabled || index.row != 0 {
let tagCell = self.cellForItem(at: index) as! YYTTagCell
let tagTitle = tagCell.titleLabel.text ?? ""
let actionSheet = UIAlertController(title: "Are you sure to delete '\(tagTitle)'?", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
actionSheet.addAction(UIAlertAction(title: "Delete", style: .default, handler:{ (UIAlertAction) in
print("User requested delete for tag: \(tagTitle)")
self.removeTag(at: index.row)
}))
let currentController = self.getCurrentViewController()
currentController?.present(actionSheet, animated: true, completion: nil)
}
} else {
let actionSheet = UIAlertController(title: "Are you sure to delete all tags?", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
actionSheet.addAction(UIAlertAction(title: "Delete", style: .default, handler:{ (UIAlertAction) in
print("User requested delete for all tags")
self.removeAllTags()
}))
let currentController = self.getCurrentViewController()
currentController?.present(actionSheet, animated: true, completion: nil)
}
}
// MARK: Collection View
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return isAddEnabled ? tagsList.count+1:tagsList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tagCell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as! YYTTagCell
tagCell.textField.delegate = self
if isAddEnabled && indexPath.row == 0 {
tagCell.backgroundColor = GraphicColors.green
tagCell.layer.borderColor = GraphicColors.darkGreen.cgColor
tagCell.titleLabel.textColor = .white
tagCell.titleLabel.text = "+"
tagCell.titleLabel.font = UIFont.init(name: "DINCondensed-Bold", size: 24)
tagCell.textField.textColor = .white
tagCell.textField.placeholder = addTagPlaceHolder
tagCell.textField.font = UIFont.init(name: "DINCondensed-Bold", size: 16)
} else {
tagCell.backgroundColor = .clear
tagCell.titleLabel.textColor = .darkGray
tagCell.titleLabel.font = UIFont.init(name: "DINCondensed-Bold", size: 16)
tagCell.textField.textColor = .darkGray
tagCell.textField.font = UIFont.init(name: "DINCondensed-Bold", size: 16)
tagCell.layer.borderColor = GraphicColors.orange.cgColor
let index = isAddEnabled ? indexPath.row - 1 : indexPath.row
tagCell.titleLabel.text = tagsList.object(at: index) as? String
}
return tagCell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if isAddEnabled && indexPath.row == 0 {
let cellSize = isEditing ? CGSize(width: 90, height: 32):CGSize(width: 30, height: 32)
isEditing = false
return cellSize
}
let index = isAddEnabled ? indexPath.row - 1 : indexPath.row
var titleWidth = (tagsList.object(at: index) as! String).estimateSizeWidth(font: UIFont.init(name: "DINCondensed-Bold", size: 16)!, padding: 32.0 / 1.5)
titleWidth = titleWidth > collectionView.frame.width * 0.475 ? collectionView.frame.width * 0.475:titleWidth
return CGSize(width: titleWidth, height: 32)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: 5, left: 5, bottom: 5, right: 5)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! YYTTagCell
if isAddEnabled && indexPath.row == 0 {
print("Add Tag Button tapped")
isEditing = true
cell.switchMode(enableEditing: true)
collectionView.performBatchUpdates(nil, completion: nil)
} else if self.allowsMultipleSelection {
cell.backgroundColor = .orange
selectedTagList.add(cell.titleLabel.text!)
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if self.allowsMultipleSelection {
let cell = collectionView.cellForItem(at: indexPath) as! YYTTagCell
cell.backgroundColor = .white
selectedTagList.remove(cell.titleLabel.text!)
}
}
// MARK: UITextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text != "" {
if tagsList.contains(textField.text!.capitalized) {
let alert = UIAlertController(title: "Duplicate Tag", message: nil, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler:{ (UIAlertAction) in
textField.becomeFirstResponder()
}))
self.getCurrentViewController()?.present(alert, animated: true, completion: nil)
return
}
tagsList.add(textField.text!.capitalized)
self.reloadData()
}
(textField.superview?.superview as! YYTTagCell).switchMode(enableEditing: false)
self.performBatchUpdates(nil, completion: nil)
}
}
| 39.424528 | 176 | 0.752931 |
fffdb605e9869bb3c09ede132f4a3fdeaa967233 | 6,216 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import TSCBasic
import TSCUtility
import PackageModel
import PackageGraph
import SPMTestSupport
import SourceControl
import Workspace
final class PinsStoreTests: XCTestCase {
let v1: Version = "1.0.0"
func testBasics() throws {
let fooPath = AbsolutePath("/foo")
let barPath = AbsolutePath("/bar")
let foo = PackageIdentity(path: fooPath)
let bar = PackageIdentity(path: barPath)
let fooRepo = RepositorySpecifier(url: fooPath.pathString)
let barRepo = RepositorySpecifier(url: barPath.pathString)
let revision = Revision(identifier: "81513c8fd220cf1ed1452b98060cd80d3725c5b7")
let fooRef = PackageReference.remote(identity: foo, location: fooRepo.url)
let barRef = PackageReference.remote(identity: bar, location: barRepo.url)
let state = CheckoutState(revision: revision, version: v1)
let pin = PinsStore.Pin(packageRef: fooRef, state: state)
// We should be able to round trip from JSON.
XCTAssertEqual(try PinsStore.Pin(json: pin.toJSON()), pin)
let fs = InMemoryFileSystem()
let pinsFile = AbsolutePath("/pinsfile.txt")
var store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
// Pins file should not be created right now.
XCTAssert(!fs.exists(pinsFile))
XCTAssert(store.pins.map{$0}.isEmpty)
store.pin(packageRef: fooRef, state: state)
try store.saveState()
XCTAssert(fs.exists(pinsFile))
// Load the store again from disk.
let store2 = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
// Test basics on the store.
for s in [store, store2] {
XCTAssert(s.pins.map{$0}.count == 1)
XCTAssertEqual(s.pinsMap[bar], nil)
let fooPin = s.pinsMap[foo]!
XCTAssertEqual(fooPin.packageRef, fooRef)
XCTAssertEqual(fooPin.state.version, v1)
XCTAssertEqual(fooPin.state.revision, revision)
XCTAssertEqual(fooPin.state.description, v1.description)
}
// We should be able to pin again.
store.pin(packageRef: fooRef, state: state)
store.pin(
packageRef: fooRef,
state: CheckoutState(revision: revision, version: "1.0.2")
)
store.pin(packageRef: barRef, state: state)
try store.saveState()
store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
XCTAssert(store.pins.map{$0}.count == 2)
// Test branch pin.
do {
store.pin(
packageRef: barRef,
state: CheckoutState(revision: revision, branch: "develop")
)
try store.saveState()
store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
let barPin = store.pinsMap[bar]!
XCTAssertEqual(barPin.state.branch, "develop")
XCTAssertEqual(barPin.state.version, nil)
XCTAssertEqual(barPin.state.revision, revision)
XCTAssertEqual(barPin.state.description, "develop")
}
// Test revision pin.
do {
store.pin(packageRef: barRef, state: CheckoutState(revision: revision))
try store.saveState()
store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
let barPin = store.pinsMap[bar]!
XCTAssertEqual(barPin.state.branch, nil)
XCTAssertEqual(barPin.state.version, nil)
XCTAssertEqual(barPin.state.revision, revision)
XCTAssertEqual(barPin.state.description, revision.identifier)
}
}
func testLoadingSchema1() throws {
let fs = InMemoryFileSystem()
let pinsFile = AbsolutePath("/pinsfile.txt")
try fs.writeFileContents(pinsFile) {
$0 <<< """
{
"object": {
"pins": [
{
"package": "Clang_C",
"repositoryURL": "https://github.com/something/Clang_C.git",
"state": {
"branch": null,
"revision": "90a9574276f0fd17f02f58979423c3fd4d73b59e",
"version": "1.0.2",
}
},
{
"package": "Commandant",
"repositoryURL": "https://github.com/something/Commandant.git",
"state": {
"branch": null,
"revision": "c281992c31c3f41c48b5036c5a38185eaec32626",
"version": "0.12.0"
}
}
]
},
"version": 1
}
"""
}
let store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
XCTAssertEqual(store.pinsMap.keys.map { $0.description }.sorted(), ["clang_c", "commandant"])
}
func testEmptyPins() throws {
let fs = InMemoryFileSystem()
let pinsFile = AbsolutePath("/pinsfile.txt")
let store = try PinsStore(pinsFile: pinsFile, fileSystem: fs)
try store.saveState()
XCTAssertFalse(fs.exists(pinsFile))
let fooPath = AbsolutePath("/foo")
let foo = PackageIdentity(path: fooPath)
let fooRef = PackageReference.remote(identity: foo, location: fooPath.pathString)
let revision = Revision(identifier: "81513c8fd220cf1ed1452b98060cd80d3725c5b7")
store.pin(packageRef: fooRef, state: CheckoutState(revision: revision, version: v1))
XCTAssert(!fs.exists(pinsFile))
try store.saveState()
XCTAssert(fs.exists(pinsFile))
store.unpinAll()
try store.saveState()
XCTAssertFalse(fs.exists(pinsFile))
}
}
| 36.564706 | 101 | 0.583333 |
2871e950ba2d39bd32781c27ae96793dd90ab29f | 4,186 | //
// GKItemViewController.swift
// MySwiftObject
//
// Created by wangws1990 on 2019/9/10.
// Copyright © 2019 wangws1990. All rights reserved.
//
import UIKit
class GKNovelItemController: BaseViewController {
var chapter :NSInteger = 0
var pageIndex:NSInteger = 0
var content:GKNovelContent!
var emptyData : Bool = false
lazy var tryButton : UIButton = {
var button : UIButton = UIButton.init()
button.layer.masksToBounds = true
button.layer.cornerRadius = 18
button.setBackgroundImage(UIImage.imageWithColor(color: AppColor), for: .normal);
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.setTitleColor(Appxffffff, for: .normal)
button.setTitle("点击重试", for: .normal)
button.isHidden = true
return button;
}()
private lazy var titleLab: UILabel = {
var label :UILabel = UILabel.init();
label.textColor = UIColor.init(hex: "999999");
label.font = UIFont.systemFont(ofSize:12);
return label
}()
private lazy var subTitleLab: UILabel = {
var subTitleLab :UILabel = UILabel.init();
subTitleLab.textColor = UIColor.init(hex: "999999");
subTitleLab.font = UIFont.systemFont(ofSize: 12);
subTitleLab.textAlignment = .right;
return subTitleLab
}()
private lazy var loadLab: UILabel = {
var label : UILabel = UILabel.init();
label.font = UIFont.systemFont(ofSize: 18);
label.textColor = Appx999999;
label.textAlignment = .center;
label.text = "数据加载中...";
return label;
}()
private lazy var readView: GKNovelView = {
var readView = GKNovelView.init(frame: BaseMacro.init().AppFrame)
readView.backgroundColor = UIColor.clear;
return readView
}()
private lazy var mainView: UIImageView = {
let mainView : UIImageView = UIImageView.init();
return mainView;
}()
func emptyData(empty : Bool){
self.emptyData = true;
self.loadLab.text = "数据空空如也.."
self.tryButton.isHidden = true;
}
func setModel(model:GKNovelContent, chapter:NSInteger, pageIndex:NSInteger){
self.content = model;
self.pageIndex = pageIndex;
self.chapter = chapter;
self.readView.content = model.attContent(page: pageIndex)
self.titleLab.text = model.title;
self.subTitleLab.text = String(pageIndex+1) + "/" + String(model.pageCount);
let res : Bool = self.readView.content.string.count == 0 ? false : true
self.tryButton.isHidden = res
self.loadLab.isHidden = res
self.loadLab.text = "数据加载失败..."
}
private func setThemeUI(){
self.mainView.image = GKNovelSetManager.defaultSkin();
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.mainView);
self.mainView.snp.makeConstraints { (make) in
make.edges.equalToSuperview();
}
self.view.addSubview(self.readView);
self.view.addSubview(self.titleLab);
self.view.addSubview(self.subTitleLab);
self.view.addSubview(self.loadLab);
self.view.addSubview(self.tryButton);
self.titleLab.snp.makeConstraints { (make) in
make.top.equalTo(BaseMacro.init().STATUS_BAR_HIGHT - 5);
make.left.equalTo(20);
}
self.subTitleLab.snp.makeConstraints { (make) in
make.right.equalTo(-20);
make.centerY.equalTo(self.titleLab);
make.left.equalTo(self.titleLab.snp.right).offset(-20);
}
self.loadLab.snp.makeConstraints { (make) in
make.centerX.centerY.equalToSuperview();
}
self.tryButton.snp.makeConstraints { (make) in
make.centerX.equalToSuperview();
make.top.equalTo(self.loadLab.snp.bottom).offset(20);
make.width.equalTo(120);
make.height.equalTo(36);
}
self.setThemeUI();
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
self.readView.frame = BaseMacro.init().AppFrame;
}
}
| 36.4 | 89 | 0.623746 |
f9814c7ce42450e7a8020bf4553cd64b8316c350 | 1,206 | //
// CoreData.swift
// pitsh
//
// Created by Ruben Zilibowitz on 19/12/21.
//
import CoreData
import Foundation
private let coreDataContainer = CoreDataContainer(name: "Pitsh")
struct CoreData {
var persistentContainer: () -> CoreDataContainer = const(coreDataContainer)
func getDocument() throws -> PitshDocument {
var doc: PitshDocument? = nil
let moc = persistentContainer().viewContext
try moc.performAndWait {
let fetchRequest: NSFetchRequest<PitshDocument> = PitshDocument.fetchRequest()
let documents = try fetchRequest.execute()
guard documents.count < 2 else {
throw NSError(domain: "Too many documents", code: 1, userInfo: nil)
}
if let result = documents.first {
doc = result
}
else {
guard let aDocument = NSEntityDescription.insertNewObject(forEntityName: "PitshDocument", into: moc) as? PitshDocument else {
throw NSError(domain: "Failed to create document", code: 1, userInfo: nil)
}
aDocument.title = "Pitsh Song"
aDocument.setupAudioFiles()
if moc.hasChanges {
try moc.save()
}
doc = aDocument
}
}
return doc!
}
}
| 28.046512 | 133 | 0.650912 |
46752c7d1be38ce83d7be2e4257f1a9733d91d6b | 844 | // RUN: %target-swift-frontend -enable-experimental-differentiable-programming -typecheck -verify %s
// Tests that Sema fails gracefully when the `Differentiable` protocol is missing.
// expected-error @+2 {{parameter type 'Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
// expected-error @+1 {{result type 'Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable (Float) -> Float
// expected-error @+2 {{parameter type 'T' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
// expected-error @+1 {{result type 'T' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
func hasDifferentiableFunctionArg<T>(_ f: @differentiable (T) -> T) {}
| 70.333333 | 139 | 0.748815 |
1c07925f326a6dcc180e40ccf4e4485c8a3bc478 | 2,822 | // RUN: %target-swift-emit-silgen -g -Xllvm -sil-print-debuginfo %s | %FileCheck %s
func nop1() {}
func nop2() {}
enum Binary {
case On
case Off
}
func isOn(_ b: Binary) -> Bool {
return b == .On
}
// CHECK: [[LOC:loc "[^"]+"]]
// First, check that we don't assign fresh locations to each case statement,
// except for any relevant debug value instructions.
// CHECK-LABEL: sil hidden @$s16switch_debuginfo5test11iySi_tF
func test1(i: Int) {
switch i {
// CHECK-NOT: [[LOC]]:[[@LINE+1]]
case 0: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
// CHECK-NOT: [[LOC]]:[[@LINE-1]]
nop1()
// CHECK-NOT: [[LOC]]:[[@LINE+1]]
case 1: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
// CHECK-NOT: [[LOC]]:[[@LINE-1]]
nop1()
default: // CHECK-NOT: [[LOC]]:[[@LINE]]
nop1()
}
}
// Next, check that case statements and switch subjects have the same locations.
// CHECK-LABEL: sil hidden @$s16switch_debuginfo5test21sySS_tF
func test2(s: String) {
switch s {
case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
nop1()
case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
nop2()
default:
nop1()
}
}
// Fallthrough shouldn't affect case statement locations.
// CHECK-LABEL: sil hidden @$s16switch_debuginfo5test31sySS_tF
func test3(s: String) {
switch s {
case "a", "b":
// CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-2]]:10
// CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
nop1()
fallthrough
case "b", "c":
// CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-7]]:10
// CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE-8]]:10
nop2()
fallthrough
default:
nop1()
}
}
// It should be possible to set breakpoints on where clauses.
// CHECK-LABEL: sil hidden @$s16switch_debuginfo5test41byAA6BinaryO_tF
func test4(b: Binary) {
switch b {
case let _ // CHECK-NOT: [[LOC]]:[[@LINE]]
where isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11
nop1()
case let _ // CHECK-NOT: [[LOC]]:[[@LINE]]
where !isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11
nop2()
default:
nop1()
}
}
// Check that we set the right locations before/after nested switches.
// CHECK-LABEL: sil hidden @$s16switch_debuginfo5test51sySS_tF
func test5(s: String) {
switch s {
case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
switch "b" {
case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-1]]:12
nop1()
default:
nop2()
}
if "c" == "c" { // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE]]
nop1()
}
default:
nop1()
}
if "d" == "d" { // CHECK: string_literal utf8 "d", [[LOC]]:[[@LINE]]
nop1()
}
}
| 26.87619 | 85 | 0.568746 |
56edaac2e1faba0d01caf64090a213b8bcdea9b4 | 5,942 | import Foundation
import Cache
import CryptoKit
import Debug
public protocol Requestable: Codable {
associatedtype P: NetworkParameters
static var decoder: ResponseDecoder { get }
static var method: RequestMethod { get }
/// The scheme subcomponent of the URL. Defaults to "https"
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding).
/// Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
/// Attempting to set the scheme with an invalid scheme string will cause an exception.
static var scheme: String { get }
/// The host subcomponent. Example: "www.apple.com"
///
/// - Attention: Don't include any path separators.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding).
/// Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
static var host: String { get }
/// The path subcomponent.
///
/// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding).
/// Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
static func path(given parameters: P) -> URLPath?
static func headers(given parameters: P) -> [String: String]?
static func handle(response: URLResponse, data: Data?) -> Error?
static func generateId(given parameters: P) -> String
}
public extension Requestable {
static var scheme: String { "https" }
static var decoder: ResponseDecoder { JSONDecoder() }
static func url(given parameters: P) -> URL {
var components = URLComponents()
components.scheme = scheme
components.host = host
components.path = path(given: parameters)?.pathString ?? ""
guard let url = components.url else {
fatalError("Failed to create valid URL. \(dump(components))")
}
return url
}
}
extension Requestable {
public static func headers(given parameters: P) -> [String: String]? { nil }
public static func fetch(given parameters: P, delegate: RequestDelegateConfig?, with networkManager: NetworkManagerProvider = NetworkManager.shared, dataCallback: @escaping (Self) -> Void) {
let requestTask = Self.requestTask(given: parameters, delegate: delegate, dataCallback: dataCallback)
if let cacheable = Self.self as? Cacheable.Type {
let isExpired = (try? networkManager.isObjectExpired(for: requestTask.id)) ?? true
if isExpired {
networkManager.enqueue(requestTask)
}
else if case .success(let data) = cacheable.cachedData(type: Self.self, for: requestTask.id, with: networkManager) {
dataCallback(data)
}
else {
networkManager.enqueue(requestTask)
}
} else {
networkManager.enqueue(requestTask)
}
}
/// Create a URLSessionNetworkTask for a request response.
/// - Parameter parameters: The parameters for the network response.
/// - Returns: A URL session task. (QueueableTask)
public static func requestTask(given parameters: P, delegate: RequestDelegateConfig?, dataCallback: ((Self) -> Void)?) -> QueueableTask {
URLSessionNetworkTask(
method: method,
url: url(given: parameters),
parameters: parameters,
headers: headers(given: parameters),
cachePolicy: (Self.self as? Cacheable.Type)?.cachePolicy,
dataCallback: dataCallback,
delegate: delegate
)
}
public static func generateId(given parameters: P) -> String {
let urlString = url(given: parameters).absoluteString
guard
let encodedParameters = try? JSONEncoder().encode(parameters),
let hash = try? SHA256.hash(data: JSONEncoder().encode([method.rawValue, urlString, String(decoding: encodedParameters, as: UTF8.self)]))
else {
Debug.log(
level: .error,
"Failed to runtime agnostically hash a URLSessionNetworkTask id. Falling back to Hasher().",
params: [
"Response Type": "\(Self.self)",
"Parameters Type": "\(P.self)",
"URL": "\(urlString)",
"method": method.rawValue,
]
)
var hasher = Hasher()
hasher.combine(method)
hasher.combine(urlString)
hasher.combine(parameters)
return "\(urlString) | \(hasher.finalize())"
}
let stringHash = hash.map { String(format: "%02hhx", $0) }.joined()
return "\(urlString) | \(stringHash)"
}
}
extension Requestable where P == NoParameters {
/// Create a URLSessionNetworkTask for a request response without any parameter requirements.
/// - Returns: The URL session task. (QueueableTask)
public static func requestTask(delegate: RequestDelegateConfig?, dataCallback: @escaping (_ data: Self) -> Void) -> QueueableTask {
requestTask(given: .none, delegate: delegate, dataCallback: dataCallback)
}
}
public enum RequestMethod: String {
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
case trace = "TRACE"
case options = "OPTIONS"
case connect = "CONNECT"
case patch = "PATCH"
}
| 41.552448 | 194 | 0.635813 |
ff6f5b4dad7be07f14da3bfac16d8cdc8ac68079 | 3,076 | //
// UserSettingsTableViewController.swift
// Balapoint
//
// Created by David S on 8/19/18.
// Copyright © 2018 David S. All rights reserved.
// Allows user to view settings.
import UIKit
import Firebase
protocol UserSettingTableViewControllerDelegate {
func updateUserSettings()
}
class UserSettingsTableViewController: UITableViewController {
var delegate: UserSettingTableViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Settings"
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "Futura", size: 18)!]
setBackButton()
}
// @IBAction func goToTermsPage(_ sender: Any) {
// if let url = URL(string: "https://www.balapoint.com/terms.html") {
// UIApplication.shared.open(url, options: [:])
// }
// }
@IBAction func goToPrivacyPage(_ sender: Any) {
if let url = URL(string: "https://app.termly.io/document/privacy-policy/e0616598-966c-4640-82f6-442bfc25f28b") {
UIApplication.shared.open(url, options: [:])
}
}
// Logout
@IBAction func logoutBtn_TouchUpInside(_ sender: Any) {
AuthService.logout(onSuccess: {
let storyboard = UIStoryboard(name: "Start", bundle: nil)
let signInVC = storyboard.instantiateViewController(withIdentifier: "SignInViewController")
self.present(signInVC, animated: true, completion: nil)
}) { (errorMessage) in
print("ERROR: \(String(describing: errorMessage))")
}
}
// Delete Account
@IBAction func deleteAccount_TouchUpInside(_ sender: Any) {
let controller = UIAlertController(title:"Are you sure?", message: "Deleting your account will delete your posts and information.", preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Yes, I'm sure.", style: .destructive, handler: { (_) in
let user = Auth.auth().currentUser
user?.delete { error in
if let error = error {
print("There was an error deleting this user: \(error)")
} else {
Auth.auth().currentUser?.delete()
print("Successfully deleted account")
let storyboard = UIStoryboard(name: "Start", bundle: nil)
let signInVC = storyboard.instantiateViewController(withIdentifier: "SignInViewController")
self.present(signInVC, animated: true, completion: nil)
}
}
}))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(controller, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
// override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return
// }
}
| 37.512195 | 169 | 0.631339 |
f8e2c559402fc1799da82fa32c76a7c5cf81d751 | 1,466 | import Dispatch
/**
A protocol for any type-erased function.
*/
public protocol AnyFunction: AnyDefinition {
/**
Name of the function. JavaScript refers to the function by this name.
*/
var name: String { get }
/**
Bool value indicating whether the function takes promise as the last argument.
*/
var takesPromise: Bool { get }
/**
An array of argument types that the function takes. If the last type is `Promise`, it's not included.
*/
var argumentTypes: [AnyArgumentType] { get }
/**
A number of arguments the function takes. If the last argument is of type `Promise`, it is not counted.
*/
var argumentsCount: Int { get }
/**
Dispatch queue on which each function's call is run.
*/
var queue: DispatchQueue? { get }
/**
Whether the function needs to be called asynchronously from JavaScript.
*/
var isAsync: Bool { get }
/**
Calls the function on given module with arguments and a promise.
*/
func call(args: [Any], promise: Promise)
/**
Synchronously calls the function with given arguments. If the function takes a promise,
the current thread will be locked until the promise rejects or resolves with the return value.
*/
func callSync(args: [Any]) -> Any
/**
Specifies on which queue the function should run.
*/
func runOnQueue(_ queue: DispatchQueue?) -> Self
/**
Makes the JavaScript function synchronous.
*/
func runSynchronously() -> Self
}
| 25.275862 | 106 | 0.680764 |
4a033c5715f7095392ba9b321c011404c39716eb | 15,949 | import UIKit
/// Роутер, показывающий UIPopoverController с UIViewController'ом, обернутым или необернутым в UINavigationController
public protocol PopoverPresentationRouter: class {
// MARK: - UIViewController in UIPopoverController
func presentPopoverFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
func presentPopoverFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverTransitionsAnimator)
func presentPopoverFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
func presentPopoverFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverTransitionsAnimator)
// MARK: - UIViewController in UINavigationController in UIPopoverController
func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator)
func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator,
navigationController: UINavigationController)
func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator)
func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator,
navigationController: UINavigationController)
}
// MARK: - PopoverPresentationRouter Default Impl
extension PopoverPresentationRouter where
Self: RouterTransitionable,
Self: RouterIdentifiable,
Self: TransitionIdGeneratorHolder,
Self: TransitionsHandlersProviderHolder,
Self: RouterControllersProviderHolder
{
// MARK: - UIViewController in UIPopoverController
public func presentPopoverFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
{
presentPopoverFromRect(
rect,
inView: view,
withViewControllerDerivedFrom: deriveViewController,
animator: PopoverTransitionsAnimator()
)
}
public func presentPopoverFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverTransitionsAnimator)
{
let animatingTransitionsHandler = transitionsHandlersProvider.animatingTransitionsHandler()
let animatingTransitionsHandlerBox = RouterTransitionsHandlerBox(
animatingTransitionsHandler: animatingTransitionsHandler
)
let presentingTransitionsHandlerBox = transitionsHandlersProvider.topTransitionsHandlerBox(
transitionsHandlerBox: transitionsHandlerBox
)
let generatedTransitionId = transitionIdGenerator.generateNewTransitionId()
let routerSeed = RouterSeed(
transitionsHandlerBox: animatingTransitionsHandlerBox,
transitionId: generatedTransitionId,
presentingTransitionsHandler: presentingTransitionsHandlerBox.unbox(),
transitionsHandlersProvider: transitionsHandlersProvider,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: controllersProvider
)
let viewController = deriveViewController(routerSeed)
do {
let resetContext = ResettingTransitionContext(
registeringViewController: viewController,
animatingTransitionsHandler: animatingTransitionsHandler,
transitionId: generatedTransitionId
)
animatingTransitionsHandler.resetWithTransition(context: resetContext)
}
let popoverController = UIPopoverController(contentViewController: viewController)
let popoverContext = PresentationTransitionContext(
presentingViewController: viewController,
inPopoverController: popoverController,
fromRect: rect,
inView: view,
targetTransitionsHandler: animatingTransitionsHandler,
animator: animator,
transitionId: generatedTransitionId
)
presentingTransitionsHandlerBox.unbox().performTransition(context: popoverContext)
}
public func presentPopoverFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
{
presentPopoverFromBarButtonItem(
barButtonItem,
withViewControllerDerivedFrom: deriveViewController,
animator: PopoverTransitionsAnimator()
)
}
public func presentPopoverFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverTransitionsAnimator)
{
let animatingTransitionsHandler = transitionsHandlersProvider.animatingTransitionsHandler()
let animatingTransitionsHandlerBox = RouterTransitionsHandlerBox(
animatingTransitionsHandler: animatingTransitionsHandler
)
let presentingTransitionsHandlerBox = transitionsHandlersProvider.topTransitionsHandlerBox(
transitionsHandlerBox: transitionsHandlerBox
)
let generatedTransitionId = transitionIdGenerator.generateNewTransitionId()
let routerSeed = RouterSeed(
transitionsHandlerBox: animatingTransitionsHandlerBox,
transitionId: generatedTransitionId,
presentingTransitionsHandler: presentingTransitionsHandlerBox.unbox(),
transitionsHandlersProvider: transitionsHandlersProvider,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: controllersProvider
)
let viewController = deriveViewController(routerSeed)
do {
let resetContext = ResettingTransitionContext(
registeringViewController: viewController,
animatingTransitionsHandler: animatingTransitionsHandler,
transitionId: generatedTransitionId
)
animatingTransitionsHandler.resetWithTransition(context: resetContext)
}
let popoverController = UIPopoverController(contentViewController: viewController)
let popoverContext = PresentationTransitionContext(
presentingViewController: viewController,
inPopoverController: popoverController,
fromBarButtonItem: barButtonItem,
targetTransitionsHandler: animatingTransitionsHandler,
animator: animator,
transitionId: generatedTransitionId
)
presentingTransitionsHandlerBox.unbox().performTransition(context: popoverContext)
}
// MARK: - UIViewController in UINavigationController in UIPopoverController
public func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
{
presentPopoverWithNavigationControllerFromRect(
rect,
inView: view,
withViewControllerDerivedFrom: deriveViewController,
animator: PopoverNavigationTransitionsAnimator()
)
}
public func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator)
{
presentPopoverWithNavigationControllerFromRect(
rect,
inView: view,
withViewControllerDerivedFrom: deriveViewController,
animator: animator,
navigationController: controllersProvider.navigationController()
)
}
public func presentPopoverWithNavigationControllerFromRect(
_ rect: CGRect,
inView view: UIView,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator,
navigationController: UINavigationController)
{
let navigationTransitionsHandler = transitionsHandlersProvider.navigationTransitionsHandler(
navigationController: navigationController
)
let navigationTransitionsHandlerBox = RouterTransitionsHandlerBox(
animatingTransitionsHandler: navigationTransitionsHandler
)
let presentingTransitionsHandlerBox = transitionsHandlersProvider.topTransitionsHandlerBox(
transitionsHandlerBox: transitionsHandlerBox
)
let generatedTransitionId = transitionIdGenerator.generateNewTransitionId()
let routerSeed = RouterSeed(
transitionsHandlerBox: navigationTransitionsHandlerBox,
transitionId: generatedTransitionId,
presentingTransitionsHandler: presentingTransitionsHandlerBox.unbox(),
transitionsHandlersProvider: transitionsHandlersProvider,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: controllersProvider
)
let viewController = deriveViewController(routerSeed)
do {
let resetContext = ResettingTransitionContext(
settingRootViewController: viewController,
forNavigationController: navigationController,
animatingTransitionsHandler: navigationTransitionsHandler,
animator: SetNavigationTransitionsAnimator(),
transitionId: generatedTransitionId
)
navigationTransitionsHandler.resetWithTransition(context: resetContext)
}
let popoverController = UIPopoverController(contentViewController: navigationController)
let popoverContext = PresentationTransitionContext(
presentingViewController: viewController,
inNavigationController: navigationController,
inPopoverController: popoverController,
fromRect: rect,
inView: view,
targetTransitionsHandler: navigationTransitionsHandler,
animator: animator,
transitionId: generatedTransitionId
)
presentingTransitionsHandlerBox.unbox().performTransition(context: popoverContext)
}
public func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController)
{
presentPopoverWithNavigationControllerFromBarButtonItem(
barButtonItem,
withViewControllerDerivedFrom: deriveViewController,
animator: PopoverNavigationTransitionsAnimator()
)
}
public func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator)
{
presentPopoverWithNavigationControllerFromBarButtonItem(
barButtonItem,
withViewControllerDerivedFrom: deriveViewController,
animator: animator,
navigationController: controllersProvider.navigationController()
)
}
public func presentPopoverWithNavigationControllerFromBarButtonItem(
_ barButtonItem: UIBarButtonItem,
withViewControllerDerivedFrom deriveViewController: (_ routerSeed: RouterSeed) -> UIViewController,
animator: PopoverNavigationTransitionsAnimator,
navigationController: UINavigationController)
{
let navigationTransitionsHandler = transitionsHandlersProvider.navigationTransitionsHandler(
navigationController: navigationController
)
let navigationTransitionsHandlerBox = RouterTransitionsHandlerBox(
animatingTransitionsHandler: navigationTransitionsHandler
)
let presentingTransitionsHandlerBox = transitionsHandlersProvider.topTransitionsHandlerBox(
transitionsHandlerBox: transitionsHandlerBox
)
let generatedTransitionId = transitionIdGenerator.generateNewTransitionId()
let routerSeed = RouterSeed(
transitionsHandlerBox: navigationTransitionsHandlerBox,
transitionId: generatedTransitionId,
presentingTransitionsHandler: presentingTransitionsHandlerBox.unbox(),
transitionsHandlersProvider: transitionsHandlersProvider,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: controllersProvider
)
let viewController = deriveViewController(routerSeed)
do {
let resetContext = ResettingTransitionContext(
settingRootViewController: viewController,
forNavigationController: navigationController,
animatingTransitionsHandler: navigationTransitionsHandler,
animator: SetNavigationTransitionsAnimator(),
transitionId: generatedTransitionId
)
navigationTransitionsHandler.resetWithTransition(context: resetContext)
}
let popoverController = UIPopoverController(contentViewController: navigationController)
let popoverContext = PresentationTransitionContext(
presentingViewController: viewController,
inNavigationController: navigationController,
inPopoverController: popoverController,
fromBarButtonItem: barButtonItem,
targetTransitionsHandler: navigationTransitionsHandler,
animator: animator,
transitionId: generatedTransitionId
)
presentingTransitionsHandlerBox.unbox().performTransition(context: popoverContext)
}
}
| 42.989218 | 118 | 0.707066 |
d6d8b982531e94495fb8dc4143f9683f13e3767a | 923 | //
// Hidden.swift
// Squash
//
// Created by Cory Kacal on 1/30/20.
// Copyright © 2020 Cory Kacal. All rights reserved.
//
import SwiftUI
import Foundation
extension View {
/// Whether the view is hidden.
/// - Parameter bool: Set to `true` to hide the view. Set to `false` to show the view.
func isHidden(_ bool: Bool) -> some View {
modifier(HiddenModifier(isHidden: bool))
}
}
/// Creates a view modifier that can be applied, like so:
///
/// ```
/// Text("Hello World!")
/// .isHidden(true)
/// ```
///
/// Variables can be used in place so that the content can be changed dynamically.
private struct HiddenModifier: ViewModifier {
fileprivate let isHidden: Bool
fileprivate func body(content: Content) -> some View {
Group {
if isHidden {
content.hidden()
} else {
content
}
}
}
}
| 20.977273 | 90 | 0.588299 |
2f1adc627c69ec4fb2b0cf16e1bcc10a4a1dd1a3 | 6,441 | //
// MalertManager.swift
// Pods
//
// Created by Vitor Mesquita on 01/11/16.
//
//
import UIKit
public class Malert: BaseMalertViewController {
// MARK: - private
private let malertPresentationManager = MalertPresentationManager()
// MARK: - internal
let malertView: MalertView
var malertConstraints: [NSLayoutConstraint] = []
var visibleViewConstraints: [NSLayoutConstraint] = []
let tapToDismiss: Bool
let dismissOnActionTapped: Bool
var completionBlock: (() -> Void)?
lazy var visibleView: UIView = {
let visibleView = UIView()
visibleView.translatesAutoresizingMaskIntoConstraints = false
return visibleView
}()
required init?(coder aDecoder: NSCoder) {
self.malertView = MalertView()
self.tapToDismiss = false
self.dismissOnActionTapped = false
super.init(coder: aDecoder)
}
public init(title: String? = nil, customView: UIView? = nil, tapToDismiss: Bool = true, dismissOnActionTapped: Bool = true) {
self.malertView = MalertView()
self.tapToDismiss = tapToDismiss
self.dismissOnActionTapped = dismissOnActionTapped
super.init(nibName: nil, bundle: nil)
self.malertView.seTitle(title)
self.malertView.setCustomView(customView)
self.animationType = .modalBottom
self.modalPresentationStyle = .custom
self.transitioningDelegate = malertPresentationManager
}
override public func loadView() {
super.loadView()
malertView.alpha = 1
malertView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(visibleView)
visibleView.addSubview(malertView)
}
override public func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapOnView))
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
self.view.addGestureRecognizer(tapRecognizer)
listenKeyboard()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
makeContraints()
}
override func keyboardWillShow(sender: NSNotification) {
super.keyboardWillShow(sender: sender)
self.viewDidLayoutSubviews()
view.layoutIfNeeded()
}
override func keyboardWillHide(sender: NSNotification) {
super.keyboardWillHide(sender: sender)
self.viewDidLayoutSubviews()
view.layoutIfNeeded()
}
deinit {
#if DEBUG
print("dealloc ---> Malert")
#endif
}
}
extension Malert {
/* Animation config */
public var animationType: MalertAnimationType {
get { return malertPresentationManager.animationType }
set { malertPresentationManager.animationType = newValue }
}
public var presentDuration: TimeInterval {
get { return malertPresentationManager.presentDuration }
set { malertPresentationManager.presentDuration = newValue }
}
public var dismissDuration: TimeInterval {
get { return malertPresentationManager.dismissDuration }
set { malertPresentationManager.dismissDuration = newValue }
}
/* Container config */
public var margin: CGFloat {
get { return malertView.margin }
set { malertView.margin = newValue }
}
public var cornerRadius: CGFloat {
get { return malertView.cornerRadius }
set { malertView.cornerRadius = newValue }
}
public var backgroundColor: UIColor? {
get { return malertView.backgroundColor }
set { malertView.backgroundColor = newValue }
}
/// Leading space
public var leadingSpace: CGFloat {
get { return malertView.leadingSpace }
set { malertView.leadingSpace = newValue }
}
/// Trailing space
public var trailingSpace: CGFloat {
get { return malertView.trailingSpace }
set { malertView.trailingSpace = newValue }
}
/* Title config */
public var textColor: UIColor {
get { return malertView.textColor }
set { malertView.textColor = newValue }
}
public var textAlign: NSTextAlignment {
get { return malertView.textAlign }
set { malertView.textAlign = newValue }
}
public var titleFont: UIFont {
get { return malertView.titleFont }
set { malertView.titleFont = newValue }
}
/* Buttons config */
public var buttonsHeight: CGFloat {
get { return malertView.buttonsHeight }
set { malertView.buttonsHeight = newValue }
}
public var separetorColor: UIColor {
get { return malertView.separetorColor }
set { malertView.separetorColor = newValue }
}
public var buttonsSpace: CGFloat {
get { return malertView.buttonsSpace }
set { malertView.buttonsSpace = newValue }
}
public var buttonsSideMargin: CGFloat {
get { return malertView.buttonsSideMargin }
set { malertView.buttonsSideMargin = newValue }
}
public var buttonsBottomMargin: CGFloat {
get { return malertView.buttonsBottomMargin }
set { malertView.buttonsBottomMargin = newValue }
}
public var buttonsAxis: NSLayoutConstraint.Axis {
get { return malertView.buttonsAxis }
set { malertView.buttonsAxis = newValue }
}
public var buttonsFont: UIFont {
get { return malertView.buttonsFont }
set { malertView.buttonsFont = newValue }
}
/* Actions */
public func addAction(_ malertButton: MalertAction) {
malertView.addButton(malertButton, actionCallback: self)
}
public func onDismissMalert(_ block: @escaping (() -> Void)) {
self.completionBlock = block
}
public func enableAction(_ malertButton: MalertAction, enable: Bool = true) {
malertView.enableButton(malertButton, enable: enable)
}
}
extension Malert: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if let button = touch.view as? MalertButtonView {
button.sendActions(for: .touchUpInside)
}
return true
}
}
| 29.95814 | 129 | 0.646173 |
3396a44a1f3fbf4a134cdd356ac6809e7fe51f6c | 179 | //
// CJEnvironmentNetworkModel.swift
// TSEnvironmentiOSDemo
//
// Created by ciyouzen on 2020/8/25.
// Copyright © 2020 dvlproad. All rights reserved.
//
import Foundation
| 17.9 | 51 | 0.726257 |
890622da683050edeb10c43d95853f7126512bf3 | 9,230 | import Quote
import XCTest
@quoted
func foo(_ x: Float) -> Float {
return 1 * x
}
class Bar {
@quoted
func instanceBar(_ x: Float) -> Float {
return 2 * x
}
@quoted
func staticBar(_ x: Float) -> Float {
return 3 * x
}
}
// NOTE: This is a test of whether this thing successfully compiles.
@quoted
func noReturnType() {
}
public final class CompilationTests: XCTestCase {
public func testClosureWithExpr() {
let q = #quote{ (x: Int, y: Int) in
x + y
}
let _ = { q(40, 2) }
assertDescription(
q,
"""
{ (x: Int, y: Int) -> Int in
return (x + y)
}
""")
assertDescription(q.type, "(Int, Int) -> Int")
}
public func testClosureWithStmts() {
let q = #quote{
let n = 42;
print(n)
}
let _ = { q() }
assertDescription(
q,
"""
{ () -> () in
let n: Int = 42
print(n)
}
""")
assertDescription(q.type, "() -> ()")
}
public func testUnquoteManual() {
let u = #quote{ (x: Int, y: Int) in
x + y
}
let _ = { u(40, 2) }
let q = #quote{ (x: Int) in
#unquote(u)(x, x)
}
let _ = { q(42) }
assertDescription(
q,
"""
{ (x: Int) -> Int in
return #unquote(u)(x, x)
}
""")
assertDescription(q.type, "(Int) -> Int")
}
public func testUnquoteAutomatic() {
let t1 = _quotedFoo()
assertStructure(
t1,
"""
Function(
Name(
"foo",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
[Parameter(
nil,
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")))],
[Return(
Binary(
IntegerLiteral(
1,
TypeName("Float", "s:Sf")),
Name(
"*",
"s:Sf1moiyS2f_SftFZ",
FunctionType(
[],
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")),
TypeName("Float", "s:Sf")))])
"""
)
let q1 = #quote(foo)
assertStructure(
q1,
"""
Unquote(
Name(
"foo",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
func foo(_ x: Float) -> Float in
return (1 * x)
},
SpecializedType(
TypeName("FunctionQuote1", "s:5Quote14FunctionQuote1C"),
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")]))
"""
)
let t2 = Bar._quotedInstanceBar()
assertStructure(
t2,
"""
Function(
Name(
"instanceBar",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
[Parameter(
nil,
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")))],
[Return(
Binary(
IntegerLiteral(
2,
TypeName("Float", "s:Sf")),
Name(
"*",
"s:Sf1moiyS2f_SftFZ",
FunctionType(
[],
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")),
TypeName("Float", "s:Sf")))])
"""
)
let bar = Bar()
blackHole(bar)
let q2 = #quote(bar.instanceBar)
assertStructure(
q2,
"""
Unquote(
Member(
Name(
"bar",
"<unstable USR>",
TypeName("Bar", "<unstable USR>")),
"instanceBar",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
func instanceBar(_ x: Float) -> Float in
return (2 * x)
},
SpecializedType(
TypeName("FunctionQuote1", "s:5Quote14FunctionQuote1C"),
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")]))
"""
)
let t3 = Bar._quotedStaticBar()
assertStructure(
t3,
"""
Function(
Name(
"staticBar",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
[Parameter(
nil,
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")))],
[Return(
Binary(
IntegerLiteral(
3,
TypeName("Float", "s:Sf")),
Name(
"*",
"s:Sf1moiyS2f_SftFZ",
FunctionType(
[],
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
Name(
"x",
"<unstable USR>",
TypeName("Float", "s:Sf")),
TypeName("Float", "s:Sf")))])
"""
)
let q3 = #quote(Bar.staticBar)
assertStructure(
q3,
"""
Unquote(
Name(
"staticBar",
"<unstable USR>",
FunctionType(
[],
[TypeName("Float", "s:Sf")],
TypeName("Float", "s:Sf"))),
func staticBar(_ x: Float) -> Float in
return (3 * x)
},
SpecializedType(
TypeName("FunctionQuote1", "s:5Quote14FunctionQuote1C"),
[TypeName("Float", "s:Sf"),
TypeName("Float", "s:Sf")]))
"""
)
}
public func testAvgPool1D() {
func threadIndex() -> Int { return 0 }
func threadCount() -> Int { return 1 }
let avgPool1D = #quote{
(out: inout [Float], input: [Float], windowSize: Int, windowStride: Int) -> Void in
let n = input.count
let outSize = (n - windowSize) / windowStride + 1
let outStart = threadIndex()
let outStride = threadCount()
for outIndex in stride(from: outStart, to: outSize, by: outStride) {
out[outIndex] = 0.0
let beginWindow = outIndex * windowStride
let endWindow = outIndex * windowStride + windowSize
for inputIndex in beginWindow..<endWindow {
out[outIndex] += input[inputIndex]
}
out[outIndex] /= Float(windowSize)
}
}
let _ = {
let x: [Float] = [1, 2, 3, 4, 5, 6]
var out: [Float] = [Float](repeating: 0, count: x.count)
let windowSize = 2
let windowStride = 2
avgPool1D(&out, x, windowSize, windowStride)
}
assertDescription(
avgPool1D,
"""
{ (out: inout [Float], input: [Float], windowSize: Int, windowStride: Int) -> Void in
let n: Int = input.count
let outSize: Int = (((n - windowSize) / windowStride) + 1)
let outStart: Int = threadIndex()
let outStride: Int = threadCount()
for outIndex in stride(from: outStart, to: outSize, by: outStride) {
out[outIndex] = 0.0
let beginWindow: Int = (outIndex * windowStride)
let endWindow: Int = ((outIndex * windowStride) + windowSize)
for inputIndex in (beginWindow ..< endWindow) {
(out[outIndex] += input[inputIndex])
}
(out[outIndex] /= Float(windowSize))
}
}
"""
)
assertDescription(avgPool1D.type, "(inout [Float], [Float], Int, Int) -> Void")
}
public func test31() {
print(#quote(42))
}
public func test32() {
print(#quote(print(42)))
}
private func blackHole(_ x: Any) {
// This method exists to silence unused variable warnings.
// TODO(TF-728): Get rid of this method.
}
public static let allTests = [
("testClosureWithExpr", testClosureWithExpr),
("testClosureWithStmts", testClosureWithStmts),
("testUnquoteManual", testUnquoteManual),
("testUnquoteAutomatic", testUnquoteAutomatic),
("testAvgPool1D", testAvgPool1D),
// NOTE: This is intentionally not run - we just need to check that the test compiles.
// ("test31", test31),
// ("test32", test32),
]
}
| 26.988304 | 99 | 0.429794 |
d91977f21d53a65fffaadba09c7521fd4ad1d1aa | 3,712 | //
// Chara.swift
// PrincessGuide
//
// Created by zzk on 2018/7/6.
// Copyright © 2018 zzk. All rights reserved.
//
import Foundation
import CoreData
extension Chara {
var card: Card? {
return Card.findByID(Int(id))
}
var iconID: Int? {
if rarity >= 3 {
return card?.iconID(style: .r3)
} else {
return card?.iconID(style: .r1)
}
}
convenience init(anotherChara: Chara, context: NSManagedObjectContext) {
self.init(context: context)
bondRank = anotherChara.bondRank
level = anotherChara.level
rank = anotherChara.rank
skillLevel = anotherChara.skillLevel
slot1 = anotherChara.slot1
slot2 = anotherChara.slot2
slot3 = anotherChara.slot3
slot4 = anotherChara.slot4
slot5 = anotherChara.slot5
slot6 = anotherChara.slot6
modifiedAt = Date()
id = anotherChara.id
rarity = anotherChara.rarity
}
func unequiped() -> [Equipment] {
var array = [Equipment]()
if let promotions = card?.promotions, promotions.count >= rank {
let currentPromotion = promotions[Int(rank - 1)]
let higherPromotions = promotions[Int(rank)..<promotions.count]
array += currentPromotion.equipmentsInSlot.enumerated().compactMap { (offset, element) -> Equipment? in
if slots[safe: offset] ?? false {
return nil
} else {
return element
}
}
array += higherPromotions.flatMap {
$0.equipmentsInSlot.compactMap { $0 }
}
}
return array
}
func maxRankUnequiped() -> [Equipment] {
if let promotions = card?.promotions {
if promotions.count == rank {
return unequiped()
} else {
var array = [Equipment]()
if let highestPromotion = promotions.last {
array += highestPromotion.equipmentsInSlot.compactMap { $0 }
}
return array
}
} else {
return []
}
}
var slots: [Bool] {
get {
return [slot1, slot2, slot3, slot4, slot5, slot6]
}
set {
guard newValue.count == 6 else {
return
}
slot1 = newValue[0]
slot2 = newValue[1]
slot3 = newValue[2]
slot4 = newValue[3]
slot5 = newValue[4]
slot6 = newValue[5]
}
}
var skillLevelUpCost: Int {
let level = Int(skillLevel)
let targetLevel = Preload.default.maxPlayerLevel
guard level < targetLevel else {
return 0
}
var cost = 0
for key in (level + 1)...targetLevel {
let value = Preload.default.skillCost[key] ?? 0
cost += value
}
return cost * Constant.presetNeededToLevelUpSkillCount
}
var experienceToMaxLevel: Int {
let level = Int(self.level)
let targetLevel = Preload.default.maxPlayerLevel
guard level < targetLevel else {
return 0
}
let targetExperience = Preload.default.unitExperience[targetLevel] ?? 0
let currentExperience = Preload.default.unitExperience[level] ?? 0
return targetExperience - currentExperience
}
}
extension Card.Promotion {
var defaultSlots: [Bool] {
return equipSlots.map {
$0 != 999999
}
}
}
| 27.094891 | 115 | 0.521282 |
28a0ab29bea1416274e79dbd35c484b645cd1fb1 | 2,226 | import Combine
import CombineWamp
import Foundation
import XCTest
// https://wamp-proto.org/_static/gen/wamp_latest.html#session-establishment
final class SessionEstablishmentTests: IntegrationTestBase {
func testSayHelloReceiveWelcome() throws {
let realm = URI("realm1")!
let session = WampSession(transport: transport(), serialization: serialization, realm: realm, roles: .allClientRoles)
let welcomeReceived = expectation(description: "it should receive welcome")
session.connect()
.sink(
receiveCompletion: { completion in
switch completion {
case let .failure(error):
XCTFail(error.localizedDescription)
case .finished:
break
}
},
receiveValue: { welcome in
welcomeReceived.fulfill()
}
).store(in: &cancellables)
wait(for: [welcomeReceived], timeout: 0.5)
}
func testSayHelloReceiveAbort() throws {
let realm = URI("invalid_realm_dude")!
let session = WampSession(transport: transport(), serialization: serialization, realm: realm, roles: .allClientRoles)
let abortReceived = expectation(description: "it should receive abort")
session.connect()
.sink(
receiveCompletion: { completion in
switch completion {
case let .failure(error):
switch error {
case let .abort(abort):
XCTAssertEqual(abort.reason, WampError.noSuchRealm.uri)
abortReceived.fulfill()
default:
XCTFail("Unexpected error received: \(error)")
}
case .finished:
break
}
},
receiveValue: { welcome in
XCTFail("Welcome was not expected in this test")
}
).store(in: &cancellables)
wait(for: [abortReceived], timeout: 0.5)
}
}
| 35.903226 | 125 | 0.52381 |
eb339aa2ae5491e02e94e1bf958b0f62c1c28963 | 4,063 | //
// SaveBookmarkActivity.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. 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 Core
class SaveBookmarkActivity: UIActivity {
private let bookmarksManager: BookmarksManager
private var bookmarkURL: URL?
private weak var controller: TabViewController?
private var isFavorite: Bool
private var activityViewControllerAccessed = false
init(controller: TabViewController, isFavorite: Bool = false, bookmarksManager: BookmarksManager = BookmarksManager()) {
self.bookmarksManager = bookmarksManager
self.controller = controller
self.isFavorite = isFavorite
super.init()
}
override var activityTitle: String? {
return isFavorite ? UserText.actionSaveFavorite : UserText.actionSaveBookmark
}
override var activityType: UIActivity.ActivityType? {
return isFavorite ? .saveFavoriteInDuckDuckGo : .saveBookmarkInDuckDuckGo
}
override var activityImage: UIImage {
return (isFavorite ? UIImage(named: "sharesheet-favorite") : UIImage(named: "sharesheet-bookmark")) ?? #imageLiteral(resourceName: "LogoShare")
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return activityItems.contains(where: { $0 is URL })
}
override func prepare(withActivityItems activityItems: [Any]) {
bookmarkURL = activityItems.first(where: { $0 is URL }) as? URL
}
override var activityViewController: UIViewController? {
guard !activityViewControllerAccessed else { return nil }
activityViewControllerAccessed = true
guard let bookmarkURL = bookmarkURL else {
activityDidFinish(true)
return nil
}
bookmarksManager.contains(url: bookmarkURL) { contains in
if contains {
DispatchQueue.main.async {
ActionMessageView.present(message: UserText.webBookmarkAlreadySaved)
self.activityDidFinish(true)
}
} else {
let linkForTitle: Link
// Get the proper title from the webview if we can
if let link = self.controller?.link, link.url == bookmarkURL {
linkForTitle = link
} else {
linkForTitle = Link(title: nil, url: bookmarkURL)
}
let title = linkForTitle.displayTitle ?? bookmarkURL.absoluteString
if self.isFavorite {
self.bookmarksManager.saveNewFavorite(withTitle: title, url: bookmarkURL)
DispatchQueue.main.async {
ActionMessageView.present(message: UserText.webSaveFavoriteDone)
self.activityDidFinish(true)
}
} else {
self.bookmarksManager.saveNewBookmark(withTitle: title, url: bookmarkURL, parentID: nil)
DispatchQueue.main.async {
ActionMessageView.present(message: UserText.webSaveBookmarkDone)
self.activityDidFinish(true)
}
}
}
}
return nil
}
}
extension UIActivity.ActivityType {
public static let saveBookmarkInDuckDuckGo = UIActivity.ActivityType("com.duckduckgo.save.bookmark")
public static let saveFavoriteInDuckDuckGo = UIActivity.ActivityType("com.duckduckgo.save.favorite")
}
| 37.971963 | 151 | 0.644105 |
08061aa9df3ec9aedc4d5f74d7d93dfc95e06f29 | 263 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a {
deinit {
struct A<T : CollectionType
struct d<d where B : a {
class a<T where B : a
| 26.3 | 87 | 0.737643 |
91e8df12c3b3b49695b847f0ffd690a8085c3746 | 4,190 | //
// AppDelegate.swift
// AppKeFuDemo7Swift
//
// Created by jack on 16/8/5.
// Copyright © 2016年 appkefu.com. All rights reserved.
//
import UIKit
/*
此appkey为演示所用,请确保应用在上线之前,到http://admin.appkefu.com/AppKeFu/admin/index.php,申请自己的appkey
*/
let APP_KEY = "6f8103225b6ca0cfec048ecc8702dbce"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: KFNavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
// Bar's background color
UINavigationBar.appearance().barTintColor = UIColorFromRGB(0x067AB5)
// Back button and such
UINavigationBar.appearance().tintColor = UIColor.white
//
let viewController = ViewController()
self.navigationController = KFNavigationController(rootViewController: viewController)
self.window?.rootViewController = self.navigationController
self.window?.makeKeyAndVisible()
AppKeFuLib.sharedInstance().login(withAppkey: APP_KEY)
//
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
AppKeFuLib.sharedInstance().uploadDeviceToken(deviceToken)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
/*
{
aps = {
alert = "客服消息:555";
badge = 1;
sound = default;
};
channel = appkefu;
message = 555;
workgroup = wgdemo;
}
*/
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
/*
*/
func UIColorFromRGB(_ rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
| 39.528302 | 285 | 0.684964 |
f469bf524843727bb69e33f2178a00f4ac4d67c1 | 1,599 | //
// HTTPClient.swift
// SwiftRxInterceptor
//
// Created by Jean-Pierre Alary on 30/11/2016.
// Copyright © 2016 Jean-Pierre Alary. All rights reserved.
//
import Foundation
import RxSwift
enum HTTPClientResult {
case success(Response)
case error(Error)
case networkError(Error)
}
protocol HTTPClient {
func send(request: URLRequest) -> Observable<HTTPClientResult>
}
final class MyHTTPClient: HTTPClient {
private let requestChain: InterceptorChain<URLRequest>
private let responseChain: InterceptorChain<Response>
// MARK: Initializer
convenience init() {
self.init(
requestChain: InterceptorChain<URLRequest>()
.add(interceptor: AnyInterceptor(base: CredentialsInterceptor()))
.add(interceptor: AnyInterceptor(base: AddLocaleInterceptor())),
responseChain: InterceptorChain<Response>()
)
}
init(requestChain: InterceptorChain<URLRequest>, responseChain: InterceptorChain<Response>) {
self.requestChain = requestChain
self.responseChain = responseChain
}
// MARK: HTTPClient
func send(request: URLRequest) -> Observable<HTTPClientResult> {
return requestChain
.proceed(object: request)
.map { (request) -> Response in
// Here you should sent the request...
return Response(request: request)
}
.withLatestFrom(Observable.just(responseChain)) { $0 }
.flatMap { $1.proceed(object: $0) }
.map { .success($0) }
}
}
| 28.553571 | 97 | 0.637899 |
db389550bd166f4c4b7843ffcab9bc0b50d7c809 | 1,184 | // https://github.com/Quick/Quick
import Quick
import Nimble
import PerspectivePhotoBrowser
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 23.215686 | 63 | 0.374155 |
099aecc3dce57b1dfe1243d2eaa889e3690a7a27 | 169 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(SnazzyNavigationViewTests.allTests)
]
}
#endif
| 16.9 | 52 | 0.698225 |
dd7556ff1f38997514b01043973da7d42e8498ea | 1,305 | //
// AcknowledgementPlistTests.swift
// PodToBUILD
//
// Created by Jerry Marino on 6/19/17.
// Copyright © 2017 Pinterest Inc. All rights reserved.
//
import XCTest
@testable import PodToBUILD
@testable import RepoToolsCore
extension Dictionary {
static func from<S: Sequence>(_ tuples: S) -> Dictionary where S.Iterator.Element == (Key, Value) {
return tuples.reduce([:]) { acc, b in
var mut = acc
mut[b.0] = b.1
return mut
}
}
}
class AcknowledgementPlistTests: XCTestCase {
func testTextLicense() {
let podspec = examplePodSpecNamed(name: "Calabash")
XCTAssertEqual(podspec.license.type, "Eclipse Public License 1.0")
XCTAssertNotNil(podspec.license.text)
}
func testTypeString() {
let podspec = examplePodSpecNamed(name: "Braintree")
XCTAssertEqual(podspec.license.type, "MIT")
}
func testEntry() {
let podspec = examplePodSpecNamed(name: "Calabash")
let entry = Dictionary.from(AcknowledgmentEntry(forPodspec: podspec))
XCTAssertEqual(entry["Title"], "Calabash")
XCTAssertEqual(entry["Type"], "PSGroupSpecifier")
XCTAssertEqual(entry["License"], "Eclipse Public License 1.0")
XCTAssertNotNil(entry["FooterText"])
}
}
| 29.659091 | 103 | 0.65364 |
46384203571172f10ad64b37065b186898319547 | 1,412 | //
// Codable.swift
// Alamofire
//
// Created by Sanchew on 2017/12/20.
//
import Foundation
//public func <<<Key>(container: KeyedDecodingContainer<Key>, key: Key) -> Bool {
// return try! container.decode(Bool.self, forKey: key)
//}
//
//public func <<<Key>(container: KeyedDecodingContainer<Key>, key: Key) -> String {
// return try! container.decode(String.self, forKey: key)
//}
//
//public func <<<Key>(container: KeyedDecodingContainer<Key>, key: Key) -> Int {
// return try! container.decode(Int.self, forKey: key)
//}
//
//
//public func <<<Key>(container: KeyedDecodingContainer<Key>, key: Key) -> Double {
// return try! container.decode(Double.self, forKey: key)
//}
//infix operator <<<
//public func <<<<Key,Value: Decodable>(container: KeyedDecodingContainer<Key>, key: Key) -> Value {
// return try! container.decode(Value.self, forKey: key)
//}
public func <<<Key,Value: Decodable>(container: KeyedDecodingContainer<Key>, key: Key) -> Value {
return try! container.decode(Value.self, forKey: key)
}
infix operator <<~: DecoderPrecedence
precedencegroup DecoderPrecedence {
associativity: left
higherThan: BitwiseShiftPrecedence
}
public func <<~<Key,Value: Decodable>(container: KeyedDecodingContainer<Key>, key: Key) -> Value? {
if container.contains(key) {
return try! container.decodeIfPresent(Value.self, forKey: key)
}
return nil
}
| 28.816327 | 100 | 0.684844 |
2f588450985f07e052ee82188a9f4bbcc1650b46 | 1,851 | //
// QRCodeGenerator.swift
// Pods
//
// Created by Nick DiStefano on 12/23/15.
//
//
import Foundation
public func qrImage(textToEncode text: String, foregroundColor: UIColor, backgroundColor: UIColor, size: CGSize) -> UIImage? {
return qrImage(textToEncode: text)?.scale(size)?.color(foregroundColor: foregroundColor, backgroundColor: backgroundColor)?.mapToUIImage()
}
public func qrImage(textToEncode text: String) -> CIImage? {
let data = text.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
return filter?.outputImage
}
public extension CIImage {
public func mapToUIImage() -> UIImage? {
return UIImage(CIImage: self)
}
public func scale(size: CGSize) -> CIImage? {
let scaleX = size.width / extent.size.width
let scaleY = size.height / extent.size.height
return imageByApplyingTransform(CGAffineTransformMakeScale(scaleX, scaleY))
}
public func color(foregroundColor foregroundColor: UIColor, backgroundColor: UIColor) -> CIImage? {
let foregroundCoreColor = convertToCIColor(foregroundColor)
let backgroundCoreColor = convertToCIColor(backgroundColor)
let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage": self, "inputColor0":foregroundCoreColor, "inputColor1":backgroundCoreColor])
return colorFilter?.outputImage
}
}
public func convertToCIColor(color: UIColor) -> CIColor {
let foregroundColorRef = color.CGColor
let foregroundColorString = CIColor(CGColor: foregroundColorRef).stringRepresentation
return CIColor(string: foregroundColorString)
}
| 34.277778 | 169 | 0.718531 |
ff7a7a8cfdeecf9dd844b7925978ff7a29070ccb | 536 | import Foundation
public extension Storage {
func transformData() -> Storage<Data> {
let storage = transform(transformer: TransformerFactory.forData())
return storage
}
#if os(iOS) || os(macOS)
func transformImage() -> Storage<Image> {
let storage = transform(transformer: TransformerFactory.forImage())
return storage
}
#endif
func transformCodable<U: Codable>(ofType: U.Type) -> Storage<U> {
let storage = transform(transformer: TransformerFactory.forCodable(ofType: U.self))
return storage
}
}
| 25.52381 | 87 | 0.710821 |
ab05e8af26e4e0157a600cab0abd2969506565ad | 4,114 | import Foundation
extension XMLDecoder {
struct UDC: UnkeyedDecodingContainer {
var elements: [XMLElement]
var dateFormatters: [DateFormatter]
var codingPath: [CodingKey] = []
var count: Int? {
return elements.count
}
var isAtEnd: Bool {
return currentIndex >= elements.count
}
var currentIndex: Int = 0
mutating func nextElement() -> XMLElement {
let element = elements[currentIndex]
currentIndex += 1
return element
}
mutating func nextValue<T>(_ converter: (String) -> T?) throws -> T {
let element = nextElement()
guard let stringValue = element.value,
let value = converter(stringValue) else {
throw DecodingError.dataCorruptedError(in: self,
debugDescription: "Malformed data.")
}
return value
}
mutating func decodeNil() throws -> Bool {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: codingPath,
debugDescription: "decodeNil not supported."))
}
mutating func decode(_ type: Bool.Type) throws -> Bool {
return try nextValue(Bool.init)
}
mutating func decode(_ type: String.Type) throws -> String {
return try nextValue(XMLDecoder.identity)
}
mutating func decode(_ type: Double.Type) throws -> Double {
return try nextValue(Double.init)
}
mutating func decode(_ type: Float.Type) throws -> Float {
return try nextValue(Float.init)
}
mutating func decode(_ type: Int.Type) throws -> Int {
return try nextValue(Int.init)
}
mutating func decode(_ type: Int8.Type) throws -> Int8 {
return try nextValue(Int8.init)
}
mutating func decode(_ type: Int16.Type) throws -> Int16 {
return try nextValue(Int16.init)
}
mutating func decode(_ type: Int32.Type) throws -> Int32 {
return try nextValue(Int32.init)
}
mutating func decode(_ type: Int64.Type) throws -> Int64 {
return try nextValue(Int64.init)
}
mutating func decode(_ type: UInt.Type) throws -> UInt {
return try nextValue(UInt.init)
}
mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
return try nextValue(UInt8.init)
}
mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
return try nextValue(UInt16.init)
}
mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
return try nextValue(UInt32.init)
}
mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
return try nextValue(UInt64.init)
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
let element = nextElement()
let decoder = XMLDecoder(element: element, dateFormatters: dateFormatters)
return try T(from: decoder)
}
mutating func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
let element = nextElement()
return KeyedDecodingContainer(KDC(element: element, dateFormatters: dateFormatters))
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let element = nextElement()
return UDC(elements: element.children, dateFormatters: dateFormatters)
}
mutating func superDecoder() throws -> Decoder {
throw DecodingError.typeMismatch(Decoder.self, DecodingError.Context(codingPath: codingPath,
debugDescription: "Does not support superDecoder"))
}
}
}
| 33.177419 | 135 | 0.566359 |
56bb3ec5f8561d31f4970101e489c5fa7d34ccd3 | 2,987 | import Foundation
struct IfPreview3D: Geometry3D {
let previewBody: Geometry3D?
let renderBody: Geometry3D?
init(ifPreview previewBody: Geometry3D? = nil, ifRender renderBody: Geometry3D? = nil) {
self.previewBody = previewBody
self.renderBody = renderBody
}
func scadString(in environment: Environment) -> String {
let previewCode = previewBody?.scadString(in: environment)
let renderCode = renderBody?.scadString(in: environment)
if let preview = previewCode, let render = renderCode {
return "if ($preview) { \(preview) } else { \(render) }"
} else if let preview = previewCode {
return "if ($preview) { \(preview) }"
} else if let render = renderCode {
return "if (!$preview) { \(render) }"
} else {
preconditionFailure("previewBody and renderBody can't both be nil.")
}
}
}
public func IfPreview(@UnionBuilder _ preview: () -> Geometry3D, @UnionBuilder ifRender render: () -> Geometry3D) -> Geometry3D {
IfPreview3D(ifPreview: preview(), ifRender: render())
}
public func IfPreview(@UnionBuilder _ preview: () -> Geometry3D) -> Geometry3D {
IfPreview3D(ifPreview: preview())
}
public func IfRender(@UnionBuilder _ render: () -> Geometry3D, @UnionBuilder ifPreview preview: () -> Geometry3D) -> Geometry3D {
IfPreview3D(ifPreview: preview(), ifRender: render())
}
public func IfRender(@UnionBuilder _ render: () -> Geometry3D) -> Geometry3D {
IfPreview3D(ifRender: render())
}
struct IfPreview2D: Geometry2D {
let previewBody: Geometry2D?
let renderBody: Geometry2D?
init(ifPreview previewBody: Geometry2D? = nil, ifRender renderBody: Geometry2D? = nil) {
self.previewBody = previewBody
self.renderBody = renderBody
}
func scadString(in environment: Environment) -> String {
let previewCode = previewBody?.scadString(in: environment)
let renderCode = renderBody?.scadString(in: environment)
if let preview = previewCode, let render = renderCode {
return "if ($preview) { \(preview) } else { \(render) }"
} else if let preview = previewCode {
return "if ($preview) { \(preview) }"
} else if let render = renderCode {
return "if (!$preview) { \(render) }"
} else {
preconditionFailure("previewBody and renderBody can't both be nil.")
}
}
}
func IfPreview(@UnionBuilder _ preview: () -> Geometry2D, @UnionBuilder ifRender render: () -> Geometry2D) -> Geometry2D {
IfPreview2D(ifPreview: preview(), ifRender: render())
}
func IfPreview(@UnionBuilder _ preview: () -> Geometry2D) -> Geometry2D {
IfPreview2D(ifPreview: preview())
}
func IfRender(@UnionBuilder _ render: () -> Geometry2D, @UnionBuilder ifPreview preview: () -> Geometry2D) -> Geometry2D {
IfPreview2D(ifPreview: preview(), ifRender: render())
}
func IfRender(@UnionBuilder _ render: () -> Geometry2D) -> Geometry2D {
IfPreview2D(ifRender: render())
}
| 35.141176 | 129 | 0.66622 |
14f3513438dfbdb3222d9f5896f9eabb2a6e8b3b | 409 | //
// DefaultProvider+TransactionDetails.swift
// ZKSyncSDK
//
// Created by Eugene Belyakov on 16/01/2021.
//
import Foundation
extension DefaultProvider {
public func transactionDetails(txHash: String,
completion: @escaping (ZKSyncResult<TransactionDetails>) -> Void) {
transport.send(method: "tx_info", params: [txHash], completion: completion)
}
}
| 24.058824 | 102 | 0.660147 |
0376ca92643d459093593727115d55941261634a | 209 | //
// FirstViewController.swift
// ClockInOut
//
// Created by 鈴木航 on 2019/09/03.
// Copyright © 2019 WataruSuzuki. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
}
| 13.933333 | 55 | 0.712919 |
f7f03e4c79ef2157b17588f0416e747686429b0f | 5,579 | //
// WhatsNewItemsView.swift
// WhatsNewKit
//
// Created by Sven Tiigi on 19.05.18.
// Copyright © 2018 WhatsNewKit. All rights reserved.
//
import UIKit
// MARK: - WhatsNewItemsView
/// The WhatsNewItemsView
class WhatsNewItemsView: UIView {
// MARK: Properties
/// The WhatsNew Items
private let items: [WhatsNew.Item]
/// The Configuration
private let configuration: WhatsNewViewController.Configuration
/// The cell display count
private var cellDisplayCount = 0
/// The TableView
private lazy var tableView: UITableView = {
// Initialize TableView
let tableView = UITableView(frame: .zero, style: .plain)
// Set clear background color
tableView.backgroundColor = .clear
// Only bounce vertical if space is needed
tableView.alwaysBounceVertical = false
// Set data source
tableView.dataSource = self
// Set delegate
tableView.delegate = self
// Clear table footer view
tableView.tableFooterView = UIView(frame: CGRect.zero)
// No seperators
tableView.separatorStyle = .none
// No selection
tableView.allowsSelection = false
// Hide Vertical Scroll Indicator
tableView.showsVerticalScrollIndicator = false
// Set indicator style based on theme backgroundcolor
tableView.indicatorStyle = self.configuration.backgroundColor.isLight ? .black : .white
// Set estimatedRowHeight so autosizing will work on iOS 10
tableView.estimatedRowHeight = 44.0
// Set automtic dimension for row height
tableView.rowHeight = UITableView.automaticDimension
// Return TableView
return tableView
}()
// MARK: Initializer
/// Default initializer
///
/// - Parameters:
/// - items: The WhatsNew Items
/// - configuration: The Configuration
init(items: [WhatsNew.Item],
configuration: WhatsNewViewController.Configuration) {
// Set items
self.items = items
// Set configuration
self.configuration = configuration
// Super init
super.init(frame: .zero)
// Set background color
self.backgroundColor = self.configuration.backgroundColor
// Add TableView
self.addSubview(self.tableView)
}
/// Initializer with Coder always returns nil
required init?(coder aDecoder: NSCoder) {
return nil
}
// MARK: View-Lifecycle
/// Layout Subviews
override func layoutSubviews() {
super.layoutSubviews()
// Initialize relative padding
let relativePadding: CGFloat = 0.05
// Set TableView frame
self.tableView.frame = CGRect(
x: self.frame.size.width * relativePadding,
y: 0,
width: self.frame.size.width - self.frame.size.width * relativePadding * 2,
height: self.frame.size.height
)
}
}
// MARK: - UITableViewDataSource
extension WhatsNewItemsView: UITableViewDataSource {
/// Retrieve number of sections
///
/// - Parameter tableView: The TableView
/// - Returns: Amount of section
public func numberOfSections(in tableView: UITableView) -> Int {
// Return one section
return 1
}
/// Retrieve number of rows in section
///
/// - Parameters:
/// - tableView: The TableView
/// - section: The section
/// - Returns: The amount of rows in section
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return items count
return self.items.count
}
/// Retrieve cell for row at IndexPath
///
/// - Parameters:
/// - tableView: The TableView
/// - indexPath: The IndexPath
/// - Returns: The configured Cell
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Verify row is contained in indicies
guard self.items.indices.contains(indexPath.row) else {
// Return unkown TableViewCell
return UITableViewCell(style: .default, reuseIdentifier: "unkown")
}
// Return WhatsNewItemTableViewCell
return WhatsNewItemTableViewCell(
item: self.items[indexPath.row],
configuration: self.configuration
)
}
}
// MARK: - UITableViewDelegate
extension WhatsNewItemsView: UITableViewDelegate {
/// TableView will display cell
///
/// - Parameters:
/// - tableView: The TableView
/// - cell: The Cell
/// - indexPath: The indexPath
func tableView(_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath) {
cell.backgroundColor = self.configuration.backgroundColor
// Unwrap cell as WhatsNewItemTableViewCell and verify cellDisplayCount is less then the items count
guard let cell = cell as? WhatsNewItemTableViewCell,
self.cellDisplayCount < self.items.count else {
// Return out of function
return
}
// Increment CellDisplayCount
self.cellDisplayCount += 1
// Animate Cell
self.configuration.itemsView.animation?.rawValue(
cell,
.init(
preferredDuration: 0.5,
preferredDelay: 0.15 * (Double(indexPath.row) + 1.0)
)
)
}
}
| 31.167598 | 108 | 0.618211 |
c1f7ff4ccf83592df91cddae75efc085975a431a | 2,213 | //
// XCUITest+Utilities.swift
// PaymentSheetUITest
//
// Created by Yuki Tokuhiro on 8/20/21.
// Copyright © 2021 stripe-ios. All rights reserved.
//
import XCTest
// There seems to be an issue with our SwiftUI buttons - XCTest fails to scroll to the button's position.
// Work around this by targeting a coordinate inside the button.
// https://stackoverflow.com/questions/33422681/xcode-ui-test-ui-testing-failure-failed-to-scroll-to-visible-by-ax-action
extension XCUIElement {
func forceTapElement() {
if self.isHittable {
self.tap()
} else {
// Tap the middle of the element.
// (Sometimes the edges of rounded buttons aren't tappable in certain web elements.)
let coordinate: XCUICoordinate = self.coordinate(
withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
coordinate.tap()
}
}
}
// https://gist.github.com/jlnquere/d2cd529874ca73624eeb7159e3633d0f
func scroll(collectionView: XCUIElement, toFindCellWithId identifier:String) -> XCUIElement? {
guard collectionView.elementType == .collectionView else {
fatalError("XCUIElement is not a collectionView.")
}
var reachedTheEnd = false
var allVisibleElements = [String]()
while !reachedTheEnd {
let cell = collectionView.cells[identifier]
// Did we find our cell ?
if cell.exists {
return cell
}
// If not: we store the list of all the elements we've got in the CollectionView
let allElements = collectionView.cells.allElementsBoundByIndex.map({$0.identifier})
// Did we read then end of the CollectionView ?
// i.e: do we have the same elements visible than before scrolling ?
reachedTheEnd = (allElements == allVisibleElements)
allVisibleElements = allElements
// Then, we do a scroll right on the scrollview
let startCoordinate = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.99))
startCoordinate.press(forDuration: 0.01, thenDragTo: collectionView.coordinate(withNormalizedOffset:CGVector(dx: 0.1, dy: 0.99)))
}
return nil
}
| 37.508475 | 137 | 0.666968 |
e4fb779a8fdad6e96a6398c55880c226d1723b65 | 426 | //
// ProfileAboutCellDecorator.swift
// DataSourceExample
//
// Created by Andrew Kochulab on 24.03.2021.
//
import Foundation
struct ProfileAboutCellDecorator: ViewDecorator {
func decorate(view: ProfileAboutCell, with item: ProfileAboutViewModel) {
view.valueLabel.text = item.message
item.didChange = { [weak view] message in
view?.valueLabel.text = message
}
}
}
| 22.421053 | 77 | 0.669014 |
ebe9b268c71d7e7588a5778b3f5a2fbe75f02b65 | 2,188 | //
// File.swift
// App
//
// Created by 牛辉 on 2017/12/3.
//
import Vapor
import FluentProvider
import Foundation
import HTTP
final class File: Model {
static let entity = "Files"
let storage = Storage()
//1.图片 2.gif 3.视频
var type : Int = 0
/**
//图片地址 http://www.walkinglove.com/download/image/15ddfa3903200e1ce8b7995857c6c0b3.png
//gif地址 http://www.walkinglove.com/download/image/15ddfa3903200e1ce8b7995857c6c0b3.gif
//视频地址 http://www.walkinglove.com/download/image/15ddfa3903200e1ce8b7995857c6c0b3.mp4
*/
var url : String = ""
/**
//图片 {"width": 100,"height": 100}
//gif {"width": 100,"height": 100}
//视频 {"width": 100,"height": 100,"duration":40,"url":""}
*/
var content : String = ""
var create_at : Int = 0
init(row: Row) throws {
type = try row.get("type")
url = try row.get("url")
content = try row.get("content")
create_at = try row.get("create_at")
}
func makeRow() throws -> Row {
return try wildcardRow()
}
init(url: String,content: String,type:Int) {
self.url = url
self.create_at = Int(Date().timeIntervalSince1970)
self.content = content
self.type = type;
}
init(url: String,type:Int) {
self.url = url
self.create_at = Int(Date().timeIntervalSince1970)
self.type = type;
}
}
extension File {
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("type", type)
try json.set("url", url)
try json.set("content", content)
try json.set("create_at", create_at)
return json
}
}
extension File: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { users in
users.id()
users.string("url")
users.string("content",length: 500)
users.int("type")
users.int("create_at")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| 28.051282 | 91 | 0.558044 |
09b43e3289538d9bec70d5224b1dfac86bbfe03f | 197 | //
// NSNotificationName.swift
// Bankey
//
// Created by Archit Patel on 2022-02-28.
//
import Foundation
extension Notification.Name {
static let logout = Notification.Name("Logout")
}
| 14.071429 | 51 | 0.695431 |
2fa1bfb8e09859917807c19a58d380369ab5201a | 1,430 | //
// Copyright 2011 - 2018 Schibsted Products & Technology AS.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import Foundation
private extension URL {
init?(string: String?) {
guard let string = string else {
return nil
}
self.init(string: string)
}
}
/**
The links and data that are associated with the terms and conditions for your client
- SeeAlso: [SPiD selfservice](http://techdocs.spid.no/selfservice/access/)
*/
public struct Terms: JSONParsable {
///
public let platformPrivacyURL: URL?
///
public let platformTermsURL: URL?
///
public let clientPrivacyURL: URL?
///
public let clientTermsURL: URL?
///
public let summary: String?
init(from json: JSONObject) throws {
let data = try json.jsonObject(for: "data")
self.platformPrivacyURL = URL(string: try? data.string(for: "platform_privacy_url"))
self.platformTermsURL = URL(string: try? data.string(for: "platform_terms_url"))
self.clientPrivacyURL = URL(string: try? data.string(for: "privacy_url"))
self.clientTermsURL = URL(string: try? data.string(for: "terms_url"))
if let summaryArray = try? data.jsonArray(of: String.self, for: "summary"), summaryArray.count > 0 {
self.summary = summaryArray.joined()
} else {
self.summary = nil
}
}
}
| 29.791667 | 108 | 0.642657 |
e086752f26307e83710793e31613c04bfa6dde22 | 3,204 | //
// BeersTests.swift
// BeersTests
//
// Created by Christian Elies on 09.05.21.
// Copyright © 2021 Christian Elies. All rights reserved.
//
@testable import Beers
import ComposableArchitecture
import Foundation
import XCTest
final class BeersTests: XCTestCase {
private let scheduler = DispatchQueue.test
private let beers: [Beer] = [.mock(), .mock()]
private lazy var environment = BeerListEnvironment(
mainQueue: scheduler.eraseToAnyScheduler,
fetchBeers: { Effect(value: self.beers) },
nextBeers: { Effect(value: .init(beers: [], page: 1)) },
fetchBeer: { id in Effect(value: .mock(id: id)) },
moveBeer: { _, _ in Effect(value: ()) },
deleteBeer: { _ in Effect(value: ()) }
)
func testOnAppear() {
let store = TestStore(
initialState: BeerListState(rowStates: [], viewState: .loading, isLoading: true),
reducer: BeerListModule.reducer,
environment: environment
)
store.assert(
.send(.onAppear),
.receive(.fetchBeers),
.do { self.scheduler.advance() },
.receive(.fetchBeersResponse(.success(.init(beers: beers, page: 1)))) { state in
state.isLoading = false
state.page = 1
let rowStates = self.beers.map { BeerListRowState(beer: $0, detailState: nil) }
state.rowStates = .init(uniqueElements: rowStates)
state.viewState = .loaded(rowStates)
}
)
}
func testSelectBeer() {
let beer: Beer = .mock()
let rowStates: [BeerListRowState] = [.init(beer: beer, detailState: nil)]
let store = TestStore(
initialState: BeerListState(
page: 1,
rowStates: .init(uniqueElements: rowStates),
viewState: .loaded(rowStates),
isLoading: false
),
reducer: BeerListModule.reducer,
environment: environment
)
store.send(.selectBeer(beer: beer)) { state in
state.selection = beer
}
}
func testRefresh() {
let beer: Beer = .mock()
let rowStates: [BeerListRowState] = [.init(beer: beer, detailState: nil)]
let store = TestStore(
initialState: BeerListState(
page: 1,
rowStates: .init(uniqueElements: rowStates),
viewState: .loaded(rowStates),
isLoading: false
),
reducer: BeerListModule.reducer,
environment: environment
)
store.assert(
.send(.refresh),
.receive(.fetchBeers) { state in
state.isLoading = true
},
.do { self.scheduler.advance() },
.receive(.fetchBeersResponse(.success(.init(beers: beers, page: 1)))) { state in
state.isLoading = false
let rowStates = self.beers.map { BeerListRowState(beer: $0, detailState: nil) }
state.rowStates = .init(uniqueElements: rowStates)
state.viewState = .loaded(rowStates)
}
)
}
}
| 33.030928 | 95 | 0.553371 |
fe8fc811cd90cdacd41eed94d15ba35319294715 | 493 | //
// ErrorsActor.swift
// SwiftyTroupeExample
//
// Created by Andryuhin Aleksandr Gennadevich on 10/9/18.
// Copyright © 2018 Andryuhin Aleksandr Gennadevich. All rights reserved.
//
import Foundation
enum ErrorHandlerMessage {
case networkError(Error?)
}
class ErrorsActor: BaseActor {
override func receive(_ message: Any) {
guard let _ = message as? ErrorHandlerMessage else {
return super.receive(message)
}
// handle message
}
}
| 19.72 | 74 | 0.675456 |
db27a1b6090ec4f2fbe83e57581030a6e784e7d4 | 10,022 | //
// ClibmingDatabase.swift
// MountainTop
//
// Created by CHANGGUEN YU on 08/09/2019.
// Copyright © 2019 CHANGGUEN YU. All rights reserved.
//
import Foundation
import SQLite
final class ClibmingDatabase {
// MARK: - Property
private var recordDB: Connection!
private var idDB: Connection!
private let userRecode = Table("UserRecode")
private let id = Expression<Int>("id")
private let startTime = Expression<Double>("StartTime")
private let finishTime = Expression<Double>("FinishTime")
private let record = Expression<String>("Record")
private let mountainID = Expression<Int>("idMountain")
private let usingID = Table("StartID")
private let primeID = Expression<Int>("id")
private let userID = Expression<Int>("using")
// MARK: - init
init?() {
do {
let documentDirectory = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// 사용자 등산기록 table
let recordFileUrl = documentDirectory.appendingPathComponent("userRecode").appendingPathExtension("sqlite3")
let recordDatabase = try Connection(recordFileUrl.path)
self.recordDB = recordDatabase
// 사용자 등산도전 id 기록 table
let idFileUrl = documentDirectory.appendingPathComponent("usingID").appendingPathExtension("sqlite3")
let idDatabase = try Connection(idFileUrl.path)
self.idDB = idDatabase
// table 생성
self.createUserRecodeTable()
self.createUsingIDTable()
} catch {
print("error: \(error)")
return nil
}
}
// MARK: - create id Table
private func createUserRecodeTable() {
let table = self.userRecode.create { t in
t.column(self.id, primaryKey: true)
t.column(self.startTime)
t.column(self.finishTime)
t.column(self.record)
t.column(self.mountainID)
}
do {
try self.recordDB.run(table)
print("create success!!")
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("error createTable: \(error.localizedDescription)")
}
}
private func createUsingIDTable() {
let table = self.usingID.create { t in
t.column(self.primeID, primaryKey: true)
t.column(self.userID)
}
do {
try self.idDB.run(table)
print("create success!!")
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("error createTable: \(error.localizedDescription)")
}
}
private func insertID(_ id: Int) {
print("setId")
let insertId = self.usingID.insert(self.userID <- id)
do {
try self.idDB.run(insertId)
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("insert error insertRecode: \(error.localizedDescription)")
}
}
public func updateID(_ id: Int) {
print("updateId")
if self.getIDTotal() == 0 {
self.insertID(0)
}
let updateFilter = self.usingID.filter(self.primeID == 1)
let updateId = updateFilter.update(self.userID <- id)
do {
try self.idDB.run(updateId)
print("recording update success id: \(id)")
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("update updateRecode: \(error.localizedDescription)")
}
}
public func getUsingID() -> Int? {
do {
let getID = self.usingID.filter(self.primeID == 1)
for ids in try idDB.prepare(getID) {
let id = try ids.get(self.userID)
return id != 0 ? id : nil
}
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
} catch {
print("getUsingID error: \(error.localizedDescription)")
}
self.updateID(0)
return nil
}
private func getIDTotal() -> Int {
let count = try? self.idDB.scalar(self.usingID.count)
print("count: \(String(describing: count))")
return count ?? 0
}
public func insertRecode(start: Double, finish: Double?, recode: String, mountainID: Int) -> Int {
print("insert Recode: \(start), \(Date(timeIntervalSinceReferenceDate: start as TimeInterval))")
let insertRecode = self.userRecode.insert(self.startTime <- start,
self.finishTime <- finish ?? 0.0,
self.record <- record,
self.mountainID <- mountainID
)
do {
let id = try self.recordDB.run(insertRecode)
print("insert success!! id: \(String(describing: id))")
return Int(id)
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
} catch {
print("insert error insertRecode: \(error.localizedDescription)")
}
return 0
}
public func updateRecode(updateID: Int, finish: Double, record: String) {
print("update Recode: \(finish), \(Date(timeIntervalSinceReferenceDate: finish as TimeInterval))")
let updateFilter = self.userRecode.filter(self.id == updateID)
let updateRecode = updateFilter.update([self.finishTime <- finish,
self.record <- record
])
do {
let id = try self.recordDB.run(updateRecode)
print("update success id: \(id)")
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("update updateRecode: \(error.localizedDescription)")
}
}
public func deleteRecode(delete: Int) {
print("delete Recode")
do {
let deleteId = self.userRecode.filter(self.id == delete)
try self.recordDB.run(deleteId.delete())
print("delete succes!!")
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
}catch {
print("delete error: \(error.localizedDescription)")
}
}
public func getTotal() -> Int {
let count = try? self.recordDB.scalar(self.userRecode.count)
print("count: \(String(describing: count))")
return count ?? 0
}
public func getAllRecode(complete: @escaping ([UserRecord]) -> Void) {
do {
var records = [UserRecord]()
for record in try recordDB.prepare(userRecode) {
let id = try record.get(self.id)
let start = try record.get(self.startTime)
let finish = try record.get(self.finishTime)
let climbingRecord = try record.get(self.record)
let mountainID = try record.get(self.mountainID)
print("id: \(id), start: \(start), finish: \(finish), record: \(climbingRecord), mountainID: \(mountainID)")
records.append(UserRecord(id: id,
start: Date(timeIntervalSinceReferenceDate: start),
finish: Date(timeIntervalSinceReferenceDate: finish),
recode: climbingRecord,
mountainID: mountainID))
}
complete(records)
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
} catch {
print("delete error: \(error.localizedDescription)")
}
}
public func getRecordID(id: Int) -> [UserRecord] {
do {
var records = [UserRecord]()
let getRow = self.userRecode.filter(self.id == id)
for record in try recordDB.prepare(getRow) {
let id = try record.get(self.id)
let start = try record.get(self.startTime)
let finish = try record.get(self.finishTime)
let climbingRecord = try record.get(self.record)
let mountainID = try record.get(self.mountainID)
records.append(UserRecord(id: id,
start: Date(timeIntervalSinceReferenceDate: start),
finish: finish != 0.0 ? Date(timeIntervalSinceReferenceDate: finish) : nil,
recode: climbingRecord,
mountainID: mountainID))
}
return records
// complete(records)
} catch let Result.error(message, code, statement) where code == SQLITE_CONSTRAINT {
print("constraint failed: \(message), in \(String(describing: statement)), code: \(code)")
} catch {
print("delete error: \(error.localizedDescription)")
}
return []
}
}
//let published_at = Expression<Date>("published_at")
//
//let published = posts.filter(published_at <= Date())
//// SELECT * FROM "posts" WHERE "published_at" <= '2014-11-18T12:45:30.000'
//
//let startDate = Date(timeIntervalSince1970: 0)
//let published = posts.filter(startDate...Date() ~= published_at)
//// SELECT * FROM "posts" WHERE "published_at" BETWEEN '1970-01-01T00:00:00.000' AND '2014-11-18T12:45:30.000'
//DateFunctions.date("now")
//// date('now')
//Date().date
//// date('2007-01-09T09:41:00.000')
//Expression<Date>("date").date
//// date("date")
| 35.413428 | 136 | 0.613351 |
22b2120ad0fccc594698beaab7e2b23abc797aa9 | 1,392 | import Foundation
extension Section {
var shouldBadgeComments: Bool {
switch self {
case .all:
return Settings.showCommentsEverywhere
case .closed, .merged:
return Settings.scanClosedAndMergedItems
case .mentioned, .mine, .participated:
return true
case .snoozed, .none:
return false
}
}
var shouldListReactions: Bool {
if API.shouldSyncReactions {
return shouldBadgeComments
}
return false
}
var shouldListStatuses: Bool {
if !Settings.showStatusItems {
return false
}
switch self {
case .all, .closed, .merged:
return Settings.showStatusesOnAllItems
case .mentioned, .mine, .participated:
return true
case .snoozed, .none:
return false
}
}
var shouldCheckStatuses: Bool {
if !Settings.showStatusItems {
return false
}
switch self {
case .all, .closed, .merged:
return Settings.showStatusesOnAllItems
case .mentioned, .mine, .participated, .snoozed:
return true
case .none:
return Settings.hidePrsThatArentPassing // if visibility depends on statuses, check for statuses on hidden PRs because they may change
}
}
}
| 26.769231 | 146 | 0.575431 |
0efa3b5954f56268172e16daf532acfde2c49dc2 | 3,654 | //
// MainMenuVC.swift
// Project-Swift
//
// Created by Erico GT on 26/07/17.
// Copyright © 2017 Atlantic Solutions. All rights reserved.
//
//MARK: - • INTERFACE HEADERS
//MARK: - • FRAMEWORK HEADERS
import UIKit
//MARK: - • OTHERS IMPORTS
class MainMenuVC: PMViewController{
//MARK: - • LOCAL DEFINES
//MARK: - • PUBLIC PROPERTIES
//MARK: - • PRIVATE PROPERTIES
//MARK: - • INITIALISERS
//MARK: - • CUSTOM ACCESSORS (SETS & GETS)
//MARK: - • DEALLOC
deinit {
// NSNotificationCenter no longer needs to be cleaned up!
}
//MARK: - • SUPER CLASS OVERRIDES
override func setupLayout(screenName:String){
super.setupLayout(screenName: "Tela de Exemplo")
//Caso seja preciso delegação para o alertView (a classe deve implmentar 'ASAlertViewDelegate' e 'ASAlertViewDataSource'):
//self.alertView.setDelegate(self)
//self.alertView.setDataSource(self)
//Aditional code here...
}
//MARK: - • CONTROLLER LIFECYCLE/ TABLEVIEW/ DATA-SOURCE
override func viewDidLoad() {
super.viewDidLoad()
App.Delegate.updateTabBarController()
//pod 'SCLAlertView'
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.leftBarButtonItem = App.Delegate.createSideMenuItem()
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .fastForward, target: self, action: #selector(actionOpenVariableContainerSample(sender:)))
self.view.backgroundColor = App.Style.colorView_Light
let arrayImages:Array<UIImage> = [UIImage(named:"flame_a_0001.png")!,
UIImage(named:"flame_a_0002.png")!,
UIImage(named:"flame_a_0003.png")!,
UIImage(named:"flame_a_0004.png")!,
UIImage(named:"flame_a_0005.png")!,
UIImage(named:"flame_a_0006.png")!]
let alert:SCLAlertViewPlus = SCLAlertViewPlus.createRichAlert(bodyMessage: "Este aplicativo é um projeto modelo para Swift 4.0.\nVárias classes, frameworks e pods já constam no projeto, prontas para uso.\n\nBasta fazer uma cópia e renomear para um novo projeto!", images: arrayImages, animationTimePerFrame: 0.1)
alert.addButton(title: "OK", type: SCLAlertButtonType.Default){
print("OK")
}
alert.showSuccess("Bem vindo!", subTitle: "")
}
//MARK: - • INTERFACE/PROTOCOL METHODS
//MARK: - • PUBLIC METHODS
//MARK: - • ACTION METHODS
//MARK: - • PRIVATE METHODS (INTERNAL USE ONLY)
@objc private func actionOpenVariableContainerSample(sender:Any){
self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: " ", style: .plain, target: nil, action: nil);
//
let storyboard:UIStoryboard = UIStoryboard.init(name: "Test", bundle: Bundle.main)
let vcProd:PickUpVariableContainerVC = storyboard.instantiateViewController(withIdentifier: "PickUpVariableContainerVC") as! PickUpVariableContainerVC
vcProd.awakeFromNib()
self.navigationController?.pushViewController(vcProd, animated: true)
}
}
| 31.5 | 320 | 0.60208 |
e965956c10a088b16148316b71b6ddf0e1794c88 | 9,100 | // The MIT License (MIT)
//
// Copyright (c) 2019 Lucas Nelaupe
//
// 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
/// `JSONEncoder` and `JSONDecoder` to serialize JobInfo
public class DecodableSerializer: JobInfoSerializer {
private let encoder: JSONEncoder
private let decoder: JSONDecoder
/// Init decodable with custom `JSONEncoder` and `JSONDecoder`
public init(encoder: JSONEncoder = JSONEncoder(), decoder: JSONDecoder = JSONDecoder()) {
self.encoder = encoder
self.decoder = decoder
}
public func serialize(info: JobInfo) throws -> String {
let encoded = try encoder.encode(info)
guard let string = String(data: encoded, encoding: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [],
debugDescription: "Unable to convert decoded data to utf-8")
)
}
return string
}
public func deserialize(json: String) throws -> JobInfo {
guard let data = json.data(using: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [],
debugDescription: "Unable to convert decoded data to utf-8")
)
}
return try decoder.decode(JobInfo.self, from: data)
}
}
extension JobInfo: Decodable {
enum JobInfoKeys: String, CodingKey {
case type = "type"
case uuid = "uuid"
case override = "override"
case includeExecutingJob = "includeExecutingJob"
case queueName = "group"
case tags = "tags"
case delay = "delay"
case deadline = "deadline"
case requireNetwork = "requireNetwork"
case isPersisted = "isPersisted"
case params = "params"
case createTime = "createTime"
case interval = "runCount"
case maxRun = "maxRun"
case executor = "executor"
case retries = "retries"
case runCount = "interval"
case requireCharging = "requireCharging"
case priority = "priority"
case qualityOfService = "qualityOfService"
case timeout = "timeout"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: JobInfoKeys.self)
let type: String = try container.decode(String.self, forKey: .type)
let uuid: String = try container.decode(String.self, forKey: .uuid)
let override: Bool = try container.decode(Bool.self, forKey: .override)
let includeExecutingJob: Bool = try container.decode(Bool.self, forKey: .includeExecutingJob)
let queueName: String = try container.decode(String.self, forKey: .queueName)
let tags: Set<String> = try container.decode(Set.self, forKey: .tags)
let delay: TimeInterval? = try container.decodeIfPresent(TimeInterval.self, forKey: .delay)
let deadline: Date? = try container.decodeIfPresent(Date.self, forKey: .deadline)
let requireNetwork: NetworkType = try container.decode(NetworkType.self, forKey: .requireNetwork)
let isPersisted: Bool = try container.decode(Bool.self, forKey: .isPersisted)
let params: [String: Any] = try container.decode([String: Any].self, forKey: .params)
let createTime: Date = try container.decode(Date.self, forKey: .createTime)
let interval: TimeInterval = try container.decode(TimeInterval.self, forKey: .interval)
let maxRun: Limit = try container.decode(Limit.self, forKey: .maxRun)
let executor: Executor = try container.decode(Executor.self, forKey: .executor)
let retries: Limit = try container.decode(Limit.self, forKey: .retries)
let runCount: Double = try container.decode(Double.self, forKey: .runCount)
let requireCharging: Bool = try container.decode(Bool.self, forKey: .requireCharging)
let priority: Int? = try container.decode(Int?.self, forKey: .priority)
let qualityOfService: Int? = try container.decode(Int?.self, forKey: .qualityOfService)
let timeout: TimeInterval? = try container.decode(TimeInterval?.self, forKey: .timeout)
self.init(
type: type,
queueName: queueName,
uuid: uuid,
override: override,
includeExecutingJob: includeExecutingJob,
tags: tags,
delay: delay,
deadline: deadline,
requireNetwork: requireNetwork,
isPersisted: isPersisted,
params: params,
createTime: createTime,
interval: interval,
maxRun: maxRun,
executor: executor,
retries: retries,
runCount: runCount,
requireCharging: requireCharging,
priority: Operation.QueuePriority(fromValue: priority),
qualityOfService: QualityOfService(fromValue: qualityOfService),
timeout: timeout
)
}
}
extension JobInfo: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: JobInfoKeys.self)
try container.encode(type, forKey: .type)
try container.encode(uuid, forKey: .uuid)
try container.encode(override, forKey: .override)
try container.encode(includeExecutingJob, forKey: .includeExecutingJob)
try container.encode(queueName, forKey: .queueName)
try container.encode(tags, forKey: .tags)
try container.encode(delay, forKey: .delay)
try container.encode(deadline, forKey: .deadline)
try container.encode(requireNetwork, forKey: .requireNetwork)
try container.encode(isPersisted, forKey: .isPersisted)
try container.encode(params, forKey: .params)
try container.encode(createTime, forKey: .createTime)
try container.encode(interval, forKey: .interval)
try container.encode(maxRun, forKey: .maxRun)
try container.encode(executor, forKey: .executor)
try container.encode(retries, forKey: .retries)
try container.encode(runCount, forKey: .runCount)
try container.encode(requireCharging, forKey: .requireCharging)
try container.encode(priority.rawValue, forKey: .priority)
try container.encode(qualityOfService.rawValue, forKey: .qualityOfService)
try container.encode(timeout, forKey: .timeout)
}
}
internal extension KeyedDecodingContainer {
func decode(_ type: Data.Type, forKey key: KeyedDecodingContainer.Key) throws -> Data {
let json = try self.decode(String.self, forKey: key)
guard let data = json.data(using: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [key],
debugDescription: "Unable to convert string to utf-8")
)
}
return data
}
func decode(_ type: [String: Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [String: Any] {
let data = try self.decode(Data.self, forKey: key)
guard let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [key],
debugDescription: "Decoded value is not a dictionary")
)
}
return dict
}
}
internal extension KeyedEncodingContainer {
mutating func encode(_ value: [String: Any], forKey key: KeyedEncodingContainer.Key) throws {
let jsonData = try JSONSerialization.data(withJSONObject: value)
guard let utf8 = String(data: jsonData, encoding: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [key],
debugDescription: "The given data was not valid JSON.")
)
}
try self.encode(utf8, forKey: key)
}
}
| 44.390244 | 120 | 0.653077 |
715f5c93d8dd66ae37c173838741f21feaf85540 | 1,990 | //
// q371-sum-of-two-integers.swift
// leetcode-swift
// Source* : https://leetcode.com/problems/sum-of-two-integers/
// Category* : BitManipulation
//
// Created by Tianyu Wang on 16/7/1.
// Github : http://github.com/wty21cn
// Website : http://wty.im
// Linkedin : https://www.linkedin.com/in/wty21cn
// Mail : mailto:[email protected]
/******************************************************************************************************
*
* Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
*
* Example:
* Given a = 1 and b = 2, return 3.
*
* Credits:
* Special thanks to @fujiaozhu for adding this problem and creating all test cases.
*
******************************************************************************************************/
/*
For bit by by manipulation addition, without considering the adding, there are four cases
0+0=0
0+1=1
1+0=1
1+1=0
so you can get the result digit at their original position using XOR (^)
Then let's deal with adding, also four cases
0+0=0 x
0+1=1 x > no adding
1+0=1 x
1+1=0 -> has adding
you can get the adding generatee by the addtion at each position using AND (&)
Consider the position of each digit is "ABC", so the adding generated by addition on position C will be added to position B, it is the same for position B and A.
you can get the final adding for this round by using left shift (<<)
*/
import Foundation
struct q371 {
class Solution {
func getSum(_ a: Int, _ b: Int) -> Int {
var sum = a
var carry = b
while carry != 0 {
let t = sum ^ carry
carry = (sum & carry) << 1
sum = t
}
return sum
}
}
static func getSolution() -> Void {
print(Solution().getSum(-1203940,1230912848102))
}
}
| 25.844156 | 162 | 0.524623 |
fc803bdd77b51653bf9548c10e5d3c56740a1608 | 1,732 | //
// String+SafeLookup.swift
// Swiftest
//
// Created by Brian Strobach on 12/17/18.
//
extension String {
/// Swiftest: Safely subscript string with index.
///
/// "Hello World!"[safe: 3] -> "l"
/// "Hello World!"[safe: 20] -> nil
///
/// - Parameter i: index.
public subscript(safe i: Int) -> Character? {
guard i >= 0 && i < count else { return nil }
return self[index(startIndex, offsetBy: i)]
}
/// Swiftest: Safely subscript string within a half-open range.
///
/// "Hello World!"[safe: 6..<11] -> "World"
/// "Hello World!"[safe: 21..<110] -> nil
///
/// - Parameter range: Half-open range.
public subscript(safe range: CountableRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil }
return String(self[lowerIndex..<upperIndex])
}
/// Swiftest: Safely subscript string within a closed range.
///
/// "Hello World!"[safe: 6...11] -> "World!"
/// "Hello World!"[safe: 21...110] -> nil
///
/// - Parameter range: Closed range.
public subscript(safe range: ClosedRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil }
return String(self[lowerIndex..<upperIndex])
}
}
| 37.652174 | 140 | 0.598152 |
200d0a314acb0fd1437497a93e4ef1065a730744 | 1,093 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SUEModifier",
platforms: [
.iOS(.v14),
.macOS(.v11)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "SUEModifier",
targets: ["SUEModifier"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "SUEModifier",
dependencies: []),
.testTarget(
name: "SUEModifierTests",
dependencies: ["SUEModifier"]),
]
)
| 33.121212 | 117 | 0.607502 |
e98cd1abfcc42f88df60605491d617ca50ea3d98 | 955 | // ===----------------------------------------------------------------------===
//
// This source file is part of the CosmosSwift open source project.
//
// ResponseEcho.swift last updated 16/07/2020
//
// Copyright © 2020 Katalysis B.V. and the CosmosSwift project authors.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of CosmosSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
// ===----------------------------------------------------------------------===
import Foundation
/// Echoes a string to test an abci client/server implementation.
public struct ResponseEcho {
/// The string sent in the request.
public let message: String
/// Echoes a string to test an abci client/server implementation.
/// - Parameter message: The string sent in the request.
public init(message: String) {
self.message = message
}
}
| 31.833333 | 79 | 0.588482 |
8a4852bd88122485a579146de825322622979ef7 | 1,901 | import SwiftUI
import SharedUI
import SongPlaying
import PlaylistList
public struct HomeView: View {
@ObservedObject var viewModel = HomeViewModel()
public init() {}
public var body: some View {
NavigationView {
ZStack {
links
allViews
}
.navigationTitle(viewModel.title)
.navigationBarTitleDisplayMode(.inline)
}
}
private var gradientLine: some View {
LinearGradient(
colors: gradientColors,
startPoint: .leading,
endPoint: .trailing
).frame(height: 1)
}
private var gradientColors: [Color] {
[
.newmLightBlue,
.newmBlue,
.newmPurple,
.newmPink,
.newmRed,
.newmOrange,
.newmYellow,
.newmGreen
]
}
private var links: some View {
ZStack {
// IDLink<ArtistView>(selectedID: viewModel.selectedArtist?.artistID)
IDLink<SongPlayingView>(selectedID: viewModel.selectedSong?.songID)
IDLink<PlaylistListView>(selectedID: viewModel.selectedPlaylist?.playlistID)
}
}
private var allViews: some View {
VStack {
gradientLine
ScrollView {
VStack {
SectionSelectorView(selectedIndex: $viewModel.selectedSectionIndex, sectionTitles: viewModel.sections)
HomeScrollingContentView<ArtistCell>(selectedDataModel: $viewModel.selectedArtist, dataModels: viewModel.artists, title: viewModel.artistSectionTitle, spacing: 8)
HomeScrollingContentView<SongCell>(selectedDataModel: $viewModel.selectedSong, dataModels: viewModel.songs, title: viewModel.songsSectionTitle, spacing: 8)
HomeScrollingContentView<PlaylistCell>(selectedDataModel: $viewModel.selectedPlaylist, dataModels: viewModel.playlists, title: viewModel.playlistsSectionTitle, spacing: 12)
}
}
}
.frame(maxHeight: .infinity, alignment: .top)
.onAppear { viewModel.deselectAll() }
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
.preferredColorScheme(.dark)
}
}
| 25.689189 | 177 | 0.740663 |
e6a11862533232839dc8ef164f8eb2be49eb5915 | 1,281 | //
// MoreOptionsView.swift
// Blint
//
// Created by Ferit Bölezek on 2017-06-22.
// Copyright © 2017 Ferit Bölezek. All rights reserved.
//
import UIKit
class MoreOptionsView: UIView {
weak var delegate: MoreViewDelegate?
@IBOutlet weak var blockButton: UIButton!
@IBOutlet weak var moreOptionsNameTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
layoutView()
}
override init(frame: CGRect) {
super.init(frame: frame)
layoutView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layoutView()
}
func layoutView() {
self.clipsToBounds = true
self.layer.cornerRadius = 10
let view = Bundle.main.loadNibNamed("moreOptions", owner: self, options: nil)?.first as! UIView
view.frame = self.bounds
self.addSubview(view)
}
@IBAction func reportThisUserTapped(_ sender: Any) {
delegate?.reportUserTapped()
}
@IBAction func blockThisUserTapped(_ sender: Any) {
delegate?.blockUserTapped()
}
@IBAction func cancelTapped(_ sender: Any) {
delegate?.cancelTapped()
}
}
| 21.35 | 103 | 0.593286 |
48d695810bbdde764b1bd2cc79e216f62e2131e0 | 25,977 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TulsiGenerator
class XcodeProjectGeneratorTests: XCTestCase {
static let outputFolderPath = "/dev/null/project"
static let projectName = "ProjectName"
let outputFolderURL = URL(fileURLWithPath: XcodeProjectGeneratorTests.outputFolderPath)
let xcodeProjectPath = "\(XcodeProjectGeneratorTests.outputFolderPath)/\(XcodeProjectGeneratorTests.projectName).xcodeproj"
let workspaceRoot = URL(fileURLWithPath: "/workspace")
let testTulsiVersion = "9.99.999.9999"
let buildTargetLabels = ["//test:MainTarget", "//test/path/to/target:target"].map({ BuildLabel($0) })
let pathFilters = Set<String>(["test", "additional"])
let additionalFilePaths = ["additional/File1", "additional/File2"]
let bazelURL = TulsiParameter(value: URL(fileURLWithPath: "/test/dir/testBazel"),
source: .explicitlyProvided)
let resourceURLs = XcodeProjectGenerator.ResourceSourcePathURLs(
buildScript: URL(fileURLWithPath: "/scripts/Build"),
cleanScript: URL(fileURLWithPath: "/scripts/Clean"),
extraBuildScripts: [URL(fileURLWithPath: "/scripts/Logging")],
iOSUIRunnerEntitlements: URL(fileURLWithPath: "/generatedProjectResources/iOSXCTRunner.entitlements"),
macOSUIRunnerEntitlements: URL(fileURLWithPath: "/generatedProjectResources/macOSXCTRunner.entitlements"),
stubInfoPlist: URL(fileURLWithPath: "/generatedProjectResources/StubInfoPlist.plist"),
stubIOSAppExInfoPlistTemplate: URL(fileURLWithPath: "/generatedProjectResources/stubIOSAppExInfoPlist.plist"),
stubWatchOS2InfoPlist: URL(fileURLWithPath: "/generatedProjectResources/StubWatchOS2InfoPlist.plist"),
stubWatchOS2AppExInfoPlist: URL(fileURLWithPath: "/generatedProjectResources/StubWatchOS2AppExInfoPlist.plist"),
bazelWorkspaceFile: URL(fileURLWithPath: "/WORKSPACE"),
tulsiPackageFiles: [URL(fileURLWithPath: "/tulsi/tulsi_aspects.bzl")])
var config: TulsiGeneratorConfig! = nil
var mockLocalizedMessageLogger: MockLocalizedMessageLogger! = nil
var mockFileManager: MockFileManager! = nil
var mockExtractor: MockWorkspaceInfoExtractor! = nil
var generator: XcodeProjectGenerator! = nil
var writtenFiles = Set<String>()
override func setUp() {
super.setUp()
mockLocalizedMessageLogger = MockLocalizedMessageLogger()
mockFileManager = MockFileManager()
mockExtractor = MockWorkspaceInfoExtractor()
writtenFiles.removeAll()
}
func testSuccessfulGeneration() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.pbxproj"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.xcworkspace/xcuserdata/USER.xcuserdatad/WorkspaceSettings.xcsettings"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-path-to-target-target.xcscheme"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-MainTarget.xcscheme"))
let supportScriptsURL = mockFileManager.homeDirectoryForCurrentUser.appendingPathComponent(
"Library/Application Support/Tulsi/Scripts", isDirectory: true)
XCTAssert(mockFileManager.directoryOperations.contains(supportScriptsURL.path))
let cacheReaderURL = supportScriptsURL.appendingPathComponent("bazel_cache_reader",
isDirectory: false)
XCTAssert(mockFileManager.copyOperations.keys.contains(cacheReaderURL.path))
let xcp = "\(xcodeProjectPath)/xcuserdata/USER.xcuserdatad/xcschemes/xcschememanagement.plist"
XCTAssert(!mockFileManager.attributesMap.isEmpty)
mockFileManager.attributesMap.forEach { (path, attrs) in
XCTAssertNotNil(attrs[.modificationDate])
}
XCTAssert(mockFileManager.writeOperations.keys.contains(xcp))
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testExtensionPlistGeneration() {
@discardableResult
func addRule(_ labelName: String,
type: String,
attributes: [String: AnyObject] = [:],
weakDependencies: Set<BuildLabel>? = nil,
extensions: Set<BuildLabel>? = nil,
extensionType: String? = nil,
productType: PBXTarget.ProductType? = nil) -> BuildLabel {
let label = BuildLabel(labelName)
mockExtractor.labelToRuleEntry[label] = Swift.type(of: self).makeRuleEntry(label,
type: type,
attributes: attributes,
weakDependencies: weakDependencies,
extensions: extensions,
productType: productType,
extensionType: extensionType)
return label
}
let test1 = addRule("//test:ExtFoo", type: "ios_extension", extensionType: "com.apple.extension-foo", productType: .AppExtension)
let test2 = addRule("//test:ExtBar", type: "ios_extension", extensionType: "com.apple.extension-bar", productType: .AppExtension)
addRule("//test:Application", type: "ios_application", extensions: [test1, test2], productType: .Application)
prepareGenerator(mockExtractor.labelToRuleEntry)
func assertPlist(withData data: Data, equalTo value: NSDictionary) {
let content = try! PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil) as! NSDictionary
XCTAssertEqual(content, value)
}
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(mockFileManager.writeOperations.keys.contains("\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtFoo.plist"))
assertPlist(withData: mockFileManager.writeOperations["\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtFoo.plist"]!,
equalTo: ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.extension-foo"]])
XCTAssert(mockFileManager.writeOperations.keys.contains("\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtBar.plist"))
assertPlist(withData: mockFileManager.writeOperations["\(xcodeProjectPath)/.tulsi/Resources/Stub_test-ExtBar.plist"]!,
equalTo: ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.extension-bar"]])
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testUnresolvedLabelsThrows() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
mockExtractor.labelToRuleEntry = [:]
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
XCTFail("Generation succeeded unexpectedly")
} catch XcodeProjectGenerator.ProjectGeneratorError.labelResolutionFailed(let missingLabels) {
for label in buildTargetLabels {
XCTAssert(missingLabels.contains(label), "Expected missing label \(label) not found")
}
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testInvalidPathThrows() {
let ruleEntries = XcodeProjectGeneratorTests.labelToRuleEntryMapForLabels(buildTargetLabels)
prepareGenerator(ruleEntries)
let invalidOutputFolderString = "/dev/null/bazel-build"
let invalidOutputFolderURL = URL(fileURLWithPath: invalidOutputFolderString)
do {
_ = try generator.generateXcodeProjectInFolder(invalidOutputFolderURL)
XCTFail("Generation succeeded unexpectedly")
} catch XcodeProjectGenerator.ProjectGeneratorError.invalidXcodeProjectPath(let pathFound,
let reason) {
// Expected failure on path with a /bazel-* directory.
XCTAssertEqual(pathFound, invalidOutputFolderString)
XCTAssertEqual(reason, "a Bazel generated temp directory (\"/bazel-\")")
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testTestSuiteSchemeGenerationWithSkylarkUnitTest() {
checkTestSuiteSchemeGeneration("apple_unit_test",
testProductType: .UnitTest,
testHostAttributeName: "test_host")
}
func testTestSuiteSchemeGenerationWithSkylarkUITest() {
checkTestSuiteSchemeGeneration("apple_ui_test",
testProductType: .UIUnitTest,
testHostAttributeName: "test_host")
}
func checkTestSuiteSchemeGeneration(_ testRuleType: String,
testProductType: PBXTarget.ProductType,
testHostAttributeName: String) {
@discardableResult
func addRule(_ labelName: String,
type: String,
attributes: [String: AnyObject] = [:],
weakDependencies: Set<BuildLabel>? = nil,
productType: PBXTarget.ProductType? = nil) -> BuildLabel {
let label = BuildLabel(labelName)
mockExtractor.labelToRuleEntry[label] = Swift.type(of: self).makeRuleEntry(label,
type: type,
attributes: attributes,
weakDependencies: weakDependencies,
productType: productType)
return label
}
let app = addRule("//test:Application", type: "ios_application", productType: .Application)
let test1 = addRule("//test:TestOne",
type: testRuleType,
attributes: [testHostAttributeName: app.value as AnyObject],
productType: testProductType)
let test2 = addRule("//test:TestTwo",
type: testRuleType,
attributes: [testHostAttributeName: app.value as AnyObject],
productType: testProductType)
addRule("//test:UnusedTest", type: testRuleType, productType: testProductType)
addRule("//test:TestSuite", type: "test_suite", weakDependencies: Set([test1, test2]))
prepareGenerator(mockExtractor.labelToRuleEntry)
do {
_ = try generator.generateXcodeProjectInFolder(outputFolderURL)
mockLocalizedMessageLogger.assertNoErrors()
mockLocalizedMessageLogger.assertNoWarnings()
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.pbxproj"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/project.xcworkspace/xcuserdata/USER.xcuserdatad/WorkspaceSettings.xcsettings"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-Application.xcscheme"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-TestOne.xcscheme"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-TestTwo.xcscheme"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/test-UnusedTest.xcscheme"))
XCTAssert(writtenFiles.contains("\(xcodeProjectPath)/xcshareddata/xcschemes/TestSuite_Suite.xcscheme"))
} catch let e {
XCTFail("Unexpected exception \(e)")
}
}
func testProjectSDKROOT() {
func validate(_ types: [(String, String)], _ expectedSDKROOT: String?, line: UInt = #line) {
let rules = types.map() { tuple in
// Both the platform and osDeploymentTarget must be set in order to create a valid
// deploymentTarget for the RuleEntry.
XcodeProjectGeneratorTests.makeRuleEntry(BuildLabel(tuple.0), type: tuple.0, platformType: tuple.1,
osDeploymentTarget: "this_must_not_be_nil")
}
let sdkroot = XcodeProjectGenerator.projectSDKROOT(rules)
XCTAssertEqual(sdkroot, expectedSDKROOT, line: line)
}
let iosAppTuple = ("ios_application", "ios")
let tvExtensionTuple = ("tvos_extension", "tvos")
validate([iosAppTuple], "iphoneos")
validate([iosAppTuple, iosAppTuple], "iphoneos")
validate([iosAppTuple, tvExtensionTuple], nil)
validate([tvExtensionTuple], "appletvos")
}
// MARK: - Private methods
private static func labelToRuleEntryMapForLabels(_ labels: [BuildLabel]) -> [BuildLabel: RuleEntry] {
var ret = [BuildLabel: RuleEntry]()
for label in labels {
ret[label] = makeRuleEntry(label, type: "ios_application", productType: .Application)
}
return ret
}
private static func makeRuleEntry(_ label: BuildLabel,
type: String,
attributes: [String: AnyObject] = [:],
artifacts: [BazelFileInfo] = [],
sourceFiles: [BazelFileInfo] = [],
nonARCSourceFiles: [BazelFileInfo] = [],
dependencies: Set<BuildLabel> = Set(),
secondaryArtifacts: [BazelFileInfo] = [],
weakDependencies: Set<BuildLabel>? = nil,
buildFilePath: String? = nil,
objcDefines: [String]? = nil,
swiftDefines: [String]? = nil,
includePaths: [RuleEntry.IncludePath]? = nil,
extensions: Set<BuildLabel>? = nil,
productType: PBXTarget.ProductType? = nil,
extensionType: String? = nil,
platformType: String? = nil,
osDeploymentTarget: String? = nil) -> RuleEntry {
return RuleEntry(label: label,
type: type,
attributes: attributes,
artifacts: artifacts,
sourceFiles: sourceFiles,
nonARCSourceFiles: nonARCSourceFiles,
dependencies: dependencies,
secondaryArtifacts: secondaryArtifacts,
weakDependencies: weakDependencies,
extensions: extensions,
productType: productType,
platformType: platformType,
osDeploymentTarget: osDeploymentTarget,
buildFilePath: buildFilePath,
objcDefines: objcDefines,
swiftDefines: swiftDefines,
includePaths: includePaths,
extensionType: extensionType)
}
private func prepareGenerator(_ ruleEntries: [BuildLabel: RuleEntry]) {
let options = TulsiOptionSet()
// To avoid creating ~/Library folders and changing UserDefaults during CI testing.
config = TulsiGeneratorConfig(projectName: XcodeProjectGeneratorTests.projectName,
buildTargetLabels: Array(ruleEntries.keys),
pathFilters: pathFilters,
additionalFilePaths: additionalFilePaths,
options: options,
bazelURL: bazelURL)
let projectURL = URL(fileURLWithPath: xcodeProjectPath, isDirectory: true)
mockFileManager.allowedDirectoryCreates.insert(projectURL.path)
let tulsiworkspace = projectURL.appendingPathComponent("tulsi-workspace")
mockFileManager.allowedDirectoryCreates.insert(tulsiworkspace.path)
let bazelCacheReaderURL = mockFileManager.homeDirectoryForCurrentUser.appendingPathComponent(
"Library/Application Support/Tulsi/Scripts", isDirectory: true)
mockFileManager.allowedDirectoryCreates.insert(bazelCacheReaderURL.path)
let xcshareddata = projectURL.appendingPathComponent("project.xcworkspace/xcshareddata")
mockFileManager.allowedDirectoryCreates.insert(xcshareddata.path)
let xcuserdata = projectURL.appendingPathComponent("project.xcworkspace/xcuserdata/USER.xcuserdatad")
mockFileManager.allowedDirectoryCreates.insert(xcuserdata.path)
let xcschemes = projectURL.appendingPathComponent("xcshareddata/xcschemes")
mockFileManager.allowedDirectoryCreates.insert(xcschemes.path)
let userXcschemes = projectURL.appendingPathComponent("xcuserdata/USER.xcuserdatad/xcschemes")
mockFileManager.allowedDirectoryCreates.insert(userXcschemes.path)
let scripts = projectURL.appendingPathComponent(".tulsi/Scripts")
mockFileManager.allowedDirectoryCreates.insert(scripts.path)
let utils = projectURL.appendingPathComponent(".tulsi/Utils")
mockFileManager.allowedDirectoryCreates.insert(utils.path)
let resources = projectURL.appendingPathComponent(".tulsi/Resources")
mockFileManager.allowedDirectoryCreates.insert(resources.path)
let tulsiBazelRoot = projectURL.appendingPathComponent(".tulsi/Bazel")
mockFileManager.allowedDirectoryCreates.insert(tulsiBazelRoot.path)
let tulsiBazelPackage = projectURL.appendingPathComponent(".tulsi/Bazel/tulsi")
mockFileManager.allowedDirectoryCreates.insert(tulsiBazelPackage.path)
let mockTemplate = ["NSExtension": ["NSExtensionPointIdentifier": "com.apple.intents-service"]]
let templateData = try! PropertyListSerialization.data(fromPropertyList: mockTemplate, format: .xml, options: 0)
mockFileManager.mockContent[resourceURLs.stubIOSAppExInfoPlistTemplate.path] = templateData
mockExtractor.labelToRuleEntry = ruleEntries
generator = XcodeProjectGenerator(workspaceRootURL: workspaceRoot,
config: config,
localizedMessageLogger: mockLocalizedMessageLogger,
workspaceInfoExtractor: mockExtractor,
resourceURLs: resourceURLs,
tulsiVersion: testTulsiVersion,
fileManager: mockFileManager,
pbxTargetGeneratorType: MockPBXTargetGenerator.self)
generator.redactWorkspaceSymlink = true
generator.suppressModifyingUserDefaults = true
generator.suppressGeneratingBuildSettings = true
generator.writeDataHandler = { (url, _) in
self.writtenFiles.insert(url.path)
}
generator.usernameFetcher = { "USER" }
}
}
class MockFileManager: FileManager {
var filesThatExist = Set<String>()
var allowedDirectoryCreates = Set<String>()
var directoryOperations = [String]()
var copyOperations = [String: String]()
var writeOperations = [String: Data]()
var removeOperations = [String]()
var mockContent = [String: Data]()
var attributesMap = [String: [FileAttributeKey: Any]]()
override open var homeDirectoryForCurrentUser: URL {
return URL(fileURLWithPath: "/Users/__MOCK_USER__", isDirectory: true)
}
override func fileExists(atPath path: String) -> Bool {
return filesThatExist.contains(path)
}
override func createDirectory(at url: URL,
withIntermediateDirectories createIntermediates: Bool,
attributes: [FileAttributeKey: Any]?) throws {
guard !allowedDirectoryCreates.contains(url.path) else {
directoryOperations.append(url.path)
if let attributes = attributes {
self.setAttributes(attributes, path: url.path)
}
return
}
throw NSError(domain: "MockFileManager: Directory creation disallowed",
code: 0,
userInfo: nil)
}
override func createDirectory(atPath path: String,
withIntermediateDirectories createIntermediates: Bool,
attributes: [FileAttributeKey: Any]?) throws {
guard !allowedDirectoryCreates.contains(path) else {
directoryOperations.append(path)
if let attributes = attributes {
self.setAttributes(attributes, path: path)
}
return
}
throw NSError(domain: "MockFileManager: Directory creation disallowed",
code: 0,
userInfo: nil)
}
override func removeItem(at URL: URL) throws {
removeOperations.append(URL.path)
}
override func removeItem(atPath path: String) throws {
removeOperations.append(path)
}
override func copyItem(at srcURL: URL, to dstURL: URL) throws {
copyOperations[dstURL.path] = srcURL.path
}
override func copyItem(atPath srcPath: String, toPath dstPath: String) throws {
copyOperations[dstPath] = srcPath
}
override func contents(atPath path: String) -> Data? {
return mockContent[path]
}
override func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey : Any]? = nil) -> Bool {
if writeOperations.keys.contains(path) {
fatalError("Attempting to overwrite an existing file at \(path)")
}
writeOperations[path] = data
if let attr = attr {
self.setAttributes(attr, path: path)
}
return true
}
fileprivate func setAttributes(_ attributes: [FileAttributeKey : Any], path: String) {
var currentAttributes = attributesMap[path] ?? [FileAttributeKey : Any]()
attributes.forEach { (k, v) in
currentAttributes[k] = v
}
attributesMap[path] = currentAttributes
}
override func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws {
self.setAttributes(attributes, path: path)
}
}
final class MockPBXTargetGenerator: PBXTargetGeneratorProtocol {
var project: PBXProject
static func getRunTestTargetBuildConfigPrefix() -> String {
return "TestRunner__"
}
static func workingDirectoryForPBXGroup(_ group: PBXGroup) -> String {
return ""
}
static func mainGroupForOutputFolder(_ outputFolderURL: URL, workspaceRootURL: URL) -> PBXGroup {
return PBXGroup(name: "mainGroup",
path: "/A/Test/Path",
sourceTree: .Absolute,
parent: nil)
}
required init(bazelPath: String,
bazelBinPath: String,
project: PBXProject,
buildScriptPath: String,
stubInfoPlistPaths: StubInfoPlistPaths,
tulsiVersion: String,
options: TulsiOptionSet,
localizedMessageLogger: LocalizedMessageLogger,
workspaceRootURL: URL,
suppressCompilerDefines: Bool,
redactWorkspaceSymlink: Bool) {
self.project = project
}
func generateFileReferencesForFilePaths(_ paths: [String], pathFilters: Set<String>?) {
}
func registerRuleEntryForIndexer(_ ruleEntry: RuleEntry,
ruleEntryMap: RuleEntryMap,
pathFilters: Set<String>,
processedEntries: inout [RuleEntry: (NSOrderedSet)]) {
}
func generateIndexerTargets() -> [String: PBXTarget] {
return [:]
}
func generateBazelCleanTarget(_ scriptPath: String, workingDirectory: String) {
}
func generateTopLevelBuildConfigurations(_ buildSettingOverrides: [String: String]) {
}
func generateBuildTargetsForRuleEntries(_ ruleEntries: Set<RuleEntry>,
ruleEntryMap: RuleEntryMap) throws {
// This works as this file only tests native targets that don't have multiple configurations.
let namedRuleEntries = ruleEntries.map() { (e: RuleEntry) -> (String, RuleEntry) in
return (e.label.asFullPBXTargetName!, e)
}
var testTargetLinkages = [(PBXTarget, BuildLabel)]()
for (name, entry) in namedRuleEntries {
let target = project.createNativeTarget(name,
deploymentTarget: entry.deploymentTarget,
targetType: entry.pbxTargetType!)
if let hostLabelString = entry.attributes[.test_host] as? String {
let hostLabel = BuildLabel(hostLabelString)
testTargetLinkages.append((target, hostLabel))
}
}
for (testTarget, testHostLabel) in testTargetLinkages {
let hostTarget = project.targetByName(testHostLabel.asFullPBXTargetName!) as! PBXNativeTarget
project.linkTestTarget(testTarget, toHostTarget: hostTarget)
}
}
}
| 47.230909 | 171 | 0.655118 |
79c7b68fc573361ee5b33a4bf7c12111d347a1b2 | 7,696 | import XCTest
@testable import Marshroute
final class PeekAndPopUtilityImplTests_invokesPopAction: BasePeekAndPopUtilityImplTestCase {
func testPeekAndPopUtility_invokesPopAction_ifSomeTransitionOccursNotDuringActivePeek() {
// Given
let expectation = self.expectation()
bindSourceViewControllerToWindow()
registerSourceViewControllerForPreviewing()
// When
invokeTransitionToPeekViewController(
popAction: {
expectation.fulfill()
}
)
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesPopAction_ifPeekBeginsOnOffscreenRegisteredViewControllerAndSomeTransitionOccurs() {
// Given
let expectation = self.expectation()
unbindSourceViewControllerFromWindow()
registerSourceViewControllerForPreviewing()
// When
beginPeekOnRegisteredViewController()
invokeTransitionToPeekViewController(
popAction: {
expectation.fulfill()
}
)
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesPopAction_ifPeekGetsCommitedOnOnscreenRegisteredViewController() {
// Given
let expectation = self.expectation()
bindSourceViewControllerToWindow()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
expectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
commitPickOnRegisteredViewController()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesPopAction_ifSamePeekFailedToBeginAndNewPeekGetsCommitedOnOnscreenRegisteredViewController() {
// Given
let expectation = self.expectation()
bindSourceViewControllerToWindow()
bindSourceViewController2ToWindow()
registerSourceViewControllerForPreviewing()
registerSourceViewController2ForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
expectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
beginPeekOnRegisteredViewController2()
commitPickOnRegisteredViewController2()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifPeekBeginsOnOnscreenRegisteredViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
invertedExpectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifPeekBeginsOnOnscreenRegisteredViewControllerWithNotNavigationParentViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
bindPeekViewControllerToAnotherParent()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
invertedExpectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifPeekGetsCommitedOnOnscreenRegisteredViewControllerWithNotPeekViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
invertedExpectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
commitPickOnRegisteredViewControllerToNotPeekViewController()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifPeekGetsInterruptedWithAnotherTransitionOnOnscreenRegisteredViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
invertedExpectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
interruptPeekWithAnotherTransitionOnRegisteredViewController()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifSamePeekIsAlreadyBeganAndNewPeekBeginsOnOnscreenRegisteredViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
bindSourceViewController2ToWindow()
registerSourceViewControllerForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController()
}
)
registerSourceViewController2ForPreviewing(
onPeek: { _ in
invertedExpectation.fulfill()
}
)
// When
beginPeekOnRegisteredViewController()
beginPeekOnRegisteredViewController2()
// Then
waitForExpectations(timeout: asyncTimeout)
}
func testPeekAndPopUtility_invokesNoPopAction_ifSamePeekFailedToBeginAndNewPeekBeginsOnOnscreenRegisteredViewController() {
// Given
let invertedExpectation = self.invertedExpectation()
bindSourceViewControllerToWindow()
bindSourceViewController2ToWindow()
registerSourceViewControllerForPreviewing()
registerSourceViewController2ForPreviewing(
onPeek: { _ in
self.invokeTransitionToPeekViewController(
popAction: {
invertedExpectation.fulfill()
}
)
}
)
// When
beginPeekOnRegisteredViewController()
beginPeekOnRegisteredViewController2()
// Then
waitForExpectations(timeout: asyncTimeout)
}
}
| 30.0625 | 137 | 0.587838 |
26f9b344faf632c48fa304c385862116900a3c14 | 697 | // swift-tools-version:5.6
import PackageDescription
let package = Package(
name: "Report",
platforms: [
.iOS(.v15)
],
products: [
.library(name: "Report", type: .dynamic, targets: ["Report"]),
.library(name: "ReportStatic", type: .static, targets: ["Report"])
],
dependencies: [
.package(url: "[email protected]:apple/swift-docc-plugin.git", from: "1.0.0")
],
targets: [
.target(
name: "Report",
dependencies: [],
path: "sources/main"
),
.testTarget(
name: "ReportTests",
dependencies: ["Report"],
path: "sources/tests"
)
]
)
| 24.034483 | 82 | 0.506456 |
ef2de07fbb6f3723d321dffcba81b76d72e72bbb | 357 | // swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "Ion",
platforms: [.iOS(.v10), .macOS(.v10_12), .tvOS(.v10), .watchOS(.v2)],
products: [
.library(
name: "Ion",
targets: ["Ion"]),
],
targets: [
.target(
name: "Ion",
path: "Common")
]
)
| 21 | 73 | 0.478992 |
e8a07ff66831d649ae6563a760a660550fb32f76 | 3,427 | //
// JXCoolTransitioningDelegate.swift
// 按钮位置变化
//
// Created by apple on 16/2/17.
// Copyright © 2016年 kang. All rights reserved.
//
import UIKit
class JXCoolTransitioningDelegate: NSObject {
fileprivate var isPop : Bool = true
}
//MARK: delegate - UIViewControllerAnimatedTransitioning(动画代理)
extension JXCoolTransitioningDelegate : UIViewControllerAnimatedTransitioning{
//转场时间
internal func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
return 0.25
}
/// 转场动画(主动提供转场动画,一旦实现了这个方法,原有的转场动画失效)
///
/// - Parameter transitionContext: 转场上下文,提供转场动画的相关信息
internal func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
let fromVc = transitionContext.viewController(forKey: .from)
let toVc = transitionContext.viewController(forKey: .to)
let animateVc = isPop ? toVc : fromVc
let animateView = animateVc!.view
let transZero = CGAffineTransform(scaleX: 0.8, y: 0.8)
let midTrans = CGAffineTransform(scaleX: 0.01, y: 0.01)
let transIty = CGAffineTransform.identity
var damping = 3.0
if isPop {
transitionContext.containerView.addSubview(animateView!)
damping = 0.75
}
animateView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
animateView?.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
animateView?.center = CGPoint(x: UIScreen.main.bounds.width * 0.5, y: UIScreen.main.bounds.height * 0.5)
animateView?.transform = isPop ?transZero : transIty
UIView.animate(withDuration: transitionDuration(using: transitionContext),
delay: 0,
usingSpringWithDamping: CGFloat(damping),
initialSpringVelocity: 5.0,
options: UIViewAnimationOptions.beginFromCurrentState,
animations: { () -> Void in
animateView?.transform = self.isPop ? transIty : midTrans
if !self.isPop {
animateView?.alpha = 0
}
}) { _ in
if self.isPop == false {
animateView?.removeFromSuperview()
}
//注意:转场动画结束必须写
transitionContext.completeTransition(true)
}
}
}
//MARK: delegate - UIViewControllerTransitioningDelegate (视图控制器专场代理)
extension JXCoolTransitioningDelegate : UIViewControllerTransitioningDelegate{
//调度转场动画的控制器是谁
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{
return JXPresentationController(presentedViewController: presented, presenting: presenting)
}
//返回转场动画代理
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPop = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPop = false
return self
}
}
| 32.951923 | 170 | 0.623286 |
1de3738e02807884e3e4b237effbe6a6bdb2abcc | 4,324 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
struct HistorgramShapeMismatch: Error {}
/// Histograms are stored with exponentially increasing bucket sizes.
/// The first bucket is [0, `multiplier`) where `multiplier` = 1 + resolution
/// Bucket n (n>=1) contains [`multiplier`**n, `multiplier`**(n+1))
/// There are sufficient buckets to reach max_bucket_start
public struct Histogram {
public private(set) var sum: Double
public private(set) var sumOfSquares: Double
public private(set) var countOfValuesSeen: Double
private var multiplier: Double
private var oneOnLogMultiplier: Double
public private(set) var minSeen: Double
public private(set) var maxSeen: Double
private var maxPossible: Double
public private(set) var buckets: [UInt32]
/// Initialise a histogram.
/// - parameters:
/// - resolution: Defines the width of the buckets - see the description of this structure.
/// - maxBucketStart: Defines the start of the greatest valued bucket.
public init(resolution: Double = 0.01, maxBucketStart: Double = 60e9) {
precondition(resolution > 0.0)
precondition(maxBucketStart > resolution)
self.sum = 0.0
self.sumOfSquares = 0.0
self.multiplier = 1.0 + resolution
self.oneOnLogMultiplier = 1.0 / log(1.0 + resolution)
self.maxPossible = maxBucketStart
self.countOfValuesSeen = 0.0
self.minSeen = maxBucketStart
self.maxSeen = 0.0
let numBuckets = Histogram.bucketForUnchecked(
value: maxBucketStart,
oneOnLogMultiplier: self.oneOnLogMultiplier
) + 1
precondition(numBuckets > 1)
precondition(numBuckets < 100_000_000)
self.buckets = .init(repeating: 0, count: numBuckets)
}
/// Determine a bucket index given a value - does no bounds checking
private static func bucketForUnchecked(value: Double, oneOnLogMultiplier: Double) -> Int {
return Int(log(value) * oneOnLogMultiplier)
}
private func bucketFor(value: Double) -> Int {
let bucket = Histogram.bucketForUnchecked(
value: self.clamp(value: value),
oneOnLogMultiplier: self.oneOnLogMultiplier
)
assert(bucket < self.buckets.count)
assert(bucket >= 0)
return bucket
}
/// Force a value to be within the bounds of 0 and `self.maxPossible`
/// - parameters:
/// - value: The value to force within bounds
/// - returns: The value forced into the bounds for buckets.
private func clamp(value: Double) -> Double {
return min(self.maxPossible, max(0, value))
}
/// Add a value to this histogram, updating buckets and stats
/// - parameters:
/// - value: The value to add.
public mutating func add(value: Double) {
self.sum += value
self.sumOfSquares += value * value
self.countOfValuesSeen += 1
if value < self.minSeen {
self.minSeen = value
}
if value > self.maxSeen {
self.maxSeen = value
}
self.buckets[self.bucketFor(value: value)] += 1
}
/// Merge two histograms together updating `self`
/// - parameters:
/// - source: the other histogram to merge into this.
public mutating func merge(source: Histogram) throws {
guard (self.buckets.count == source.buckets.count) ||
(self.multiplier == source.multiplier) else {
// Fail because these histograms don't match.
throw HistorgramShapeMismatch()
}
self.sum += source.sum
self.sumOfSquares += source.sumOfSquares
self.countOfValuesSeen += source.countOfValuesSeen
if source.minSeen < self.minSeen {
self.minSeen = source.minSeen
}
if source.maxSeen > self.maxSeen {
self.maxSeen = source.maxSeen
}
for bucket in 0 ..< self.buckets.count {
self.buckets[bucket] += source.buckets[bucket]
}
}
}
| 35.154472 | 97 | 0.694727 |
1e244bd965081cae6bc850243d228650870b352a | 4,670 | //
// FolioReaderPageIndicator.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 10/09/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
class FolioReaderPageIndicator: UIView {
var pagesLabel: UILabel!
var minutesLabel: UILabel!
var totalMinutes: Int!
var totalPages: Int!
var currentPage: Int = 1 {
didSet { self.reloadViewWithPage(self.currentPage) }
}
fileprivate var readerConfig: FolioReaderConfig
fileprivate var folioReader: FolioReader
init(frame: CGRect, readerConfig: FolioReaderConfig, folioReader: FolioReader) {
self.readerConfig = readerConfig
self.folioReader = folioReader
super.init(frame: frame)
let color = self.folioReader.isNight(self.readerConfig.nightModeBackground, UIColor.white)
backgroundColor = color
layer.shadowColor = color.cgColor
layer.shadowOffset = CGSize(width: 0, height: -6)
layer.shadowOpacity = 1
layer.shadowRadius = 4
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.rasterizationScale = UIScreen.main.scale
layer.shouldRasterize = true
pagesLabel = UILabel(frame: CGRect.zero)
pagesLabel.font = UIFont(name: "Avenir-Light", size: 10)!
pagesLabel.textAlignment = NSTextAlignment.right
addSubview(pagesLabel)
minutesLabel = UILabel(frame: CGRect.zero)
minutesLabel.font = UIFont(name: "Avenir-Light", size: 10)!
minutesLabel.textAlignment = NSTextAlignment.right
// minutesLabel.alpha = 0
addSubview(minutesLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("storyboards are incompatible with truth and beauty")
}
func reloadView(updateShadow: Bool) {
minutesLabel.sizeToFit()
pagesLabel.sizeToFit()
let fullW = pagesLabel.frame.width + minutesLabel.frame.width
minutesLabel.frame.origin = CGPoint(x: frame.width/2-fullW/2, y: 2)
pagesLabel.frame.origin = CGPoint(x: minutesLabel.frame.origin.x+minutesLabel.frame.width, y: 2)
if updateShadow {
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
self.reloadColors()
}
}
func reloadColors() {
let color = self.folioReader.isNight(self.readerConfig.nightModeBackground, UIColor.white)
backgroundColor = color
// Animate the shadow color change
let animation = CABasicAnimation(keyPath: "shadowColor")
let currentColor = UIColor(cgColor: layer.shadowColor!)
animation.fromValue = currentColor.cgColor
animation.toValue = color.cgColor
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.duration = 0.6
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
layer.add(animation, forKey: "shadowColor")
minutesLabel.textColor = self.folioReader.isNight(UIColor(white: 1, alpha: 0.3), UIColor(white: 0, alpha: 0.6))
pagesLabel.textColor = self.folioReader.isNight(UIColor(white: 1, alpha: 0.6), UIColor(white: 0, alpha: 0.9))
}
fileprivate func reloadViewWithPage(_ page: Int) {
let pagesRemaining = self.folioReader.needsRTLChange ? totalPages-(totalPages-page+1) : totalPages-page
if pagesRemaining == 1 {
pagesLabel.text = " " + self.readerConfig.localizedReaderOnePageLeft
} else {
pagesLabel.text = " \(pagesRemaining) " + self.readerConfig.localizedReaderManyPagesLeft
}
let minutesRemaining = Int(ceil(CGFloat((pagesRemaining * totalMinutes)/totalPages)))
if minutesRemaining > 1 {
minutesLabel.text = "\(minutesRemaining) " + self.readerConfig.localizedReaderManyMinutes+" ·"
} else if minutesRemaining == 1 {
minutesLabel.text = self.readerConfig.localizedReaderOneMinute+" ·"
} else {
minutesLabel.text = self.readerConfig.localizedReaderLessThanOneMinute+" ·"
}
reloadView(updateShadow: false)
}
}
extension FolioReaderPageIndicator: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// Set the shadow color to the final value of the animation is done
if let keyPath = anim.value(forKeyPath: "keyPath") as? String , keyPath == "shadowColor" {
let color = self.folioReader.isNight(self.readerConfig.nightModeBackground, UIColor.white)
layer.shadowColor = color.cgColor
}
}
}
| 38.916667 | 119 | 0.674518 |
2009e27af8f302bb2215d031b41bbfdac2f9eba4 | 10,653 | /*
Copyright (c) 2019, Apple Inc. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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.
*/
import Foundation
extension OCKStore {
open func fetchPatients(query: OCKPatientQuery = OCKPatientQuery(), callbackQueue: DispatchQueue = .main,
completion: @escaping (Result<[OCKPatient], OCKStoreError>) -> Void) {
context.perform {
do {
let predicate = try self.buildPredicate(for: query)
let patientsObjects = OCKCDPatient.fetchFromStore(in: self.context, where: predicate) { fetchRequest in
fetchRequest.fetchLimit = query.limit ?? 0
fetchRequest.fetchOffset = query.offset
fetchRequest.sortDescriptors = self.buildSortDescriptors(from: query)
}
let patients = patientsObjects.map(self.makePatient)
callbackQueue.async { completion(.success(patients)) }
} catch {
self.context.rollback()
let message = "Failed to fetch patients with query: \(String(describing: query)). \(error.localizedDescription)"
callbackQueue.async { completion(.failure(.fetchFailed(reason: message))) }
}
}
}
open func addPatients(_ patients: [OCKPatient], callbackQueue: DispatchQueue = .main,
completion: ((Result<[OCKPatient], OCKStoreError>) -> Void)? = nil) {
context.perform {
do {
try self.validateNumberOfPatients()
try OCKCDPatient.validateNewIDs(patients.map { $0.id }, in: self.context)
let persistablePatients = patients.map(self.createPatient)
try self.context.save()
let updatedPatients = persistablePatients.map(self.makePatient)
callbackQueue.async {
self.patientDelegate?.patientStore(self, didAddPatients: updatedPatients)
completion?(.success(updatedPatients))
}
} catch {
self.context.rollback()
callbackQueue.async {
completion?(.failure(.addFailed(reason: "Failed to insert OCKPatients: [\(patients)]. \(error.localizedDescription)")))
}
}
}
}
open func updatePatients(_ patients: [OCKPatient], callbackQueue: DispatchQueue = .main,
completion: ((Result<[OCKPatient], OCKStoreError>) -> Void)? = nil) {
context.perform {
do {
let ids = patients.map { $0.id }
try OCKCDPatient.validateUpdateIdentifiers(ids, in: self.context)
let updatedPatients = try self.performVersionedUpdate(values: patients, addNewVersion: self.createPatient)
try self.context.save()
let patients = updatedPatients.map(self.makePatient)
callbackQueue.async {
self.patientDelegate?.patientStore(self, didUpdatePatients: patients)
completion?(.success(patients))
}
} catch {
self.context.rollback()
callbackQueue.async {
completion?(.failure(.updateFailed(reason: "Failed to update OCKPatients: [\(patients)]. \(error.localizedDescription)")))
}
}
}
}
open func deletePatients(_ patients: [OCKPatient], callbackQueue: DispatchQueue = .main,
completion: ((Result<[OCKPatient], OCKStoreError>) -> Void)? = nil) {
context.perform {
do {
let markedDeleted: [OCKCDPatient] = try self.performDeletion(values: patients)
try self.context.save()
let deletedPatients = markedDeleted.map(self.makePatient)
callbackQueue.async {
self.patientDelegate?.patientStore(self, didDeletePatients: deletedPatients)
completion?(.success(deletedPatients))
}
} catch {
self.context.rollback()
callbackQueue.async {
completion?(.failure(.deleteFailed(reason: "Failed to delete OCKPatients: [\(patients)]. \(error.localizedDescription)")))
}
}
}
}
// MARK: Private
/// - Remark: This does not commit the transaction. After calling this function one or more times, you must call `context.save()` in order to
/// persist the changes to disk. This is an optimization to allow batching.
/// - Remark: You should verify that the object does not already exist in the database and validate its values before calling this method.
private func createPatient(from patient: OCKPatient) -> OCKCDPatient {
let persistablePatient = OCKCDPatient(context: context)
persistablePatient.name = OCKCDPersonName(context: context)
persistablePatient.copyVersionInfo(from: patient)
persistablePatient.allowsMissingRelationships = configuration.allowsEntitiesWithMissingRelationships
persistablePatient.name.copyPersonNameComponents(patient.name)
persistablePatient.sex = patient.sex?.rawValue
persistablePatient.birthday = patient.birthday
persistablePatient.allergies = patient.allergies
return persistablePatient
}
/// - Remark: This method is intended to create a value type struct from a *persisted* NSManagedObject. Calling this method with an
/// object that is not yet commited is a programmer error.
private func makePatient(from object: OCKCDPatient) -> OCKPatient {
assert(object.localDatabaseID != nil, "Do not create a patient from an object that isn't persisted yet!")
var patient = OCKPatient(id: object.id, name: object.name.makeComponents())
patient.sex = object.sex == nil ? nil : OCKBiologicalSex(rawValue: object.sex!)
patient.birthday = object.birthday
patient.allergies = object.allergies
patient.copyVersionedValues(from: object)
return patient
}
private func buildPredicate(for query: OCKPatientQuery) throws -> NSPredicate {
var predicate = NSPredicate(value: true)
let notDeletedPredicate = NSPredicate(format: "%K == nil", #keyPath(OCKCDVersionedObject.deletedDate))
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, notDeletedPredicate])
if let interval = query.dateInterval {
let intervalPredicate = OCKCDVersionedObject.newestVersionPredicate(in: interval)
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, intervalPredicate])
}
if !query.ids.isEmpty {
let idPredicate = NSPredicate(format: "%K IN %@", #keyPath(OCKCDVersionedObject.id), query.ids)
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, idPredicate])
}
if !query.versionIDs.isEmpty {
let versionPredicate = NSPredicate(format: "self IN %@", try query.versionIDs.map(objectID))
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, versionPredicate])
}
if !query.remoteIDs.isEmpty {
let remotePredicate = NSPredicate(format: "%K IN %@", #keyPath(OCKCDObject.remoteID), query.remoteIDs)
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, remotePredicate])
}
if !query.groupIdentifiers.isEmpty {
predicate = predicate.including(groupIdentifiers: query.groupIdentifiers)
}
if !query.tags.isEmpty {
predicate = predicate.including(tags: query.tags)
}
return predicate
}
private func buildSortDescriptors(from query: OCKPatientQuery?) -> [NSSortDescriptor] {
guard let orders = query?.extendedSortDescriptors else { return [] }
return orders.map { order -> NSSortDescriptor in
switch order {
case .effectiveDate(let ascending): return NSSortDescriptor(keyPath: \OCKCDPatient.effectiveDate, ascending: ascending)
case .givenName(let ascending): return NSSortDescriptor(keyPath: \OCKCDPatient.name.givenName, ascending: ascending)
case .familyName(let ascending): return NSSortDescriptor(keyPath: \OCKCDPatient.name.familyName, ascending: ascending)
case .groupIdentifier(let ascending): return NSSortDescriptor(keyPath: \OCKCDPatient.groupIdentifier, ascending: ascending)
}
}
}
private func validateNumberOfPatients() throws {
let fetchRequest = OCKCDPatient.fetchRequest()
let numberOfPatients = try context.count(for: fetchRequest)
if numberOfPatients > 0 {
let explanation = """
OCKStore` only supports one patient per store.
If you would like to have more than one patient, create a new store for that patient.
"""
throw OCKStoreError.addFailed(reason: explanation)
}
}
}
| 50.728571 | 145 | 0.658218 |
0367a58064b33bc33ad127dfdc4a674ac8e2f8ce | 2,331 | //
// LocationPoint.swift
// IBMWeather
//
// Created by Mac on 14.06.2020.
// Copyright © 2020 Lammax. All rights reserved.
//
import Foundation
/*
{
"location":{
"latitude":56.86,
"longitude":35.88,
"city":"Тверь",
"locale":{
"locale1":null,
"locale2":"Тверь",
"locale3":null,
"locale4":null
},
"neighborhood":null,
"adminDistrict":"Тверская область",
"adminDistrictCode":null,
"postalCode":"170006",
"postalKey":"1700:RU",
"country":"Россия",
"countryCode":"RU",
"ianaTimeZone":"Europe/Moscow",
"displayName":"Тверь",
"dstEnd":null,
"dstStart":null,
"dmaCd":null,
"placeId":"9d0093ab6d98b74c37bd2ff19771fc7ec71e0ba5491ec39bf568f7afdba7929b",
"disputedArea":false,
"canonicalCityId":"33c5a5acaa02868dc4190646cb9e2eb8ab8b1487d4d2b51265c38cdaa327c1c9",
"countyId":null,
"locId":null,
"locationCategory":null,
"pollenId":null,
"pwsId":null,
"regionalSatellite":"eur",
"tideId":null,
"type":"postal",
"zoneId":null
}
}
*/
struct LocationPoint: Decodable {
let location: Location?
init(location: Location? = nil) {
self.location = location
}
static var placeholder: LocationPoint {
LocationPoint()
}
}
struct Location: Decodable {
let latitude: Double?
let longitude: Double?
let city: String?
let locale: Locale?
let neighborhood: String?
let adminDistrict: String?
let adminDistrictCode: String?
let postalCode: String?
let postalKey: String?
let country: String?
let countryCode: String?
let ianaTimeZone: String?
let displayName: String?
let dstEnd: String?
let dstStart: String?
let dmaCd: String?
let placeId: String?
let disputedArea: Bool?
let canonicalCityId: String?
let countyId: String?
let locId: String?
let locationCategory: String?
let pollenId: String?
let pwsId: String?
let regionalSatellite: String?
let tideId: String?
let type: String?
let zoneId: String?
}
struct Locale: Decodable {
let locale1: String?
let locale2: String?
let locale3: String?
let locale4: String?
}
| 23.079208 | 92 | 0.608323 |
766a86d7516b17beb9c223c8aeccf39764978fd3 | 4,249 | // Copyright (c) 2022 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
struct Download: Codable {
enum State: Int, Codable {
case pending // Collection— Just created
case urlRequested
case readyForDownload
case enqueued
case inProgress // Collection– Not all of the requested children are downloaded
case paused // Collection— All requested children are downloaded, but not all children have been requested
case cancelled
case failed
case complete // Collection— All children have been requested and downloaded
case error
}
var id: UUID
var requestedAt: Date
var lastValidatedAt: Date?
var fileName: String?
var remoteURL: URL?
var progress: Double = 0
var state: State
var contentID: Int
var ordinal: Int = 0 // We copy this from the Content, and it is used to sort the queue
var localURL: URL? {
guard let fileName = fileName,
let downloadDirectory = Download.downloadDirectory else {
return nil
}
return downloadDirectory.appendingPathComponent(fileName)
}
static var downloadDirectory: URL? {
let fileManager = FileManager.default
let documentsDirectories = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
guard let documentsDirectory = documentsDirectories.first else {
return nil
}
return documentsDirectory.appendingPathComponent("downloads", isDirectory: true)
}
}
extension Download: DownloadProcessorModel { }
extension Download: Equatable {
// We override this function because SQLite doesn't store dates to the same accuracy as Date
static func == (lhs: Download, rhs: Download) -> Bool {
lhs.id == rhs.id &&
lhs.fileName == rhs.fileName &&
lhs.remoteURL == rhs.remoteURL &&
lhs.progress == rhs.progress &&
lhs.state == rhs.state &&
lhs.contentID == rhs.contentID &&
lhs.ordinal == rhs.ordinal &&
lhs.requestedAt.equalEnough(to: rhs.requestedAt) &&
((lhs.lastValidatedAt == nil && rhs.lastValidatedAt == nil) || lhs.lastValidatedAt!.equalEnough(to: rhs.lastValidatedAt!))
}
}
extension Download {
static func create(for content: Content) -> Download {
Download(
id: UUID(),
requestedAt: Date(),
lastValidatedAt: nil,
fileName: nil,
remoteURL: nil,
progress: 0,
state: .pending,
contentID: content.id,
ordinal: content.ordinal ?? 0)
}
}
extension Download {
var isDownloading: Bool {
[.inProgress, .paused].contains(state) && remoteURL != nil
}
var isDownloaded: Bool {
[.complete].contains(state) && remoteURL != nil
}
}
extension Download: Hashable { }
| 36.008475 | 128 | 0.715462 |
f5e970ca4e9a4164f03f91c9fcb200a43984c3c7 | 993 | //
// ViewController.swift
// SearchWord
//
// Created by miguel tomairo on 5/1/20.
// Copyright © 2020 rapser. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.url(forResource: "capitals", withExtension: "json")!
let contents = try! Data(contentsOf: path)
let words = try! JSONDecoder().decode([Word].self, from: contents)
let wordSearch = WordSearch()
wordSearch.words = words
wordSearch.makeGrid()
let output = wordSearch.render()
let url = getDocumentDirectory().appendingPathComponent("ouput.pdf")
print(url)
try? output.write(to: url)
}
func getDocumentDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}
| 22.568182 | 90 | 0.592145 |
46678b2b3b8f678e5fb46673db433e55c53d5c39 | 225 | //
// API.swift
// XJDomainLive
//
// Created by 李胜兵 on 2016/12/8.
// Copyright © 2016年 付公司. All rights reserved.
//
import UIKit
let kApiHomeList = "http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1"
| 20.454545 | 89 | 0.693333 |
23c4323263fea9d6e2b8b893853cf9ba11e9256b | 628 | public protocol Runner {
// metadata can be accessed via owned["metadata"]
func addTask(_ task: GeneralizedTask, options: [String: Any]?)
func resume()
func waitUntilQueueIsEmpty()
var resultHandler: ((GeneralizedTask, StringKeyedSafeDictionary?, Any) -> Void)? { get set }
var errorHandler: ((GeneralizedTask, StringKeyedSafeDictionary?, Error) -> Void)? { get set }
var sharedData: StringKeyedSafeDictionary { get set }
}
public extension Runner {
func addTask<T: Task>(_ task: T, options: [String: Any]? = nil) {
self.addTask(GeneralizedTask(from: task), options: options)
}
}
| 33.052632 | 97 | 0.687898 |
50b708c91de26c41790a9923020786feb8312fc0 | 7,185 | //
// MessageActionsEndpointIntegrationTests.swift
//
// PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
// Copyright © 2019 PubNub Inc.
// https://www.pubnub.com/
// https://www.pubnub.com/terms
//
// 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 PubNub
import XCTest
class MessageActionsEndpointIntegrationTests: XCTestCase {
let testsBundle = Bundle(for: MessageActionsEndpointIntegrationTests.self)
let testChannel = "SwiftITest-MessageActions"
// swiftlint:disable:next cyclomatic_complexity function_body_length
func testAddThenDeleteMessageAction() {
let addExpect = expectation(description: "Add Message Action Expectation")
let fetchExpect = expectation(description: "Fetch Message Action Expectation")
let removeExpect = expectation(description: "Remove Message Action Expectation")
let addedEventExcept = expectation(description: "Add Message Action Event Expectation")
let removedEventExcept = expectation(description: "Remove Message Action Event Expectation")
let configuration = PubNubConfiguration(from: testsBundle)
let client = PubNub(configuration: configuration)
let actionType = "reaction"
let actionValue = "smiley_face"
let listener = SubscriptionListener()
listener.didReceiveMessageAction = { event in
switch event {
case let .added(action):
XCTAssertEqual(action.actionType, actionType)
XCTAssertEqual(action.actionValue, actionValue)
addedEventExcept.fulfill()
case let .removed(action):
XCTAssertEqual(action.actionType, actionType)
XCTAssertEqual(action.actionValue, actionValue)
removedEventExcept.fulfill()
}
}
listener.didReceiveStatus = { [unowned self] status in
switch status {
case let .success(connection):
if connection.isConnected {
client.publishWithMessageAction(
channel: self.testChannel,
message: "Hello!",
actionType: actionType, actionValue: actionValue
) { [unowned self] publishResult in
switch publishResult {
case let .success(messageAction):
XCTAssertEqual(messageAction.publisher, configuration.uuid)
XCTAssertEqual(messageAction.actionType, actionType)
XCTAssertEqual(messageAction.actionValue, actionValue)
// Fetch the Message
client.fetchMessageActions(channel: self.testChannel) { [unowned self] actionResult in
switch actionResult {
case let .success((messageActions, _)):
// Assert that we successfully published to server
XCTAssertNotNil(messageActions.filter { $0.actionTimetoken == messageAction.actionTimetoken })
// Remove the message
client.removeMessageActions(
channel: self.testChannel,
message: messageAction.messageTimetoken,
action: messageAction.actionTimetoken
) { removeResult in
switch removeResult {
case let .success((channel, _, _)):
XCTAssertEqual(channel, self.testChannel)
case .failure:
XCTFail("Failed Fetching Message Actions")
}
removeExpect.fulfill()
}
case .failure:
XCTFail("Failed Fetching Message Actions")
}
fetchExpect.fulfill()
}
case .failure:
XCTFail("Failed Fetching Message Actions")
}
addExpect.fulfill()
}
}
case .failure:
XCTFail("An error occurred")
}
}
client.add(listener)
client.subscribe(to: [testChannel])
defer { listener.cancel() }
wait(for: [addExpect, fetchExpect, removeExpect, addedEventExcept, removedEventExcept], timeout: 10.0)
}
func testFetchMessageActionsEndpoint() {
let fetchExpect = expectation(description: "Fetch Message Actions Expectation")
let configuration = PubNubConfiguration(from: testsBundle)
let client = PubNub(configuration: configuration)
client.fetchMessageActions(channel: testChannel) { result in
switch result {
case .success:
break
case .failure:
XCTFail("Failed Fetching Message Actions")
}
fetchExpect.fulfill()
}
wait(for: [fetchExpect], timeout: 10.0)
}
func testHistoryWithMessageActions() {
let addExpect = expectation(description: "Add Message Action Expectation")
let historyExpect = expectation(description: "Fetch Message Action Expectation")
let configuration = PubNubConfiguration(from: testsBundle)
let client = PubNub(configuration: configuration)
let actionType = "reaction"
let actionValue = "smiley_face"
client.publishWithMessageAction(
channel: testChannel,
message: "Hello!",
actionType: actionType, actionValue: actionValue
) { [unowned self] publishResult in
switch publishResult {
case let .success(messageAction):
XCTAssertEqual(messageAction.publisher, configuration.uuid)
XCTAssertEqual(messageAction.actionType, actionType)
XCTAssertEqual(messageAction.actionValue, actionValue)
client.fetchMessageHistory(for: [self.testChannel], includeActions: true) { historyResult in
switch historyResult {
case let .success((messages, _)):
let channelHistory = messages[self.testChannel]
XCTAssertNotNil(channelHistory)
let message = channelHistory?.filter { $0.published == messageAction.messageTimetoken }
XCTAssertNotNil(message)
case .failure:
XCTFail("Failed Fetching Message Actions")
}
historyExpect.fulfill()
}
case .failure:
XCTFail("Failed Fetching Message Actions")
}
addExpect.fulfill()
}
wait(for: [addExpect, historyExpect], timeout: 10.0)
}
}
| 38.42246 | 112 | 0.666806 |
fbb60b794252cf567d599023674d9014ea42fd6e | 767 | //
// SegueHandler.swift
// Moody
//
// Created by Florian on 12/06/15.
// Copyright © 2015 objc.io. All rights reserved.
//
import UIKit
protocol SegueHandler {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandler where Self: UIViewController, SegueIdentifier.RawValue == String {
func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier)
else { fatalError("Unknown segue: \(segue))") }
return segueIdentifier
}
func performSegue(withIdentifier segueIdentifier: SegueIdentifier) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: nil)
}
}
| 24.741935 | 89 | 0.711864 |
9bbd5eb4cf274026c79469564bf6e488c6306b3d | 879 | //
// CustomErrorExtention.swift
// Submission1GameApp
//
// Created by izzudin on 22/11/20.
// Copyright © 2020 izzudin. All rights reserved.
//
import Foundation
public enum URLError: LocalizedError {
case invalidResponse
case addressUnreachable(URL?)
public var errorDescription: String? {
switch self {
case .invalidResponse:
return "The server responded with gerbage."
case .addressUnreachable(let url):
return "\(url?.absoluteString ?? "") is unreachable"
}
}
}
public enum DatabaseError: LocalizedError {
case invalidInstance
case requestFailed
public var errorDescription: String? {
switch self {
case .invalidInstance:
return "Database can't instance."
case .requestFailed:
return "Your request failed"
}
}
}
| 23.131579 | 64 | 0.630262 |
14ea018c3447721d167658ad953c4f8c17bba4d1 | 634 | //
// ViewController.swift
// SwiftyNewsKit
//
// Created by DanielZSY on 05/18/2021.
// Copyright (c) 2021 DanielZSY. All rights reserved.
//
import UIKit
import SwiftyNewsKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let itemvc = ZMessageViewController()
self.navigationController?.pushViewController(itemvc, animated: true)
default: break
}
}
}
| 21.862069 | 92 | 0.64511 |
2345be6da33f126cbdb181665aef647b0a0d1b22 | 2,568 | //
// TransactionsVC.swift
// WalletExample
//
// Created by Sacha DSO on 11/12/2017.
// Copyright © 2017 freshos. All rights reserved.
//
import UIKit
import Ark
class TransactionsVC: UITableViewController {
let account = Account(address: "AK3wUpsmyFrWvgytFRoaHatEKj3uxUBZE6")
var transactions = [Transaction]()
init() {
super.init(nibName: nil, bundle: nil)
title = "Transactions"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = UIRefreshControl()
tableView.register(TransactionCell.self, forCellReuseIdentifier: "TransactionCell")
refreshControl?.addTarget(self, action:#selector(refresh), for: .valueChanged)
refresh()
}
@objc
func refresh() {
account.fetchTransactions().then { fetchedTransactions in
self.transactions = fetchedTransactions
self.tableView.reloadData()
}.finally {
self.refreshControl?.endRefreshing()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let transaction = transactions[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "TransactionCell", for: indexPath) as! TransactionCell
cell.id.text = "Id: " + transaction.id
cell.confirmations.text = transaction.confirmations == nil ? "unknown" : "\(transaction.confirmations!) confirmations"
let df = DateFormatter()
df.dateStyle = .short
df.timeStyle = .short
cell.date.text = df.string(from: transaction.date!)
cell.from.text = "From: " + transaction.senderId!
if transaction.type == 3 {
cell.to.text = "Vote"
} else {
cell.to.text = "To: " + transaction.recipientId!
}
if transaction.type == 3 {
cell.amount.text = "-\(transaction.fee!.toStandard()) ARK"
cell.amount.textColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1)
} else {
cell.amount.text = "\(transaction.amount!.toStandard()) ARK"
cell.amount.textColor = UIColor(red: 76/255.0, green: 217/255.0, blue: 100/255.0, alpha: 1)
}
return cell
}
}
| 34.702703 | 126 | 0.625 |
cc437008193522643e211c36a4f551580331e73e | 1,011 | //
// HistoryDto.swift
// Roschat
//
// Created by Aleksander Evtuhov on 17/11/2018.
// Copyright © 2018 Кирилл Володин. All rights reserved.
//
import Foundation
import SwiftyJSON
class HistoryDto {
var id: Int
var botTime: Int
var botMessage: DialogStateDto
var complited: Bool = false
var userTime: Int!
var userMessage: UserMessageDto!
init(json: JSON) {
self.id = json["id"].intValue
self.botTime = json["botTime"].intValue
guard let botMessage = DialogStateDto(json: json["botMessage"]) else { fatalError() }
self.botMessage = botMessage
if json["userTime"].int != nil {
complited = true
self.userTime = json["userTime"].intValue
self.userMessage = UserMessageDto(json: json["userMessage"])
}
}
init(id: Int, botTime: Int, botMessage: DialogStateDto) {
self.id = id
self.botTime = botTime
self.botMessage = botMessage
}
}
| 24.658537 | 93 | 0.608309 |
670bc9ad10ddd18f389f6e72faab13122d9a8042 | 919 | //
// AppDelegate.swift
// Sock
//
// Created by Matt Lorentz on 3/12/19.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@IBAction func newTab(_ sender: NSMenuItem) {
guard let window = NSApplication.shared.mainWindow else {
return
}
let storyboard = NSStoryboard(name: "Main", bundle: nil)
guard let newTab: NSWindowController =
storyboard.instantiateController(withIdentifier: "Window") as? NSWindowController else {
return
}
window.addTabbedWindow(newTab.window!, ordered: .above)
}
}
| 23.564103 | 100 | 0.653972 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.