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
|
---|---|---|---|---|---|
ff41107bfa0c56db7057d94673af0af2d54fa8a7 | 1,630 | import CoreImage
import UIKit
final class ChromaKeyFilterFactory {
/// - SeeAlso:
/// https://developer.apple.com/documentation/coreimage/applying_a_chroma_key_effect?language=swift
/// https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_filer_recipes/ci_filter_recipes.html
static func make(fromHue: CGFloat, toHue: CGFloat) -> CIFilter? {
let size = 64
var cubeRGB = [Float]()
for z in 0 ..< size {
let blue = CGFloat(z) / CGFloat(size-1)
for y in 0 ..< size {
let green = CGFloat(y) / CGFloat(size-1)
for x in 0 ..< size {
let red = CGFloat(x) / CGFloat(size-1)
let hue = getHue(red: red, green: green, blue: blue)
let alpha: CGFloat = (hue >= fromHue && hue <= toHue) ? 0 : 1
cubeRGB.append(Float(red * alpha))
cubeRGB.append(Float(green * alpha))
cubeRGB.append(Float(blue * alpha))
cubeRGB.append(Float(alpha))
}
}
}
let data = Data(buffer: UnsafeBufferPointer(start: &cubeRGB, count: cubeRGB.count))
let parameters: [String: Any] = ["inputCubeDimension": size, "inputCubeData": data]
let colorCubeFilter = CIFilter(name: "CIColorCube", parameters: parameters)
return colorCubeFilter
}
static func getHue(red: CGFloat, green: CGFloat, blue: CGFloat) -> CGFloat {
let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
var hue: CGFloat = 0
color.getHue(&hue, saturation: nil, brightness: nil, alpha: nil)
return hue
}
}
| 37.906977 | 148 | 0.621472 |
29ce595fb199d5a5159eaa4344143fbe2dac2456 | 1,224 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
public class AKShakerAudioUnit: AKAudioUnitBase {
var type: AUParameter!
var amplitude: AUParameter!
public override func createDSP() -> AKDSPRef {
return createShakerDSP()
}
public override init(componentDescription: AudioComponentDescription,
options: AudioComponentInstantiationOptions = []) throws {
try super.init(componentDescription: componentDescription, options: options)
type = AUParameter(
identifier: "Type",
name: "type",
address: 0,
range: 0...22,
unit: .generic,
flags: .default)
amplitude = AUParameter(
identifier: "amplitude",
name: "Amplitude",
address: 1,
range: 0...10,
unit: .generic,
flags: .default)
parameterTree = AUParameterTree.createTree(withChildren: [type, amplitude])
type.value = 0
amplitude.value = 0.5
}
public func triggerType(_ type: AUValue, amplitude: AUValue) {
triggerTypeShakerDSP(dsp, type, amplitude)
}
}
| 29.142857 | 100 | 0.602124 |
d62b6896d216b3c34e3e30a902375274292d404d | 4,258 | //
// DraggableView.swift
// HUE
//
// Created by James Taylor on 2015-03-30.
// Copyright (c) 2015 James Lin Taylor. Both rights reserved.
//
import UIKit
protocol DraggableViewDelegate: class {
func draggableViewBeganDragging(view: DraggableView)
func draggableView(view: DraggableView, draggingEndedWithVelocity velocity: CGPoint)
}
struct DraggableViewAxis : OptionSetType {
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
init(rawValue value: UInt) { self.value = value }
init(nilLiteral: ()) { self.value = 0 }
static var allZeros: DraggableViewAxis { return self.init(0) }
static func fromMask(raw: UInt) -> DraggableViewAxis { return self.init(raw) }
var rawValue: UInt { return self.value }
static var Horizontal: DraggableViewAxis { return self.init(0b0) }
static var Vertical: DraggableViewAxis { return self.init(0b1) }
}
class DraggableView: UIView, UIGestureRecognizerDelegate {
weak var delegate: DraggableViewDelegate?
var animator: UIDynamicAnimator
var attachmentBehaviour: UIAttachmentBehavior?
var axes: DraggableViewAxis = [.Horizontal, .Vertical] // default
var viewToDrag: UIView!
init(frame: CGRect, inView containerView: UIView) {
self.animator = UIDynamicAnimator(referenceView: containerView)
super.init(frame: frame)
self.viewToDrag = self
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:"))
panGestureRecognizer.delegate = self
self.addGestureRecognizer(panGestureRecognizer)
}
convenience init(inView containerView: UIView) {
self.init(frame: CGRectZero, inView: containerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Handlers
func handlePan(sender: UIPanGestureRecognizer) {
let translationInView = sender.translationInView(self)
sender.setTranslation(CGPointZero, inView: self)
switch sender.state {
case .Began:
self.attachmentBehaviour = UIAttachmentBehavior(item: self.viewToDrag, attachedToAnchor: CGPoint(x: self.viewToDrag.center.x, y: self.viewToDrag.center.y))
self.animator.addBehavior(self.attachmentBehaviour!)
self.delegate?.draggableViewBeganDragging(self)
case .Changed:
if self.axes.intersect(.Horizontal) != [] {
self.attachmentBehaviour?.anchorPoint.x += translationInView.x
}
if self.axes.intersect(.Vertical) != [] {
self.attachmentBehaviour?.anchorPoint.y += translationInView.y
}
default:
self.animator.removeBehavior(self.attachmentBehaviour!)
var velocity = sender.velocityInView(self)
if self.axes.intersect(.Horizontal) == [] {
velocity.x = 0
}
if self.axes.intersect(.Vertical) == [] {
velocity.y = 0
}
self.delegate?.draggableView(self, draggingEndedWithVelocity: velocity)
}
}
// MARK: - UIGestureRecognizerDelegate
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
var velocity = (panGestureRecognizer as UIPanGestureRecognizer).velocityInView(self)
velocity.x = abs(velocity.x)
velocity.y = abs(velocity.y)
if (self.axes.intersect(.Horizontal) != []) && (velocity.x > velocity.y) {
return true
}
if (self.axes.intersect(.Vertical) != []) && (velocity.y > velocity.x) {
return true
}
return false
}
return true
}
}
| 31.308824 | 167 | 0.592532 |
e900925840226a9bff1a9136fabac17cf805164f | 1,366 | //
// ViewController.swift
// FavoriteThings
//
// Created by Jason Schatz on 11/18/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Model
let favoriteThings: [String] = [
//TODO: Fill this array with your favorite things. Then use this collection to populate your table.
]
// MARK: Table View Data Source Methods
// number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// TODO: Implement this method to get the correct row count
let placeholderCount = 2
return placeholderCount
}
// cell for row at index path
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// TODO: Implement method
// 1. Dequeue a reusable cell from the table, using the correct “reuse identifier”
// 2. Find the model object that corresponds to that row
// 3. Set the images and labels in the cell with the data from the model object
// 4. return the cell.
let placeholderCell = UITableViewCell()
return placeholderCell
}
}
| 31.045455 | 107 | 0.674231 |
d907aba2dfb2d3eecca81ea21a44cdd1aed1978d | 2,081 | //
// ChannelModel.swift
// BaseSwift
//
// Created by Gary on 2017/1/4.
// Copyright © 2017年 shadowR. All rights reserved.
//
import SRKit
import ObjectMapper
class ChannelModel: BaseBusinessModel {
var name: String? {
var name = base
if let localLang = localLang, NSLocale.preferredLanguages[0].hasPrefix(localLang) {
name = localValue
}
return name
}
var cellWidth: CGFloat = 0
private var base: String?
private var langs: [ParamDictionary]?
private var localLang: String? //只存在base和唯一一种本地化的语言
private var localValue: String? //只存在base和唯一一种本地化的语言
override init() {
super.init()
}
init(id: String) {
super.init()
self.id = id
}
init?(JSON: [String: Any], context: MapContext? = nil) {
super.init()
if let id = JSON[Param.Key.id] as? String {
self.id = id
}
guard let name = JSON[Param.Key.name] as? ParamDictionary else {
return
}
if let base = name[Param.Key.base] as? String {
self.base = base
}
langs = []
name.forEach { (key, value) in
if !isEmptyString(key) && Param.Key.base != key {
langs?.append([key : value])
if let string = value as? String {
localLang = key
localValue = string
}
}
}
}
required init?(map: Map) {
fatalError("init(map:) has not been implemented")
}
func toJSON() -> [String : Any] {
var dictionary = [:] as ParamDictionary
if let id = id {
dictionary[Param.Key.id] = id
}
var names = [:] as ParamDictionary
if let langs = langs {
langs.forEach { $0.forEach { names[$0.key] = $0.value } }
}
if let base = base {
names[Param.Key.base] = base
}
dictionary[Param.Key.name] = names
return dictionary
}
}
| 25.072289 | 91 | 0.515137 |
5b172cedb284153e493cc54f3cedf73dd43789a4 | 9,095 | //
// TextViewController.swift
// ShiftToday
//
// Created by Matthew Merritt on 12/27/16.
// Copyright © 2017 MerrittWare. All rights reserved.
//
import UIKit
public protocol MMTodoTextViewControllerDelegate {
func saveTodo(todo: MMTodo, isAdding: Bool)
}
public class MMTodoTextViewController: UIViewController {
var delegate: MMTodoTextViewControllerDelegate!
var todo: MMTodo!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var statusButton: UIBarButtonItem!
@IBOutlet weak var priorityButton: UIBarButtonItem!
@IBOutlet weak var toolBar: UIToolbar!
var fromPreview = false
var isPrviewing = false
var needsSaving = false
let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 240, height: 22))
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textField.text = "Title"
textField.font = UIFont.systemFont(ofSize: 17)
textField.textColor = UIColor.darkText
textField.textAlignment = .center
textField.delegate = self
self.navigationItem.titleView = textField
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MMTodoTextViewController.textFieldDoneButtonAction(_:)))
doneButton.tag = textField.tag
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textView.inputAccessoryView = toolBar
// textView.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.text = todo.todo
textField.text = todo.name
priorityButton.title = todo.priority.rawValue
statusButton.title = todo.status.rawValue
// TODO: - Need to get statusbar and navigationbar height
if isPrviewing {
textView.contentInset.top += 66
toolBar.isHidden = true
} else if fromPreview {
textView.contentInset.top -= 66
toolBar.isHidden = false
}
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isEditing = false
todo.todo = textView.text
if delegate != nil && needsSaving {
if todo.name.count < 1 {
let array = todo.todo.components(separatedBy: CharacterSet.newlines)
todo.name = array.first!
}
delegate.saveTodo(todo: todo, isAdding: false)
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func textFieldDoneButtonAction(_ sender: UIBarButtonItem) {
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension MMTodoTextViewController {
override public var previewActionItems : [UIPreviewActionItem] {
// let infoAction = UIPreviewAction(title: "File Information", style: .default) { (action, viewController) -> Void in
//// self.filesCollectionViewController.fileInfo()
// }
let shareAction = UIPreviewAction(title: "Share", style: .default) { (action, viewController) -> Void in
// self.shareActionView()
}
// let renameAction = UIPreviewAction(title: "Rename", style: .default) { (action, viewController) -> Void in
//// self.document.renameActionView()
// }
// let deleteAction = UIPreviewAction(title: "Remove", style: .destructive) { (action, viewController) -> Void in
//// self.document.removeActionView(confirm: true)
// }
// return [infoAction, shareAction, renameAction, deleteAction]
return [shareAction]
}
}
// MARK: - UITextFieldDelegate
extension MMTodoTextViewController: UITextFieldDelegate, UITextViewDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
textField.borderStyle = .roundedRect
}
public func textFieldDidEndEditing(_ textField: UITextField) {
textField.borderStyle = .none
todo.name = textField.text!
needsSaving = true
}
public func textViewDidEndEditing(_ textView: UITextView) {
needsSaving = true
}
}
// MARK: - IBActions
extension MMTodoTextViewController {
@IBAction func nameButtonAction(_ sender: UIBarButtonItem) {
// Swift.print("nameButtonAction")
let popover = UIViewController()
popover.modalPresentationStyle = .popover
if let presentation = popover.popoverPresentationController {
presentation.delegate = self
presentation.barButtonItem = sender
}
present(popover, animated: true, completion: nil)
}
@IBAction func priorityButtonAction(_ sender: UIBarButtonItem) {
// Swift.print("priorityButtonAction")
let picker = storyboard?.instantiateViewController(withIdentifier: "TodoPickerViewID") as? MMTodoPickerViewController
picker?.delegate = self
picker?.modalPresentationStyle = .popover
picker?.preferredContentSize = CGSize(width: 375, height: 260)
picker?.pickerType = .priority
picker?.pickerValue = todo.priority
picker?.isModalInPopover = true
if let presentation = picker?.popoverPresentationController {
presentation.delegate = self
presentation.barButtonItem = sender
}
present(picker!, animated: true, completion: nil)
}
@IBAction func statusButtonAction(_ sender: UIBarButtonItem) {
let picker = storyboard?.instantiateViewController(withIdentifier: "TodoPickerViewID") as? MMTodoPickerViewController
picker?.delegate = self
picker?.modalPresentationStyle = .popover
picker?.preferredContentSize = CGSize(width: 375, height: 260)
picker?.pickerType = .status
picker?.pickerValue = todo.status
picker?.isModalInPopover = true
if let presentation = picker?.popoverPresentationController {
presentation.delegate = self
presentation.barButtonItem = sender
}
present(picker!, animated: true, completion: nil)
}
@IBAction func dueDateButtonAction(_ sender: UIBarButtonItem) {
let picker = storyboard?.instantiateViewController(withIdentifier: "TodoPickerViewID") as? MMTodoPickerViewController
picker?.delegate = self
picker?.modalPresentationStyle = .popover
picker?.preferredContentSize = CGSize(width: 375, height: 260)
picker?.pickerType = .dueDate
picker?.pickerValue = todo.dueAt
picker?.isModalInPopover = true
if let presentation = picker?.popoverPresentationController {
presentation.delegate = self
presentation.barButtonItem = sender
}
present(picker!, animated: true, completion: nil)
}
}
extension MMTodoTextViewController: MMTodoPickerViewControllerDelegate {
func didCancel(indexPath: IndexPath?) {
}
func didSelect(selection: Any, ofType pickerType: MMTodoPickerType, indexPath: IndexPath?) {
// Swift.print("Selected: \(selection) ofType: \(pickerType)")
switch pickerType {
case .priority:
todo.priority = selection as! MMTodo.Priority
priorityButton.title = todo.priority.rawValue
needsSaving = true
case .status:
todo.status = selection as! MMTodo.Status
statusButton.title = todo.status.rawValue
needsSaving = true
case .createDate:
todo.createdAt = selection as! Date
needsSaving = true
case .dueDate:
todo.dueAt = selection as? Date
needsSaving = true
}
}
}
extension MMTodoTextViewController: UIPopoverPresentationControllerDelegate {
// MARK: Popover delegate functions
// Override iPhone behavior that presents a popover as fullscreen.
// i.e. now it shows same popover box within on iPhone & iPad
public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
// show popover box for iPhone and iPad both
return UIModalPresentationStyle.none
}
}
| 32.598566 | 179 | 0.66674 |
b9bbc6cf6ca97b6e44050fd860aca6d842f8c2a2 | 200 | import Foundation
struct ListRequest: Encodable {
let janus = "message"
let transaction: String
let body: Body = Body()
struct Body: Encodable {
let request = "list"
}
}
| 16.666667 | 31 | 0.625 |
c1062d29a319f9e2c9acd3873a2c737e79faf189 | 1,008 | // RUN: %empty-directory(%t)
// RUN: touch %t/empty.swift
// RUN: %{python} %utils/split_file.py -o %t %s
// RUN: %target-swift-frontend -verify -emit-module -o %t/errors.partial.swiftmodule -module-name errors -experimental-allow-module-with-compiler-errors %t/errors.swift
// RUN: %target-swift-frontend -emit-module -o %t/errorsempty.partial.swiftmodule -module-name errors %t/empty.swift
// RUN: %target-swift-frontend -module-name errors -emit-module -o %t/errors.swiftmodule -experimental-allow-module-with-compiler-errors %t/errors.partial.swiftmodule %t/errorsempty.partial.swiftmodule
// RUN: %target-swift-frontend -emit-module -o %t/mods/uses.swiftmodule -experimental-allow-module-with-compiler-errors -I %t/mods %t/uses.swift 2>&1 | %FileCheck -check-prefix=CHECK-USES %s
// BEGIN errors.swift
typealias AnAlias = undefined // expected-error {{cannot find type 'undefined'}}
// BEGIN uses.swift
import errors
func test(a: AnAlias) {}
// CHECK-USES-NOT: cannot find type 'AnAlias' in scope
| 50.4 | 201 | 0.747024 |
dbce5597dbe913b9593d84a7ef83850fb643385f | 930 | //
// AppConstants.swift
// FlightsSRPAssignment
//
// Created by Satyam Sehgal on 08/06/19.
// Copyright © 2019 Satyam Sehgal. All rights reserved.
//
import Foundation
import UIKit
struct AppConstants {
enum HTTPMethod : String {
case get = "GET"
case post = "POST"
case put = "PUT"
}
enum StoryBoards: String {
case main = "Main"
}
enum SortCriteriaType: String {
case shortestFirst = "Shortest First"
case leastPrice = "Least Price"
case earlyDeparture = "Early Departure"
case lateDeparture = "Late Departure"
}
static let disableStateBgColor = UIColor(red: 67/255, green: 67/255, blue: 67/255, alpha: 1.0)
static let enableStateBgColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1.0)
static let disableTextColor: UIColor = .white
static let enableTextColor: UIColor = .black
}
| 25.833333 | 100 | 0.637634 |
69aa9c42d1450446d95ff7fd32dea9361190b139 | 817 | //
// BackEaseInOut.swift
// Easing
//
// Created by Justin Forsyth on 10/15/15.
// Copyright © 2015 jforce. All rights reserved.
//
import Foundation
public class BackEaseInOut : EasingFunction{
var s: Float = 1.70158;
convenience init(back: Float){
self.init();
self.s = back;
}
override public func calculate(var t: Float, var b: Float, var c: Float, var d: Float)->Float{
let t0 = t / (d / 2);
if t0 < 1{
let s0 = s * 1.525;
return c/2*(t0*t0*((s0+1)*t0 - s0)) + b;
}
let t1 = t0 - 2;
let s0 = s * 1.525;
return c/2*((t1)*t1*((s0+1)*t1 + s0) + 2) + b;
}
} | 19 | 98 | 0.428397 |
8ad05b5c3256a4a2dc57c7140e29c58bde1b1b7e | 883 | //
// WJLrcLabel.swift
// PlayerPro
//
// Created by William on 2019/4/24.
// Copyright © 2019 William. All rights reserved.
//
import UIKit
class WJLrcLabel: UILabel {
var line: WJLrcLineModel?
var isHighlight: Bool = false {
didSet {
setNeedsDisplay()
}
}
var highlightWidth: CGFloat = 0.0 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if isHighlight {
/// 颜色填充
kTintColor.setFill()
UIRectFillUsingBlendMode(CGRect(x: 0.0,
y: 0.0,
width: highlightWidth,
height: self.frame.size.height),
.sourceIn)
}
}
}
| 21.536585 | 76 | 0.445074 |
1d89c3b245a6408100454973d8078e2eff9b160e | 24,238 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension String {
// FIXME(strings): at least temporarily remove it to see where it was applied
/// Creates a new string from the given substring.
///
/// - Parameter substring: A substring to convert to a standalone `String`
/// instance.
///
/// - Complexity: O(*n*), where *n* is the length of `substring`.
@inlinable
public init(_ substring: __shared Substring) {
self = String._fromSubstring(substring)
}
}
/// A slice of a string.
///
/// When you create a slice of a string, a `Substring` instance is the result.
/// Operating on substrings is fast and efficient because a substring shares
/// its storage with the original string. The `Substring` type presents the
/// same interface as `String`, so you can avoid or defer any copying of the
/// string's contents.
///
/// The following example creates a `greeting` string, and then finds the
/// substring of the first sentence:
///
/// let greeting = "Hi there! It's nice to meet you! 👋"
/// let endOfSentence = greeting.firstIndex(of: "!")!
/// let firstSentence = greeting[...endOfSentence]
/// // firstSentence == "Hi there!"
///
/// You can perform many string operations on a substring. Here, we find the
/// length of the first sentence and create an uppercase version.
///
/// print("'\(firstSentence)' is \(firstSentence.count) characters long.")
/// // Prints "'Hi there!' is 9 characters long."
///
/// let shoutingSentence = firstSentence.uppercased()
/// // shoutingSentence == "HI THERE!"
///
/// Converting a Substring to a String
/// ==================================
///
/// This example defines a `rawData` string with some unstructured data, and
/// then uses the string's `prefix(while:)` method to create a substring of
/// the numeric prefix:
///
/// let rawInput = "126 a.b 22219 zzzzzz"
/// let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
/// // numericPrefix is the substring "126"
///
/// When you need to store a substring or pass it to a function that requires a
/// `String` instance, you can convert it to a `String` by using the
/// `String(_:)` initializer. Calling this initializer copies the contents of
/// the substring to a new string.
///
/// func parseAndAddOne(_ s: String) -> Int {
/// return Int(s, radix: 10)! + 1
/// }
/// _ = parseAndAddOne(numericPrefix)
/// // error: cannot convert value...
/// let incrementedPrefix = parseAndAddOne(String(numericPrefix))
/// // incrementedPrefix == 127
///
/// Alternatively, you can convert the function that takes a `String` to one
/// that is generic over the `StringProtocol` protocol. The following code
/// declares a generic version of the `parseAndAddOne(_:)` function:
///
/// func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int {
/// return Int(s, radix: 10)! + 1
/// }
/// let genericallyIncremented = genericParseAndAddOne(numericPrefix)
/// // genericallyIncremented == 127
///
/// You can call this generic function with an instance of either `String` or
/// `Substring`.
///
/// - Important: Don't store substrings longer than you need them to perform a
/// specific operation. A substring holds a reference to the entire storage
/// of the string it comes from, not just to the portion it presents, even
/// when there is no other reference to the original string. Storing
/// substrings may, therefore, prolong the lifetime of string data that is
/// no longer otherwise accessible, which can appear to be memory leakage.
@_fixed_layout
public struct Substring {
@usableFromInline
internal var _slice: Slice<String>
@inlinable @inline(__always)
internal init(_ slice: Slice<String>) {
self._slice = slice
_invariantCheck()
}
@inline(__always)
internal init(_ slice: _StringGutsSlice) {
self.init(String(slice._guts)[slice.range])
}
/// Creates an empty substring.
@inlinable @inline(__always)
public init() {
self.init(Slice())
}
}
extension Substring {
/// Returns the underlying string from which this Substring was derived.
@_alwaysEmitIntoClient
public var base: String { return _slice.base }
@inlinable @inline(__always)
internal var _wholeGuts: _StringGuts { return base._guts }
@inlinable
internal var _offsetRange: Range<Int> {
@inline(__always) get {
let start = _slice.startIndex
let end = _slice.endIndex
_internalInvariant(start.transcodedOffset == 0 && end.transcodedOffset == 0)
return Range(uncheckedBounds: (start._encodedOffset, end._encodedOffset))
}
}
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
self.base._invariantCheck()
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension Substring: StringProtocol {
public typealias Index = String.Index
public typealias SubSequence = Substring
@inlinable
public var startIndex: Index {
@inline(__always) get { return _slice.startIndex }
}
@inlinable
public var endIndex: Index {
@inline(__always) get { return _slice.endIndex }
}
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
_precondition(i < endIndex, "Cannot increment beyond endIndex")
_precondition(i >= startIndex, "Cannot increment an invalid index")
return _slice.index(after: i)
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
_precondition(i <= endIndex, "Cannot decrement an invalid index")
_precondition(i > startIndex, "Cannot decrement beyond startIndex")
return _slice.index(before: i)
}
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let result = _slice.index(i, offsetBy: n)
_precondition(
(_slice._startIndex ... _slice.endIndex).contains(result),
"Operation results in an invalid index")
return result
}
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
let result = _slice.index(i, offsetBy: n, limitedBy: limit)
_precondition(result.map {
(_slice._startIndex ... _slice.endIndex).contains($0)
} ?? true,
"Operation results in an invalid index")
return result
}
@inlinable @inline(__always)
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
public subscript(i: Index) -> Character {
return _slice[i]
}
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Iterator.Element == Iterator.Element {
_slice.replaceSubrange(bounds, with: newElements)
}
public mutating func replaceSubrange(
_ bounds: Range<Index>, with newElements: Substring
) {
replaceSubrange(bounds, with: newElements._slice)
}
/// Creates a string from the given Unicode code units in the specified
/// encoding.
///
/// - Parameters:
/// - codeUnits: A collection of code units encoded in the encoding
/// specified in `sourceEncoding`.
/// - sourceEncoding: The encoding in which `codeUnits` should be
/// interpreted.
@inlinable // specialization
public init<C: Collection, Encoding: _UnicodeEncoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
) where C.Iterator.Element == Encoding.CodeUnit {
self.init(String(decoding: codeUnits, as: sourceEncoding))
}
/// Creates a string from the null-terminated, UTF-8 encoded sequence of
/// bytes at the given pointer.
///
/// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous,
/// UTF-8 encoded bytes ending just before the first zero byte.
public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
self.init(String(cString: nullTerminatedUTF8))
}
/// Creates a string from the null-terminated sequence of bytes at the given
/// pointer.
///
/// - Parameters:
/// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code
/// units in the encoding specified in `sourceEncoding`, ending just
/// before the first zero code unit.
/// - sourceEncoding: The encoding in which the code units should be
/// interpreted.
@inlinable // specialization
public init<Encoding: _UnicodeEncoding>(
decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type
) {
self.init(
String(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding))
}
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // specialization
public func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result {
// TODO(String performance): Detect when we cover the rest of a nul-
// terminated String, and thus can avoid a copy.
return try String(self).withCString(body)
}
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(encodedAs:_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameters:
/// - body: A closure with a pointer parameter that points to a
/// null-terminated sequence of code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(encodedAs:_:)` method. The pointer argument is valid
/// only for the duration of the method's execution.
/// - targetEncoding: The encoding in which the code units should be
/// interpreted.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // specialization
public func withCString<Result, TargetEncoding: _UnicodeEncoding>(
encodedAs targetEncoding: TargetEncoding.Type,
_ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result
) rethrows -> Result {
// TODO(String performance): Detect when we cover the rest of a nul-
// terminated String, and thus can avoid a copy.
return try String(self).withCString(encodedAs: targetEncoding, body)
}
}
extension Substring : CustomReflectable {
public var customMirror: Mirror { return String(self).customMirror }
}
extension Substring : CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(self) }
}
}
extension Substring : CustomDebugStringConvertible {
public var debugDescription: String { return String(self).debugDescription }
}
extension Substring : LosslessStringConvertible {
@inlinable
public init(_ content: String) {
self = content[...]
}
}
extension Substring {
@_fixed_layout
public struct UTF8View {
@usableFromInline
internal var _slice: Slice<String.UTF8View>
}
}
extension Substring.UTF8View : BidirectionalCollection {
public typealias Index = String.UTF8View.Index
public typealias Indices = String.UTF8View.Indices
public typealias Element = String.UTF8View.Element
public typealias SubSequence = Substring.UTF8View
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UTF8View, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).utf8,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(before i: Index) -> Index { return _slice.index(before: i) }
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
public subscript(r: Range<Index>) -> Substring.UTF8View {
// FIXME(strings): tests.
_precondition(r.lowerBound >= startIndex && r.upperBound <= endIndex,
"UTF8View index range out of bounds")
return Substring.UTF8View(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var utf8: UTF8View {
get {
return base.utf8[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UTF8View) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init?(_ codeUnits: Substring.UTF8View) {
let guts = codeUnits._slice.base._guts
guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex),
guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else {
return nil
}
self = String(Substring(codeUnits))
}
}
extension Substring {
@_fixed_layout
public struct UTF16View {
@usableFromInline
internal var _slice: Slice<String.UTF16View>
}
}
extension Substring.UTF16View : BidirectionalCollection {
public typealias Index = String.UTF16View.Index
public typealias Indices = String.UTF16View.Indices
public typealias Element = String.UTF16View.Element
public typealias SubSequence = Substring.UTF16View
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UTF16View, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).utf16,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index { return _slice.index(before: i) }
@inlinable
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
@inlinable
public subscript(r: Range<Index>) -> Substring.UTF16View {
return Substring.UTF16View(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var utf16: UTF16View {
get {
return base.utf16[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UTF16View) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init?(_ codeUnits: Substring.UTF16View) {
let guts = codeUnits._slice.base._guts
guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex),
guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else {
return nil
}
self = String(Substring(codeUnits))
}
}
extension Substring {
@_fixed_layout
public struct UnicodeScalarView {
@usableFromInline
internal var _slice: Slice<String.UnicodeScalarView>
}
}
extension Substring.UnicodeScalarView : BidirectionalCollection {
public typealias Index = String.UnicodeScalarView.Index
public typealias Indices = String.UnicodeScalarView.Indices
public typealias Element = String.UnicodeScalarView.Element
public typealias SubSequence = Substring.UnicodeScalarView
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UnicodeScalarView, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).unicodeScalars,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index { return _slice.index(before: i) }
@inlinable
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
@inlinable
public subscript(r: Range<Index>) -> Substring.UnicodeScalarView {
return Substring.UnicodeScalarView(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var unicodeScalars: UnicodeScalarView {
get {
return base.unicodeScalars[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UnicodeScalarView) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init(_ content: Substring.UnicodeScalarView) {
self = String(Substring(content))
}
}
// FIXME: The other String views should be RangeReplaceable too.
extension Substring.UnicodeScalarView : RangeReplaceableCollection {
@inlinable
public init() { _slice = Slice.init() }
public mutating func replaceSubrange<C : Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_slice.replaceSubrange(target, with: replacement)
}
}
extension Substring : RangeReplaceableCollection {
@_specialize(where S == String)
@_specialize(where S == Substring)
@_specialize(where S == Array<Character>)
public init<S : Sequence>(_ elements: S)
where S.Element == Character {
if let str = elements as? String {
self = str[...]
return
}
if let subStr = elements as? Substring {
self = subStr
return
}
self = String(elements)[...]
}
@inlinable // specialize
public mutating func append<S : Sequence>(contentsOf elements: S)
where S.Element == Character {
var string = String(self)
self = Substring() // Keep unique storage if possible
string.append(contentsOf: elements)
self = Substring(string)
}
}
extension Substring {
public func lowercased() -> String {
return String(self).lowercased()
}
public func uppercased() -> String {
return String(self).uppercased()
}
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> String {
return try String(self.lazy.filter(isIncluded))
}
}
extension Substring : TextOutputStream {
public mutating func write(_ other: String) {
append(contentsOf: other)
}
}
extension Substring : TextOutputStreamable {
@inlinable // specializable
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(String(self))
}
}
extension Substring : ExpressibleByUnicodeScalarLiteral {
@inlinable
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
extension Substring : ExpressibleByExtendedGraphemeClusterLiteral {
@inlinable
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
}
extension Substring : ExpressibleByStringLiteral {
@inlinable
public init(stringLiteral value: String) {
self.init(value)
}
}
// String/Substring Slicing
extension String {
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> Substring {
_boundsCheck(r)
return Substring(Slice(base: self, bounds: r))
}
}
extension Substring {
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> Substring {
return Substring(_slice[r])
}
}
| 30.034696 | 82 | 0.685741 |
16a3252a6ec2ea68fed3800aad77b279feafacb1 | 11,602 | //
// CourceMainTableView.swift
// FMDemo
//
// Created by mba on 17/2/9.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
fileprivate var kMainCellId = "CourceMainTableViewCell"
class CourceMainTableView: RefreshBaseTableView {
var parentVC: CourceMainViewController?
var cid: String!
fileprivate var tbHeadView = CourceHeadTbView.courceHeadTbView()
fileprivate var footAddBtn: UIButton = {
let footAddBtn = UIButton()
footAddBtn.setImage(UIImage.init(named: "add"), for: .normal)
footAddBtn.adjustsImageWhenHighlighted = false
footAddBtn.backgroundColor = UIColor.colorWithHexString("41A0FD")
footAddBtn.addTarget(self, action: #selector(actionAdd(sender:)), for: .touchUpInside)
footAddBtn.layer.cornerRadius = 5
footAddBtn.layer.masksToBounds = true
return footAddBtn
}()
fileprivate var tbFootView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 80))
fileprivate var alert: UIAlertController?
override func setUI() {
let nib = UINib(nibName: kMainCellId, bundle: nil)
register(nib, forCellReuseIdentifier: kMainCellId)
delegate = self
dataSource = self
separatorStyle = .none
tableHeaderView = tbHeadView
tbFootView.backgroundColor = UIColor.clear
tbFootView.addSubview(footAddBtn)
footAddBtn.frame = CGRect(x: 10, y: 20, width: tbFootView.frame.size.width - 20, height: 40)
tableFooterView = tbFootView
mj_footer.isHidden = true
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
override func loadData() {
KeService.actionGetMaterials(cid: cid, success: { (bean) in
self.dataList = bean.data
self.loadCompleted()
self.changceCourseStatus()
}) { (error) in
self.loadError(error)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: -
extension CourceMainTableView {
/// 设置hbHeadView
open func setcid(cid: String, title: String) {
self.cid = cid
tbHeadView.cid = cid
tbHeadView.titleLabel.text = title
}
fileprivate func changceCourseStatus() {
NotificationCenter.default.post(name: .shouldReLoadMainData, object: nil, userInfo: nil)
var isComplet = true
for bean in (self.dataList as? [GetMaterialsData])! {
if "unrecorded" == bean.state {
isComplet = isComplet && false
} else if "recorded" == bean.state {
isComplet = isComplet && true
}
}
if isComplet {
tbHeadView.courceStatusLabel.text = "课程未上架"
}else{
tbHeadView.courceStatusLabel.text = "课程未完善"
}
}
}
extension CourceMainTableView {
func actionAdd(sender: UIButton) {
self.alert = UIAlertController(title: "\n\n", message: "", preferredStyle: .alert)
let textView = BorderTextView(frame: CGRect(x: 5, y: 5, width: 270 - 10, height: 80), textContainer: nil)
textView.setPlaceholder(kCreatMaterialTitleString, maxTip: 50)
alert?.view.addSubview(textView)
let cancelAction = UIAlertAction(title: "取消", style: .default, handler: nil)
let okAction = UIAlertAction(title: "确定", style: .default, handler: { (action) in
if textView.text.isEmpty {
MBAProgressHUD.showInfoWithStatus("增加章节失败,章节标题不能为空")
return
}
KeService.actionMaterial(cid: self.cid, title: textView.text, success: { (bean) in
let object = GetMaterialsData(JSON: ["time":"0", "mid": bean.mid ?? "", "title": textView.text, "state": "unrecorded"])
self.dataList?.append(object!)
let indexPath = IndexPath(row: (self.dataList?.count)!-1, section: 0)
self.insertRows(at: [indexPath], with: .right)
self.changceCourseStatus()
}, failure: { (error) in
})
})
alert?.addAction(cancelAction)
alert?.addAction(okAction)
self.parentVC?.present(alert!, animated: true, completion: {
textView.becomeFirstResponder()
})
}
}
extension CourceMainTableView {
// 有headTitle 就设置高度
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let titleHeadLabel = UILabel()
titleHeadLabel.text = "章节(课程不分章节时,默认为单一章节课程)"
let titleH:CGFloat = 30
let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: titleH))
titleHeadLabel.frame = CGRect(x: 10, y: 5, width: view.size.width, height: titleH)
titleHeadLabel.font = UIFont.systemFont(ofSize: 13)
view.addSubview(titleHeadLabel)
titleHeadLabel.textColor = UIColor.gray
view.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor)
return view
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
// func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// let sourceIndex = sourceIndexPath.row
// let destinationIndex = destinationIndexPath.row
// let object = dataList?[sourceIndex]
// self.dataList?.remove(at: sourceIndex)
// self.dataList?.insert(object!, at: destinationIndex)
// }
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let reNameAction = UITableViewRowAction(style: .normal, title: "编辑") { (action, index) in
let sourceIndex = indexPath.row
let object = self.dataList?[sourceIndex] as? GetMaterialsData
self.alert = UIAlertController(title: "\n\n", message: "", preferredStyle: .alert)
let textView = BorderTextView(frame: CGRect(x: 5, y: 5, width: 270 - 10, height: 80), textContainer: nil)
textView.setPlaceholder(kCreatMaterialTitleString, maxTip: 50)
self.alert?.view.addSubview(textView)
textView.text = "\(object?.title ?? "")"
let cancelAction = UIAlertAction(title: "取消", style: .default, handler: { (action) in
self.endEditing(true)
tableView.setEditing(false, animated: false)
})
let okAction = UIAlertAction(title: "确定", style: .default, handler: { (action) in
self.endEditing(true)
if textView.text.isEmpty {
MBAProgressHUD.showInfoWithStatus("修改章节标题失败,章节标题不能为空")
return
}
if textView.text != object?.title! {
let oldText = object?.title!
KeService.actionMaterial(mid: object?.mid!, cid: self.cid, title: textView.text, success: { (bean) in
}, failure: { (error) in
object?.title = oldText
self.dataList?[sourceIndex] = object!
tableView.reloadRows(at: [index], with: .right)
})
}
object?.title = textView.text
self.dataList?[sourceIndex] = object!
tableView.reloadRows(at: [index], with: .right)
})
self.alert?.addAction(cancelAction)
self.alert?.addAction(okAction)
self.parentVC?.navigationController?.present(self.alert!, animated: true, completion: {
})
}
let moveAction = UITableViewRowAction(style: .normal, title: "向上") { (action, index) in
let sourceIndex = indexPath.row
if sourceIndex == 0 { return }
let destinationIndex = sourceIndex - 1
let object = self.dataList?[sourceIndex]
self.dataList?.remove(at: sourceIndex)
self.dataList?.insert(object!, at: destinationIndex)
let toIndexPath = IndexPath(row: destinationIndex, section: 0)
tableView.moveRow(at: indexPath, to: toIndexPath)
tableView.setEditing(false, animated: true)
var sort = [String]()
for bean in self.dataList! {
guard let object = bean as? GetMaterialsData else { return}
sort.append(object.mid ?? "")
}
KeService.actionMaterialSort(cid:self.cid, sort: sort, success: { (bean) in
}, failure: { (error) in
self.dataList?.remove(at: destinationIndex)
self.dataList?.insert(object!, at: sourceIndex)
tableView.moveRow(at: indexPath, to: toIndexPath)
})
}
let deleteAction = UITableViewRowAction(style: .normal, title: "删除") { (action, index) in
if self.dataList?.count ?? 0 <= 1 {
MBAProgressHUD.showErrorWithStatus("章节需要保留一个")
return
}
let object = self.dataList?[index.row] as? GetMaterialsData
KeService.actionMaterialDelete(mid: object?.mid ?? "", success: { (bean) in
}, failure: { (error) in
self.dataList?.append(object!)
tableView.insertRows(at: [index], with: .fade)
MBAProgressHUD.showInfoWithStatus("删除失败")
})
self.dataList?.remove(at: index.row)
tableView.deleteRows(at: [index], with: .fade)
self.changceCourseStatus()
}
reNameAction.backgroundColor = UIColor.colorWithHexString("62d9a0")
moveAction.backgroundColor = UIColor.colorWithHexString("feba6a")
deleteAction.backgroundColor = UIColor.colorWithHexString("f45e5e")
return [deleteAction, moveAction, reNameAction]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let bean = self.dataList?[indexPath.row] as? GetMaterialsData else { return }
if bean.url?.isEmpty ?? true{
parentVC?.pushToRecordViewController(mid: (bean.mid)!)
} else {
parentVC?.pushToPlayCourceMaterialViewController(url: (bean.url)!)
}
}
}
extension CourceMainTableView {
//键盘的出现
func keyBoardWillShow(_ notification: Notification){
//获取userInfo
let kbInfo = notification.userInfo
//获取键盘的size
let kbRect = (kbInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
//键盘的y偏移量
let changeY = kbRect.origin.y - UIScreen.main.bounds.height
//键盘弹出的时间
// let duration = kbInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double
//界面偏移动画
UIView.animate(withDuration: 0.5) {
self.alert?.view.transform = CGAffineTransform(translationX: 0, y: changeY/2)
}
}
//键盘的隐藏
func keyBoardWillHide(_ notification: Notification){
}
}
| 39.195946 | 154 | 0.597569 |
d7fd0b24dbd550f7c01ed10a276c21f44a4108dd | 2,155 | //
// AnimationBarButton.swift
// TestCollectionView
//
// Created by Alex K. on 23/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class AnimatingBarButton: UIBarButtonItem, Rotatable {
@IBInspectable var normalImageName: String = ""
@IBInspectable var selectedImageName: String = ""
@IBInspectable var duration: Double = 1
let normalView = UIImageView(frame: .zero)
let selectedView = UIImageView(frame: .zero)
}
// MARK: life cicle
extension AnimatingBarButton {
override func awakeFromNib() {
super.awakeFromNib()
customView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
// customView?.backgroundColor = .redColor()
configurateImageViews()
}
}
// MARK: public
extension AnimatingBarButton {
func animationSelected(selected: Bool) {
if selected {
rotateAnimationFrom(normalView, toItem: selectedView, duration: duration)
} else {
rotateAnimationFrom(selectedView, toItem: normalView, duration: duration)
}
}
}
// MARK: Create
extension AnimatingBarButton {
private func configurateImageViews() {
configureImageView(normalView, imageName: normalImageName)
configureImageView(selectedView, imageName: selectedImageName)
selectedView.alpha = 0
// normalView.hidden = true
}
private func configureImageView(imageView: UIImageView, imageName: String) {
guard let customView = customView else { return }
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: imageName)
imageView.contentMode = .ScaleAspectFit
// imageView.backgroundColor = .greenColor()
// imageView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
customView.addSubview(imageView)
// add constraints
[(NSLayoutAttribute.CenterX, 12), (.CenterY, -1)].forEach { info in
(customView, imageView) >>>- {
$0.attribute = info.0
$0.constant = CGFloat(info.1)
}
}
[NSLayoutAttribute.Height, .Width].forEach { attribute in
imageView >>>- {
$0.attribute = attribute
$0.constant = 20
}
}
}
}
| 24.770115 | 79 | 0.679814 |
e4ed9ade0e1ffa7bc45046e494aad8c213ef836c | 703 | //
// AppDelegate.swift
// FitTrack
//
// Created by roman.sherbakov on 07/11/2016.
// Copyright (c) 2016 roman.sherbakov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .LightContent
ZoomStartupAnimation.performAnimation(window!, navControllerIdentifier: "navigationController", backgroundImage: UIImage(named: "bg")!, animationImage: UIImage(named: "logo")!)
return true
}
}
| 27.038462 | 184 | 0.721195 |
90c5d20eadc0d58a7d5a94ffb5c78d7f931c523b | 829 | //
// CountedFlushTriggerTests.swift
//
//
// Created by Brian Michel on 9/7/15.
//
//
import XCTest
class CountedFlushTriggerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 23.027778 | 111 | 0.617612 |
6ac62aae35d6fbd318abc13a49609db279c40493 | 2,314 | import Quick
import XCTest
@testable import CombineXTests
@testable import CXFoundationTests
@testable import CXInconsistentTests
QCKMain([
AnyCancellableSpec.self,
AnySubscriberSpec.self,
CombineIdentifierSpec.self,
DemandSpec.self,
AssertNoFailureSpec.self,
AutoconnectSpec.self,
BufferSpec.self,
CollectByCountSpec.self,
CollectByTimeSpec.self,
ConcatenateSpec.self,
DebounceSpec.self,
DelaySpec.self,
DropUntilOutputSpec.self,
EmptySpec.self,
FlatMapSpec.self,
FutureSpec.self,
HandleEventsSpec.self,
JustSpec.self,
MapErrorSpec.self,
MeasureIntervalSpec.self,
MergeSpec.self,
MulticastSpec.self,
OptionalSpec.self,
OutputSpec.self,
PrefixUntilOutputSpec.self,
PrintSpec.self,
ReceiveOnSpec.self,
PublishedSpec.self,
RecordSpec.self,
RemoveDuplicatesSpec.self,
ReplaceErrorSpec.self,
ReplaceEmptySpec.self,
ResultSpec.self,
RetrySpec.self,
SequenceSpec.self,
ShareSpec.self,
SubscribeOnSpec.self,
SwitchToLatestSpec.self,
ThrottleSpec.self,
TimeoutSpec.self,
TryAllSatisfySpec.self,
TryCatchSpec.self,
TryCompactMapSpec.self,
TryDropWhileSpec.self,
TryPrefixWhileSpec.self,
TryReduceSpec.self,
TryRemoveDuplicatesSpec.self,
TryScanSpec.self,
ZipSpec.self,
ImmediateSchedulerSpec.self,
PassthroughSubjectSpec.self,
CurrentValueSubjectSpec.self,
AssignSpec.self,
SinkSpec.self,
ObserableObjectSpec.self,
// MARK: - CXFoundation
CoderSpec.self,
KeyValueObservingSpec.self,
NotificationCenterSpec.self,
SchedulerSpec.self,
TimerSpec.self,
URLSessionSpec.self,
// MARK: - CXInconsistentTests
FailingSubjectSpec.self,
FailingTimerSpec.self,
FailingBufferSpec.self,
FailingFlatMapSpec.self,
SuspiciousBufferSpec.self,
SuspiciousDemandSpec.self,
SuspiciousSwitchToLatestSpec.self,
FixedSpec.self,
VersioningDelaySpec.self,
VersioningReceiveOnSpec.self,
VersioningObserableObjectSpec.self,
VersioningCollectByTimeSpec.self,
VersioningSwitchToLatestSpec.self,
VersioningFutureSpec.self,
VersioningSinkSpec.self,
VersioningAssignSpec.self,
])
| 22.910891 | 39 | 0.720398 |
764b189a1df1b221d5154e7a901d7ec681078dc0 | 2,284 | //
// SceneDelegate.swift
// Prework
//
// Created by Cao Mai on 3/27/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.09434 | 147 | 0.711909 |
5bd68f4e7c27bdf3b9cf9deaa359283c0e03ea28 | 35,793 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// State of the current decoding process.
public enum DecodingState {
/// Continue decoding.
case `continue`
/// Stop decoding until more data is ready to be processed.
case needMoreData
}
/// Common errors thrown by `ByteToMessageDecoder`s.
public enum ByteToMessageDecoderError: Error {
/// More data has been received by a `ByteToMessageHandler` despite the fact that an error has previously been
/// emitted. The associated `Error` is the error previously emitted and the `ByteBuffer` is the extra data that has
/// been received. The common cause for this error to be emitted is the user not having torn down the `Channel`
/// after previously an `Error` has been sent through the pipeline using `fireErrorCaught`.
case dataReceivedInErrorState(Error, ByteBuffer)
/// This error can be thrown by `ByteToMessageDecoder`s if there was unexpectedly some left-over data when the
/// `ByteToMessageDecoder` was removed from the pipeline or the `Channel` was closed.
case leftoverDataWhenDone(ByteBuffer)
}
extension ByteToMessageDecoderError {
// TODO: For NIO 3, make this an enum case (or whatever best way for Errors we have come up with).
/// This error can be thrown by `ByteToMessageDecoder`s if the incoming payload is larger than the max specified.
public struct PayloadTooLargeError: Error {}
}
/// `ByteToMessageDecoder`s decode bytes in a stream-like fashion from `ByteBuffer` to another message type.
///
/// ### Purpose
///
/// A `ByteToMessageDecoder` provides a simplified API for handling streams of incoming data that can be broken
/// up into messages. This API boils down to two methods: `decode`, and `decodeLast`. These two methods, when
/// implemented, will be used by a `ByteToMessageHandler` paired with a `ByteToMessageDecoder` to decode the
/// incoming byte stream into a sequence of messages.
///
/// The reason this helper exists is to smooth away some of the boilerplate and edge case handling code that
/// is often necessary when implementing parsers in a SwiftNIO `ChannelPipeline`. A `ByteToMessageDecoder`
/// never needs to worry about how inbound bytes will be buffered, as `ByteToMessageHandler` deals with that
/// automatically. A `ByteToMessageDecoder` also never needs to worry about memory exclusivity violations
/// that can occur when re-entrant `ChannelPipeline` operations occur, as `ByteToMessageHandler` will deal with
/// those as well.
///
/// ### Implementing ByteToMessageDecoder
///
/// A type that implements `ByteToMessageDecoder` must implement two methods: `decode` and `decodeLast`.
///
/// `decode` is the main decoding method, and is the one that will be called most often. `decode` is invoked
/// whenever data is received by the wrapping `ByteToMessageHandler`. It is invoked with a `ByteBuffer` containing
/// all the received data (including any data previously buffered), as well as a `ChannelHandlerContext` that can be
/// used in the `decode` function.
///
/// `decode` is called in a loop by the `ByteToMessageHandler`. This loop continues until one of two cases occurs:
///
/// 1. The input `ByteBuffer` has no more readable bytes (i.e. `.readableBytes == 0`); OR
/// 2. The `decode` method returns `.needMoreData`.
///
/// The reason this method is invoked in a loop is to ensure that the stream-like properties of inbound data are
/// respected. It is entirely possible for `ByteToMessageDecoder` to receive either fewer bytes than a single message,
/// or multiple messages in one go. Rather than have the `ByteToMessageDecoder` handle all of the complexity of this,
/// the logic can be boiled down to a single choice: has the `ByteToMessageDecoder` been able to move the state forward
/// or not? If it has, rather than containing an internal loop it may simply return `.continue` in order to request that
/// `decode` be invoked again immediately. If it has not, it can return `.needMoreData` to ask to be left alone until more
/// data has been returned from the network.
///
/// Essentially, if the next parsing step could not be taken because there wasn't enough data available, return `.needMoreData`.
/// Otherwise, return `.continue`. This will allow a `ByteToMessageDecoder` implementation to ignore the awkward way data
/// arrives from the network, and to just treat it as a series of `decode` calls.
///
/// `decodeLast` is a cousin of `decode`. It is also called in a loop, but unlike with `decode` this loop will only ever
/// occur once: when the `ChannelHandlerContext` belonging to this `ByteToMessageDecoder` is about to become invalidated.
/// This invalidation happens in two situations: when EOF is received from the network, or when the `ByteToMessageDecoder`
/// is being removed from the `ChannelPipeline`. The distinction between these two states is captured by the value of
/// `seenEOF`.
///
/// In this condition, the `ByteToMessageDecoder` must now produce any final messages it can with the bytes it has
/// available. In protocols where EOF is used as a message delimiter, having `decodeLast` called with `seenEOF == true`
/// may produce further messages. In other cases, `decodeLast` may choose to deliver any buffered bytes as "leftovers",
/// either in error messages or via `channelRead`. This can occur if, for example, a protocol upgrade is occurring.
///
/// As with `decode`, `decodeLast` is invoked in a loop. This allows the same simplification as `decode` allows: when
/// a message is completely parsed, the `decodeLast` function can return `.continue` and be re-invoked from the top,
/// rather than containing an internal loop.
///
/// Note that the value of `seenEOF` may change between calls to `decodeLast` in some rare situations.
///
/// ### Implementers Notes
///
/// /// `ByteToMessageHandler` will turn your `ByteToMessageDecoder` into a `ChannelInboundHandler`. `ByteToMessageHandler`
/// also solves a couple of tricky issues for you. Most importantly, in a `ByteToMessageDecoder` you do _not_ need to
/// worry about re-entrancy. Your code owns the passed-in `ByteBuffer` for the duration of the `decode`/`decodeLast` call and
/// can modify it at will.
///
/// If a custom frame decoder is required, then one needs to be careful when implementing
/// one with `ByteToMessageDecoder`. Ensure there are enough bytes in the buffer for a
/// complete frame by checking `buffer.readableBytes`. If there are not enough bytes
/// for a complete frame, return without modifying the reader index to allow more bytes to arrive.
///
/// To check for complete frames without modifying the reader index, use methods like `buffer.getInteger`.
/// You _MUST_ use the reader index when using methods like `buffer.getInteger`.
/// For example calling `buffer.getInteger(at: 0)` is assuming the frame starts at the beginning of the buffer, which
/// is not always the case. Use `buffer.getInteger(at: buffer.readerIndex)` instead.
///
/// If you move the reader index forward, either manually or by using one of `buffer.read*` methods, you must ensure
/// that you no longer need to see those bytes again as they will not be returned to you the next time `decode` is
/// called. If you still need those bytes to come back, consider taking a local copy of buffer inside the function to
/// perform your read operations on.
///
/// The `ByteBuffer` passed in as `buffer` is a slice of a larger buffer owned by the `ByteToMessageDecoder`
/// implementation. Some aspects of this buffer are preserved across calls to `decode`, meaning that any changes to
/// those properties you make in your `decode` method will be reflected in the next call to decode. In particular,
/// moving the reader index forward persists across calls. When your method returns, if the reader index has advanced,
/// those bytes are considered "consumed" and will not be available in future calls to `decode`.
/// Please note, however, that the numerical value of the `readerIndex` itself is not preserved, and may not be the same
/// from one call to the next. Please do not rely on this numerical value: if you need
/// to recall where a byte is relative to the `readerIndex`, use an offset rather than an absolute value.
///
/// ### Using ByteToMessageDecoder
///
/// To add a `ByteToMessageDecoder` to the `ChannelPipeline` use
///
/// channel.pipeline.addHandler(ByteToMessageHandler(MyByteToMessageDecoder()))
///
public protocol ByteToMessageDecoder {
/// The type of the messages this `ByteToMessageDecoder` decodes to.
associatedtype InboundOut
/// Decode from a `ByteBuffer`.
///
/// This method will be called in a loop until either the input `ByteBuffer` has nothing to read left or
/// `DecodingState.needMoreData` is returned. If `DecodingState.continue` is returned and the `ByteBuffer`
/// contains more readable bytes, this method will immediately be invoked again, unless `decodeLast` needs
/// to be invoked instead.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
/// - buffer: The `ByteBuffer` from which we decode.
/// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called
/// again once more data is present in the `ByteBuffer`.
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState
/// Decode from a `ByteBuffer` when no more data is incoming and the `ByteToMessageDecoder` is about to leave
/// the pipeline.
///
/// This method is called in a loop only once, when the `ChannelHandlerContext` goes inactive (i.e. when `channelInactive` is fired or
/// the `ByteToMessageDecoder` is removed from the pipeline).
///
/// Like with `decode`, this method will be called in a loop until either `DecodingState.needMoreData` is returned from the method
/// or until the input `ByteBuffer` has no more readable bytes. If `DecodingState.continue` is returned and the `ByteBuffer`
/// contains more readable bytes, this method will immediately be invoked again.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
/// - buffer: The `ByteBuffer` from which we decode.
/// - seenEOF: `true` if EOF has been seen. Usually if this is `false` the handler has been removed.
/// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called
/// again when more data is present in the `ByteBuffer`.
mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
/// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
mutating func decoderRemoved(context: ChannelHandlerContext)
/// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
mutating func decoderAdded(context: ChannelHandlerContext)
/// Determine if the read bytes in the given `ByteBuffer` should be reclaimed and their associated memory freed.
/// Be aware that reclaiming memory may involve memory copies and so is not free.
///
/// - parameters:
/// - buffer: The `ByteBuffer` to check
/// - return: `true` if memory should be reclaimed, `false` otherwise.
mutating func shouldReclaimBytes(buffer: ByteBuffer) -> Bool
}
/// Some `ByteToMessageDecoder`s need to observe `write`s (which are outbound events). `ByteToMessageDecoder`s which
/// implement the `WriteObservingByteToMessageDecoder` protocol will be notified about every outbound write.
///
/// `WriteObservingByteToMessageDecoder` may only observe a `write` and must not try to transform or block it in any
/// way. After the `write` method returns the `write` will be forwarded to the next outbound handler.
public protocol WriteObservingByteToMessageDecoder: ByteToMessageDecoder {
/// The type of `write`s.
associatedtype OutboundIn
/// `write` is called for every incoming `write` incoming to the corresponding `ByteToMessageHandler`.
///
/// - parameters:
/// - data: The data that was written.
mutating func write(data: OutboundIn)
}
extension ByteToMessageDecoder {
public mutating func decoderRemoved(context: ChannelHandlerContext) {
}
public mutating func decoderAdded(context: ChannelHandlerContext) {
}
/// Default implementation to detect once bytes should be reclaimed.
public func shouldReclaimBytes(buffer: ByteBuffer) -> Bool {
// We want to reclaim in the following cases:
//
// 1. If there is at least 2kB of memory to reclaim
// 2. If the buffer is more than 50% reclaimable memory and is at least
// 1kB in size.
if buffer.readerIndex >= 2048 {
return true
}
return buffer.storageCapacity > 1024 && (buffer.storageCapacity - buffer.readerIndex) < buffer.readerIndex
}
public func wrapInboundOut(_ value: InboundOut) -> NIOAny {
return NIOAny(value)
}
public mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState {
while try self.decode(context: context, buffer: &buffer) == .continue {}
return .needMoreData
}
}
private struct B2MDBuffer {
/// `B2MDBuffer`'s internal state, either we're already processing a buffer or we're ready to.
private enum State {
case processingInProgress
case ready
}
/// Can we produce a buffer to be processed right now or not?
enum BufferAvailability {
/// No, because no bytes available
case nothingAvailable
/// No, because we're already processing one
case bufferAlreadyBeingProcessed
/// Yes please, here we go.
case available(ByteBuffer)
}
/// Result of a try to process a buffer.
enum BufferProcessingResult {
/// Could not process a buffer because we are already processing one on the same call stack.
case cannotProcessReentrantly
/// Yes, we did process some.
case didProcess(DecodingState)
}
private var state: State = .ready
private var buffers: CircularBuffer<ByteBuffer> = CircularBuffer(initialCapacity: 4)
private let emptyByteBuffer: ByteBuffer
init(emptyByteBuffer: ByteBuffer) {
assert(emptyByteBuffer.readableBytes == 0)
self.emptyByteBuffer = emptyByteBuffer
}
}
// MARK: B2MDBuffer Main API
extension B2MDBuffer {
/// Start processing some bytes if possible, if we receive a returned buffer (through `.available(ByteBuffer)`)
/// we _must_ indicate the processing has finished by calling `finishProcessing`.
mutating func startProcessing(allowEmptyBuffer: Bool) -> BufferAvailability {
switch self.state {
case .processingInProgress:
return .bufferAlreadyBeingProcessed
case .ready where self.buffers.count > 0:
var buffer = self.buffers.removeFirst()
buffer.writeBuffers(self.buffers)
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much
if buffer.readableBytes > 0 || allowEmptyBuffer {
self.state = .processingInProgress
return .available(buffer)
} else {
return .nothingAvailable
}
case .ready:
assert(self.buffers.isEmpty)
if allowEmptyBuffer {
self.state = .processingInProgress
return .available(self.emptyByteBuffer)
}
return .nothingAvailable
}
}
mutating func finishProcessing(remainder buffer: inout ByteBuffer) -> Void {
assert(self.state == .processingInProgress)
self.state = .ready
if buffer.readableBytes == 0 && self.buffers.isEmpty {
// fast path, no bytes left and no other buffers, just return
return
}
if buffer.readableBytes > 0 {
self.buffers.prepend(buffer)
} else {
buffer.discardReadBytes()
buffer.writeBuffers(self.buffers)
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much
self.buffers.append(buffer)
}
}
mutating func append(buffer: ByteBuffer) {
if buffer.readableBytes > 0 {
self.buffers.append(buffer)
}
}
}
// MARK: B2MDBuffer Helpers
private extension ByteBuffer {
mutating func writeBuffers(_ buffers: CircularBuffer<ByteBuffer>) {
guard buffers.count > 0 else {
return
}
var requiredCapacity: Int = self.writerIndex
for buffer in buffers {
requiredCapacity += buffer.readableBytes
}
self.reserveCapacity(requiredCapacity)
for var buffer in buffers {
self.writeBuffer(&buffer)
}
}
}
private extension B2MDBuffer {
func _testOnlyOneBuffer() -> ByteBuffer? {
switch self.buffers.count {
case 0:
return nil
case 1:
return self.buffers.first
default:
let firstIndex = self.buffers.startIndex
var firstBuffer = self.buffers[firstIndex]
for var buffer in self.buffers[self.buffers.index(after: firstIndex)...] {
firstBuffer.writeBuffer(&buffer)
}
return firstBuffer
}
}
}
/// A handler which turns a given `ByteToMessageDecoder` into a `ChannelInboundHandler` that can then be added to a
/// `ChannelPipeline`.
///
/// Most importantly, `ByteToMessageHandler` handles the tricky buffer management for you and flattens out all
/// re-entrancy on `channelRead` that may happen in the `ChannelPipeline`.
public final class ByteToMessageHandler<Decoder: ByteToMessageDecoder> {
public typealias InboundIn = ByteBuffer
public typealias InboundOut = Decoder.InboundOut
private enum DecodeMode {
/// This is a usual decode, ie. not the last chunk
case normal
/// Last chunk
case last
}
private enum RemovalState {
/// Not added to any `ChannelPipeline` yet.
case notAddedToPipeline
/// No one tried to remove this handler.
case notBeingRemoved
/// The user-triggered removal has been started but isn't complete yet. This state will not be entered if the
/// removal is triggered by Channel teardown.
case removalStarted
/// The user-triggered removal is complete. This state will not be entered if the removal is triggered by
/// Channel teardown.
case removalCompleted
/// This handler has been removed from the pipeline.
case handlerRemovedCalled
}
private enum State {
case active
case leftoversNeedProcessing
case done
case error(Error)
var isError: Bool {
switch self {
case .active, .leftoversNeedProcessing, .done:
return false
case .error:
return true
}
}
var isFinalState: Bool {
switch self {
case .active, .leftoversNeedProcessing:
return false
case .done, .error:
return true
}
}
var isActive: Bool {
switch self {
case .done, .error, .leftoversNeedProcessing:
return false
case .active:
return true
}
}
var isLeftoversNeedProcessing: Bool {
switch self {
case .done, .error, .active:
return false
case .leftoversNeedProcessing:
return true
}
}
}
internal private(set) var decoder: Decoder? // only `nil` if we're already decoding (ie. we're re-entered)
private let maximumBufferSize: Int?
private var queuedWrites = CircularBuffer<NIOAny>(initialCapacity: 1) // queues writes received whilst we're already decoding (re-entrant write)
private var state: State = .active {
willSet {
assert(!self.state.isFinalState, "illegal state on state set: \(self.state)") // we can never leave final states
}
}
private var removalState: RemovalState = .notAddedToPipeline
// sadly to construct a B2MDBuffer we need an empty ByteBuffer which we can only get from the allocator, so IUO.
private var buffer: B2MDBuffer!
private var seenEOF: Bool = false
private var selfAsCanDequeueWrites: CanDequeueWrites? = nil
/// @see: ByteToMessageHandler.init(_:maximumBufferSize)
public convenience init(_ decoder: Decoder) {
self.init(decoder, maximumBufferSize: nil)
}
/// Initialize a `ByteToMessageHandler`.
///
/// - parameters:
/// - decoder: The `ByteToMessageDecoder` to decode the bytes into message.
/// - maximumBufferSize: The maximum number of bytes to aggregate in-memory.
public init(_ decoder: Decoder, maximumBufferSize: Int? = nil) {
self.decoder = decoder
self.maximumBufferSize = maximumBufferSize
}
deinit {
if self.removalState != .notAddedToPipeline {
// we have been added to the pipeline, if not, we don't need to check our state.
assert(self.removalState == .handlerRemovedCalled,
"illegal state in deinit: removalState = \(self.removalState)")
assert(self.state.isFinalState, "illegal state in deinit: state = \(self.state)")
}
}
}
// MARK: ByteToMessageHandler: Test Helpers
extension ByteToMessageHandler {
internal var cumulationBuffer: ByteBuffer? {
return self.buffer._testOnlyOneBuffer()
}
}
private protocol CanDequeueWrites {
func dequeueWrites()
}
extension ByteToMessageHandler: CanDequeueWrites where Decoder: WriteObservingByteToMessageDecoder {
fileprivate func dequeueWrites() {
while self.queuedWrites.count > 0 {
// self.decoder can't be `nil`, this is only allowed to be called when we're not already on the stack
self.decoder!.write(data: self.unwrapOutboundIn(self.queuedWrites.removeFirst()))
}
}
}
// MARK: ByteToMessageHandler's Main API
extension ByteToMessageHandler {
@inline(__always) // allocations otherwise (reconsider with Swift 5.1)
private func withNextBuffer(allowEmptyBuffer: Bool, _ body: (inout Decoder, inout ByteBuffer) throws -> DecodingState) rethrows -> B2MDBuffer.BufferProcessingResult {
switch self.buffer.startProcessing(allowEmptyBuffer: allowEmptyBuffer) {
case .bufferAlreadyBeingProcessed:
return .cannotProcessReentrantly
case .nothingAvailable:
return .didProcess(.needMoreData)
case .available(var buffer):
var possiblyReclaimBytes = false
var decoder: Decoder? = nil
swap(&decoder, &self.decoder)
assert(decoder != nil) // self.decoder only `nil` if we're being re-entered, but .available means we're not
defer {
swap(&decoder, &self.decoder)
if buffer.readableBytes > 0 && possiblyReclaimBytes {
// we asserted above that the decoder we just swapped back in was non-nil so now `self.decoder` must
// be non-nil.
if self.decoder!.shouldReclaimBytes(buffer: buffer) {
buffer.discardReadBytes()
}
}
self.buffer.finishProcessing(remainder: &buffer)
}
let decodeResult = try body(&decoder!, &buffer)
// If we .continue, there's no point in trying to reclaim bytes because we'll loop again. If we need more
// data on the other hand, we should try to reclaim some of those bytes.
possiblyReclaimBytes = decodeResult == .needMoreData
return .didProcess(decodeResult)
}
}
private func processLeftovers(context: ChannelHandlerContext) {
guard self.state.isActive else {
// we are processing or have already processed the leftovers
return
}
do {
switch try self.decodeLoop(context: context, decodeMode: .last) {
case .didProcess:
self.state = .done
case .cannotProcessReentrantly:
self.state = .leftoversNeedProcessing
}
} catch {
self.state = .error(error)
context.fireErrorCaught(error)
}
}
private func tryDecodeWrites() {
if self.queuedWrites.count > 0 {
// this must succeed because unless we implement `CanDequeueWrites`, `queuedWrites` must always be empty.
self.selfAsCanDequeueWrites!.dequeueWrites()
}
}
private func decodeLoop(context: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult {
assert(!self.state.isError)
var allowEmptyBuffer = decodeMode == .last
while (self.state.isActive && self.removalState == .notBeingRemoved) || decodeMode == .last {
let result = try self.withNextBuffer(allowEmptyBuffer: allowEmptyBuffer) { decoder, buffer in
let decoderResult: DecodingState
if decodeMode == .normal {
assert(self.state.isActive, "illegal state for normal decode: \(self.state)")
decoderResult = try decoder.decode(context: context, buffer: &buffer)
} else {
allowEmptyBuffer = false
decoderResult = try decoder.decodeLast(context: context, buffer: &buffer, seenEOF: self.seenEOF)
}
if decoderResult == .needMoreData, let maximumBufferSize = self.maximumBufferSize, buffer.readableBytes > maximumBufferSize {
throw ByteToMessageDecoderError.PayloadTooLargeError()
}
return decoderResult
}
switch result {
case .didProcess(.continue):
self.tryDecodeWrites()
continue
case .didProcess(.needMoreData):
if self.queuedWrites.count > 0 {
self.tryDecodeWrites()
continue // we might have received more, so let's spin once more
} else {
return .didProcess(.needMoreData)
}
case .cannotProcessReentrantly:
return .cannotProcessReentrantly
}
}
return .didProcess(.continue)
}
}
// MARK: ByteToMessageHandler: ChannelInboundHandler
extension ByteToMessageHandler: ChannelInboundHandler {
public func handlerAdded(context: ChannelHandlerContext) {
guard self.removalState == .notAddedToPipeline else {
preconditionFailure("\(self) got readded to a ChannelPipeline but ByteToMessageHandler is single-use")
}
self.removalState = .notBeingRemoved
self.buffer = B2MDBuffer(emptyByteBuffer: context.channel.allocator.buffer(capacity: 0))
// here we can force it because we know that the decoder isn't in use if we're just adding this handler
self.selfAsCanDequeueWrites = self as? CanDequeueWrites // we need to cache this as it allocates.
self.decoder!.decoderAdded(context: context)
}
public func handlerRemoved(context: ChannelHandlerContext) {
// very likely, the removal state is `.notBeingRemoved` or `.removalCompleted` here but we can't assert it
// because the pipeline might be torn down during the formal removal process.
self.removalState = .handlerRemovedCalled
if !self.state.isFinalState {
self.state = .done
}
self.selfAsCanDequeueWrites = nil
// here we can force it because we know that the decoder isn't in use because the removal is always
// eventLoop.execute'd
self.decoder!.decoderRemoved(context: context)
}
/// Calls `decode` until there is nothing left to decode.
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let buffer = self.unwrapInboundIn(data)
if case .error(let error) = self.state {
context.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer))
return
}
self.buffer.append(buffer: buffer)
do {
switch try self.decodeLoop(context: context, decodeMode: .normal) {
case .didProcess:
switch self.state {
case .active:
() // cool, all normal
case .done, .error:
() // fair, all done already
case .leftoversNeedProcessing:
// seems like we received a `channelInactive` or `handlerRemoved` whilst we were processing a read
switch try self.decodeLoop(context: context, decodeMode: .last) {
case .didProcess:
() // expected and cool
case .cannotProcessReentrantly:
preconditionFailure("bug in NIO: non-reentrant decode loop couldn't run \(self), \(self.state)")
}
self.state = .done
}
case .cannotProcessReentrantly:
// fine, will be done later
()
}
} catch {
self.state = .error(error)
context.fireErrorCaught(error)
}
}
/// Call `decodeLast` before forward the event through the pipeline.
public func channelInactive(context: ChannelHandlerContext) {
self.seenEOF = true
self.processLeftovers(context: context)
context.fireChannelInactive()
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event as? ChannelEvent == .some(.inputClosed) {
self.seenEOF = true
self.processLeftovers(context: context)
}
context.fireUserInboundEventTriggered(event)
}
}
extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler where Decoder: WriteObservingByteToMessageDecoder {
public typealias OutboundIn = Decoder.OutboundIn
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
if self.decoder != nil {
let data = self.unwrapOutboundIn(data)
assert(self.queuedWrites.isEmpty)
self.decoder!.write(data: data)
} else {
self.queuedWrites.append(data)
}
context.write(data, promise: promise)
}
}
/// A protocol for straightforward encoders which encode custom messages to `ByteBuffer`s.
/// To add a `MessageToByteEncoder` to a `ChannelPipeline`, use
/// `channel.pipeline.addHandler(MessageToByteHandler(myEncoder)`.
public protocol MessageToByteEncoder {
associatedtype OutboundIn
/// Called once there is data to encode.
///
/// - parameters:
/// - data: The data to encode into a `ByteBuffer`.
/// - out: The `ByteBuffer` into which we want to encode.
func encode(data: OutboundIn, out: inout ByteBuffer) throws
}
extension ByteToMessageHandler: RemovableChannelHandler {
public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {
precondition(self.removalState == .notBeingRemoved)
self.removalState = .removalStarted
context.eventLoop.execute {
self.processLeftovers(context: context)
assert(!self.state.isLeftoversNeedProcessing, "illegal state: \(self.state)")
switch self.removalState {
case .removalStarted:
self.removalState = .removalCompleted
case .handlerRemovedCalled:
// if we're here, then the channel has also been torn down between the start and the completion of
// the user-triggered removal. That's okay.
()
default:
assertionFailure("illegal removal state: \(self.removalState)")
}
// this is necessary as it'll complete the promise.
context.leavePipeline(removalToken: removalToken)
}
}
}
/// A handler which turns a given `MessageToByteEncoder` into a `ChannelOutboundHandler` that can then be added to a
/// `ChannelPipeline`.
public final class MessageToByteHandler<Encoder: MessageToByteEncoder>: ChannelOutboundHandler {
public typealias OutboundOut = ByteBuffer
public typealias OutboundIn = Encoder.OutboundIn
private enum State {
case notInChannelYet
case operational
case error(Error)
case done
var readyToBeAddedToChannel: Bool {
switch self {
case .notInChannelYet:
return true
case .operational, .error, .done:
return false
}
}
}
private var state: State = .notInChannelYet
private let encoder: Encoder
private var buffer: ByteBuffer? = nil
public init(_ encoder: Encoder) {
self.encoder = encoder
}
}
extension MessageToByteHandler {
public func handlerAdded(context: ChannelHandlerContext) {
precondition(self.state.readyToBeAddedToChannel,
"illegal state when adding to Channel: \(self.state)")
self.state = .operational
self.buffer = context.channel.allocator.buffer(capacity: 256)
}
public func handlerRemoved(context: ChannelHandlerContext) {
self.state = .done
self.buffer = nil
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.state {
case .notInChannelYet:
preconditionFailure("MessageToByteHandler.write called before it was added to a Channel")
case .error(let error):
promise?.fail(error)
context.fireErrorCaught(error)
return
case .done:
// let's just ignore this
return
case .operational:
// there's actually some work to do here
break
}
let data = self.unwrapOutboundIn(data)
do {
self.buffer!.clear()
try self.encoder.encode(data: data, out: &self.buffer!)
context.write(self.wrapOutboundOut(self.buffer!), promise: promise)
} catch {
self.state = .error(error)
promise?.fail(error)
context.fireErrorCaught(error)
}
}
}
| 44.134402 | 170 | 0.661023 |
33e5a1692d347117818bc9126a8cb52ce4eecd26 | 654 | //
// DTSArchiveResponseModel.swift
// TTBaseModel
//
// Created by Burhan on 15.10.2020.
// Copyright © 2020 Turkish Technic. All rights reserved.
//
import Foundation
import ObjectMapper
public class DTSArchiveResponseModel: Mappable {
// MARK: Properties
public var workOrders: [WoItem]?
public required init() {
}
public required init(map: Map) {
}
// MARK: Mapping
public func mapping(map: Map) {
self.workOrders <- map[SerializationKeys.workOrders]
}
}
extension DTSArchiveResponseModel {
private struct SerializationKeys {
static let workOrders = "workOrders"
}
}
| 19.235294 | 60 | 0.663609 |
c18a98cfbe537884612e15a9b66fb97c4a56e92b | 3,733 | //
// ZapTests
//
// Created by Otto Suess on 30.03.18.
// Copyright © 2018 Otto Suess. All rights reserved.
//
@testable import Library
import SwiftBTC
import XCTest
final class InputNumberFormatterTests: XCTestCase {
// swiftlint:disable:next function_body_length
func testInputs() {
let fiat = FiatCurrency(currencyCode: "USD", symbol: "$", localized: "$", exchangeRate: 1)
let data: [(String, Currency, String?)] = [
("1", Bitcoin(unit: .satoshi), "1"),
("1.", Bitcoin(unit: .satoshi), nil),
("1.0", Bitcoin(unit: .satoshi), nil),
("23456", Bitcoin(unit: .satoshi), "23,456"),
("", Bitcoin(unit: .bit), ""),
("100", Bitcoin(unit: .bit), "100"),
("100.00", Bitcoin(unit: .bit), "100.00"),
("1000", Bitcoin(unit: .bit), "1,000"),
(".7777", Bitcoin(unit: .bit), nil),
("100.000", Bitcoin(unit: .bit), nil),
("100.0000000", Bitcoin(unit: .bit), nil),
("10000.", Bitcoin(unit: .bit), "10,000."),
("10000..", Bitcoin(unit: .bit), nil),
("8888.8", Bitcoin(unit: .bit), "8,888.8"),
("100000000", Bitcoin(unit: .bit), "100,000,000"),
("100.000", Bitcoin(unit: .milliBitcoin), "100.000"),
("100.00000", Bitcoin(unit: .milliBitcoin), "100.00000"),
("100.00001", Bitcoin(unit: .milliBitcoin), "100.00001"),
("100.000000", Bitcoin(unit: .milliBitcoin), nil),
("1000.00000", Bitcoin(unit: .milliBitcoin), "1,000.00000"),
("00", Bitcoin(unit: .bitcoin), nil),
(".", Bitcoin(unit: .bitcoin), "0."),
("20567890", Bitcoin(unit: .bitcoin), "20,567,890"),
("20567890.12345678", Bitcoin(unit: .bitcoin), "20,567,890.12345678"),
("20567890.123456780", Bitcoin(unit: .bitcoin), nil),
("", fiat, ""),
("100", fiat, "100"),
("100.00", fiat, "100.00"),
("1000", fiat, "1,000"),
(".7777", fiat, nil),
("100.000", fiat, nil),
("100.0000000", fiat, nil),
("10000.", fiat, "10,000."),
("10000..", fiat, nil),
("8888.8", fiat, "8,888.8"),
("100000000", fiat, "100,000,000"),
(".0", Bitcoin(unit: .bitcoin), "0.0"),
(".00", Bitcoin(unit: .bitcoin), "0.00"),
(".000", Bitcoin(unit: .bitcoin), "0.000"),
(".0000", Bitcoin(unit: .bitcoin), "0.0000"),
(".00001", Bitcoin(unit: .bitcoin), "0.00001"),
(".00010000", Bitcoin(unit: .bitcoin), "0.00010000"),
(".00000000", Bitcoin(unit: .bitcoin), "0.00000000"),
(".00000001", Bitcoin(unit: .bitcoin), "0.00000001"),
(".000000001", Bitcoin(unit: .bitcoin), nil),
(".0000", Bitcoin(unit: .milliBitcoin), "0.0000"),
(".00001", Bitcoin(unit: .milliBitcoin), "0.00001"),
(".000001", Bitcoin(unit: .milliBitcoin), nil),
(".00", Bitcoin(unit: .bit), "0.00"),
(".01", Bitcoin(unit: .bit), "0.01"),
(".001", Bitcoin(unit: .bit), nil),
(".", Bitcoin(unit: .satoshi), nil),
(".0", Bitcoin(unit: .satoshi), nil),
(".0", fiat, "0.0"),
(".00", fiat, "0.00"),
(".000", fiat, nil),
(".0000", fiat, nil),
(".00001", fiat, nil)
]
for (input, currency, output) in data {
let formatter = InputNumberFormatter(currency: currency)
XCTAssertEqual(formatter.validate(input), output, "(\(input), \(currency) = \(String(describing: output)))")
}
}
}
| 44.440476 | 120 | 0.485133 |
62b88ff4acdb6a0f925fd36f459bc65d750774f8 | 1,221 | //
// Property.swift
// Practical
//
// Created by Peter Lafferty on 16/02/2016.
// Copyright © 2016 Peter Lafferty. All rights reserved.
//
import Foundation
import Decodable
public struct Property {
public let name:String
public let id:String
public let price:String?
public let currency:String?
public let rating: Int?
public let type:String
public let image:[Image]
public let descriptionByProperty:String?
public let descriptionByEditor:String?
}
extension Property: Decodable {
public static func decode(_ j: Any) throws -> Property {
var rating:Int? = try? j => "overallRating" => "overall"
if rating == nil {
rating = try? j => "rating" => "overall" as Int
}
return try Property(
name: j => "name",
id: j => "id",
price: try? j => "lowestPricePerNight" => "value",
currency: try? j => "lowestPricePerNight" => "currency",
rating: rating,
type: j => "type",
image: j => "images",
descriptionByProperty: try? j => "description",
descriptionByEditor: try? j => "hostelworldSays"
)
}
}
| 25.978723 | 68 | 0.577396 |
dedc79b76afd6fc951eea3135a98c2e482177ada | 841 | //
// Application+Routes.swift
// Vaporizer
//
// Created by Christopher Reitz on 29.08.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import Vapor
import Auth
import Routing
import HTTP
extension Application {
public func publicRoutes(_ drop: Droplet) {
let indexController = IndexController(droplet: drop)
let userController = UserController(droplet: drop)
drop.get("/", handler: indexController.index)
drop.get("/health", handler: indexController.health)
drop.post("/register", handler: userController.store)
}
public func protectedRoutes(_ drop: Droplet, protectedGroup: RouteGroup<Responder, Droplet>) {
protectedGroup.resource("users", UserController(droplet: drop))
protectedGroup.resource("forms", FormController(droplet: drop))
}
}
| 29 | 98 | 0.703924 |
69f01d5f1251043f14a86a73416109eccf62883b | 968 | //
// ObjectOperation.swift
// Gloden Palace Casino
//
// Created by albutt on 2018/12/26.
// Copyright © 2018 海创中盈. All rights reserved.
//
import Foundation
/// 对象类型
class ObjectOperation<R: BackendAPIRequest, O: Codable>: BaseOperation<R, O> {
var success: ((O) -> Void)?
var failure: ((Int?, String?, Error?) -> Void)?
var exception: ((NSError) -> Void)?
override func handleSuccess(item: ResponseItem<O>) {
super.handleSuccess(item: item)
if let resp = item.resp {
success?(resp)
} else {
failure?(item.code, item.msg, BackendError.emptyResponse)
}
}
override func handleFailure(code: Int?, msg: String?, error: Error?) {
super.handleFailure(code: code, msg: msg, error: error)
failure?(code, msg, error)
}
override func handleException(error: NSError) {
super.handleException(error: error)
exception?(error)
}
}
| 26.162162 | 78 | 0.605372 |
71fdbbf77db32c85df9e977f7f7296d909dd777b | 1,928 | //
// CalloutButtonArea.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-09-30.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This view is the part of the callout that covers the button
that was tapped or pressed to trigger the callout.
*/
public struct CalloutButtonArea: View {
/**
Create an autocomplete toolbar item style.
- Parameters:
- frame: The button area frame.
- style: The style to use, by default `.standard`.
*/
public init(
frame: CGRect,
style: CalloutStyle = .standard) {
self.frame = frame
self.style = style
}
private let frame: CGRect
private let style: CalloutStyle
public var body: some View {
HStack(alignment: .top, spacing: 0) {
calloutCurve.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
buttonBody
calloutCurve
}
}
}
private extension CalloutButtonArea {
var backgroundColor: Color { style.backgroundColor }
var cornerRadius: CGFloat { style.buttonCornerRadius }
var curveSize: CGSize { style.curveSize }
}
private extension CalloutButtonArea {
var buttonBody: some View {
CustomRoundedRectangle(bottomLeft: cornerRadius, bottomRight: cornerRadius)
.foregroundColor(backgroundColor)
.frame(frame.size)
}
var calloutCurve: some View {
CalloutCurve()
.frame(width: curveSize.width, height: curveSize.height)
.foregroundColor(backgroundColor)
}
}
struct CalloutButtonArea_Previews: PreviewProvider {
static var previews: some View {
CalloutButtonArea(
frame: CGRect(x: 0, y: 0, width: 50, height: 50),
style: .standard)
.padding(30)
.background(Color.gray)
.cornerRadius(20)
}
}
| 24.717949 | 83 | 0.614108 |
e4319228dd8e14dc8404ed3a7e850ea2a9c1c1a3 | 19,874 | //
// LineLexer.swift
// Apodimark
//
/*
HOW TO READ THE COMMENTS:
Example:
Lorem Ipsum blah blah
|_<---
Means that scanner points to “s”
Therefore:
- “p” has already been read
- scanner.startIndex is the index of “s”
- the next scanner.peek() will return “s”
*/
/// Error type used for parsing a List line
fileprivate enum ListParsingError: Error {
case notAListMarker
case emptyListItem(ListKind)
}
extension MarkdownParser {
/// Advances the scanner to the end of the valid marker, or throws an error and leaves the scanner intact
/// if the list marker is invalid.
/// - parameter scanner: a scanner whose `startIndex` points to the first token of the list marker
/// (e.g. a hyphen, an asterisk, a digit)
/// - throws: `ListParsingError.notAListMarker` if the list marker is invalid
/// - returns: the kind of the list marker
fileprivate static func readListMarker(_ scanner: inout Scanner<View>) throws -> ListKind {
guard case let firstToken? = scanner.pop() else {
preconditionFailure()
}
var value: Int
switch firstToken {
case Codec.hyphen : return .bullet(.hyphen)
case Codec.asterisk : return .bullet(.star)
case Codec.plus : return .bullet(.plus)
case Codec.zero...Codec.nine: value = Codec.digit(representedByToken: firstToken)
case _ : preconditionFailure()
}
// 1234)
// |_<---
var length = 1
try scanner.popWhile { token in
guard case let token? = token, token != Codec.linefeed else {
throw ListParsingError.notAListMarker // e.g. 1234 followed by end of line / end of string
}
switch token {
case Codec.fullstop, Codec.rightparen:
return .stop // e.g. 1234|)| -> hurray! confirm and stop now
case Codec.zero...Codec.nine:
guard length < 9 else {
throw ListParsingError.notAListMarker // e.g. 123456789|0| -> too long
}
length += 1
value = value * 10 + Codec.digit(representedByToken: token)
return .pop // e.g. 12|3| -> ok, keep reading
case _:
throw ListParsingError.notAListMarker // e.g. 12|a| -> not a list marker
}
}
// will not crash because popWhile threw an error if lastToken is not fullstop or rightparen
let lastToken = scanner.pop()!
switch lastToken {
case Codec.fullstop : return .number(.dot, value)
case Codec.rightparen: return .number(.parenthesis, value)
default : fatalError()
}
}
/// Tries to parse a List. Advances the scanner to the end of the line and return the parsed line.
/// - parameter scanner: a scanner whose `startIndex` points to the start of potential List line
/// - parameter indent: the indent of the line being parsed
/// - return: the parsed Line
fileprivate static func parseList(_ scanner: inout Scanner<View>, indent: Indent, context: LineLexerContext<Codec>) -> Line {
let indexBeforeList = scanner.startIndex
// let initialSubView = scanner
// 1234)
// |_<---
do {
let kind = try MarkdownParser.readListMarker(&scanner)
// 1234)
// |_<---
guard case let token? = scanner.pop(ifNot: Codec.linefeed) else {
throw ListParsingError.emptyListItem(kind)
}
guard token == Codec.space else {
throw ListParsingError.notAListMarker
}
// 1234)
// |_<---
let rest = parseLine(&scanner, context: context)
return Line(.list(kind, rest), indent, indexBeforeList ..< scanner.startIndex)
}
catch ListParsingError.notAListMarker {
// xxxxx…
// |_<--- scanner could point anywhere but not past the end of the line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeList ..< scanner.startIndex)
}
catch ListParsingError.emptyListItem(let kind) {
// 1234)\n
// |__<---
let finalIndices = indexBeforeList ..< scanner.startIndex
let rest = Line(.empty, indent, finalIndices)
return Line(.list(kind, rest), indent, finalIndices)
}
catch {
fatalError()
}
}
}
/// State used for read the content of a Header line
fileprivate enum HeaderTextReadingState { // e.g. for # Hello World #### \n
case text // # He|_
case textSpaces // # Hello |_
case hashes // # Hello World #|_
case endSpaces // # Hello World #### |_
}
extension MarkdownParser {
/// Reads the content of a Header line
/// - parameter scanner: a scanner whose `startIndex` points to to the start of the text in a Header line
/// - returns: the index pointing to the end of the text in the header
fileprivate static func readHeaderText(_ scanner: inout Scanner<View>) -> View.Index {
var state = HeaderTextReadingState.textSpaces
var end = scanner.startIndex
while case let token? = scanner.pop(ifNot: Codec.linefeed) {
switch state {
case .text:
if token == Codec.space { state = .textSpaces }
else { end = scanner.startIndex }
case .textSpaces:
if token == Codec.space { break }
else if token == Codec.hash { state = .hashes }
else { (state, end) = (.text, scanner.startIndex) }
case .hashes:
if token == Codec.hash { state = .hashes }
else if token == Codec.space { state = .endSpaces }
else { (state, end) = (.text, scanner.startIndex) }
case .endSpaces:
if token == Codec.space { break }
else if token == Codec.hash { (state, end) = (.hashes, scanner.data.index(before: scanner.startIndex)) }
else { (state, end) = (.text, scanner.startIndex) }
}
}
return end
}
}
/// Error type used for parsing a header line
fileprivate enum HeaderParsingError: Error {
case notAHeader
case emptyHeader(Int32)
}
extension MarkdownParser {
/// Tries to parse a Header. Advances the scanner to the end of the line.
/// - parameter scanner: a scanner whose `startIndex` points the start of a potential Header line
/// - parameter indent: the indent of the line being parsed
/// - return: the parsed Line
fileprivate static func parseHeader(_ scanner: inout Scanner<View>, indent: Indent) -> Line {
let indexBeforeHeader = scanner.startIndex
// xxxxxx
// |_<--- (start of line)
do {
var level: Int32 = 0
try scanner.popWhile { token in
guard case let token? = token else {
throw HeaderParsingError.emptyHeader(level)
}
switch token {
case Codec.hash where level < 6:
level = level + 1
return .pop
case Codec.space:
return .stop
case Codec.linefeed:
throw HeaderParsingError.emptyHeader(level)
default:
throw HeaderParsingError.notAHeader
}
}
// ## Hello
// |_<---
scanner.popWhile(Codec.space)
// ## Hello
// |_<---
let start = scanner.startIndex
let end = readHeaderText(&scanner)
// ## Hello World ####\n
// | | |__<---
// |_ |_
// start end
let headerkind = LineKind.header(start ..< end, level)
return Line(headerkind, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch HeaderParsingError.notAHeader {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch HeaderParsingError.emptyHeader(let level) {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
let lineKind = LineKind.header(scanner.startIndex ..< scanner.startIndex, level)
return Line(lineKind, indent, indexBeforeHeader ..< scanner.startIndex)
}
catch {
fatalError()
}
}
}
/// Error type used for a parsing a Fence
fileprivate enum FenceParsingError: Error {
case notAFence
case emptyFence(FenceKind, Int32)
}
extension MarkdownParser {
/// Tries to read the name of Fence line.
///
/// Advances the scanner to the end of the line if it succeeded, throws an error otherwise.
///
/// - parameter scanner: a scanner pointing to the first letter of a potential Fence’s name
/// - throws: `FenceParsingError.notAFence` if the line is not a Fence line
/// - returns: the index pointing to the end of the name
fileprivate static func readFenceName(_ scanner: inout Scanner<View>) throws -> View.Index {
// ``` name
// |_<---
var end = scanner.startIndex
while case let token? = scanner.pop(ifNot: Codec.linefeed) {
switch token {
case Codec.space:
break
case Codec.backtick:
throw FenceParsingError.notAFence
case _:
end = scanner.startIndex
}
}
// ``` name \n
// |_ |__<---
// end
return end
}
}
extension MarkdownParser {
/// Tries to parse a Fence line.
///
/// Advances the scanner to the end of the line.
///
/// - parameter scanner: a scanner whose pointing to the start of what might be a Fence line
/// - parameter indent: the indent of the line being parsed
/// - returns: the parsed line
fileprivate static func parseFence(_ scanner: inout Scanner<View>, indent: Indent) -> Line {
let indexBeforeFence = scanner.startIndex
guard let firstLetter = scanner.pop() else { preconditionFailure() }
let kind: FenceKind = firstLetter == Codec.backtick ? .backtick : .tilde
// ``` name
// |_<---
do {
var level: Int32 = 1
try scanner.popWhile { token in
guard case let token? = token else {
throw FenceParsingError.emptyFence(kind, level)
}
switch token {
case firstLetter:
level = level + 1
return .pop
case Codec.linefeed:
guard level >= 3 else {
throw FenceParsingError.notAFence
}
throw FenceParsingError.emptyFence(kind, level)
case _:
guard level >= 3 else {
throw FenceParsingError.notAFence
}
return .stop
}
}
// ``` name
// |_<---
scanner.popWhile(Codec.space)
// ``` name
// |_<---
let start = scanner.startIndex
let end = try readFenceName(&scanner)
// ``` name \n
// | | |__<---
// |_ |_
// start end
let linekind = LineKind.fence(kind, start ..< end, level)
return Line(linekind, indent, indexBeforeFence ..< scanner.startIndex)
}
catch FenceParsingError.notAFence {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexBeforeFence ..< scanner.startIndex)
}
catch FenceParsingError.emptyFence(let kind, let level) {
// scanner could point anywhere but not past end of line
scanner.popUntil(Codec.linefeed)
let linekind = LineKind.fence(kind, scanner.startIndex ..< scanner.startIndex, level)
return Line(linekind, indent, indexBeforeFence ..< scanner.startIndex)
}
catch {
fatalError()
}
}
}
/// Error type used for parsing a ThematicBreak line
fileprivate struct NotAThematicBreakError: Error {}
extension MarkdownParser {
/// Tries to read a ThematicBreak line.
///
/// Advances the scanner to the end of the line if it succeeded, throws an error otherwise.
///
/// - precondition: `firstToken == scanner.pop()`
///
/// (not checked at runtime)
///
/// - parameter scanner: a scanner pointing to the start of what might be a ThematicBreak line
/// - parameter firstToken: the first token of the potential ThematicBreak line
/// - throws: `NotAThematicBreakError()` if the line is not a ThematicBreak line
fileprivate static func readThematicBreak(_ scanner: inout Scanner<View>, firstToken: Codec.CodeUnit) throws {
// * * *
// |_<--- (start of line)
var level = 0
try scanner.popWhile { token in
guard case let token? = token, token != Codec.linefeed else {
guard level >= 3 else {
throw NotAThematicBreakError() // e.g. * * -> not enough stars -> not a thematic break
}
return .stop // e.g. * * * * -> hurray! confirm and stop now
}
switch token {
case firstToken: // e.g. * * |*| -> ok, keep reading
level += 1
return .pop
case Codec.space, Codec.tab: // e.g. * * | | -> ok, keep reading
return .pop
default:
throw NotAThematicBreakError() // e.g. * * |g| -> not a thematic break!
}
}
}
}
/// Error type used when parsing a ReferenceDefinition line
fileprivate struct NotAReferenceDefinitionError: Error {}
extension MarkdownParser {
/// Tries to parse a ReferenceDefinition line.
///
/// Advances the scanner to the end of line if it succeeded, throws an error otherwise.
///
/// - parameter scanner: a scanner pointing to the first token of what might be a ReferenceDefinition line
/// - parameter indent: the indent of the line being parsed
/// - throws: `NotAReferenceDefinitionError()` if the line is not a ReferenceDefinition line
/// - returns: the parsed line
fileprivate static func parseReferenceDefinition(_ scanner: inout Scanner<View>, indent: Indent) throws -> Line {
// [hello]: world
// |_<---
let indexBeforeRefDef = scanner.startIndex
_ = scanner.pop()
// [hello]: world
// |_<---
let idxBeforeTitle = scanner.startIndex
var escapeNext = false
try scanner.popWhile { (token: Codec.CodeUnit?) throws -> PopOrStop in
guard case let token? = token, token != Codec.linefeed else {
throw NotAReferenceDefinitionError()
}
guard !escapeNext else {
escapeNext = false
return .pop
}
guard token != Codec.leftsqbck else {
throw NotAReferenceDefinitionError()
}
guard token != Codec.rightsqbck else {
return .stop
}
escapeNext = (token == Codec.backslash)
return .pop
}
let idxAfterTitle = scanner.startIndex
guard idxAfterTitle > scanner.data.index(after: idxBeforeTitle) else {
throw NotAReferenceDefinitionError()
}
_ = scanner.pop(Codec.rightsqbck)
// [hello]: world
// |_<---
guard scanner.pop(Codec.colon) else { throw NotAReferenceDefinitionError() }
scanner.popWhile(Codec.space)
let idxBeforeDefinition = scanner.startIndex
// [hello]: world
// |_<---
scanner.popUntil(Codec.linefeed)
let idxAfterDefinition = scanner.startIndex
guard idxBeforeDefinition < idxAfterDefinition else {
throw NotAReferenceDefinitionError()
}
let definition = idxBeforeDefinition ..< idxAfterDefinition
let title = idxBeforeTitle ..< idxAfterTitle
return Line(.reference(title, definition), indent, indexBeforeRefDef ..< scanner.startIndex)
}
}
struct LineLexerContext <C: MarkdownParserCodec> {
var listKindBeingRead: C.CodeUnit?
static var `default`: LineLexerContext {
return .init(listKindBeingRead: nil)
}
}
extension MarkdownParser {
static func parseLine(_ scanner: inout Scanner<View>, context: LineLexerContext<Codec>) -> Line {
// xxxxx
// |_<--- (start of line)
var indent = Indent()
scanner.popWhile { (token: Codec.CodeUnit?) -> PopOrStop in
guard case let token? = token else {
return .stop
}
guard case let indentKind? = IndentKind(token, codec: Codec.self) else {
return .stop
}
indent.add(indentKind)
return .pop
}
let indexAfterIndent = scanner.startIndex
// xxxx
// |_<--- (after indent)
guard case let firstToken? = scanner.peek() else {
return Line(.empty, Indent(), scanner.indices)
}
switch firstToken {
case Codec.quote:
_ = scanner.pop()!
let rest = parseLine(&scanner, context: .default)
return Line(.quote(rest), indent, indexAfterIndent ..< scanner.startIndex)
case Codec.underscore:
guard case .some = try? readThematicBreak(&scanner, firstToken: firstToken) else {
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
return Line(.thematicBreak, indent, indexAfterIndent ..< scanner.startIndex)
case Codec.hyphen, Codec.asterisk:
if firstToken != context.listKindBeingRead, case .some = try? readThematicBreak(&scanner, firstToken: firstToken) {
return Line(.thematicBreak, indent, indexAfterIndent ..< scanner.startIndex)
} else {
var context = context
context.listKindBeingRead = firstToken
return parseList(&scanner, indent: indent, context: context)
}
case Codec.plus, Codec.zero...Codec.nine:
return parseList(&scanner, indent: indent, context: context)
case Codec.hash:
return parseHeader(&scanner, indent: indent)
case Codec.linefeed:
return Line(.empty, indent, indexAfterIndent ..< scanner.startIndex)
case Codec.backtick, Codec.tilde:
return parseFence(&scanner, indent: indent)
case Codec.leftsqbck:
guard case let line? = try? parseReferenceDefinition(&scanner, indent: indent) else {
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
return line
case _:
scanner.popUntil(Codec.linefeed)
return Line(.text, indent, indexAfterIndent ..< scanner.startIndex)
}
}
}
| 33.514334 | 129 | 0.563198 |
23bbeac4ee06899fe4956f6f78926bd34138390e | 4,266 | //
// DECryptoError.swift
// DialExt
//
// Created by Aleksei Gordeev on 20/06/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
public enum DECryptoError: LocalizedError {
case failToInitializeSodium
case failToGenerateRandomData
case failToGenerateKeyPair
case failToGenerateSharedSecret
case noNonceStored
case wrongNonce
case nonceAlreadyUsedBefore
case failToProcessNonceList
case failToDecodeMessage
case failToStoreNewNonce
case noSharedSecretStored
case noKeychainGroupProvided
case nonceListLimitTooSmall
case stringEncodingFailed
case stringDecodingFailed
public var errorDescription: String? {
return localizedDescription
}
public var localizedDescription: String {
switch self {
case .failToInitializeSodium: return "Sodium failed"
case .failToGenerateRandomData: return "Fail to generate random data"
case .failToGenerateKeyPair: return "Fail to generate key pair"
case .failToGenerateSharedSecret: return "Fail to generate Shared Secret"
case .noNonceStored: return "No stored nonce found"
case .wrongNonce: return "Nonce is wrong"
case .nonceAlreadyUsedBefore: return "Nonce in list of already user nonces"
case .failToProcessNonceList: return "Problems with nonce list processing"
case .failToDecodeMessage: return "Message decoding failed"
case .failToStoreNewNonce: return "Could not store new nonce"
case .noSharedSecretStored: return "No shared secret found"
case .noKeychainGroupProvided: return "No keychain group providen by service subclass"
case .nonceListLimitTooSmall: return "Nonce list limit too small, should be at least '1'"
case .stringDecodingFailed: return "Fail to read string: decoding failed"
case .stringEncodingFailed: return "Fail to write string: encoding failed"
}
}
}
public enum DEEncryptedPushNotificationError: Error {
case noAlertData
case noNonce
case noAlertDataTitle
case noAlertDataBody
case noAlertBadge
case noAlertSound
case invalidLocalizationKey
case mutableContentUnavailable
}
public struct DEDetailedError: LocalizedError {
public let baseError: Error
public let userInfo: UserInfo
public var basicError: BasicError? {
return baseError as? BasicError
}
public init(baseError: Error, info: UserInfo = [:]) {
self.baseError = baseError
self.userInfo = info
}
public init(_ basicError: BasicError, info: UserInfo = [:]) {
self.init(baseError: basicError, info: info)
}
public enum BasicError: Error {
case invalidLocalizationKey
case notificationAlertTitleLocalizationKey
case notificationAlertBodyLocalizationKey
}
public var localizedDescription: String {
return self.baseError.localizedDescription
}
public var errorDescription: String? {
if let localizedError = self.baseError as? LocalizedError {
return localizedError.errorDescription
}
return self.baseError.localizedDescription
}
public static func invalidLocalizationKey(_ key: String?) -> DEDetailedError {
var info: UserInfo = [:]
if let key = key {
info[UserInfoKey.key] = key
}
return self.init(.invalidLocalizationKey, info: info)
}
public static func notificationAlertTitleLocalizationKey(_ key: String?) -> DEDetailedError {
var info: UserInfo = [:]
if let key = key {
info[UserInfoKey.key] = key
}
return self.init(.notificationAlertTitleLocalizationKey, info: info)
}
public static func notificationAlertBodyLocalizationKey(_ key: String?) -> DEDetailedError {
var info: UserInfo = [:]
if let key = key {
info[UserInfoKey.key] = key
}
return self.init(.notificationAlertBodyLocalizationKey, info: info)
}
public typealias UserInfo = [AnyHashable : Any]
public struct UserInfoKey {
public static let key = "im.dialext.de_error.key"
}
}
| 32.075188 | 97 | 0.683544 |
465763e28942a4752ad21c4f4793c7a39e9c364a | 13,934 | //
// IndexExtractable+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/23/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
// MARK: -
// MARK: Value
public extension IndexExtractable {
public func value<V: Value>(for index: Index) throws -> V {
let any = try self.any(for: index)
do {
guard let result = try V.value(from: any) as? V else {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: V.self, actual: any)
}
return result
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value>(for index: Index) -> V? {
return try? self.value(for: index)
}
public func value<V: Value>(for index: Index, or value: V) -> V {
guard let result: V = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Transform Value
public extension IndexExtractable {
public func value<V: Value, T>(for index: Index, with transform:(V) throws -> T) throws -> T {
let rawValue: V = try self.value(for: index)
return try transform(rawValue)
}
public func value<V: Value, T>(for index: Index, with transform:(V?) throws -> T) throws -> T {
let rawValue: V? = self.value(for: index)
return try transform(rawValue)
}
public func value<V: Value, T>(for index: Index, with transform:(V) -> T?) -> T? {
guard let rawValue: V = try? self.value(for: index) else { return nil }
return transform(rawValue)
}
public func value<V: Value, T>(for index: Index, with transform:(V?) -> T?) -> T? {
let rawValue: V? = self.value(for: index)
return transform(rawValue)
}
}
// MARK: -
// MARK: Array of Value's
public extension IndexExtractable {
public func value<V: Value>(for index: Index) throws -> [V] {
let any = try self.any(for: index)
do {
return try Array<V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value>(for index: Index) -> [V]? {
return try? self.value(for: index)
}
public func value<V: Value>(for index: Index, or value: [V]) -> [V] {
guard let result: [V] = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Array of Transformed Value's
public extension IndexExtractable {
public func value<V: Value, T>(for index: Index, with transform:(V) throws -> T) throws -> [T] {
let any = try self.any(for: index)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for index: Index, with transform:(V) throws -> T) -> [T]? {
return try? self.value(for: index, with: transform)
}
public func value<V: Value, T>(for index: Index, with transform:(V?) throws -> T) throws -> [T] {
let any = try self.any(for: index)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for index: Index, with transform:(V?) throws -> T) -> [T]? {
return try? self.value(for: index, with: transform)
}
}
// MARK: -
// MARK: Array of Optional Value's
public extension IndexExtractable {
public func value<V: Value>(for index: Index) throws -> [V?] {
let any = try self.any(for: index)
do {
return try Array<V?>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value>(for index: Index) -> [V?]? {
return try? self.value(for: index)
}
public func value<V: Value>(for index: Index, or value: [V?]) -> [V?] {
guard let result: [V?] = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Array of Transformed Optional Value's
public extension IndexExtractable {
public func value<V: Value, T>(for index: Index, with transform:(V) -> T?) throws -> [T?] {
let any = try self.any(for: index)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for index: Index, with transform:(V) -> T?) -> [T?]? {
return try? self.value(for: index, with: transform)
}
public func value<V: Value, T>(for index: Index, with transform:(V?) -> T?) throws -> [T?] {
let any = try self.any(for: index)
do {
return try Array<V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for index: Index, with transform:(V?) -> T?) -> [T?]? {
return try? self.value(for: index, with: transform)
}
}
// MARK: -
// MARK: Dictionary of Value's
public extension IndexExtractable {
public func value<K, V: Value>(for index: Index) throws -> [K: V] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value>(for index: Index) -> [K: V]? {
return try? self.value(for: index)
}
public func value<K, V: Value>(for index: Index, or value: [K: V]) -> [K: V] {
guard let result: [K: V] = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Dictionary of Transformed Value's
public extension IndexExtractable {
public func value<K, V: Value, T>(for index: Index, with transform:(V) throws -> T) throws -> [K: T] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for index: Index, with transform:(V) throws -> T) -> [K: T]? {
return try? self.value(for: index, with: transform)
}
public func value<K, V: Value, T>(for index: Index, with transform:(V?) throws -> T) throws -> [K: T] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for index: Index, with transform:(V?) throws -> T) -> [K: T]? {
return try? self.value(for: index, with: transform)
}
}
// MARK: -
// MARK: Dictionary of Optional Value's
public extension IndexExtractable {
public func value<K, V: Value>(for index: Index) throws -> [K: V?] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V?>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value>(for index: Index) -> [K: V?]? {
return try? self.value(for: index)
}
public func value<K, V: Value>(for index: Index, or value: [K: V?]) -> [K: V?] {
guard let result: [K: V?] = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Dictionary of Transformed Optional Value's
public extension IndexExtractable {
public func value<K, V: Value, T>(for index: Index, with transform:(V) -> T?) throws -> [K: T?] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for index: Index, with transform:(V) -> T?) -> [K: T?]? {
return try? self.value(for: index)
}
public func value<K, V: Value, T>(for index: Index, with transform:(V?) -> T?) throws -> [K: T?] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for index: Index, with transform:(V?) -> T?) -> [K: T?]? {
return try? self.value(for: index)
}
}
// MARK: -
// MARK: Set of Value's
public extension IndexExtractable {
public func value<V: Value>(for index: Index) throws -> Set<V> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value>(for index: Index) -> Set<V>? {
return try? self.value(for: index)
}
public func value<V: Value>(for index: Index, or value: Set<V>) -> Set<V> {
guard let result: Set<V> = self.value(for: index) else { return value }
return result
}
}
// MARK: -
// MARK: Set of Transformed Value's
public extension IndexExtractable {
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V) throws -> T) throws -> Set<T> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V) throws -> T) -> Set<T>? {
return try? self.value(for: index, with: transform)
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V?) throws -> T) throws -> Set<T> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V?) throws -> T) -> Set<T>? {
return try? self.value(for: index, with: transform)
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V) -> T?) throws -> Set<T> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V) -> T?) -> Set<T>? {
return try? self.value(for: index, with: transform)
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V?) -> T?) throws -> Set<T> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for index: Index, with transform:(V?) -> T?) -> Set<T>? {
return try? self.value(for: index, with: transform)
}
}
| 37.058511 | 115 | 0.604277 |
50482aa4f0c8e7928674de6dfe4570d799b4b422 | 2,352 | // Created for weg-li in 2021.
import Combine
import ComposableArchitecture
import ComposableCoreLocation
import MapKit
@testable import weg_li
import XCTest
class OfficeMapperTests: XCTestCase {
var sut: RegulatoryOfficeMapper!
private var bag = Set<AnyCancellable>()
let districts = DistrictFixtures.districts
override func setUp() {
super.setUp()
sut = .live(districts)
}
func test_officeMappingByPostalCode() {
let address = GeoAddress(
street: "TestStrasse 3",
city: "Berlin",
postalCode: "10629"
)
Effect(sut.mapAddressToDistrict(address))
.upstream
.sink(
receiveCompletion: { completion in
if case .failure = completion {
XCTFail()
}
},
receiveValue: { value in
XCTAssertEqual(value, self.districts[0])
}
)
.store(in: &bag)
}
func test_officeMappingByCityName() {
let address = GeoAddress(
street: "TestStrasse 3",
city: "Berlin",
postalCode: "12345"
)
Effect(sut.mapAddressToDistrict(address))
.upstream
.sink(
receiveCompletion: { completion in
if case .failure = completion {
XCTFail()
}
},
receiveValue: { value in
XCTAssertEqual(value, self.districts[0])
}
)
.store(in: &bag)
}
func test_officeMappingByCityName_shouldFail_whenPostalCodeAndCityName() {
let address = GeoAddress(
street: "TestStrasse 3",
city: "Rendsburg",
postalCode: "00001"
)
Effect(sut.mapAddressToDistrict(address))
.upstream
.sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
XCTAssertEqual(error, .unableToMatchRegularityOffice)
}
},
receiveValue: { value in
XCTFail()
}
)
.store(in: &bag)
}
}
| 27.034483 | 78 | 0.493622 |
5d80499f9f6983da8f13ba518de3e37276249ae2 | 1,464 |
import UIKit
import Firebase
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
FIRApp.configure()
self.initSignInGG()
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let schem = url.scheme
print("xxxxx SCHEM = \(String(describing: schem))")
return GIDSignIn.sharedInstance().handle(url as URL!, sourceApplication: options[.sourceApplication] as! String, annotation: options[.annotation])
}
// MARK: - GIDSignInDelegate
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
if let error = error {
print("\(error.localizedDescription)")
} else {
// get userInfo
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!,
withError error: Error!) {
// Perform any operations when the user disconnects from app here.
// ...
}
func initSignInGG() {
GIDSignIn.sharedInstance().clientID = AppConfig.CLIENT_ID
GIDSignIn.sharedInstance().delegate = self
}
}
| 29.877551 | 154 | 0.645492 |
fe359224af2ca639950e9a2434b56f6c973905c0 | 5,630 | //
// Constant.swift
// Constrictor
//
// Created by Pedro Carrasco on 22/05/2018.
// Copyright © 2018 Pedro Carrasco. All rights reserved.
//
import UIKit
//
// Constant.swift
// Constrictor
//
// Created by Pedro Carrasco on 22/05/2018.
// Copyright © 2018 Pedro Carrasco. All rights reserved.
//
import UIKit
// MARK: - Constant
public struct Constant: Equatable {
let x: CGFloat
let y: CGFloat
let top: CGFloat
let bottom: CGFloat
let right: CGFloat
let left: CGFloat
let leading: CGFloat
let trailing: CGFloat
let width: CGFloat
let height: CGFloat
}
// MARK: - Internal Custom Initializer
extension Constant {
init(attribute: ConstrictorAttribute, value: CGFloat) {
switch attribute {
case .top, .topGuide: self = .top(value)
case .bottom, .bottomGuide: self = .bottom(value)
case .right, .rightGuide: self = .right(value)
case .left, .leftGuide: self = .left(value)
case .leading, .leadingGuide: self = .leading(value)
case .trailing, .trailingGuide: self = .trailing(value)
case .centerX, .centerXGuide: self = .x(value)
case .centerY, .centerYGuide: self = .y(value)
case .width: self = .width(value)
case .height: self = .height(value)
case .none: self = .zero
}
}
init(size: CGFloat) {
self = .width(size) & .height(size)
}
}
// MARK: - Modifiers
public extension Constant {
static func x(_ value: CGFloat) -> Constant {
return Constant(x: value, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func y(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: value,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func top(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: value, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func bottom(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: value,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func leading(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: value, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func trailing(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: value,
width: 0.0, height: 0.0)
}
static func right(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: value, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func left(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: value,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
static func width(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: value, height: 0.0)
}
static func height(_ value: CGFloat) -> Constant {
return Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: value)
}
static func all(_ value: CGFloat) -> Constant {
return Constant(x: value, y: value,
top: value, bottom: value,
right: value, left: value,
leading: value, trailing: value,
width: value, height: value)
}
static let zero = Constant(x: 0.0, y: 0.0,
top: 0.0, bottom: 0.0,
right: 0.0, left: 0.0,
leading: 0.0, trailing: 0.0,
width: 0.0, height: 0.0)
}
// MARK: - Operator
public extension Constant {
public static func & (lhs: Constant, rhs: Constant) -> Constant {
return .init(x: lhs.x + rhs.x, y: lhs.y + rhs.y,
top: lhs.top + rhs.top, bottom: lhs.bottom + rhs.bottom,
right: lhs.right + rhs.right, left: lhs.left + rhs.left,
leading: lhs.leading + rhs.leading, trailing: lhs.trailing + rhs.trailing,
width: lhs.width + rhs.width, height: lhs.height + rhs.height)
}
}
| 32.732558 | 95 | 0.46714 |
e9abc1c659fdc9c9690ddb7bc50e3a45c22315ca | 1,868 | import Foundation
import BTKit
import RuuviStorage
import RuuviReactor
import RuuviLocal
import RuuviService
import RuuviUser
class TagSettingsTableConfigurator {
func configure(view: TagSettingsTableViewController) {
let r = AppAssembly.shared.assembler.resolver
let router = TagSettingsRouter()
router.transitionHandler = view
let presenter = TagSettingsPresenter()
presenter.view = view
presenter.router = router
presenter.errorPresenter = r.resolve(ErrorPresenter.self)
presenter.photoPickerPresenter = r.resolve(PhotoPickerPresenter.self)
presenter.foreground = r.resolve(BTForeground.self)
presenter.background = r.resolve(BTBackground.self)
presenter.calibrationService = r.resolve(CalibrationService.self)
presenter.alertService = r.resolve(RuuviServiceAlert.self)
presenter.settings = r.resolve(RuuviLocalSettings.self)
presenter.connectionPersistence = r.resolve(RuuviLocalConnections.self)
presenter.pushNotificationsManager = r.resolve(PushNotificationsManager.self)
presenter.permissionPresenter = r.resolve(PermissionPresenter.self)
presenter.ruuviReactor = r.resolve(RuuviReactor.self)
presenter.ruuviStorage = r.resolve(RuuviStorage.self)
presenter.ruuviUser = r.resolve(RuuviUser.self)
presenter.activityPresenter = r.resolve(ActivityPresenter.self)
presenter.ruuviLocalImages = r.resolve(RuuviLocalImages.self)
presenter.ruuviOwnershipService = r.resolve(RuuviServiceOwnership.self)
presenter.ruuviSensorPropertiesService = r.resolve(RuuviServiceSensorProperties.self)
presenter.featureToggleService = r.resolve(FeatureToggleService.self)
view.measurementService = r.resolve(MeasurementsService.self)
view.output = presenter
}
}
| 43.44186 | 93 | 0.751606 |
ac021da9404f6fd597846b451e7ea848c102990b | 3,233 | //
// LikeButtonView.swift
// ACHNBrowserUI
//
// Created by Eric Lewis on 4/19/20.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
struct LikeButtonView: View {
@EnvironmentObject private var collection: UserCollection
let item: Item?
let variant: Variant?
let villager: Villager?
init(item: Item, variant: Variant?) {
self.item = item
self.variant = variant
self.villager = nil
}
init(villager: Villager) {
self.villager = villager
self.variant = nil
self.item = nil
}
private var isInCollection: Bool {
if let item = item {
if let variant = variant {
return collection.variantIn(item: item, variant: variant)
}
return collection.items.contains(item) || collection.critters.contains(item)
} else if let villager = villager {
return collection.villagers.contains(villager)
}
return false
}
var imageName: String {
if item != nil {
if item?.isCritter == true {
return isInCollection ? "checkmark.seal.fill" : "checkmark.seal"
} else {
return isInCollection ? "star.fill" : "star"
}
} else {
return isInCollection ? "heart.fill" : "heart"
}
}
var color: Color {
if item != nil {
if item?.isCritter == true {
return .acTabBarBackground
}
return .yellow
}
return .red
}
var body: some View {
Button(action: {
if let item = self.item {
switch item.appCategory {
case .fish, .bugs, .fossils:
let added = self.collection.toggleCritters(critter: item)
FeedbackGenerator.shared.triggerNotification(type: added ? .success : .warning)
default:
if let variant = self.variant {
let added = self.collection.toggleVariant(item: item, variant: variant)
FeedbackGenerator.shared.triggerNotification(type: added ? .success : .warning)
return
}
let added = self.collection.toggleItem(item: item)
FeedbackGenerator.shared.triggerNotification(type: added ? .success : .warning)
}
} else if let villager = self.villager {
let added = self.collection.toggleVillager(villager: villager)
FeedbackGenerator.shared.triggerNotification(type: added ? .success : .warning)
}
}) {
Image(systemName: imageName).foregroundColor(color)
}
.scaleEffect(self.isInCollection ? 1.3 : 1.0)
.buttonStyle(BorderlessButtonStyle())
.animation(.spring(response: 0.5, dampingFraction: 0.3, blendDuration: 0.5))
}
}
struct StarButtonView_Previews: PreviewProvider {
static var previews: some View {
LikeButtonView(item: static_item, variant: nil)
.environmentObject(UserCollection.shared)
}
}
| 32.33 | 103 | 0.557996 |
d5e3ee14ed3033a292a59e710cdd27e69490dde8 | 1,222 | //
// WLOpenUrl.swift
// WLToolKit_Swift
//
// Created by three stone 王 on 2018/11/14.
// Copyright © 2018年 three stone 王. All righWL reserved.
//
import UIKit
// MARK: openUrl
@objc public final class WLOpenUrl: NSObject {
@objc (openUrlWithUrl:)
public static func openUrl(urlString: String) {
if let url = URL(string: urlString) {
if #available(iOS 10.0, *) {
// iOS 8 及其以上系统运行
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
// MARK: openSetting
extension WLOpenUrl {
@objc (openSetting)
public static func openSetting() {
let settingUrl = URL(string: UIApplication.openSettingsURLString)
if let url = settingUrl, UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
// iOS 8 及其以上系统运行
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
| 25.458333 | 84 | 0.53437 |
26e115114128fbb64077ac37c4d50897af535a6f | 2,372 | //
// SceneDelegate.swift
// LongTermTask
//
// Created by Rostyslav Druzhchenko on 09.06.2020.
// Copyright © 2020 Rostyslav Druzhchenko. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.925926 | 147 | 0.716273 |
79cb9c132d9503a61c4215559c7bad0cf6fc6241 | 4,238 | //
// RememberIt_Widget.swift
// RememberIt-Widget
//
// Created by Stewart Lynch on 2020-09-15.
// Copyright © 2020 CreaTECH Solutions. All rights reserved.
//
import WidgetKit
import SwiftUI
struct RememberItEntry: TimelineEntry {
let date: Date = Date()
let rememberItem: RememberItem
}
struct Provider: TimelineProvider {
@AppStorage("rememberItem", store: UserDefaults(suiteName: "group.com.createchsol.IRemember")) var primaryItemData: Data = Data()
func placeholder(in context: Context) -> RememberItEntry {
let rememberItem = RememberItem(title: "Rental SUV", icon: "car", detail1: "749 AAP", detail2: "Gray Ford Echo Sport")
return RememberItEntry(rememberItem: rememberItem)
}
func getSnapshot(in context: Context, completion: @escaping (RememberItEntry) -> ()) {
guard let rememberItem = try? JSONDecoder().decode(RememberItem.self, from: primaryItemData) else {
print("Unable to decode primary item.")
return
}
let entry = RememberItEntry(rememberItem: rememberItem)
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
guard let rememberItem = try? JSONDecoder().decode(RememberItem.self, from: primaryItemData) else {
print("Unable to decode primary item.")
return
}
let entry = RememberItEntry(rememberItem: rememberItem)
let timeline = Timeline(entries: [entry], policy: .never)
completion(timeline)
}
}
struct RememberIt_WidgetEntryView : View {
var entry: Provider.Entry
@Environment(\.widgetFamily) var family
var body: some View {
if family == .systemSmall {
SmallWidget(entry: entry)
} else {
MediumWidget(entry: entry)
}
}
}
struct SmallWidget: View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading) {
HStack {
Image(entry.rememberItem.icon)
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.red)
Text(entry.rememberItem.title)
.font(.headline)
}
Text(entry.rememberItem.detail1).font(.title)
.layoutPriority(1)
Text(entry.rememberItem.detail2).font(.body)
Spacer()
}
.padding(5)
}
}
struct MediumWidget: View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading) {
HStack {
Image(entry.rememberItem.icon)
.resizable()
.frame(width: 125, height: 125)
.foregroundColor(.red)
VStack(alignment: .leading) {
Text(entry.rememberItem.title)
.font(.title)
Text(entry.rememberItem.detail1).font(.largeTitle)
.fixedSize(horizontal: false, vertical: true)
}
}
Text(entry.rememberItem.detail2).font(.body)
Spacer()
}.padding()
}
}
@main
struct RememberIt_Widget: Widget {
let kind: String = "RememberIt_Widget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
RememberIt_WidgetEntryView(entry: entry)
}
.configurationDisplayName("I Remember")
.description("These are the I Remember Widgets.")
.supportedFamilies([.systemSmall, .systemMedium])
}
}
struct RememberIt_Widget_Previews: PreviewProvider {
static let rememberItem = RememberItem(title: "Rental SUV", icon: "car", detail1: "749 AAP", detail2: "Gray Ford Echo Sport")
static var previews: some View {
Group {
RememberIt_WidgetEntryView(entry: RememberItEntry(rememberItem: rememberItem))
.previewContext(WidgetPreviewContext(family: .systemSmall))
RememberIt_WidgetEntryView(entry: RememberItEntry(rememberItem: rememberItem))
.previewContext(WidgetPreviewContext(family: .systemMedium))
}
}
}
| 32.852713 | 133 | 0.60571 |
1137ee2ac3490af6aa05a8c8a7b91abce719d452 | 3,771 | //
// Model.swift
// HKSplitMenu
//
// Created by Harley on 2017/1/10.
// Copyright © 2017年 Sinoyd. All rights reserved.
//
import UIKit
import Comet
import ObjectMapper
class Model: NSObject, Mappable {
// var id = 0
// var updated_at: Date?
// var created_at: Date?
// var deleted_at: Date?
override init() {}
required public init?(map: Map) {}
func mapping(map: Map) {
autoMapping(map: map)
}
func customMappings() -> [String:String] {
return [:]
}
func dateTransform(for keyPath:String) -> TimeConvertor {
return TimeConvertor()
}
private func autoMapping(map: Map) {
let mirror = Mirror(reflecting: self)
self.process(mirror: mirror,map: map)
}
private func process(mirror: Mirror,map: Map) {
for child in mirror.children {
autoMap(child: child, withMap: map)
}
if let superMirror = mirror.superclassMirror {
process(mirror: superMirror,map: map)
}
}
private func autoMap(child: Mirror.Child, withMap map: Map) {
guard let name = child.label else {
return
}
let mi = Mirror(reflecting: child.value)
let key = customMappings()[name] ?? name
guard let rawValue = map.JSON[key], !(rawValue is NSNull) else {
return
}
// Auto mapping String
if mi.subjectType == String.self {
if let value = try? map.value(key) as String {
setValue(value, forKeyPath: name)
}
}
// Auto mapping String Array
if mi.subjectType == [String].self {
if let value = try? map.value(key) as [String] {
setValue(value, forKeyPath: name)
}
}
// Auto mapping Int
else if mi.subjectType == Int.self {
if let value = try? map.value(key) as Int {
setValue(value, forKeyPath: name)
}
}
// Auto mapping Double
else if mi.subjectType == Double.self {
if let value = try? map.value(key) as Double {
setValue(value, forKeyPath: name)
}
}
// Auto mapping Date
else if mi.subjectType == Date?.self ||
mi.subjectType == Date.self
{
let transform = dateTransform(for: name)
if let value = try? map.value(key, using: transform) as Date {
setValue(value, forKeyPath: name)
}
}
else {
// setValue(rawValue, forKeyPath: name)
}
}
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
// RunDebug {
// print("Auto Mapping", self.classForCoder.description(), "======")
// print("UndefinedKey: ", key)
//// print(" Value: ", value ?? "nil")
// print("")
// }
}
}
public class TimeConvertor: TransformType {
public typealias Object = Date
public typealias JSON = Any
private var format: String
public init(format: String = "yyyy-MM-dd HH:mm:ss") {
self.format = format
}
public func transformFromJSON(_ value: Any?) -> Date? {
if let timeInterval = value as? TimeInterval {
return Date(timeIntervalSince1970: timeInterval)
}
if let timeString = value as? String {
return Date(string: timeString, format: format)
}
return nil
}
public func transformToJSON(_ value: Date?) -> Any? {
return value?.string()
}
}
| 26.1875 | 79 | 0.523999 |
1eda7e417bc55e714a7653e8a9ef0a04eed93ff6 | 28,306 | /*
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
-----------------------------------------------------------------
An extemely simple rendition of the Xcode project model into a plist. There
is only enough functionality to allow serialization of Xcode projects.
*/
extension Xcode.Project: PropertyListSerializable {
/// Generates and returns the contents of a `project.pbxproj` plist. Does
/// not generate any ancillary files, such as a set of schemes.
///
/// Many complexities of the Xcode project model are not represented; we
/// should not add functionality to this model unless it's needed, since
/// implementation of the full Xcode project model would be unnecessarily
/// complex.
public func generatePlist() -> PropertyList {
// The project plist is a bit special in that it's the archive for the
// whole file. We create a plist serializer and serialize the entire
// object graph to it, and then return an archive dictionary containing
// the serialized object dictionaries.
let serializer = PropertyListSerializer()
serializer.serialize(object: self)
return .dictionary([
"archiveVersion": .string("1"),
"objectVersion": .string("46"), // Xcode 8.0
"rootObject": .identifier(serializer.id(of: self)),
"objects": .dictionary(serializer.idsToDicts),
])
}
/// Called by the Serializer to serialize the Project.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXProject` plist dictionary.
// Note: we skip things like the `Products` group; they get autocreated
// by Xcode when it opens the project and notices that they are missing.
// Note: we also skip schemes, since they are not in the project plist.
var dict = [String: PropertyList]()
dict["isa"] = .string("PBXProject")
// Since the project file is generated, we opt out of upgrade-checking.
// FIXME: Shoule we really? Why would we not want to get upgraded?
dict["attributes"] = .dictionary(["LastUpgradeCheck": .string("9999"),
"LastSwiftMigration": .string("9999")])
dict["compatibilityVersion"] = .string("Xcode 3.2")
dict["developmentRegion"] = .string("English")
// Build settings are a bit tricky; in Xcode, each is stored in a named
// XCBuildConfiguration object, and the list of build configurations is
// in turn stored in an XCConfigurationList. In our simplified model,
// we have a BuildSettingsTable, with three sets of settings: one for
// the common settings, and one each for the Debug and Release overlays.
// So we consider the BuildSettingsTable to be the configuration list.
dict["buildConfigurationList"] = .identifier(serializer.serialize(object: buildSettings))
dict["mainGroup"] = .identifier(serializer.serialize(object: mainGroup))
dict["hasScannedForEncodings"] = .string("0")
dict["knownRegions"] = .array([.string("en")])
if let productGroup = productGroup {
dict["productRefGroup"] = .identifier(serializer.id(of: productGroup))
}
dict["projectDirPath"] = .string(projectDir)
// Ensure that targets are output in a sorted order.
let sortedTargets = targets.sorted(by: { $0.name < $1.name })
dict["targets"] = .array(sortedTargets.map({ target in
.identifier(serializer.serialize(object: target))
}))
return dict
}
}
/// Private helper function that constructs and returns a partial property list
/// dictionary for references. The caller can add to the returned dictionary.
/// FIXME: It would be nicer to be able to use inheritance to serialize the
/// attributes inherited from Reference, but but in Swift 3.0 we get an error
/// that "declarations in extensions cannot override yet".
fileprivate func makeReferenceDict(
reference: Xcode.Reference,
serializer: PropertyListSerializer,
xcodeClassName: String
) -> [String: PropertyList] {
var dict = [String: PropertyList]()
dict["isa"] = .string(xcodeClassName)
dict["path"] = .string(reference.path)
if let name = reference.name {
dict["name"] = .string(name)
}
dict["sourceTree"] = .string(reference.pathBase.asString)
return dict
}
extension Xcode.Group: PropertyListSerializable {
/// Called by the Serializer to serialize the Group.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXGroup` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from Reference, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
var dict = makeReferenceDict(reference: self, serializer: serializer, xcodeClassName: "PBXGroup")
dict["children"] = .array(subitems.map({ reference in
// For the same reason, we have to cast as `PropertyListSerializable`
// here; as soon as we try to make Reference conform to the protocol,
// we get the problem of not being able to override `serialize(to:)`.
.identifier(serializer.serialize(object: reference as! PropertyListSerializable))
}))
return dict
}
}
extension Xcode.FileReference: PropertyListSerializable {
/// Called by the Serializer to serialize the FileReference.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXFileReference` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from Reference, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
var dict = makeReferenceDict(reference: self, serializer: serializer, xcodeClassName: "PBXFileReference")
if let fileType = fileType {
dict["explicitFileType"] = .string(fileType)
}
// FileReferences don't need to store a name if it's the same as the path.
if name == path {
dict["name"] = nil
}
return dict
}
}
extension Xcode.Target: PropertyListSerializable {
/// Called by the Serializer to serialize the Target.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create either a `PBXNativeTarget` or an `PBXAggregateTarget` plist
// dictionary (depending on whether or not we have a product type).
var dict = [String: PropertyList]()
dict["isa"] = .string(productType == nil ? "PBXAggregateTarget" : "PBXNativeTarget")
dict["name"] = .string(name)
// Build settings are a bit tricky; in Xcode, each is stored in a named
// XCBuildConfiguration object, and the list of build configurations is
// in turn stored in an XCConfigurationList. In our simplified model,
// we have a BuildSettingsTable, with three sets of settings: one for
// the common settings, and one each for the Debug and Release overlays.
// So we consider the BuildSettingsTable to be the configuration list.
// This is the same situation as for Project.
dict["buildConfigurationList"] = .identifier(serializer.serialize(object: buildSettings))
dict["buildPhases"] = .array(buildPhases.map({ phase in
// Here we have the same problem as for Reference; we cannot inherit
// functionality since we're in an extension.
.identifier(serializer.serialize(object: phase as! PropertyListSerializable))
}))
/// Private wrapper class for a target dependency relation. This is
/// glue between our value-based settings structures and the Xcode
/// project model's identity-based TargetDependency objects.
class TargetDependency: PropertyListSerializable {
var target: Xcode.Target
init(target: Xcode.Target) {
self.target = target
}
func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXTargetDependency` plist dictionary.
var dict = [String: PropertyList]()
dict["isa"] = .string("PBXTargetDependency")
dict["target"] = .identifier(serializer.id(of: target))
return dict
}
}
dict["dependencies"] = .array(dependencies.map({ dep in
// In the Xcode project model, target dependencies are objects,
// so we need a helper class here.
.identifier(serializer.serialize(object: TargetDependency(target: dep.target)))
}))
dict["productName"] = .string(productName)
if let productType = productType {
dict["productType"] = .string(productType.asString)
}
if let productReference = productReference {
dict["productReference"] = .identifier(serializer.id(of: productReference))
}
return dict
}
}
/// Private helper function that constructs and returns a partial property list
/// dictionary for build phases. The caller can add to the returned dictionary.
/// FIXME: It would be nicer to be able to use inheritance to serialize the
/// attributes inherited from BuildPhase, but but in Swift 3.0 we get an error
/// that "declarations in extensions cannot override yet".
fileprivate func makeBuildPhaseDict(
buildPhase: Xcode.BuildPhase,
serializer: PropertyListSerializer,
xcodeClassName: String
) -> [String: PropertyList] {
var dict = [String: PropertyList]()
dict["isa"] = .string(xcodeClassName)
dict["files"] = .array(buildPhase.files.map({ file in
.identifier(serializer.serialize(object: file))
}))
return dict
}
extension Xcode.HeadersBuildPhase: PropertyListSerializable {
/// Called by the Serializer to serialize the HeadersBuildPhase.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXHeadersBuildPhase` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from BuildPhase, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
return makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXHeadersBuildPhase")
}
}
extension Xcode.SourcesBuildPhase: PropertyListSerializable {
/// Called by the Serializer to serialize the SourcesBuildPhase.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXSourcesBuildPhase` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from BuildPhase, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
return makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXSourcesBuildPhase")
}
}
extension Xcode.FrameworksBuildPhase: PropertyListSerializable {
/// Called by the Serializer to serialize the FrameworksBuildPhase.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXFrameworksBuildPhase` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from BuildPhase, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
return makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXFrameworksBuildPhase")
}
}
extension Xcode.CopyFilesBuildPhase: PropertyListSerializable {
/// Called by the Serializer to serialize the FrameworksBuildPhase.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXCopyFilesBuildPhase` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from BuildPhase, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
var dict = makeBuildPhaseDict(
buildPhase: self,
serializer: serializer,
xcodeClassName: "PBXCopyFilesBuildPhase")
dict["dstPath"] = .string("") // FIXME: needs to be real
dict["dstSubfolderSpec"] = .string("") // FIXME: needs to be real
return dict
}
}
extension Xcode.ShellScriptBuildPhase: PropertyListSerializable {
/// Called by the Serializer to serialize the ShellScriptBuildPhase.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXShellScriptBuildPhase` plist dictionary.
// FIXME: It would be nicer to be able to use inheritance for the code
// inherited from BuildPhase, but but in Swift 3.0 we get an error that
// "declarations in extensions cannot override yet".
var dict = makeBuildPhaseDict(
buildPhase: self,
serializer: serializer,
xcodeClassName: "PBXShellScriptBuildPhase")
dict["shellPath"] = .string("/bin/sh") // FIXME: should be settable
dict["shellScript"] = .string(script)
return dict
}
}
extension Xcode.BuildFile: PropertyListSerializable {
/// Called by the Serializer to serialize the BuildFile.
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `PBXBuildFile` plist dictionary.
var dict = [String: PropertyList]()
dict["isa"] = .string("PBXBuildFile")
if let fileRef = fileRef {
dict["fileRef"] = .identifier(serializer.id(of: fileRef))
}
let settingsDict = settings.asPropertyList()
if !settingsDict.isEmpty {
dict["settings"] = settingsDict
}
return dict
}
}
extension Xcode.BuildSettingsTable: PropertyListSerializable {
/// Called by the Serializer to serialize the BuildFile. It is serialized
/// as an XCBuildConfigurationList and two additional XCBuildConfiguration
/// objects (one for debug and one for release).
fileprivate func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
/// Private wrapper class for BuildSettings structures. This is glue
/// between our value-based settings structures and the Xcode project
/// model's identity-based XCBuildConfiguration objects.
class BuildSettingsDictWrapper: PropertyListSerializable {
let name: String
var baseSettings: BuildSettings
var overlaySettings: BuildSettings
let xcconfigFileRef: Xcode.FileReference?
init(
name: String,
baseSettings: BuildSettings,
overlaySettings: BuildSettings,
xcconfigFileRef: Xcode.FileReference?
) {
self.name = name
self.baseSettings = baseSettings
self.overlaySettings = overlaySettings
self.xcconfigFileRef = xcconfigFileRef
}
func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {
// Create a `XCBuildConfiguration` plist dictionary.
var dict = [String: PropertyList]()
dict["isa"] = .string("XCBuildConfiguration")
dict["name"] = .string(name)
// Combine the base settings and the overlay settings.
dict["buildSettings"] = combineBuildSettingsPropertyLists(
baseSettings: baseSettings.asPropertyList(),
overlaySettings: overlaySettings.asPropertyList())
// Add a reference to the base configuration, if there is one.
if let xcconfigFileRef = xcconfigFileRef {
dict["baseConfigurationReference"] = .identifier(serializer.id(of: xcconfigFileRef))
}
return dict
}
}
// Create a `XCConfigurationList` plist dictionary.
var dict = [String: PropertyList]()
dict["isa"] = .string("XCConfigurationList")
dict["buildConfigurations"] = .array([
// We use a private wrapper to "objectify" our two build settings
// structures (which, being structs, are value types).
.identifier(serializer.serialize(object: BuildSettingsDictWrapper(
name: "Debug",
baseSettings: common,
overlaySettings: debug,
xcconfigFileRef: xcconfigFileRef))),
.identifier(serializer.serialize(object: BuildSettingsDictWrapper(
name: "Release",
baseSettings: common,
overlaySettings: release,
xcconfigFileRef: xcconfigFileRef))),
])
// FIXME: What is this, and why are we setting it?
dict["defaultConfigurationIsVisible"] = .string("0")
// FIXME: Should we allow this to be set in the model?
dict["defaultConfigurationName"] = .string("Release")
return dict
}
}
protocol PropertyListDictionaryConvertible {
func asPropertyList() -> PropertyList
}
extension PropertyListDictionaryConvertible {
// FIXME: Internal only for unit testing.
//
/// Returns a property list representation of the build settings, in which
/// every struct field is represented as a dictionary entry. Fields of
/// type `String` are represented as `PropertyList.string` values; fields
/// of type `[String]` are represented as `PropertyList.array` values with
/// `PropertyList.string` values as the array elements. The property list
/// dictionary only contains entries for struct fields that aren't nil.
///
/// Note: BuildSettings is a value type and PropertyListSerializable only
/// applies to classes. Creating a property list representation is totally
/// independent of that serialization infrastructure (though it might well
/// be invoked during of serialization of actual model objects).
func asPropertyList() -> PropertyList {
// Borderline hacky, but the main thing is that adding or changing a
// build setting does not require any changes to the property list
// representation code. Using a handcoded serializer might be more
// efficient but not even remotely as robust, and robustness is the
// key factor for this use case, as there aren't going to be millions
// of BuildSettings structs.
var dict = [String: PropertyList]()
let mirror = Mirror(reflecting: self)
for child in mirror.children {
guard let name = child.label else {
preconditionFailure("unnamed build settings are not supported")
}
switch child.value {
case nil:
continue
case let value as String:
dict[name] = .string(value)
case let value as [String]:
dict[name] = .array(value.map({ .string($0) }))
default:
// FIXME: I haven't found a way of distinguishing a value of an
// unexpected type from a value that is nil; they all seem to go
// throught the `default` case instead of the `nil` case above.
// Hopefully someone reading this will clue me in about what I
// did wrong. But currently we will silently fail to serialize
// any struct field that isn't a `String` or a `[String]` (or
// an optional of either of those two).
// This would only come up if a field were to be added of a type
// other than `String` or `[String]`.
continue
}
}
return .dictionary(dict)
}
}
extension Xcode.BuildFile.Settings: PropertyListDictionaryConvertible {}
extension Xcode.BuildSettingsTable.BuildSettings: PropertyListDictionaryConvertible {}
/// Private helper function that combines a base property list and an overlay
/// property list, respecting the semantics of `$(inherited)` as we go.
fileprivate func combineBuildSettingsPropertyLists(
baseSettings: PropertyList,
overlaySettings: PropertyList
) -> PropertyList {
// Extract the base and overlay dictionaries.
guard case let .dictionary(baseDict) = baseSettings else {
preconditionFailure("base settings plist must be a dictionary")
}
guard case let .dictionary(overlayDict) = overlaySettings else {
preconditionFailure("overlay settings plist must be a dictionary")
}
// Iterate over the overlay values and apply them to the base.
var resultDict = baseDict
for (name, value) in overlayDict {
if let array = baseDict[name]?.array, let overlayArray = value.array, overlayArray.first?.string == "$(inherited)" {
resultDict[name] = .array(array + overlayArray.dropFirst())
} else {
resultDict[name] = value
}
}
return .dictionary(resultDict)
}
/// A simple property list serializer with the same semantics as the Xcode
/// property list serializer. Not generally reusable at this point, but only
/// because of implementation details (architecturally it isn't tied to Xcode).
fileprivate class PropertyListSerializer {
/// Private struct that represents a strong reference to a serializable
/// object. This prevents any temporary objects from being deallocated
/// during the serialization and replaced with other objects having the
/// same object identifier (a violation of our assumptions)
struct SerializedObjectRef: Hashable, Equatable {
let object: PropertyListSerializable
init(_ object: PropertyListSerializable) {
self.object = object
}
var hashValue: Int {
return ObjectIdentifier(object).hashValue
}
static func == (lhs: SerializedObjectRef, rhs: SerializedObjectRef) -> Bool {
return lhs.object === rhs.object
}
}
/// Maps objects to the identifiers that have been assigned to them. The
/// next identifier to be assigned is always one greater than the number
/// of entries in the mapping.
var objsToIds = [SerializedObjectRef: String]()
/// Maps serialized objects ids to dictionaries. This may contain fewer
/// entries than `objsToIds`, since ids are assigned upon reference, but
/// plist dictionaries are created only upon actual serialization. This
/// dictionary is what gets written to the property list.
var idsToDicts = [String: PropertyList]()
/// Returns the quoted identifier for the object, assigning one if needed.
func id(of object: PropertyListSerializable) -> String {
// We need a "serialized object ref" wrapper for the `objsToIds` map.
let serObjRef = SerializedObjectRef(object)
if let id = objsToIds[serObjRef] {
return "\"\(id)\""
}
// We currently always assign identifiers starting at 1 and going up.
// FIXME: This is a suboptimal format for object identifier strings;
// for debugging purposes they should at least sort in numeric order.
let id = object.objectID ?? "OBJ_\(objsToIds.count + 1)"
objsToIds[serObjRef] = id
return "\"\(id)\""
}
/// Serializes `object` by asking it to construct a plist dictionary and
/// then adding that dictionary to the serializer. This may in turn cause
/// recursive invocations of `serialize(object:)`; the closure of these
/// invocations end up serializing the whole object graph.
@discardableResult func serialize(object: PropertyListSerializable) -> String {
// Assign an id for the object, if it doesn't already have one.
let id = self.id(of: object)
// If that id is already in `idsToDicts`, we've detected recursion or
// repeated serialization.
precondition(idsToDicts[id] == nil, "tried to serialize \(object) twice")
// Set a sentinel value in the `idsToDicts` mapping to detect recursion.
idsToDicts[id] = .dictionary([:])
// Now recursively serialize the object, and store the result (replacing
// the sentinel).
idsToDicts[id] = .dictionary(object.serialize(to: self))
// Finally, return the identifier so the caller can store it (usually in
// an attribute in its own serialization dictionary).
return id
}
}
fileprivate protocol PropertyListSerializable: class {
/// Called by the Serializer to construct and return a dictionary for a
/// serializable object. The entries in the dictionary should represent
/// the receiver's attributes and relationships, as PropertyList values.
///
/// Every object that is written to the Serializer is assigned an id (an
/// arbitrary but unique string). Forward references can use `id(of:)`
/// of the Serializer to assign and access the id before the object is
/// actually written.
///
/// Implementations can use the Serializer's `serialize(object:)` method
/// to serialize owned objects (getting an id to the serialized object,
/// which can be stored in one of the attributes) or can use the `id(of:)`
/// method to store a reference to an unowned object.
///
/// The implementation of this method for each serializable objects looks
/// something like this:
///
/// // Create a `PBXSomeClassOrOther` plist dictionary.
/// var dict = [String: PropertyList]()
/// dict["isa"] = .string("PBXSomeClassOrOther")
/// dict["name"] = .string(name)
/// if let path = path { dict["path"] = .string(path) }
/// dict["mainGroup"] = .identifier(serializer.serialize(object: mainGroup))
/// dict["subitems"] = .array(subitems.map({ .string($0.id) }))
/// dict["cross-ref"] = .identifier(serializer.id(of: unownedObject))
/// return dict
///
/// FIXME: I'm not totally happy with how this looks. It's far too clunky
/// and could be made more elegant. However, since the Xcode project model
/// is static, this is not something that will need to evolve over time.
/// What does need to evolve, which is how the project model is constructed
/// from the package contents, is where the elegance and simplicity really
/// matters. So this is acceptable for now in the interest of getting it
/// done.
/// A custom ID to use for the instance, if enabled.
///
/// This ID must be unique across the entire serialized graph.
var objectID: String? { get }
/// Should create and return a property list dictionary of the object's
/// attributes. This function may also use the serializer's `serialize()`
/// function to serialize other objects, and may use `id(of:)` to access
/// ids of objects that either have or will be serialized.
func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList]
}
extension PropertyListSerializable {
var objectID: String? {
return nil
}
}
extension PropertyList {
var isEmpty: Bool {
switch self {
case let .identifier(string): return string.isEmpty
case let .string(string): return string.isEmpty
case let .array(array): return array.isEmpty
case let .dictionary(dictionary): return dictionary.isEmpty
}
}
}
| 47.733558 | 124 | 0.659789 |
6af3ab12af64a19cf08e5f5728ac3e3ffc829525 | 444 | //
// AppDelegate.swift
// SSLCommerzIntegration
//
// Created by Romana on 22/8/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
| 20.181818 | 145 | 0.716216 |
3346dae19eaf9845da5fee5352244031ba31f051 | 603 | //
// ReusableViewType.swift
//
// Created by Chandler De Angelis on 9/2/16.
//
import Foundation
import UIKit
public protocol ReusableViewType {
static var reuseIdentifier: String { get }
}
extension ReusableViewType where Self: NSObject {
static public var reuseIdentifier: String {
let classString = NSStringFromClass(self)
if classString.contains(".") {
return classString.components(separatedBy: ".")[1]
} else {
return classString
}
}
}
extension UIViewController: ReusableViewType {}
extension UIView: ReusableViewType {}
| 22.333333 | 62 | 0.678275 |
b92cb60bfdea6d2d5e359598976ea30cc31b2d94 | 1,854 | //
// Macro.swift
// Coconut
//
// Created by Dami on 05/10/2016.
//
//
import Foundation
import CGtk
func gtkScreenPositionFromCocoa(origin: NSPoint) -> NSPoint {
let screen = gdk_screen_get_default()
let height = gdk_screen_get_height(screen)
return NSPoint(x: origin.x, y: CGFloat(height - Int32(origin.y)))
}
func convertPoint(point: NSPoint, frame: NSRect) -> NSPoint {
return NSPoint(x: point.x, y: frame.size.height - point.y)
}
func toWidget(pointer: UnsafeMutablePointer<gpointer>?) -> UnsafeMutablePointer<GtkWidget> {
return unsafeBitCast(pointer, to: UnsafeMutablePointer<GtkWidget>.self)
}
func toWindow(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<GtkWindow> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<GtkWindow>.self)
}
func toContainer(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<GtkContainer> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<GtkContainer>.self)
}
func toGrid(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<GtkGrid> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<GtkGrid>.self)
}
func toFixed(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<GtkFixed> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<GtkFixed>.self)
}
func toGPointer(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<gpointer?> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<gpointer?>.self)
}
func toButton(widget: UnsafeMutablePointer<GtkWidget>?) -> UnsafeMutablePointer<GtkButton> {
return unsafeBitCast(widget, to: UnsafeMutablePointer<GtkButton>.self)
}
func connectSignal(object: UnsafeMutablePointer<GObject>?, signal: String, callback: @escaping GCallback) {
g_signal_connect_data (object, signal, callback, nil, nil, G_CONNECT_AFTER)
}
| 34.333333 | 107 | 0.765912 |
e598e4e26dce9093da15fbca54dbc94381135d83 | 1,617 | //
// TerraRegion.swift
// TerraIncognitaExample
//
// Created by Valeriy Bezuglyy on 30/07/2017.
// Copyright © 2017 Valeriy Bezuglyy. All rights reserved.
//
import Foundation
import CoreLocation
// lat - vertical
// lon - horizontal
class TerraRegion {
var topLeft: CLLocationCoordinate2D
var topRight: CLLocationCoordinate2D
var bottomLeft: CLLocationCoordinate2D
var bottomRight: CLLocationCoordinate2D
init(topLeft: CLLocationCoordinate2D,
topRight: CLLocationCoordinate2D,
bottomLeft: CLLocationCoordinate2D,
bottomRight: CLLocationCoordinate2D) {
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
}
func containsCoordinate(_ coordinate:CLLocationCoordinate2D) -> Bool {
//TODO: search in trapezoid
var latInside = false
if topLeft.latitude < bottomLeft.latitude {
latInside = coordinate.latitude >= topLeft.latitude && coordinate.latitude <= bottomLeft.latitude
}
else {
latInside = coordinate.latitude >= bottomLeft.latitude && coordinate.latitude <= topLeft.latitude
}
var lonInside = false
if topLeft.longitude < topRight.longitude {
lonInside = coordinate.longitude >= topLeft.longitude && coordinate.longitude <= topRight.longitude
}
else {
lonInside = coordinate.longitude >= topRight.longitude && coordinate.longitude <= topLeft.longitude
}
return latInside && lonInside
}
}
| 31.705882 | 111 | 0.664193 |
e5041d3b4af202496c16652344f50896f30f35a6 | 1,157 | //
// RecallCommandTests.swift
// UPNCalculatorTests
//
// Created by holgermayer on 03.02.20.
// Copyright © 2020 holgermayer. All rights reserved.
//
import XCTest
@testable import UPNCalculator
class RecallCommandTests: XCTestCase {
var engine : UPNEngine!
var registerController : RegisterController!
var display : CalculatorDisplay!
var mockDelegate : DisplayMockDelegate!
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
engine = UPNEngine()
registerController = RegisterController()
registerController.delegate = engine
display = CalculatorDisplay()
mockDelegate = DisplayMockDelegate()
display.delegate = mockDelegate
}
func testRecall(){
let testObject = RecallCommand(calculatorEngine: engine, display: display, registerController: registerController)
let result = testObject.execute()
XCTAssertTrue(registerController.registerAccess == .Recall)
XCTAssertTrue(result == .StoreRecall)
}
}
| 28.925 | 122 | 0.674157 |
1ce0c9a1d4c35c582e7994d7069d68a0fcd6b584 | 3,768 | //
// MemoryGame.swift
// Memorize
//
// Created by Luciano Nunes de Siqueira on 17/05/21.
//
import Foundation
struct MemoryGame<CardContent> where CardContent: Equatable{
private(set) var cards: Array<Card>
private var indexOfTheOneAndOnlyFaceUpCard: Int?{
get { cards.indices.filter { cards[$0].isFaceUp }.only }
set {
for index in cards.indices {
cards[index].isFaceUp = index == newValue
}
}
}
mutating func choose(card: Card){
print("card chosen: \(card) ")
if let chosenIndex = cards.firstIndex(matching: card), !cards[chosenIndex].isFaceUp, !cards[chosenIndex].isMatched{
if let potencialMatchIndex = indexOfTheOneAndOnlyFaceUpCard{
if cards[chosenIndex].content == cards[potencialMatchIndex].content {
cards[chosenIndex].isMatched = true
cards[potencialMatchIndex].isMatched = true
}
cards[chosenIndex].isFaceUp = true
} else {
indexOfTheOneAndOnlyFaceUpCard = chosenIndex
}
}
}
init(numberOfPairsOfCards: Int, cardContentFactory: (Int) -> CardContent) {
cards = Array<Card>()
for pairIndex in 0..<numberOfPairsOfCards{
let content = cardContentFactory(pairIndex)
cards.append(Card(content: content, id: pairIndex*2))
cards.append(Card(content: content, id: pairIndex*2+1))
}
cards.shuffle()
}
struct Card: Identifiable {
var isFaceUp: Bool = false {
didSet {
if isFaceUp {
startUsingBonusTime()
}
else
{
stopUsingBonusTime()
}
}
}
var isMatched: Bool = false {
didSet {
stopUsingBonusTime()
}
}
var content: CardContent
var id: Int
//var content: CardContent
//var id: Int
var bonusTimeLimit: TimeInterval = 6
private var faceUpTime: TimeInterval {
if let lastFaceUpDate = self.lastFaceUpDate {
return pastFaceUpTime + Date().timeIntervalSince(lastFaceUpDate)
} else {
return pastFaceUpTime
}
}
var lastFaceUpDate: Date?
var pastFaceUpTime: TimeInterval = 0
var bonusTimeRemaining: TimeInterval {
max(0, bonusTimeLimit - faceUpTime)
}
var bonusRemaining: Double {
(bonusTimeLimit > 0 && bonusTimeRemaining > 0) ? bonusTimeRemaining/bonusTimeLimit : 0
}
var hasEarnedBonus: Bool {
isMatched && bonusTimeRemaining > 0
}
var isConsumingBonusTime: Bool {
isFaceUp && !isMatched && bonusTimeRemaining > 0
}
private mutating func startUsingBonusTime() {
if isConsumingBonusTime, lastFaceUpDate == nil {
lastFaceUpDate = Date()
}
}
private mutating func stopUsingBonusTime() {
pastFaceUpTime = faceUpTime
lastFaceUpDate = nil
}
}
}
| 31.4 | 123 | 0.474522 |
9174736a565eab0946773dbcfc1da72521a49185 | 24,718 | //
// ViewController.swift
// Filterer
//
// Created by Emmanuel Lopez Guerrero on 5/9/20.
// Copyright © 2020 Emmanuel Lopez Guerrero. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var redFlag:Int = 0, blueFlag:Int=0, greenFlag:Int=0, yellowFlag:Int=0, darkFlag:Int=0
var OriginalImage: UIImage?
var filteredImage: UIImage?
@IBOutlet var secundaryMenu: UIView!
@IBOutlet var sliderMenu: UIView!
@IBOutlet var filterSlider: UISlider!
@IBOutlet var buttonMenu: UIView!
@IBOutlet var imageView: UIImageView!
@IBOutlet var imageViewfiltered: UIImageView!
@IBOutlet var EditButton: UIButton!
@IBOutlet var filterButton: UIButton!
@IBOutlet var compareButton: UIButton!
@IBOutlet var OriginalImageLabel: UILabel!
@IBAction func onSlider(_ sender: UISlider) {
let sliderColor:Int = Int(roundf(filterSlider.value))
filterSlider.value = roundf(filterSlider.value)
let images = imageView.image
let myRGBA = RGBAImage(image: OriginalImage!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = OriginalImage
if (redFlag == 1){
switch sliderColor {
case 1:
filteredImage = PhotoFilter.FilterImageContrast(Level: LevelFilter.low, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 2:
filteredImage = PhotoFilter.FilterImageContrast(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 3:
filteredImage = PhotoFilter.FilterImageContrast(Level: LevelFilter.high, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
default:
filteredImage = PhotoFilter.FilterImageContrast(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
}
}
if (blueFlag == 1){
switch sliderColor {
case 1:
filteredImage = PhotoFilter.FilterImageTemperatureCold(Level: LevelFilter.low, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 2:
filteredImage = PhotoFilter.FilterImageTemperatureCold(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 3:
filteredImage = PhotoFilter.FilterImageTemperatureCold(Level: LevelFilter.high, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
default:
filteredImage = PhotoFilter.FilterImageTemperatureCold(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
}
}
if (greenFlag == 1){
switch sliderColor {
case 1:
filteredImage = PhotoFilter.FilterImageTemperatureHot(Level: LevelFilter.low, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 2:
filteredImage = PhotoFilter.FilterImageTemperatureHot(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 3:
filteredImage = PhotoFilter.FilterImageTemperatureHot(Level: LevelFilter.high, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
default:
filteredImage = PhotoFilter.FilterImageTemperatureHot(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
}
}
if (yellowFlag == 1){
switch sliderColor {
case 1:
filteredImage = PhotoFilter.FilterImageBright(Level: LevelFilter.low, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 2:
filteredImage = PhotoFilter.FilterImageBright(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 3:
filteredImage = PhotoFilter.FilterImageBright(Level: LevelFilter.high, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
default:
filteredImage = PhotoFilter.FilterImageBright(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
}
}
if (darkFlag == 1){
switch sliderColor {
case 1:
filteredImage = PhotoFilter.FilterImageDark(Level: LevelFilter.low, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 2:
filteredImage = PhotoFilter.FilterImageDark(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
case 3:
filteredImage = PhotoFilter.FilterImageDark(Level: LevelFilter.high, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
default:
filteredImage = PhotoFilter.FilterImageDark(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
}
}
}
@IBAction func onFilter(_ sender: UIButton) {
if (sender.isSelected){
hiddenMenu()
sender.isSelected = false
}else{
showSecondaryMenu()
hiddenSliderMenu()
EditButton.isSelected = false
sender.isSelected = true
}
}
@IBAction func onEdit(_ sender: UIButton) {
if (sender.isSelected){
hiddenMenu()
hiddenSliderMenu()
sender.isSelected = false
}else{
hiddenMenu()
showSliderMenu()
filterButton.isSelected = false
sender.isSelected = true
}
}
func showSliderMenu(){
view.addSubview(sliderMenu)
sliderMenu.translatesAutoresizingMaskIntoConstraints = false
sliderMenu.backgroundColor = UIColor.white.withAlphaComponent(0.5)
let bottomConstraint = sliderMenu.bottomAnchor.constraint(equalTo: buttonMenu.topAnchor)
let leftConstraint = sliderMenu.leftAnchor.constraint(equalTo: view.leftAnchor)
let rightConstraint = sliderMenu.rightAnchor.constraint(equalTo: view.rightAnchor)
let heightConstraint = sliderMenu.heightAnchor.constraint(equalToConstant: 44)
NSLayoutConstraint.activate([bottomConstraint, leftConstraint, rightConstraint, heightConstraint])
view.layoutIfNeeded()
self.sliderMenu.alpha = 0
UIView.animate(withDuration: 0.4){
self.sliderMenu.alpha = 1.0
}
}
func hiddenSliderMenu(){
UIView.animate(withDuration: 0.4, animations: {
self.secundaryMenu.alpha = 1.0
}){completed in
if completed == true{
self.sliderMenu.removeFromSuperview()
}
}
}
@IBAction func onNewPhoto(_ sender: Any) {
let actionSheet = UIAlertController(title: "New photo", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title:"Camera", style: .default, handler: {action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Album", style: .default, handler: {action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func showCamera(){
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
present(cameraPicker, animated: true, completion: nil)
}
func showAlbum(){
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .photoLibrary
present(cameraPicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
imageView.image = image
OriginalImage = image
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
dismiss(animated: true, completion: nil)
}
func hiddenMenu(){
UIView.animate(withDuration: 0.4, animations: {
self.secundaryMenu.alpha = 1.0
}){completed in
if completed == true{
self.secundaryMenu.removeFromSuperview()
}
}
}
func showUIViewFiltered(){
UIView.animate(withDuration: 0.4){
self.imageView.alpha = 0
self.imageViewfiltered.alpha = 1
}
}
func hiddenUIViewFiltered(){
UIView.animate(withDuration: 0.4){
self.imageView.alpha = 1
self.imageViewfiltered.alpha = 0
}
}
func showSecondaryMenu(){
view.addSubview(secundaryMenu)
let bottomConstraint = secundaryMenu.bottomAnchor.constraint(equalTo: buttonMenu.topAnchor)
let leftConstraint = secundaryMenu.leftAnchor.constraint(equalTo: view.leftAnchor)
let rightConstraint = secundaryMenu.rightAnchor.constraint(equalTo: view.rightAnchor)
let heightConstraint = secundaryMenu.heightAnchor.constraint(equalToConstant: 54)
NSLayoutConstraint.activate([bottomConstraint, leftConstraint, rightConstraint, heightConstraint])
view.layoutIfNeeded()
self.secundaryMenu.alpha = 0
UIView.animate(withDuration: 0.4){
self.secundaryMenu.alpha = 1.0
}
}
@objc func tapGestures(sender: UILongPressGestureRecognizer) {
if sender.state == .began{
imageView.image = OriginalImage
OriginalImageLabel.isHidden = false
}
if sender.state == .ended{
imageView.image = filteredImage
OriginalImageLabel.isHidden = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
imageViewfiltered.alpha = 0
imageView.isUserInteractionEnabled = true
imageViewfiltered.isUserInteractionEnabled = true
OriginalImageLabel.isHidden = true
let tapGestures = UILongPressGestureRecognizer(target: self, action: #selector(self.tapGestures))
imageView.addGestureRecognizer(tapGestures)
compareButton.isEnabled = false
EditButton.isEnabled = false
OriginalImage = imageView.image
secundaryMenu.translatesAutoresizingMaskIntoConstraints = false
secundaryMenu.backgroundColor = UIColor.white.withAlphaComponent(0.5)
}
/*Compare button*/
@IBAction func onCompare(_ sender: UIButton) {
if (sender.isSelected){
showUIViewFiltered()
imageView.image = OriginalImage
sender.isSelected = false
}else{
hiddenUIViewFiltered()
imageViewfiltered.image = filteredImage
sender.isSelected = true
}
}
/*SecondaryDarkFilter*/
@IBAction func onSecondaryPurpleFilter(_ sender: UIButton) {
let images = imageView.image
let myRGBA = RGBAImage(image: images!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = PhotoFilter.FilterImageDark(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
compareButton.isEnabled = true
EditButton.isEnabled = true
darkFlag = 1
}
/*SecondaryYellowFilter*/
@IBAction func onSecondaryYellowFilter(_ sender: UIButton) {
let images = imageView.image
let myRGBA = RGBAImage(image: images!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = PhotoFilter.FilterImageBright(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
compareButton.isEnabled = true
EditButton.isEnabled = true
yellowFlag = 1
}
/*SecondaryBlueFilter*/
@IBAction func onSecondaryBlueFilter(_ sender: UIButton) {
let images = imageView.image
let myRGBA = RGBAImage(image: images!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = PhotoFilter.FilterImageTemperatureCold(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
compareButton.isEnabled = true
EditButton.isEnabled = true
blueFlag = 1
}
/*SecondaryGreenFilter*/
@IBAction func onSecondaryGreenFilter(_ sender: UIButton) {
let images = imageView.image
let myRGBA = RGBAImage(image: images!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = PhotoFilter.FilterImageTemperatureHot(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
compareButton.isEnabled = true
EditButton.isEnabled = true
greenFlag = 1
}
/*SecondaryRedFilter*/
@IBAction func onSecondaryRedFilter(_ sender: UIButton) {
let images = imageView.image
let myRGBA = RGBAImage(image: images!)
let PhotoFilter = Photo()
let ColorDictionary = PhotoFilter.ReadColors(imageParam: images!)
filteredImage = PhotoFilter.FilterImageContrast(Level: LevelFilter.medium, avgColor: ColorDictionary, myRGBA: myRGBA!)
imageView.image = filteredImage
compareButton.isEnabled = true
EditButton.isEnabled = true
redFlag = 1
}
/*share*/
@IBAction func onShare(_ sender: AnyObject) {
let activityController = UIActivityViewController(activityItems:["Check out my first app", imageView.image!], applicationActivities: nil)
present(activityController, animated: true, completion: nil)
}
}
protocol FilterType {
func FilterImageContrast(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage
func FilterImageBright(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage
func FilterImageDark(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage
func FilterImageTemperatureHot(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage
func FilterImageTemperatureCold(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage
}
class Filters:FilterType {
func FilterImageBright(Level: LevelFilter, avgColor: Dictionary<String, Int>, myRGBA: RGBAImage) -> UIImage {
let avgRed = avgColor["Red"]
let avgBlue = avgColor["Blue"]
let avgGreen = avgColor["Green"]
var myRGBA = myRGBA
for y in 0..<myRGBA.height{
for x in 0..<myRGBA.width{
let index = y * myRGBA.width + x
var pixel = myRGBA.pixels[index]
var BlueDiff = Int(pixel.blue) - avgBlue!
var RedDiff = Int(pixel.red) - avgRed!
var GreenDiff = Int(pixel.green) - avgGreen!
if(RedDiff>0 && GreenDiff>0 && BlueDiff>0)
{
switch Level.rawValue{
case "high":
RedDiff = RedDiff+15
GreenDiff = GreenDiff+15
BlueDiff = BlueDiff+15
case "medium":
RedDiff = RedDiff+12
GreenDiff = GreenDiff+12
BlueDiff = BlueDiff+12
case "low":
RedDiff = RedDiff+7
GreenDiff = GreenDiff+7
BlueDiff = BlueDiff+7
default:
RedDiff = RedDiff+12
GreenDiff = GreenDiff+12
BlueDiff = BlueDiff+12
}
pixel.red = UInt8( max(0,min(255,avgRed! + RedDiff)))
pixel.blue = UInt8( max(0,min(255,avgBlue! + BlueDiff)))
pixel.green = UInt8( max(0,min(255,avgGreen! + GreenDiff)))
myRGBA.pixels[index] = pixel
}
}
}
return (myRGBA.toUIImage())!
}
func FilterImageDark(Level: LevelFilter, avgColor: Dictionary<String, Int>, myRGBA: RGBAImage) -> UIImage {
let avgRed = avgColor["Red"]
let avgBlue = avgColor["Blue"]
let avgGreen = avgColor["Green"]
var myRGBA = myRGBA
for y in 0..<myRGBA.height{
for x in 0..<myRGBA.width{
let index = y * myRGBA.width + x
var pixel = myRGBA.pixels[index]
var BlueDiff = Int(pixel.blue) - avgBlue!
var RedDiff = Int(pixel.red) - avgRed!
var GreenDiff = Int(pixel.green) - avgGreen!
if(RedDiff>0 && GreenDiff>0 && BlueDiff>0)
{
switch Level.rawValue{
case "high":
RedDiff = RedDiff-15
GreenDiff = GreenDiff-15
BlueDiff = BlueDiff-15
case "medium":
RedDiff = RedDiff-12
GreenDiff = GreenDiff-12
BlueDiff = BlueDiff-12
case "low":
RedDiff = RedDiff-7
GreenDiff = GreenDiff-7
BlueDiff = BlueDiff-7
default:
RedDiff = RedDiff-12
GreenDiff = GreenDiff-12
BlueDiff = BlueDiff-12
}
pixel.red = UInt8( max(0,min(255,avgRed! + RedDiff)))
pixel.blue = UInt8( max(0,min(255,avgBlue! + BlueDiff)))
pixel.green = UInt8( max(0,min(255,avgGreen! + GreenDiff)))
myRGBA.pixels[index] = pixel
}
}
}
return (myRGBA.toUIImage())!
}
func FilterImageTemperatureHot(Level: LevelFilter, avgColor: Dictionary<String, Int>, myRGBA: RGBAImage) -> UIImage {
let avgRed = avgColor["Red"]
let avgGreen = avgColor["Green"]
var myRGBA = myRGBA
for y in 0..<myRGBA.height{
for x in 0..<myRGBA.width{
let index = y * myRGBA.width + x
var pixel = myRGBA.pixels[index]
var RedDiff = Int(pixel.red) - avgRed!
var GreenDiff = Int(pixel.green) - avgGreen!
if(RedDiff>0 && GreenDiff>0)
{
switch Level.rawValue{
case "high":
RedDiff = RedDiff+20
GreenDiff = GreenDiff+20
case "medium":
RedDiff = RedDiff+15
GreenDiff = GreenDiff+15
case "low":
RedDiff = RedDiff+10
GreenDiff = GreenDiff+10
default:
RedDiff = RedDiff+10
GreenDiff = GreenDiff+10
}
pixel.red = UInt8( max(0,min(255,avgRed! + RedDiff)))
pixel.green = UInt8( max(0,min(255,avgGreen! + GreenDiff)))
myRGBA.pixels[index] = pixel
}
}
}
return (myRGBA.toUIImage())!
}
func FilterImageTemperatureCold(Level: LevelFilter, avgColor: Dictionary<String, Int>, myRGBA: RGBAImage) -> UIImage {
var myRGBA = myRGBA
let avgRed = avgColor["Red"]
let avgBlue = avgColor["Blue"]
for y in 0..<myRGBA.height{
for x in 0..<myRGBA.width{
let index = y * myRGBA.width + x
var pixel = myRGBA.pixels[index]
var RedDiff = Int(pixel.red) - avgRed!
var BlueDiff = Int(pixel.blue) - avgBlue!
if(RedDiff>0 && BlueDiff>0)
{
switch Level.rawValue{
case "high":
RedDiff = RedDiff+20
BlueDiff = BlueDiff+30
case "medium":
RedDiff = RedDiff+10
BlueDiff = BlueDiff+20
case "low":
RedDiff = RedDiff+5
BlueDiff = BlueDiff+10
default:
RedDiff = RedDiff+5
BlueDiff = BlueDiff+10
}
pixel.red = UInt8( max(0,min(255,avgRed! + RedDiff)))
pixel.blue = UInt8( max(0,min(255,avgBlue! + BlueDiff)))
myRGBA.pixels[index] = pixel
}
}
}
return (myRGBA.toUIImage())!
}
func FilterImageContrast(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage {
let avgRed = avgColor["Red"]
var myRGBA = myRGBA
for y in 0..<myRGBA.height{
for x in 0..<myRGBA.width{
let index = y * myRGBA.width + x
var pixel = myRGBA.pixels[index]
var redDiff = Int(pixel.red) - avgRed!
if(redDiff>0)
{
switch Level.rawValue{
case "high":
redDiff = redDiff+30
case "medium":
redDiff = redDiff+20
case "low":
redDiff = redDiff+10
default:
redDiff = redDiff+10
}
pixel.red = UInt8( max(0,min(255,avgRed! + redDiff)))
myRGBA.pixels[index] = pixel
}
}
}
return (myRGBA.toUIImage())!
}
}
class Photo:Filters{
let images = UIImage(named: "sample")
override init(){
super.init()
_ = self.ReadColors(imageParam: images!)
}
func ReadColors(imageParam: UIImage) -> Dictionary<String,Int>{
var myRGBA = RGBAImage(image: images!)
var ColorDictionary:[String:Int] = [:]
var totalRed = 0, totalGreen = 0, totalBlue = 0, avgRed = 0, avgBlue = 0, avgGreen = 0, count = 0
for y in 0..<myRGBA!.height{
for x in 0..<myRGBA!.width{
let index = y * myRGBA!.width + x
var pixel = myRGBA!.pixels[index]
totalRed += Int(pixel.red)
totalBlue += Int(pixel.blue)
totalGreen += Int(pixel.green)
}
}
count = myRGBA!.width * myRGBA!.height
avgRed = totalBlue/count
avgBlue = totalGreen/count
avgGreen = totalGreen/count
ColorDictionary.updateValue(avgRed, forKey: "Red")
ColorDictionary.updateValue(avgBlue, forKey: "Blue")
ColorDictionary.updateValue(avgGreen, forKey: "Green")
return ColorDictionary
}
}
enum LevelFilter : String{
case low
case medium
case high
}
| 38.86478 | 149 | 0.568007 |
4aab6f5dfb8ea8c47526809eb4819e85e03f3a72 | 2,347 | //
// SearchPreferencesActionCreatorTests.swift
// PlacesFinderTests
//
// Copyright (c) 2019 Justin Peckner
//
// 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 Nimble
import Quick
import SwiftDux
class SearchPreferencesActionCreatorTests: QuickSpec {
// swiftlint:disable implicitly_unwrapped_optional
override func spec() {
describe("setMeasurementSystem()") {
var result: Action!
context("when the arg is .imperial") {
beforeEach {
result = SearchPreferencesActionCreator.setMeasurementSystem(.imperial)
}
it("returns SearchPreferencesAction.setDistance, with a distance of ten miles") {
expect(result as? SearchPreferencesAction) == .setDistance(.imperial(.tenMiles))
}
}
context("when the arg is .metric") {
beforeEach {
result = SearchPreferencesActionCreator.setMeasurementSystem(.metric)
}
it("returns SearchPreferencesAction.setDistance, with a distance of twenty kilometers") {
expect(result as? SearchPreferencesAction) == .setDistance(.metric(.twentyKilometers))
}
}
}
}
}
| 37.253968 | 106 | 0.669791 |
0eedfa8763786037931581fe9a138fc0480d0e92 | 903 | //
// Pin.swift
// meep-app
//
// Created by David Garcia on 29/07/2020.
// Copyright © 2020 David Garcia. All rights reserved.
//
import MapKit
class Pin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var companyZoneId: Int
var pinTintColor: UIColor {
switch companyZoneId {
case 402:
return .red
case 378:
return .blue
case 382:
return .yellow
case 467:
return .purple
case 473:
return .green
case 412:
return .orange
default:
return .clear
}
}
init(title: String, companyZoneId: Int, coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
self.title = title
self.companyZoneId = companyZoneId
super.init()
}
}
| 21 | 81 | 0.554817 |
71c037889399faf91dbf36e058def052f3389651 | 439 | //
// AudioPlayable.swift
//
//
// Created by Alex Kovalov on 23.01.2021.
// Copyright © 2021 . All rights reserved.
//
import Foundation
protocol AudioPlayable {
var currentTime: TimeInterval { get set }
var duration: TimeInterval { get }
var onDidFinishPlaying: ((_ successfully: Bool) -> Void)? { get set }
var isPlaying: Bool { get }
init(contentsOf url: URL)
func play()
func pause()
}
| 19.086957 | 73 | 0.630979 |
6a347d4424a95994c9967d4bf41e81f11598f50d | 6,082 | //
// Track.swift
// Mixpanel
//
// Created by Yarden Eitan on 6/3/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
func += <K, V> (left: inout [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
class Track {
let apiToken: String
let lock: ReadWriteLock
let metadata: SessionMetadata
init(apiToken: String, lock: ReadWriteLock, metadata: SessionMetadata) {
self.apiToken = apiToken
self.lock = lock
self.metadata = metadata
}
func track(event: String?,
properties: Properties? = nil,
eventsQueue: Queue,
timedEvents: InternalProperties,
superProperties: InternalProperties,
distinctId: String,
anonymousId: String?,
userId: String?,
hadPersistedDistinctId: Bool?,
epochInterval: Double) -> (eventsQueque: Queue, timedEvents: InternalProperties, properties: InternalProperties) {
var ev = event
if ev == nil || ev!.isEmpty {
Logger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'")
ev = "mp_event"
}
assertPropertyTypes(properties)
let epochSeconds = Int(round(epochInterval))
let eventStartTime = timedEvents[ev!] as? Double
var p = InternalProperties()
AutomaticProperties.automaticPropertiesLock.read {
p += AutomaticProperties.properties
}
p["token"] = apiToken
p["time"] = epochSeconds
var shadowTimedEvents = timedEvents
if let eventStartTime = eventStartTime {
shadowTimedEvents.removeValue(forKey: ev!)
p["$duration"] = Double(String(format: "%.3f", epochInterval - eventStartTime))
}
p["distinct_id"] = distinctId
if anonymousId != nil {
p["$device_id"] = anonymousId
}
if userId != nil {
p["$user_id"] = userId
}
if hadPersistedDistinctId != nil {
p["$had_persisted_distinct_id"] = hadPersistedDistinctId
}
p += superProperties
if let properties = properties {
p += properties
}
var trackEvent: InternalProperties = ["event": ev!, "properties": p]
metadata.toDict().forEach { (k,v) in trackEvent[k] = v }
var shadowEventsQueue = eventsQueue
Logger.debug(message: "adding event to queue")
Logger.debug(message: trackEvent)
shadowEventsQueue.append(trackEvent)
if shadowEventsQueue.count > QueueConstants.queueSize {
Logger.warn(message: "queue is full, dropping the oldest event from the queue")
Logger.warn(message: shadowEventsQueue.first as Any)
shadowEventsQueue.remove(at: 0)
}
return (shadowEventsQueue, shadowTimedEvents, p)
}
func registerSuperProperties(_ properties: Properties,
superProperties: InternalProperties) -> InternalProperties {
if Mixpanel.mainInstance().hasOptedOutTracking() {
return superProperties
}
var updatedSuperProperties = superProperties
assertPropertyTypes(properties)
updatedSuperProperties += properties
return updatedSuperProperties
}
func registerSuperPropertiesOnce(_ properties: Properties,
superProperties: InternalProperties,
defaultValue: MixpanelType?) -> InternalProperties {
if Mixpanel.mainInstance().hasOptedOutTracking() {
return superProperties
}
var updatedSuperProperties = superProperties
assertPropertyTypes(properties)
_ = properties.map() {
let val = updatedSuperProperties[$0.key]
if val == nil ||
(defaultValue != nil && (val as? NSObject == defaultValue as? NSObject)) {
updatedSuperProperties[$0.key] = $0.value
}
}
return updatedSuperProperties
}
func unregisterSuperProperty(_ propertyName: String,
superProperties: InternalProperties) -> InternalProperties {
var updatedSuperProperties = superProperties
updatedSuperProperties.removeValue(forKey: propertyName)
return updatedSuperProperties
}
func clearSuperProperties(_ superProperties: InternalProperties) -> InternalProperties {
var updatedSuperProperties = superProperties
updatedSuperProperties.removeAll()
return updatedSuperProperties
}
func updateSuperProperty(_ update: (_ superProperties: inout InternalProperties) -> Void, superProperties: inout InternalProperties) {
update(&superProperties)
}
func time(event: String?, timedEvents: InternalProperties, startTime: Double) -> InternalProperties {
if Mixpanel.mainInstance().hasOptedOutTracking() {
return timedEvents
}
var updatedTimedEvents = timedEvents
guard let event = event, !event.isEmpty else {
Logger.error(message: "mixpanel cannot time an empty event")
return updatedTimedEvents
}
updatedTimedEvents[event] = startTime
return updatedTimedEvents
}
func clearTimedEvents(_ timedEvents: InternalProperties) -> InternalProperties {
var updatedTimedEvents = timedEvents
updatedTimedEvents.removeAll()
return updatedTimedEvents
}
func clearTimedEvent(event: String?, timedEvents: InternalProperties) -> InternalProperties {
var updatedTimedEvents = timedEvents
guard let event = event, !event.isEmpty else {
Logger.error(message: "mixpanel cannot clear an empty timed event")
return updatedTimedEvents
}
updatedTimedEvents.removeValue(forKey: event)
return updatedTimedEvents
}
}
| 36.202381 | 138 | 0.619862 |
502abc067ea4d6b5b4f451062a2ebbd0a6d5ee4d | 7,931 | import UIKit
import Combine
import WidgetKit
import KeychainAccess
class MainViewController: UIViewController, UICollectionViewDelegate {
private var cancellables: Set<AnyCancellable> = []
@IBOutlet private var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Int, Status>!
override func viewDidLoad() {
super.viewDidLoad()
let keychain = Keychain(service: "com.kishikawakatsumi.Doorlock", accessGroup: accessGroup);
let cellRegistration = UICollectionView.CellRegistration<DeviceCell, Status>(cellNib: UINib(nibName: "DeviceCell", bundle: nil)) { (cell, indexPath, item) in
cell.deviceID = keychain["deviceID"] ?? "N/A"
cell.status = item.CHSesame2Status
cell.batteryPercentage = item.batteryPercentage
cell.onLockButtonTapped = {
WidgetCenter.shared.getCurrentConfigurations {
if case .success(let widgetInfo) = $0 {
widgetInfo.forEach {
guard let config = $0.configuration as? ConfigurationIntent else { return }
guard let APIKey = config.APIKey, let secretKey = config.secretKey, let deviceID = config.deviceID else { return }
Device.lock(APIKey: APIKey, secretKey: secretKey, deviceID: deviceID)
}
}
}
}
cell.onUnlockButtonTapped = {
WidgetCenter.shared.getCurrentConfigurations {
if case .success(let widgetInfo) = $0 {
widgetInfo.forEach {
guard let config = $0.configuration as? ConfigurationIntent else { return }
guard let APIKey = config.APIKey, let secretKey = config.secretKey, let deviceID = config.deviceID else { return }
Device.unlock(APIKey: APIKey, secretKey: secretKey, deviceID: deviceID)
}
}
}
}
}
var listConfiguration = UICollectionLayoutListConfiguration(appearance: .plain)
listConfiguration.showsSeparators = true
collectionView.collectionViewLayout = UICollectionViewCompositionalLayout.list(using: listConfiguration)
dataSource = UICollectionViewDiffableDataSource<Int, Status>(collectionView: collectionView) { (collectionView, indexPath, item) -> UICollectionViewCell? in
collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
}
refreshStatus()
Timer.publish(every: 2, on: .main, in: .common)
.autoconnect()
.sink { [weak self] _ in
self?.refreshStatus()
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: Notification.Name("DoorlockRequestStartedNotification"))
.receive(on: DispatchQueue.main)
.sink { [weak self] in
guard let userInfo = $0.userInfo as? [String: String], let command = userInfo["command"] else { return }
let viewController = ProgressViewController(text: "\(command.capitalized)ing...")
self?.present(viewController, animated: true)
}
.store(in: &cancellables)
NotificationCenter.default.publisher(for: Notification.Name("DoorlockResponseReceivedNotification"))
.receive(on: DispatchQueue.main)
.sink { [weak self] (notification) in
self?.dismiss(animated: true, completion: { [weak self] in
guard let userInfo = notification.userInfo else { return }
if let response = userInfo["response"] as? HTTPURLResponse {
if response.statusCode == 200 {
return
} else if let data = userInfo["data"] as? Data,
let errorResponse = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: String],
let error = errorResponse["error"] {
let alert = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
alert.dismiss(animated: true)
})
self?.present(alert, animated: true)
return
}
} else if let error = userInfo["error"] as? Error {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
alert.dismiss(animated: true)
})
self?.present(alert, animated: true)
return
}
let alert = UIAlertController(title: "Error", message: "Unknown error occurred.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
alert.dismiss(animated: true)
})
self?.present(alert, animated: true)
})
}
.store(in: &cancellables)
}
private func refreshStatus() {
let keychain = Keychain(service: "com.kishikawakatsumi.Doorlock", accessGroup: accessGroup)
guard let APIKey = keychain["APIKey"] else { return }
guard let deviceID = keychain["deviceID"] else { return }
let session = URLSession.shared
guard let endpoint = URL(string: "https://app.candyhouse.co/api/sesame2/\(deviceID)") else { return }
var request = URLRequest(url: endpoint)
request.httpMethod = "GET"
request.addValue(APIKey, forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request, completionHandler: { [weak self] (data, response, error) -> Void in
guard let self = self else { return }
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if let error = error {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
alert.dismiss(animated: true)
})
self.present(alert, animated: true)
return
}
guard let data = data else { return }
guard let status = try? JSONDecoder().decode(Status.self, from: data) else {
if let errorResponse = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: String],
let error = errorResponse["error"] {
let alert = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
alert.dismiss(animated: true)
})
self.present(alert, animated: true)
}
return
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Status>()
snapshot.appendSections([0])
snapshot.appendItems([status])
self.dataSource.apply(snapshot)
}
})
task.resume()
}
}
| 50.196203 | 165 | 0.556802 |
564b91b154ad7e82614c6285a364827f44c37e2e | 1,190 | //
// ViewController.swift
// FirstProject
//
// Created by Eslam faisal on 9/17/19.
// Copyright © 2019 com.eslam. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var randomDiceIndex1 : Int = 0
var randomDiceIndex2 : Int = 0
@IBOutlet weak var firtBall: UIImageView!
@IBOutlet weak var secondBall: UIImageView!
let diceeImages = ["dice1","dice2","dice3","dice4","dice5","dice6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateImagesRundomly()
}
@IBAction func actinBtn(_ sender: UIButton) {
updateImagesRundomly()
}
func updateImagesRundomly() {
randomDiceIndex1 = Int(arc4random_uniform(6))
randomDiceIndex2 = Int(arc4random_uniform(6))
firtBall.image = UIImage(named: diceeImages[randomDiceIndex1])
secondBall.image = UIImage(named: diceeImages[randomDiceIndex2])
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
print(randomDiceIndex1,randomDiceIndex2)
}
}
| 23.333333 | 85 | 0.641176 |
cc295f4de785ba506eda0e350b6a03cd94863696 | 4,744 | /**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
import CardKit
import DroneCardKit
class StandardInputCell: CardDetailTableViewCell, CardDetailInputCell {
@IBOutlet weak var input: UITextField?
var type: CardDetailTableViewController.CardDetailTypes?
var inputSlot: InputSlot?
var actionCard: ActionCard?
override func awakeFromNib() {
super.awakeFromNib()
input?.keyboardType = .numberPad
}
func setupCell(card: ActionCard, indexPath: IndexPath) {
self.actionCard = card
if let slot = inputSlot {
mainLabel?.text = "\(slot.descriptor.inputDescription)"
}
//TODO: set this based on input type
input?.keyboardType = .numberPad
input?.addTarget(self, action: Selector(("inputTextChanged")), for: .editingChanged)
input?.text = getSelectedInputOption()
}
//swiftlint:disable:next cyclomatic_complexity
func getSelectedInputOption() -> String {
guard let card = self.actionCard,
let inputSlot = self.inputSlot else {
return ""
}
let inputTypeString = inputSlot.descriptor.inputType
var stringVal = ""
switch inputTypeString {
case String(describing: DCKRelativeAltitude.self):
guard let inputTypeObj: DCKRelativeAltitude = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj.metersAboveGroundAtTakeoff)
case String(describing: DCKDistance.self):
guard let inputTypeObj: DCKDistance = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj.meters)
case String(describing: DCKSpeed.self):
guard let inputTypeObj: DCKSpeed = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj.metersPerSecond)
case String(describing: DCKAngularVelocity.self):
guard let inputTypeObj: DCKAngularVelocity = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj.degreesPerSecond)
case String(describing: DCKAngle.self):
guard let inputTypeObj: DCKAngle = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj.degrees)
case String(describing: Double.self):
guard let inputTypeObj: Double = card.value(of: inputSlot) else { break }
stringVal = String(inputTypeObj)
default:
break
}
return stringVal
}
func inputTextChanged() {
guard let inputSlot = self.inputSlot,
let inputValueString = input?.text,
let inputValue = Double(inputValueString) else {
return
}
let inputTypeString = inputSlot.descriptor.inputType
var inputCard: InputCard = inputSlot.descriptor.makeCard()
do {
switch inputTypeString {
case String(describing: DCKRelativeAltitude.self):
inputCard = try inputCard.bound(withValue: DCKRelativeAltitude(metersAboveGroundAtTakeoff: inputValue))
case String(describing: DCKDistance.self):
inputCard = try inputCard.bound(withValue: DCKDistance(meters: inputValue))
case String(describing: DCKSpeed.self):
inputCard = try inputCard.bound(withValue: DCKSpeed(metersPerSecond: inputValue))
case String(describing: DCKAngularVelocity.self):
inputCard = try inputCard.bound(withValue: DCKAngularVelocity(degreesPerSecond: inputValue))
case String(describing: DCKAngle.self):
inputCard = try inputCard.bound(withValue: DCKAngle(degrees: inputValue))
case String(describing: Double.self):
inputCard = try inputCard.bound(withValue: inputValue)
default:
break
}
try actionCard?.bind(with: inputCard, in: inputSlot)
} catch {
print("error \(error)")
}
}
}
| 38.258065 | 119 | 0.637015 |
d99e160b6027595f9c8eda117f1bb99cbc7534c5 | 2,194 | //
// SystemExtensions.swift
//
// Copyright © 2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
//FIXME: code smell
public func delay(_ delay: Double, _ closure:@escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
public extension NotificationCenter {
/// Posts a notification on the deffault center on the main thread with the specified paramters
/// - Parameters:
/// - name: the name of the notification to post
/// - object: the object related to the notification
/// - userInfo: Dictionary of parameters
func postNotificationNameOnMainThread(_ name: NSNotification.Name, object: AnyObject, userInfo: [AnyHashable: Any]? = nil) {
if !Thread.isMainThread {
postAsyncNotificationNameOnMainThread(name, object: object, userInfo: userInfo)
} else {
post(name: name, object: object, userInfo: userInfo)
}
}
/// Posts a notification on the deffault center aysnchronously on the main thread with the specified paramters
/// - Parameters:
/// - name: the name of the notification to post
/// - object: the object related to the notification
/// - userInfo: Dictionary of parameters
func postAsyncNotificationNameOnMainThread(_ name: Notification.Name, object: AnyObject, userInfo: [AnyHashable: Any]?=nil) {
DispatchQueue.main.async(execute: {
self.post(name: name, object: object, userInfo: userInfo)
})
}
}
public extension NSRange {
/// Converts to a Swift String range
/// - Parameter str: the string this range applies to
/// - Returns: a swift range that matdches self in passed in string
func toStringRange(_ str: String) -> Range<String.Index>? {
guard str.count >= length - location && location < str.count else { return nil }
let fromIdx = str.index(str.startIndex, offsetBy: self.location)
guard let toIdx = str.index(fromIdx, offsetBy: self.length, limitedBy: str.endIndex) else { return nil }
return fromIdx..<toIdx
}
}
//swiftlint:disable:next identifier_name
public func MaxNSRangeIndex(_ range: NSRange) -> Int {
return range.location + range.length - 1
}
| 39.178571 | 126 | 0.729262 |
2122a41ef14ea80f6af654fd417b2a9790e5ec8e | 813 | //
// WeatherRequestResponse.swift
// SwiftNetworkAgent
//
// Created by 周际航 on 2017/8/9.
// Copyright © 2017年 com.zjh. All rights reserved.
//
import Foundation
import ObjectMapper
class WeatherRequestResponse: Mappable {
var air: [String: Any] = [:]
var alarm: [String: Any] = [:]
var forecast: [String: Any] = [:]
var observe: [String: Any] = [:]
required init?(map: Map) {
guard map.JSON["air"] != nil else {return nil}
guard map.JSON["alarm"] != nil else {return nil}
guard map.JSON["forecast"] != nil else {return nil}
guard map.JSON["observe"] != nil else {return nil}
}
func mapping(map: Map) {
air <- map["air"]
alarm <- map["alarm"]
forecast <- map["forecast"]
observe <- map["observe"]
}
}
| 25.40625 | 59 | 0.576876 |
5b045cb18a6883af3585d1491560f5ae6d7fa11a | 2,059 | //
// SettingsViewController.swift
// smartLock
//
// Created by Viktor Rudyk on 5/20/18.
// Copyright © 2018 Oleksandr Verbych. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet private weak var usernameLabel: UILabel!
@IBOutlet private weak var userImageView: UIImageView!
@IBOutlet private weak var shouldCheckLocationSwitch: UISwitch!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
usernameLabel.text = KeyStorage.getUsername()
shouldCheckLocationSwitch.isOn = KeyStorage.shouldCheckLocationBeforeOpening
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
userImageView.layer.cornerRadius = userImageView.bounds.height / 2
userImageView.clipsToBounds = true
}
// MARK: - Private methods
@IBAction private func shouldCheckLocationValueChanged(_ sender: Any) {
let newValue = shouldCheckLocationSwitch.isOn
KeyStorage.shouldCheckLocationBeforeOpening = newValue
if newValue {
LocationManager.instance.startUpdatingLocation()
} else {
LocationManager.instance.stopUpdatingLocation()
}
}
@IBAction private func logOutPressed(_ sender: UIButton) {
KeyStorage.clearUserData()
LocationManager.instance.stopUpdatingLocation()
DispatchQueue.main.async {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
UIApplication.shared.delegate?.window??.rootViewController?.dismiss(animated: false, completion: nil)
UIApplication.shared.keyWindow?.rootViewController = loginViewController
}
}
@IBAction private func closePressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| 35.5 | 113 | 0.699854 |
acfb3862016c9997243b67d11ae29decd642c532 | 1,479 | //
// AppDelegate.swift
// PUSH
//
// Created by Dennis Rudolph on 8/6/20.
// Copyright © 2020 Dennis Rudolph. All rights reserved.
//
import UIKit
import FirebaseCore
import FirebaseDatabase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
// Database.database().isPersistenceEnabled = true
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.073171 | 179 | 0.747803 |
dea58c2fa6fa13c9a1d212187cbfe8c3cc382e40 | 770 | //
// SafariWebExtensionHandler.swift
// Shared (Extension)
//
// Created by Adrien Navratil on 21/06/2022.
//
import SafariServices
import os.log
let SFExtensionMessageKey = "message"
class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
let item = context.inputItems[0] as! NSExtensionItem
let message = item.userInfo?[SFExtensionMessageKey]
os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg)
let response = NSExtensionItem()
response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ]
context.completeRequest(returningItems: [response], completionHandler: nil)
}
}
| 28.518519 | 108 | 0.723377 |
718a621f6aaa49226fac6420de1b67d55c559cba | 1,086 | //
// Card.swift
// BlackJack
//
// Created by Antonio Flores on 10/15/19.
// Copyright © 2019 Alex Paul. All rights reserved.
//
import Foundation
struct Card {
var suit: Suit
var value: Int
var isFaceCard: Bool
var face: FaceCard?
func stringify() -> String {
var cardStr = ""
if self.isFaceCard {
cardStr += self.face?.rawValue ?? "🤣"
} else {
cardStr += self.value.description
}
cardStr += self.suit.rawValue
return cardStr
}
static func newDeck(aceValue: Int) -> [Card] {
var cards = [Card]()
for cardValue in 2..<11 {
for suit in Suit.allCases {
let card = Card(suit: suit, value: cardValue, isFaceCard: false)
cards.append(card)
}
}
for face in FaceCard.allCases {
for suit in Suit.allCases {
let card = Card(suit: suit, value: 10, isFaceCard: true, face: face)
cards.append(card)
}
}
for suit in Suit.allCases {
let card = Card(suit: suit, value: aceValue, isFaceCard: false)
cards.append(card)
}
return cards
}
}
| 22.163265 | 76 | 0.597606 |
38c6ca05b11cc2528739f72ee83218b20063feb3 | 1,256 | //
// TrackingActivator.swift
// background_location_updates
//
// Created by Grab, Georg (415) on 18.06.18.
//
import Foundation
import UIKit
class TrackingActivator {
public static let KEY_DESIRED_ACCURACY: String = "io.gjg.backgroundlocationupdates/desired_accuracy"
public static let USERDEFAULTS_REALM: String = "io.gjg.backgroundlocationupdates"
static func getDefaults() -> UserDefaults {
var defaults = UserDefaults(suiteName: USERDEFAULTS_REALM)
if defaults == nil {
defaults = UserDefaults.standard
}
return defaults!
}
static func persistRequestedAccuracy(requestInterval: Double) {
getDefaults().set(requestInterval, forKey: TrackingActivator.KEY_DESIRED_ACCURACY)
}
static func clearRequestedAccuracy() {
getDefaults().removeObject(forKey: TrackingActivator.KEY_DESIRED_ACCURACY)
}
static func getRequestedAccuracy() -> Double? {
let accuracy = getDefaults().double(forKey: TrackingActivator.KEY_DESIRED_ACCURACY)
if (accuracy == 0) {
return nil
}
return accuracy
}
static func isTrackingActive() -> Bool {
return getRequestedAccuracy() != nil
}
}
| 28.545455 | 104 | 0.673567 |
ab71b8d5c8f289868487cf4365302aa152c30236 | 3,295 | /// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
final class MessagesViewController: UIViewController {
// MARK: - Properties
private let userStories = [
UserStory(username: .swift),
UserStory(username: .android),
UserStory(username: .dog)]
private lazy var miniStoryView = MiniStoryView(userStories: userStories)
// MARK: - Life cycles
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupMiniStoryView()
}
// MARK: - Layouts
private func setupMiniStoryView() {
view.addSubview(miniStoryView)
miniStoryView.backgroundColor = .lightGray
miniStoryView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[miniStoryView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
miniStoryView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor),
miniStoryView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
miniStoryView.heightAnchor.constraint(equalToConstant: 80)]
)
miniStoryView.delegate = self
}
}
// MARK: - MiniStoryViewDelegate
extension MessagesViewController: MiniStoryViewDelegate {
func didSelectUserStory(atIndex index: Int) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
let userStory = self.userStories[index]
let viewController = UserStoryViewController(userStory: userStory)
let navigationController = UINavigationController(
rootViewController: viewController)
navigationController.modalPresentationStyle = .fullScreen
self.present(navigationController, animated: true)
}
}
}
| 43.355263 | 86 | 0.749317 |
750bf30c9ed00b5b195ff7c074283dd2ee0344f4 | 833 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "AnotherHttpClient",
platforms: [
.iOS(.v13),
.macOS(.v10_15)
],
products: [
.library(
name: "AnotherHttpClient",
targets: ["AnotherHttpClient"]
),
],
dependencies: [
.package(
url: "https://github.com/rexcosta/AnotherSwiftCommonLib.git",
.branch("master")
)
],
targets: [
.target(
name: "AnotherHttpClient",
dependencies: ["AnotherSwiftCommonLib"]
),
.testTarget(
name: "AnotherHttpClientTests",
dependencies: ["AnotherHttpClient"]
),
]
)
| 23.8 | 96 | 0.548619 |
d9a6b49d2414b81cdcf74e3037a9af12751e4774 | 6,053 | //
// ChaseMerkleTree.swift
// monster-chase
//
// Created by Pabel Nunez Landestoy on 1/25/19.
// Copyright © 2019 Pocket Network. All rights reserved.
//
import Foundation
import MapKit
import CryptoSwift
struct MatchingMerkleHash {
var left:String
var right:String
var hashIndex:Int
}
public struct ChaseProofSubmission {
var proof:[String]
var answer:String
var order:[Bool]
public init(answer: String, proof: [String], order: [Bool]) {
self.answer = answer
self.proof = proof
self.order = order
}
}
public class ChaseMerkleTree: MerkleTree {
public init(chaseCenter: CLLocation) {
let elements = LocationUtils.allPossiblePoints(center: chaseCenter, diameterMT: 0.02, gpsCoordIncrements: 0.0001).map { (currLocation) -> Data in
if let locData = currLocation.concatenatedMagnitudes().data(using: .utf8) {
return locData
} else {
return Data()
}
}
super.init(elements: elements, hashFunction: { (currElement) -> Data? in
return currElement.sha3(.keccak256)
})
}
// Returns the hex representation of the merkle root
public func getRootHex() -> String {
let rootHex = getRoot().toHexString()
return rootHex.hasPrefix("0x") ? rootHex : "0x" + rootHex
}
// Custom merkle body, returns all the merkle tree layers except the root and the leaves, reversed.
// Format is: each layer separated by -, each node on each layer separated by ,
public func getMerkleBody() -> String {
var layers = getLayers()
layers.removeFirst()
layers.removeLast()
layers = layers.reversed()
let layersStrArr = layers.reduce(into: [String]()) { (result, currLayer) in
let currLayerStr = currLayer.map({ (currNode) -> String in
return currNode.toHexString()
})
result.append(currLayerStr.joined(separator: ","))
}
return layersStrArr.joined(separator: "-")
}
public static func generateChaseProofSubmission(answer: CLLocation, merkleBody: String) -> ChaseProofSubmission? {
// Setup answer points
let optionalConcatenatedPoints = LocationUtils.allPossiblePoints(center: answer, diameterMT: 0.02, gpsCoordIncrements: 0.0001).map { (currPoint) -> Data? in
if let concatenated = currPoint.concatenatedMagnitudes().data(using: .utf8)?.sha3(.keccak256) {
return concatenated
} else {
return nil
}
}
var concatenatedPoints = optionalConcatenatedPoints.reduce(into: [Data]()) { (result, optionalData) in
guard let data = optionalData else {
return
}
result.append(data)
}
concatenatedPoints = concatenatedPoints.sorted(by: { (x, y) -> Bool in
return x.toHexString() < y.toHexString()
})
let merkleLayers = merkleBody.split(separator: "-").map { (currLayer) -> [String] in
return currLayer.components(separatedBy: ",").map({ (currHash) -> String in
return currHash
})
}
var reversedMerkleLayers = [[String]]()
for arrayIndex in 0..<merkleLayers.count {
reversedMerkleLayers.append(merkleLayers[(merkleLayers.count - 1) - arrayIndex])
}
let deepestLevel = merkleLayers[merkleLayers.count - 1]
// Find the matching nodes
var nodeMatches = [MatchingMerkleHash]()
for hash in concatenatedPoints {
for siblingHash in concatenatedPoints {
var elemToCompare: Data = Data()
elemToCompare.append(hash)
elemToCompare.append(siblingHash)
elemToCompare = elemToCompare.sha3(.keccak256)
let elemToCompareStr = elemToCompare.toHexString()
if let deepestLevelIndex = deepestLevel.index(of: elemToCompareStr) {
if deepestLevelIndex >= 0 {
nodeMatches.append(
MatchingMerkleHash.init(
left: hash.toHexString(),
right: siblingHash.toHexString(),
hashIndex: deepestLevelIndex
)
)
}
}
}
}
// Build submission
var submissions = [ChaseProofSubmission]()
if nodeMatches.count > 0 {
for match in nodeMatches {
var order:[Bool] = []
var proof = [String]()
// Create answer
let answer = "0x" + match.left
// Append right as first sibling in the proof
proof.append("0x" + match.right)
// First order will always be false because answer is the lesser node
order.append(false)
// Start going up the tree via this index
var index = match.hashIndex
for layer in reversedMerkleLayers {
let pairIndex = index % 2 == 0 ? index + 1 : index - 1
if pairIndex < layer.count {
let pairNode = "0x" + layer[pairIndex]
let node = "0x" + layer[index]
proof.append(pairNode)
if (node < pairNode) {
order.append(false)
} else {
order.append(true)
}
}
index = (index / 2) | 0
}
submissions.append(ChaseProofSubmission.init(answer: answer, proof: proof, order: order))
}
}
return submissions.first
}
}
| 37.596273 | 164 | 0.536428 |
fe295766068838d869609a6f45398857acf4e1b4 | 1,118 | //
// NSAttributedString+HTML.swift
// Down
//
// Created by Rob Phillips on 6/1/16.
// Copyright © 2016-2019 Down. All rights reserved.
//
#if !os(Linux)
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension NSAttributedString {
/// Instantiates an attributed string with the given HTML string
///
/// - Parameters:
/// - htmlString: An HTML string.
///
/// - Throws:
/// `HTMLDataConversionError` or an instantiation error.
convenience init(htmlString: String) throws {
guard let data = htmlString.data(using: String.Encoding.utf8) else {
throw DownErrors.htmlDataConversionError
}
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue),
]
try self.init(data: data, options: options, documentAttributes: nil)
}
}
#endif // !os(Linux)
| 24.844444 | 83 | 0.588551 |
1118551f78b8509552bbf0caba0c85529f55de4c | 8,886 | import UIKit
let iPhoneChatCardRect = CGRect(x: 10, y: 30, width: 180, height: 215)
enum Myself {
case Include, Exclude
func isIncluded() -> Bool {
switch self {
case .Include:
return true
case .Exclude:
return false
}
}
}
class GroupChatView: UIView {
private var chatRoom: GroupChatRoom!
var chatHeadImageCV: RoundedView!
var titleLabel: UILabel!
var onlineAgo: UILabel!
var memberLabel: UILabel!
var chatHeadImages: [UIImageView] = []
var imageCollectionWidth: CGFloat = 150
convenience init(groupChatRoom: GroupChatRoom) {
self.init(frame: iPhoneChatCardRect)
self.backgroundColor = UIColor.whiteColor()
self.layer.cornerRadius = 2
self.modelInit(groupChatRoom, frame: frame)
self.imageCollectionInit()
self.detailInit()
self.addShadow(UIColor.blackColor(), opacity: 0.1, shadowRadius: 5, shadowOffset: CGSize.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func modelInit(groupChatRoom: GroupChatRoom, frame: CGRect) {
self.chatRoom = groupChatRoom
self.imageCollectionWidth = frame.width * 0.4
}
func imageCollectionInit() {
let imageCollectionRect = CGRect(x: self.bounds.midX - imageCollectionWidth / 2, y: self.bounds.minY + imageCollectionWidth / 4, width: imageCollectionWidth, height: imageCollectionWidth)
chatHeadImageCV = RoundedView(frame: imageCollectionRect)
chatHeadImageCV.clipsToBounds = true
for imageView in populateChatHeadImage() {
self.chatHeadImageCV.addSubview(imageView)
}
self.addSubview(chatHeadImageCV)
chatHeadImageCV.addCircularShadow()
}
func populateChatHeadImage() -> [UIImageView]{
switch chatRoom.personArray.count {
case 1:
return initializeChatHeadWithSelf()
case 2:
return initializeChatHeadWithTwo()
case 3:
return initializeChatHeadWithThree()
case 4:
return initializeChatHeadWithFour(Myself.Include)
default:
return initializeChatHeadWithFour(Myself.Exclude)
}
}
func detailInit() {
self.titleLabel = UILabel(frame: CGRect(x: 10, y: self.chatHeadImageCV.frame.maxY + 10, width: self.frame.width - 20, height: 30))
self.titleLabel.text = self.chatRoom.title
self.titleLabel.textAlignment = .Center
self.titleLabel.font = self.titleLabel.font.fontWithSize(14)
self.addSubview(titleLabel)
self.onlineAgo = UILabel(frame: CGRect(x: 10, y: self.titleLabel.frame.maxY - 10, width: self.frame.width - 20, height: 20))
self.onlineAgo.text = self.chatRoom.lastOnline
self.onlineAgo.textAlignment = .Center
self.onlineAgo.font = self.onlineAgo.font.fontWithSize(11)
self.onlineAgo.textColor = UIColor(red: 70/255, green: 70/255, blue: 70/255, alpha: 1)
self.addSubview(self.onlineAgo)
let line = UIView(frame: CGRect(x: self.onlineAgo.frame.origin.x, y: self.onlineAgo.frame.maxY + 10, width: self.frame.width - 20, height: 1))
line.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
line.layer.cornerRadius = 1
self.addSubview(line)
self.memberLabel = UILabel(frame: CGRect(x: 15, y: line.frame.maxY + 10, width: self.frame.width - 30, height: 30))
self.memberLabel.text = getMemberString(self.chatRoom.personArray)
self.memberLabel.textAlignment = .Center
self.memberLabel.textColor = UIColor(red: 70/255, green: 70/255, blue: 70/255, alpha: 1)
self.memberLabel.font = self.titleLabel.font.fontWithSize(11)
self.addSubview(memberLabel)
}
func getMemberString(personArray: [Person]) -> String {
var resultNames: String = ""
var totalMember = personArray.count
for person in personArray {
if totalMember == personArray.count && person.name != "Bored to death"{
resultNames += person.name
} else {
resultNames += ",\(person.name)"
}
totalMember -= 1
}
return resultNames
}
func initializeChatHeadWithSelf() -> [UIImageView] {
var chatHeadImageViewArray: [UIImageView] = []
let imageView1 = UIImageView(frame: self.chatHeadImageCV.bounds)
imageView1.image = UIImage(named: "emptyChatRoom")
chatHeadImageViewArray.append(imageView1)
return chatHeadImageViewArray
}
func initializeChatHeadWithTwo() -> [UIImageView] {
var chatHeadImageViewArray: [UIImageView] = []
for person in chatRoom.personArray {
if person.name != "Bored to death" { //the other person
let imageView1 = UIImageView(frame: self.chatHeadImageCV.bounds)
imageView1.image = person.image
chatHeadImageViewArray.append(imageView1)
break
}
}
return chatHeadImageViewArray
}
func initializeChatHeadWithThree() -> [UIImageView] {
var chatHeadImageViewArray: [UIImageView] = []
var populatedCount = 0
for person in chatRoom.personArray {
switch populatedCount {
case 0:
let imageView1 = UIImageView(frame: CGRect(x: -self.chatHeadImageCV.bounds.width / 2 - 0.5, y: self.chatHeadImageCV.bounds.minY, width: self.chatHeadImageCV.bounds.width, height: self.chatHeadImageCV.bounds.height))
imageView1.image = person.image
chatHeadImageViewArray.append(imageView1)
case 1:
let imageView2 = UIImageView(frame: CGRect(x: self.chatHeadImageCV.bounds.width / 2 + 0.5, y: self.chatHeadImageCV.bounds.minY, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView2.image = person.image
chatHeadImageViewArray.append(imageView2)
case 2:
let imageView3 = UIImageView(frame: CGRect(x: self.chatHeadImageCV.bounds.width / 2 + 0.5, y: self.chatHeadImageCV.bounds.height / 2 + 0.5, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView3.image = person.image
chatHeadImageViewArray.append(imageView3)
default: break
}
populatedCount += 1
if populatedCount == chatRoom.personArray.count {
break
}
}
return chatHeadImageViewArray
}
func initializeChatHeadWithFour(myself: Myself) -> [UIImageView] {
var chatHeadImageViewArray:[UIImageView] = []
var populatedCount = 0
for person in chatRoom.personArray {
if person.name != "Bored to death" || myself.isIncluded() { //exclude myself
switch populatedCount {
case 0:
let imageView1 = UIImageView(frame: CGRect(x: -0.5, y: -0.5, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView1.image = person.image
chatHeadImageViewArray.append(imageView1)
case 1:
let imageView2 = UIImageView(frame: CGRect(x: self.chatHeadImageCV.bounds.width / 2 + 0.5, y: -0.5, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView2.image = person.image
chatHeadImageViewArray.append(imageView2)
case 2:
let imageView3 = UIImageView(frame: CGRect(x: -0.5, y: self.chatHeadImageCV.bounds.height / 2 + 0.5, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView3.image = person.image
chatHeadImageViewArray.append(imageView3)
case 3:
let imageView4 = UIImageView(frame: CGRect(x: self.chatHeadImageCV.bounds.width / 2 + 0.5, y: self.chatHeadImageCV.bounds.height / 2 + 0.5, width: self.chatHeadImageCV.bounds.width / 2, height: self.chatHeadImageCV.bounds.height / 2))
imageView4.image = person.image
chatHeadImageViewArray.append(imageView4)
default: break
}
populatedCount += 1
if populatedCount == 4 {
break
}
}
}
return chatHeadImageViewArray
}
}
| 43.135922 | 254 | 0.616588 |
d940a3f4179abc813263f929b5eadac124933f30 | 314 | //
// Copyright © 2018 Surf. All rights reserved.
//
import UIKit
/// Describes object that can be presented in view hierarchy
protocol Presentable {
func toPresent() -> UIViewController?
}
extension UIViewController: Presentable {
func toPresent() -> UIViewController? {
return self
}
}
| 16.526316 | 60 | 0.687898 |
29a19b6eedcfa4803c98f5af32b56df006a665c0 | 9,906 | import BucketQueue
import BucketQueueModels
import BucketQueueTestHelpers
import Foundation
import QueueModels
import QueueModelsTestHelpers
import RunnerTestHelpers
import SimulatorPoolTestHelpers
import TestHelpers
import TestHistoryStorage
import TestHistoryTestHelpers
import TestHistoryTracker
import UniqueIdentifierGenerator
import UniqueIdentifierGeneratorTestHelpers
import XCTest
final class TestHistoryTrackerIntegrationTests: XCTestCase {
private let emptyResultsFixtures = TestingResultFixtures()
private let failingWorkerId: WorkerId = "failingWorkerId"
private let notFailingWorkerId: WorkerId = "notFailingWorkerId"
private let fixedDate = Date()
private lazy var workerIdsInWorkingCondition = [failingWorkerId, notFailingWorkerId]
private lazy var bucketIdGenerator = HistoryTrackingUniqueIdentifierGenerator(
delegate: UuidBasedUniqueIdentifierGenerator()
)
private lazy var testHistoryTracker = TestHistoryTrackerImpl(
testHistoryStorage: TestHistoryStorageImpl(),
uniqueIdentifierGenerator: bucketIdGenerator
)
private lazy var oneFailResultsFixtures = TestingResultFixtures()
.addingResult(success: false)
func test___accept___tells_to_accept_failures___when_retrying_is_disabled() throws {
// When
let acceptResult = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: createBucketId(),
numberOfRetries: 0,
workerId: failingWorkerId
)
// Then
XCTAssertEqual(
acceptResult.testEntriesToReenqueue,
[],
"When there is no retries then bucketsToReenqueue is empty"
)
XCTAssertEqual(
acceptResult.testingResult,
oneFailResultsFixtures.testingResult(),
"When there is no retries then testingResult is unchanged"
)
}
func test___accept___tells_to_retry___when_retrying_is_possible() throws {
// When
let acceptResult = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: createBucketId(),
numberOfRetries: 1,
workerId: failingWorkerId
)
// Then
XCTAssertEqual(
acceptResult.testEntriesToReenqueue,
[
TestEntryFixtures.testEntry(),
],
"If test failed once and numberOfRetries > 0 then bucket will be rescheduled"
)
XCTAssertEqual(
acceptResult.testingResult,
emptyResultsFixtures.testingResult(),
"If test failed once and numberOfRetries > 0 then accepted testingResult will not contain results"
)
}
func test___accept___tells_to_accept_failures___when_maximum_numbers_of_attempts_reached() throws {
// Given
let bucketId = createBucketId()
_ = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: bucketId,
numberOfRetries: 1,
workerId: failingWorkerId
)
let newBucketId = createBucketId()
testHistoryTracker.willReenqueuePreviouslyFailedTests(
whichFailedUnderBucketId: bucketId,
underNewBucketIds: [
newBucketId: TestEntryFixtures.testEntry(),
]
)
// When
let acceptResult = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: newBucketId,
numberOfRetries: 1,
workerId: failingWorkerId
)
// Then
XCTAssertEqual(
acceptResult.testEntriesToReenqueue,
[]
)
XCTAssertEqual(
acceptResult.testingResult,
oneFailResultsFixtures.testingResult()
)
}
func test___accept___tells_to_retry___when_runing_same_test_from_other_bucket() throws {
// Given
_ = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: createBucketId(),
numberOfRetries: 1,
workerId: failingWorkerId
)
let secondBucket = BucketFixtures.createBucket(
bucketId: BucketId(value: "secondIdentifier")
)
// When
let acceptResult = try testHistoryTracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: secondBucket.bucketId,
numberOfRetries: 1,
workerId: failingWorkerId
)
// Then
XCTAssertEqual(
acceptResult.testEntriesToReenqueue,
[
TestEntryFixtures.testEntry(),
]
)
XCTAssertEqual(
acceptResult.testingResult,
TestingResultFixtures().testingResult()
)
}
func test___bucketToDequeue___is_not_nil___initially() {
// Given
let queue = [
EnqueuedRunTestsPayload(
bucketId: createBucketId(),
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry()],
numberOfRetries: 1
)
]
// When
let payloadToDequeue = testHistoryTracker.enqueuedPayloadToDequeue(
workerId: failingWorkerId,
queue: queue,
workerIdsInWorkingCondition: workerIdsInWorkingCondition
)
// Then
XCTAssertEqual(payloadToDequeue, queue[0])
}
func test___bucketToDequeue___is_nil___for_failing_worker() throws {
// Given
let bucketId = createBucketId()
let payload = EnqueuedRunTestsPayload(
bucketId: bucketId,
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry()],
numberOfRetries: 0
)
try failOnce(
tracker: testHistoryTracker,
bucketId: bucketId,
workerId: failingWorkerId
)
// When
let payloadToDequeue = testHistoryTracker.enqueuedPayloadToDequeue(
workerId: failingWorkerId,
queue: [
payload,
],
workerIdsInWorkingCondition: workerIdsInWorkingCondition
)
// Then
XCTAssertEqual(payloadToDequeue, nil)
}
func test___bucketToDequeue___is_not_nil___if_there_are_not_yet_failed_buckets_in_queue() throws {
// Given
let bucketId = createBucketId()
let payload = EnqueuedRunTestsPayload(
bucketId: bucketId,
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry()],
numberOfRetries: 0
)
try failOnce(
tracker: testHistoryTracker,
bucketId: bucketId,
workerId: failingWorkerId
)
let notFailedPayload = EnqueuedRunTestsPayload(
bucketId: createBucketId(),
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry(className: "notFailed")],
numberOfRetries: 0
)
// When
let payloadToDequeue = testHistoryTracker.enqueuedPayloadToDequeue(
workerId: failingWorkerId,
queue: [
payload,
notFailedPayload,
],
workerIdsInWorkingCondition: workerIdsInWorkingCondition
)
// Then
XCTAssertEqual(payloadToDequeue, notFailedPayload)
}
func test___bucketToDequeue___is_not_nil___for_not_failing_worker() throws {
// Given
let bucketId = createBucketId()
let payload = EnqueuedRunTestsPayload(
bucketId: bucketId,
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry()],
numberOfRetries: 0
)
try failOnce(
tracker: testHistoryTracker,
bucketId: bucketId,
workerId: failingWorkerId
)
// When
let payloadToDequeue = testHistoryTracker.enqueuedPayloadToDequeue(
workerId: notFailingWorkerId,
queue: [
payload,
],
workerIdsInWorkingCondition: workerIdsInWorkingCondition
)
// Then
XCTAssertEqual(payloadToDequeue, payload)
}
private func failOnce(
tracker: TestHistoryTracker,
bucketId: BucketId,
numberOfRetries: UInt = 0,
workerId: WorkerId
) throws {
_ = tracker.enqueuedPayloadToDequeue(
workerId: workerId,
queue: [
EnqueuedRunTestsPayload(
bucketId: bucketId,
testDestination: TestDestinationFixtures.testDestination,
testEntries: [TestEntryFixtures.testEntry()],
numberOfRetries: numberOfRetries
),
],
workerIdsInWorkingCondition: workerIdsInWorkingCondition
)
_ = try tracker.accept(
testingResult: oneFailResultsFixtures.testingResult(),
bucketId: bucketId,
numberOfRetries: numberOfRetries,
workerId: workerId
)
}
private func createBucketId() -> BucketId {
BucketId(value: bucketIdGenerator.generate())
}
}
| 32.267101 | 110 | 0.610943 |
2152e5786ba9080b490653715affea9556ea6edc | 1,055 | //
// FaceDetailView.swift
// AmplifyPredictionsSampleApp
//
// Created by Stone, Nicki on 11/22/19.
// Copyright © 2019 AWS. All rights reserved.
//
import SwiftUI
struct EntityDetailView: View {
var incomingImage: UIImage
var entity: IdentifiedEntity
var body: some View {
ZStack {
Image(uiImage: incomingImage)
.resizable()
.scaledToFit()
.overlay(
GeometryReader { geometry in
Rectangle()
.path(in: CGRect(
x: self.entity.boundingBox.minX * geometry.size.width,
y: self.entity.boundingBox.minY * geometry.size.height,
width: self.entity.boundingBox.width * geometry.size.width,
height: self.entity.boundingBox.height * geometry.size.height))
.stroke(Color.red, lineWidth: 2.0)
}
)
}
}
}
| 30.142857 | 95 | 0.494787 |
718c5717051b9e3dab7f550c2224a2f62358f4be | 1,185 | import XCTest
import MapboxMaps
import CoreLocation
internal class ExampleIntegrationTest: MapViewIntegrationTestCase {
internal func testBaseClass() throws {
// Do nothing
}
internal func testWaitForIdle() throws {
guard
let mapView = mapView,
let style = style else {
XCTFail("There should be valid MapView and Style objects created by setUp.")
return
}
let expectation = XCTestExpectation(description: "Wait for map to idle")
expectation.expectedFulfillmentCount = 2
style.uri = .streets
mapView.centerCoordinate = CLLocationCoordinate2D(latitude: 42.0, longitude: -71.0)
mapView.zoom = 8.0
didFinishLoadingStyle = { _ in
expectation.fulfill()
}
didBecomeIdle = { _ in
// if let snapshot = mapView.snapshot() {
// let attachment = XCTAttachment(image: snapshot)
// self.add(attachment)
//
// // TODO: Compare images...
// //
// }
expectation.fulfill()
}
wait(for: [expectation], timeout: 5.0)
}
}
| 25.212766 | 91 | 0.57384 |
6943ec3729ad284375a310dd433a97116a155695 | 962 | //
// jitterTests.swift
// jitterTests
//
// Created by BlueYang on 2017/3/4.
// Copyright © 2017年 BlueYang. All rights reserved.
//
import XCTest
@testable import jitter
class jitterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.628898 |
2ffe32d151f574c31b8be07f9a79dbc623dcea6a | 1,571 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//798. Smallest Rotation with Highest Score
// Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]. Afterward, any entries that are less than or equal to their index are worth 1 point.
//For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
//Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive. If there are multiple answers, return the smallest such index K.
//Example 1:
//Input: [2, 3, 1, 4, 0]
//Output: 3
//Explanation:
//Scores for each K are listed below:
//K = 0, A = [2,3,1,4,0], score 2
//K = 1, A = [3,1,4,0,2], score 3
//K = 2, A = [1,4,0,2,3], score 3
//K = 3, A = [4,0,2,3,1], score 4
//K = 4, A = [0,2,3,1,4], score 3
//So we should choose K = 3, which has the highest score.
// Example 2:
//Input: [1, 3, 0, 2, 4]
//Output: 0
//Explanation: A will always have 3 points no matter how it shifts.
//So we will choose the smallest K, which is 0.
//Note:
//A will have length at most 20000.
//A[i] will be in the range [0, A.length].
//class Solution {
// func bestRotation(_ A: [Int]) -> Int {
// }
//}
// Time Is Money | 46.205882 | 246 | 0.633355 |
f518e9a430eb75f5d229533de1feac13f76de488 | 762 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-executable %s -g -o %t/extensions -emit-module
// RUN: sed -ne '/\/\/ *DEMANGLE: /s/\/\/ *DEMANGLE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test %t/extensions -type-from-mangled=%t/input | %FileCheck %s
struct Concrete {}
extension Concrete {
struct Nested {}
}
struct Generic<T> {}
protocol Proto {}
extension Generic where T : Proto {
struct Nested1 {}
}
extension Generic where T == Int {
struct Nested2 {}
}
// DEMANGLE: $s10extensions8ConcreteV6NestedVD
// CHECK: Concrete.Nested
// DEMANGLE: $s10extensions7GenericVA2A5ProtoRzlE7Nested1Vyx_GD
// CHECK: Generic<τ_0_0>.Nested1
// DEMANGLE: $s10extensions7GenericVAASiRszlE7Nested2VySi_GD
// CHECK: Generic<Int>.Nested2
| 23.090909 | 89 | 0.704724 |
267771dbe00cc12ec2aa98db5f43aa634eda1d1d | 1,517 | //
// Detroit_909UITests.swift
// Detroit 909UITests
//
// Created by Matt Dolan External macOS on 2020-12-31.
// Copyright © 2020 Matt Dolan External macOS. All rights reserved.
//
import XCTest
class Detroit_909UITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 34.477273 | 182 | 0.666447 |
46fefe0e5c9102fd509d3a89e12b066e75589a5d | 7,527 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: cosmos/base/v1beta1/coin.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
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
}
/// Coin defines a token with a denomination and an amount.
///
/// NOTE: The amount field is an Int which implements the custom method
/// signatures required by gogoproto.
struct Cosmos_Base_V1beta1_Coin {
// 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 denom: String = String()
var amount: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// DecCoin defines a token with a denomination and a decimal amount.
///
/// NOTE: The amount field is an Dec which implements the custom method
/// signatures required by gogoproto.
struct Cosmos_Base_V1beta1_DecCoin {
// 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 denom: String = String()
var amount: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// IntProto defines a Protobuf wrapper around an Int object.
struct Cosmos_Base_V1beta1_IntProto {
// 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 int: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// DecProto defines a Protobuf wrapper around a Dec object.
struct Cosmos_Base_V1beta1_DecProto {
// 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 dec: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "cosmos.base.v1beta1"
extension Cosmos_Base_V1beta1_Coin: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Coin"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "denom"),
2: .same(proto: "amount"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.denom)
case 2: try decoder.decodeSingularStringField(value: &self.amount)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.denom.isEmpty {
try visitor.visitSingularStringField(value: self.denom, fieldNumber: 1)
}
if !self.amount.isEmpty {
try visitor.visitSingularStringField(value: self.amount, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Cosmos_Base_V1beta1_Coin, rhs: Cosmos_Base_V1beta1_Coin) -> Bool {
if lhs.denom != rhs.denom {return false}
if lhs.amount != rhs.amount {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmos_Base_V1beta1_DecCoin: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".DecCoin"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "denom"),
2: .same(proto: "amount"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.denom)
case 2: try decoder.decodeSingularStringField(value: &self.amount)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.denom.isEmpty {
try visitor.visitSingularStringField(value: self.denom, fieldNumber: 1)
}
if !self.amount.isEmpty {
try visitor.visitSingularStringField(value: self.amount, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Cosmos_Base_V1beta1_DecCoin, rhs: Cosmos_Base_V1beta1_DecCoin) -> Bool {
if lhs.denom != rhs.denom {return false}
if lhs.amount != rhs.amount {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmos_Base_V1beta1_IntProto: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".IntProto"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "int"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.int)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.int.isEmpty {
try visitor.visitSingularStringField(value: self.int, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Cosmos_Base_V1beta1_IntProto, rhs: Cosmos_Base_V1beta1_IntProto) -> Bool {
if lhs.int != rhs.int {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Cosmos_Base_V1beta1_DecProto: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".DecProto"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "dec"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.dec)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.dec.isEmpty {
try visitor.visitSingularStringField(value: self.dec, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Cosmos_Base_V1beta1_DecProto, rhs: Cosmos_Base_V1beta1_DecProto) -> Bool {
if lhs.dec != rhs.dec {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 35.009302 | 140 | 0.732828 |
f90ef38a4b6bd52029cab9c7cc42899799f18d5c | 639 | import Foundation
@testable import RecipesApp
class MockedProductPageView: ProductPageViewProtocol {
var counterRecipe: Int = 0
var counterLoadCallbacks: Int = 0
var loadRecipeHandler: ((Recipe?) -> Void)?
var loadCallbacksHandler: (() -> Void)?
func load(recipe: Recipe?) {
counterRecipe += 1
if let loadRecipeHandler = loadRecipeHandler {
return loadRecipeHandler(recipe)
}
}
func loadCallbacks() {
counterLoadCallbacks += 1
if let loadCallbacksHandler = loadCallbacksHandler {
return loadCallbacksHandler()
}
}
}
| 24.576923 | 60 | 0.632238 |
6199f0b08872b67e21f4bf3b25fe8763487469d9 | 1,406 | // Copyright © 2018 Stormbird PTE. LTD.
import Foundation
class FetchAssetDefinitionsCoordinator: Coordinator {
var coordinators: [Coordinator] = []
private let assetDefinitionStore: AssetDefinitionStore
private let tokensDataStores: ServerDictionary<TokensDataStore>
private var contractsInDatabase: [AlphaWallet.Address] {
var contracts = [AlphaWallet.Address]()
for each in tokensDataStores.values {
contracts.append(contentsOf: each.enabledObject.filter {
switch $0.type {
case .erc20, .erc721, .erc875, .erc721ForTickets:
return true
case .nativeCryptocurrency:
return false
}
}.map { $0.contractAddress })
}
return contracts
}
private var contractsWithTokenScriptFileFromOfficialRepo: [AlphaWallet.Address] {
return assetDefinitionStore.contractsWithTokenScriptFileFromOfficialRepo
}
init(assetDefinitionStore: AssetDefinitionStore, tokensDataStores: ServerDictionary<TokensDataStore>) {
self.assetDefinitionStore = assetDefinitionStore
self.tokensDataStores = tokensDataStores
}
func start() {
let contracts = Array(Set(contractsInDatabase + contractsWithTokenScriptFileFromOfficialRepo))
assetDefinitionStore.fetchXMLs(forContracts: contracts)
}
} | 36.051282 | 107 | 0.684922 |
38273d43bc315bc84ed511826e772e93ed232ba1 | 8,665 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 UIKit
@objc(ContentViewAlignment)
public enum ContentViewAlignment: Int {
case any
case center
}
open class Bar: View {
/// Will layout the view.
open var willLayout: Bool {
return 0 < width && 0 < height && nil != superview
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/// Should center the contentView.
open var contentViewAlignment = ContentViewAlignment.any {
didSet {
layoutSubviews()
}
}
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset: EdgeInsetsPreset {
get {
return grid.contentEdgeInsetsPreset
}
set(value) {
grid.contentEdgeInsetsPreset = value
}
}
/// A reference to EdgeInsets.
@IBInspectable
open var contentEdgeInsets: EdgeInsets {
get {
return grid.contentEdgeInsets
}
set(value) {
grid.contentEdgeInsets = value
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.none {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// A wrapper around grid.interimSpace.
@IBInspectable
open var interimSpace: InterimSpace {
get {
return grid.interimSpace
}
set(value) {
grid.interimSpace = value
}
}
/// Grid cell factor.
@IBInspectable
open var gridFactor: CGFloat = 12 {
didSet {
assert(0 < gridFactor, "[Material Error: gridFactor must be greater than 0.]")
layoutSubviews()
}
}
/// ContentView that holds the any desired subviews.
open private(set) lazy var contentView = View()
/// Left side UIViews.
open var leftViews = [UIView]() {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Right side UIViews.
open var rightViews = [UIView]() {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Center UIViews.
open var centerViews: [UIView] {
get {
return contentView.grid.views
}
set(value) {
for v in contentView.grid.views {
v.removeFromSuperview()
}
contentView.grid.views = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
/// Basic initializer.
public init() {
super.init(frame: .zero)
frame.size = intrinsicContentSize
}
/**
A convenience initializer with parameter settings.
- Parameter leftViews: An Array of UIViews that go on the left side.
- Parameter rightViews: An Array of UIViews that go on the right side.
- Parameter centerViews: An Array of UIViews that go in the center.
*/
public init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) {
super.init(frame: .zero)
self.leftViews = leftViews ?? []
self.rightViews = rightViews ?? []
self.centerViews = centerViews ?? []
frame.size = intrinsicContentSize
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout else {
return
}
reload()
}
/// Reloads the view.
open func reload() {
var lc = 0
var rc = 0
grid.begin()
grid.views.removeAll()
for v in leftViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
lc += v.grid.columns
grid.views.append(v)
}
grid.views.append(contentView)
for v in rightViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
rc += v.grid.columns
grid.views.append(v)
}
contentView.grid.begin()
contentView.grid.offset.columns = 0
var l: CGFloat = 0
var r: CGFloat = 0
if .center == contentViewAlignment {
if leftViews.count < rightViews.count {
r = CGFloat(rightViews.count) * interimSpace
l = r
} else {
l = CGFloat(leftViews.count) * interimSpace
r = l
}
}
let p = width - l - r - contentEdgeInsets.left - contentEdgeInsets.right
let columns = Int(ceil(p / gridFactor))
if .center == contentViewAlignment {
if lc < rc {
contentView.grid.columns = columns - 2 * rc
contentView.grid.offset.columns = rc - lc
} else {
contentView.grid.columns = columns - 2 * lc
rightViews.first?.grid.offset.columns = lc - rc
}
} else {
contentView.grid.columns = columns - lc - rc
}
grid.axis.columns = columns
grid.commit()
contentView.grid.commit()
divider.reload()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
heightPreset = .normal
autoresizingMask = .flexibleWidth
interimSpacePreset = .interimSpace3
contentEdgeInsetsPreset = .square1
prepareContentView()
}
/// Prepares the contentView.
private func prepareContentView() {
contentView.backgroundColor = nil
}
}
| 30.297203 | 104 | 0.582804 |
4a7943f2b57174872fec0a917286bf0860bf92dd | 490 | // 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
// ServerAdministratorListResultProtocol is the response to a list Active Directory Administrators request.
public protocol ServerAdministratorListResultProtocol : Codable {
var value: [ServerAzureADAdministratorProtocol?]? { get set }
}
| 49 | 108 | 0.783673 |
6a1eff62abf0e59678ef8f94a868f4453c3a8fde | 1,033 | //
// Copyright 2021 PLAID, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
/// ビジュアルトラッキングで発生するイベントを委譲するためのタイプです。
@objc(KRTVisualTrackingDelegate)
public protocol VisualTrackingDelegate: AnyObject {
/// ペアリング状態が更新されたことを通知します。
///
/// - Parameters:
/// - visualTracking: ビジュアルトラッキングインスタンス
/// - isPaired: ペアリング状態を表すフラグ、端末がペアリングされていればtrue 、それ以外は false を返します。
@objc
optional func visualTrackingDevicePairingStatusUpdated(_ visualTracking: VisualTracking, isPaired: Bool)
}
| 36.892857 | 108 | 0.733785 |
16772b20d0fa287c71f7b89c85f07b93bf6d58b4 | 812 | //
// IBStylable.swift
//
// Created by Emily Ivie on 3/4/15.
//
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import UIKit
/// Protocol for stylable UIKit elements.
/// See IBStyledThings for examples.
public protocol IBStylable where Self: UIView { // Swift 4.2 do not remove class
var styler: IBStyler? { get }
var identifier: String? { get }
var defaultIdentifier: String { get } // optional
func applyStyles() // optional
func changeContentSizeCategory() // optional
}
extension IBStylable {
public var defaultIdentifier: String { return "" }
public func applyStyles() {}
public func changeContentSizeCategory() {}
}
| 29 | 93 | 0.713054 |
14fcfe5e024e3b84fa5f1bfd3e65d3e78faf27d2 | 4,332 | //
//
// BaseWebView.swift
// NavCogMiraikan
//
/*******************************************************************************
* Copyright (c) 2021 © Miraikan - The National Museum of Emerging Science and Innovation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
import Foundation
import UIKit
protocol WebAccessibilityDelegate {
func onFinished()
}
/**
The parent view implemented with WKNavigationDelegate
*/
class BaseWebView: BaseView, WKNavigationDelegate {
let webView = WKWebView()
private let lblLoading = UILabel()
private let gap = CGFloat(10)
private var isLoadingFailed = false
var accessibilityDelegate: WebAccessibilityDelegate?
override func setup() {
super.setup()
webView.navigationDelegate = self
addSubview(webView)
// Display: Loading
lblLoading.numberOfLines = 0
lblLoading.lineBreakMode = .byCharWrapping
lblLoading.textAlignment = .center
addSubview(lblLoading)
}
// MARK: Layout
override func layoutSubviews() {
// Loading
lblLoading.frame.origin.x = insets.left
lblLoading.center.y = self.center.y
lblLoading.frame.size.width = innerSize.width
}
// MARK: Public Customized Functions
public func loadContent(_ address: String) {
let url = URL(string: address)
let req = URLRequest(url: url!)
webView.load(req)
}
public func loadDetail(html: String) {
webView.loadHTMLString(html, baseURL: nil)
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
lblLoading.text = NSLocalizedString("web_loading", comment: "")
lblLoading.sizeToFit()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
lblLoading.text = NSLocalizedString("web_failed", comment: "")
lblLoading.sizeToFit()
isLoadingFailed = true
webView.isHidden = true
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
guard let response = navigationResponse.response as? HTTPURLResponse else { return }
switch response.statusCode {
case 200:
let jsClearHeader = "document.getElementsByTagName('header')[0].innerHTML = '';"
let jsClearFooter = "document.getElementsByTagName('footer')[0].innerHTML = '';"
let js = "\(jsClearHeader)\(jsClearFooter)"
webView.evaluateJavaScript(js, completionHandler: {(html, err) in
if let e = err {
print(e.localizedDescription)
}
})
decisionHandler(.allow)
case 404:
decisionHandler(.cancel)
default:
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
lblLoading.isHidden = !isLoadingFailed
lblLoading.accessibilityElementsHidden = !isLoadingFailed
accessibilityDelegate?.onFinished()
}
}
| 36.1 | 163 | 0.659511 |
ccc0e04c20d38a696a271efdcb6e7687528ec880 | 4,083 | //
// Copyright © 2021 DHSC. All rights reserved.
//
import Foundation
public class LocalizationKeyAnalyzer {
private let localisationKeyParser: DefinedLocalizationKeys
private let localizableStringKeyParser: LocalizableKeys
private let localizableStringDictKeyParser: LocalizableKeys
private let localizationKeysCalledFileParser: UsedLocalizationKeys
/// Keys from both Localizable.strings and Localizable.stringsdict
private var stringKeys: Set<LocalizableKey> {
localizableStringKeyParser.keys.union(localizableStringDictKeyParser.keys)
}
public init(
localizableStringsFile: URL,
localizableStringsDictFile: URL,
localisationKeyFile: URL,
sourceFiles: [URL]
) throws {
localisationKeyParser = try StringLocalizationKeyParser(file: localisationKeyFile)
localizableStringKeyParser = try LocalizableStringKeyParser(file: localizableStringsFile)
localizableStringDictKeyParser = try LocalizableStringDictParser(file: localizableStringsDictFile)
let definedKeys = Set<String>(
localisationKeyParser.parameterizedKeys.map {
$0.identifier
}
).union(localisationKeyParser.defaultKeys)
localizationKeysCalledFileParser = try LocalizableKeysCalledFileParser(files: sourceFiles, definedKeys: definedKeys)
}
init(
localisationKeyParser: DefinedLocalizationKeys,
localizableStringKeyParser: LocalizableKeys,
localizableStringDictKeyParser: LocalizableKeys,
localizationKeysCalledFileParser: UsedLocalizationKeys
) {
self.localisationKeyParser = localisationKeyParser
self.localizableStringKeyParser = localizableStringKeyParser
self.localizableStringDictKeyParser = localizableStringDictKeyParser
self.localizationKeysCalledFileParser = localizationKeysCalledFileParser
}
/// Keys present in Localizable.strings and Localizable.stringsdict but not in StringLocalizationkey.swift
public var undefinedKeys: Set<LocalizableKey> {
// FIXME: Refactor - Beautify
var stringKeysDict = [String: LocalizableKey]()
stringKeys.forEach { stringKeysDict[$0.key] = $0 }
let rawStringKeys = Set<String>(localizableStringKeyParser.keys.map { $0.key })
let definedDefaultKeys = localisationKeyParser.defaultKeys
let definedParameterizedKeys = localisationKeyParser.parameterizedKeys.map { $0.rawValue }
let definedKeys = definedDefaultKeys.union(definedParameterizedKeys)
let rawUndefinedKeys = rawStringKeys.subtracting(definedKeys)
// Return Set<LocalizabeKey> represantation of rawUndefinedKeys
var res: Set<LocalizableKey> = []
rawUndefinedKeys.forEach {
if let value = stringKeysDict[$0] {
res.insert(value)
}
}
return res
}
public var uncalledKeys: Set<LocalizableKey> {
var stringKeysDict = [String: LocalizableKey]()
stringKeys.forEach { stringKeysDict[$0.key] = $0 }
let calledKeys = localizationKeysCalledFileParser.keys
let uncalledDefaultKeys = localisationKeyParser.defaultKeys.subtracting(calledKeys)
let uncalledParameterizedKeys = localisationKeyParser.parameterizedKeys.filter { !calledKeys.contains($0.identifier) }
var res: Set<LocalizableKey> = []
uncalledDefaultKeys.forEach {
if let value = stringKeysDict[$0] {
res.insert(value)
}
}
uncalledParameterizedKeys.forEach {
if let value = stringKeysDict[$0.rawValue] {
res.insert(value)
}
}
return res
}
}
// MARK: - Unused localizable keys
extension LocalizationKeyAnalyzer {
var findUnusedDefaultLocalizedKeys: Set<String> {
[]
}
}
| 34.897436 | 126 | 0.67181 |
ef704373db616e8abee42c3caa94ae6d84bbbe4b | 5,459 | //
// FeaturesListViewModelTests.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@testable import SwiftyToggler
import XCTest
class FeaturesListViewModelTests: XCTestCase {
var fmToggler: SpyFeaturesManagerToggler!
var viewModel: FeaturesListViewModel!
override func setUp() {
super.setUp()
fmToggler = SpyFeaturesManagerToggler()
viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .modal(DummyWindow()))
}
override func tearDown() {
viewModel = nil
fmToggler = nil
super.tearDown()
}
func test_FeaturesCount_WithoutFeatures_IsZero() {
XCTAssertEqual(viewModel.featuresCount, 0)
}
func test_FeaturesCount_WithTwoFeatures_IsTwo() {
fmToggler = SpyFeaturesManagerToggler()
fmToggler.forceTwoFeatures = true
viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .modal(DummyWindow()))
XCTAssertEqual(viewModel.featuresCount, 2)
}
func test_CloseButtonHeight_PresetingModeModal_Returns44() {
XCTAssertEqual(viewModel.closeButtonHeight, 44)
}
func test_CloseButtonHeight_PresetingModeInParentViewNil_ReturnsZero() {
let fmToggler = SpyFeaturesManagerToggler()
let viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .inParent(DummyViewController(), nil))
XCTAssertEqual(viewModel.closeButtonHeight, 0)
}
func test_CloseButtonHeight_PresetingModeInParentViewNotNil_ReturnsZero() {
let fmToggler = SpyFeaturesManagerToggler()
let viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .inParent(DummyViewController(), DummyView()))
XCTAssertEqual(viewModel.closeButtonHeight, 0)
}
func test_TitleLabelHeight_PresetingModeModal_Returns50() {
XCTAssertEqual(viewModel.titleLabelHeight, 50)
}
func test_TitleLabelHeight_PresetingModeInParentViewNil_ReturnsZero() {
let fmToggler = SpyFeaturesManagerToggler()
let viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .inParent(DummyViewController(), nil))
XCTAssertEqual(viewModel.titleLabelHeight, 0)
}
func test_TitleLabelHeight_PresetingModeInParentViewNotNil_ReturnsZero() {
let fmToggler = SpyFeaturesManagerToggler()
let viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .inParent(DummyViewController(), DummyView()))
XCTAssertEqual(viewModel.titleLabelHeight, 0)
}
func test_ShouldShowPlaceholder_WithoutFeatures_IsTrue() {
XCTAssertTrue(viewModel.shouldShowPlaceholder)
}
func test_ShouldShowPlaceholder_WithFeatures_IsFalse() {
fmToggler = SpyFeaturesManagerToggler()
fmToggler.forceTwoFeatures = true
viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .modal(DummyWindow()))
XCTAssertFalse(viewModel.shouldShowPlaceholder)
}
func test_FeatureInfoAt_WithoutFeatures_ReturnsNil() {
let featureStatus = viewModel.featureStatus(at: IndexPath(row: 0, section: 0))
XCTAssertNil(featureStatus)
}
func test_FeatureInfoAt_WithFeaturesInvalidIndexPath_ReturnsNil() {
fmToggler = SpyFeaturesManagerToggler()
fmToggler.forceTwoFeatures = true
viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .modal(DummyWindow()))
let featureStatus = viewModel.featureStatus(at: IndexPath(row: 3, section: 0))
XCTAssertNil(featureStatus)
}
func test_FeatureInfoAt_WithFeaturesValidIndexPath_ReturnsFeatureInfo() {
fmToggler = SpyFeaturesManagerToggler()
fmToggler.forceTwoFeatures = true
viewModel = FeaturesListViewModel(featuresManager: fmToggler, presentingMode: .modal(DummyWindow()))
let featureStatus = viewModel.featureStatus(at: IndexPath(row: 1, section: 0))
XCTAssertEqual(featureStatus!.name, "F2")
XCTAssertTrue(featureStatus!.isEnabled)
}
func test_UpdateFeature_CallsSetEnable() {
viewModel.updateFeature(name: "F2", isEnabled: true)
XCTAssertTrue(fmToggler.isSetEnableCall)
XCTAssertTrue(fmToggler.setEnableIsEnableAgument!)
XCTAssertEqual(fmToggler.setEnableFeatureNameAgument, "F2")
}
func test_CloseButtonDidTap_CallsFeaturesListViewModelNeedsClose() {
let viewModelDelegate = StubFeaturesListViewModelDelegate()
viewModel.delegate = viewModelDelegate
viewModel.closeButtonDidTap()
XCTAssertTrue(viewModelDelegate.isFeaturesListViewModelNeedsCloseCalled)
}
}
| 36.152318 | 130 | 0.793002 |
0a65cb77985fc7d337948bef651c918ea5a67495 | 729 | // This class is automatically included in FastlaneRunner during build
// This autogenerated file will be overwritten or replaced during build time, or when you initialize `deliver`
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
class Deliverfile: DeliverfileProtocol {
// If you want to enable `deliver`, run `fastlane deliver init`
// After, this file will be replaced with a custom implementation that contains values you supplied
// during the `init` process, and you won't see this message
}
// Generated with fastlane 2.105.2
| 33.136364 | 110 | 0.750343 |
72ec01dc77e5975d364f913422a27864a8d8f0ff | 246 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct Q {
let : B<A>
protocol A {
protocol A : f { {
}
func f
}
}
class B<T
| 17.571429 | 87 | 0.707317 |
16359f59e4b4c5e411959de36ed44e027c2a2528 | 2,769 | //
// CachePrepareStep.swift
// Rugby
//
// Created by Vyacheslav Khorkov on 31.01.2021.
// Copyright © 2021 Vyacheslav Khorkov. All rights reserved.
//
import Files
struct CachePrepareStep: Step {
struct Output {
let scheme: String?
let targets: Set<String>
let buildInfo: BuildInfo
let products: [String]
let swiftVersion: String?
}
let verbose: Int
let isLast: Bool
let progress: Printer
private let command: Cache
private let metrics: Metrics
init(command: Cache, metrics: Metrics, logFile: File, isLast: Bool = false) {
self.command = command
self.metrics = metrics
self.verbose = command.flags.verbose
self.isLast = isLast
self.progress = RugbyPrinter(title: "Prepare", logFile: logFile, verbose: verbose, quiet: command.flags.quiet)
}
}
extension CachePrepareStep {
func run(_ buildTarget: String) throws -> Output {
if try shell("xcode-select -p") == .defaultXcodeCLTPath {
throw CacheError.cantFindXcodeCommandLineTools
}
metrics.projectSize.before = (try Folder.current.subfolder(at: .podsProject)).size()
let project = try progress.spinner("Read project") {
try ProjectProvider.shared.readProject(.podsProject)
}
metrics.compileFilesCount.before = project.pbxproj.buildFiles.count
metrics.targetsCount.before = project.pbxproj.main.targets.count
let projectPatched = project.pbxproj.main.contains(buildSettingsKey: .rugbyPatched)
if projectPatched { throw CacheError.projectAlreadyPatched }
let factory = CacheSubstepFactory(progress: progress, command: command, metrics: metrics)
let selectedPods = try factory.selectPods(project)
let (buildInfo, swiftVersion) = try factory.findBuildPods(selectedPods)
let (selectedTargets, buildTargets) = try factory.buildTargets((project: project,
selectedPods: selectedPods,
buildPods: buildInfo.pods))
if !buildTargets.isEmpty {
try factory.addBuildTarget(.init(target: buildTarget, project: project, dependencies: buildTargets))
}
let targets = selectedPods
.union(selectedTargets.map(\.name))
.union(selectedTargets.compactMap(\.productName))
done()
return Output(scheme: buildTargets.isEmpty ? nil : buildTarget,
targets: targets,
buildInfo: buildInfo,
products: selectedTargets.compactMap(\.product?.name),
swiftVersion: swiftVersion)
}
}
| 37.418919 | 118 | 0.62658 |
22ec69787db47858f662b12bb87b7348cd2687f3 | 547 | //
// AssetSkeletonCell.swift
// WavesWallet-iOS
//
// Created by Prokofev Ruslan on 17/07/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import UIKit
final class WalletAssetSkeletonCell: SkeletonTableCell, NibReusable {
@IBOutlet private weak var viewContent: UIView!
override func awakeFromNib() {
super.awakeFromNib()
viewContent.addTableCellShadowStyle()
backgroundColor = UIColor.basic50
}
class func cellHeight() -> CGFloat {
return 76
}
}
| 21.88 | 69 | 0.689214 |
38a297bcfb6b1046ec9bd9f4df7a2bdafd497a54 | 3,957 | // --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------
import AST
import Foundation
extension DeclarationModifiers {
var accessLevel: AccessLevelModifier? {
for modifier in self {
switch modifier {
case let .accessLevel(value):
return value
default:
continue
}
}
return nil
}
}
extension InitializerDeclaration {
var fullName: String {
var value = "init("
for param in parameterList {
let label = param.externalName?.textDescription ?? param.localName.textDescription
let type = param.typeAnnotation.type.textDescription
value += "\(label)[\(type)]:"
}
value += ")"
return value.replacingOccurrences(of: " ", with: "")
}
}
extension FunctionDeclaration {
var fullName: String {
var value = "\(self.name)("
for param in signature.parameterList {
let label = param.externalName?.textDescription ?? param.localName.textDescription
let type = param.typeAnnotation.type.textDescription
value += "\(label)[\(type)]:"
}
value += ")"
if self.signature.asyncKind == .async {
value += "[async]"
}
if self.signature.throwsKind != .nothrowing {
value += "[\(self.signature.throwsKind.textDescription)]"
}
return value.replacingOccurrences(of: " ", with: "")
}
}
extension ProtocolDeclaration.InitializerMember {
var fullName: String {
var value = "init("
for param in parameterList {
let label = param.externalName?.textDescription ?? param.localName.textDescription
let type = param.typeAnnotation.type.textDescription
value += "\(label)[\(type)]:"
}
value += ")"
return value.replacingOccurrences(of: " ", with: "")
}
}
extension ProtocolDeclaration.MethodMember {
var fullName: String {
var value = "\(self.name)("
for param in signature.parameterList {
let label = param.externalName?.textDescription ?? param.localName.textDescription
let type = param.typeAnnotation.type.textDescription
value += "\(label)[\(type)]:"
}
value += ")"
return value.replacingOccurrences(of: " ", with: "")
}
}
extension OperatorDeclaration {
var `operator`: String {
switch self.kind {
case let .infix(opName, _):
return opName
case let .postfix(opName):
return opName
case let .prefix(opName):
return opName
}
}
}
| 34.408696 | 94 | 0.604751 |
fc094f078289e31608098db17d63e815083b5031 | 1,475 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Podest open source project
//
// Copyright (c) 2021 Michael Nisi and collaborators
// Licensed under MIT License
//
// See https://github.com/michaelnisi/podest/blob/main/LICENSE for license information
//
//===----------------------------------------------------------------------===//
import UIKit
/// Useful default action sheet things for view controllers.
protocol ActionSheetPresenting {}
extension ActionSheetPresenting where Self: UIViewController {
static func makeCancelAction(
handler: ((UIAlertAction) -> Void)? = nil
) -> UIAlertAction {
let t = NSLocalizedString("Cancel", comment: "Cancel by default")
return UIAlertAction(title: t, style: .cancel, handler: handler)
}
static func makeOpenLinkAction(string: String?) -> UIAlertAction? {
guard let link = string, let linkURL = URL(string: link) else {
return nil
}
let t = NSLocalizedString("Open Link", comment: "Open browser link")
return UIAlertAction(title: t, style: .default) { action in
UIApplication.shared.open(linkURL)
}
}
static func makeCopyFeedURLAction(string: String) -> UIAlertAction {
let t = NSLocalizedString("Copy Feed URL", comment: "Copy non-browser link")
return UIAlertAction(title: t, style: .default) { action in
UIPasteboard.general.string = string
}
}
}
| 31.382979 | 86 | 0.618305 |
6970affc80e774349f09f847ae0e8b9dcb2809d4 | 292 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{
if a{
struct Q<T where g:d{enum b{class b
class a{
class A:b
| 24.333333 | 87 | 0.732877 |
4af61a1be24d5272b0da8171dfaf50d8d6e8351a | 4,245 | import UIKit
///Controller which glues master and detail view controllers
///And contains all animation coordinators
class ViewController: UIViewController, DetailViewControllerDelegate {
var coordinator: AnimationCoordinator!
lazy var master = MasterViewController()
lazy var detail = DetailViewController()
let detailViewOffset: CGFloat = 50.0
override func viewDidLoad() {
super.viewDidLoad()
detail.delegate = self
addChild(master)
master.addChild(detail)
view.addSubview(master.view)
master.view.translatesAutoresizingMaskIntoConstraints = false
master.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
master.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
master.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
master.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
master.view.addSubview(detail.view)
setupCoordinators()
}
override func viewDidLayoutSubviews() {
//setting up initial frame of detailViewController here because bounds of masterViewController are valid only here
detail.view.frame = master.view.bounds.offsetBy(dx: 0.0, dy: master.view.bounds.height - detailViewOffset)
}
func setupCoordinators() {
let springTimingParameters = UISpringTimingParameters(dampingRatio: 2.0)
let customCollapsingTimingParameters = UICubicTimingParameters(controlPoint1: CGPoint(x: 0.1, y: 0.75),
controlPoint2: CGPoint(x: 0.25, y: 0.9))
let customExpandingTimingParameters = UICubicTimingParameters(controlPoint1: CGPoint(x: 0.75, y: 0.1),
controlPoint2: CGPoint(x: 0.9, y: 0.25))
let easeInTimingParameters = UICubicTimingParameters(animationCurve: .easeIn)
let easeOutTimingParameters = UICubicTimingParameters(animationCurve: .easeOut)
let collapsing = {
[unowned self, unowned detail = self.detail, unowned master = self.master] in
detail.view.frame = master.view.bounds.offsetBy(dx: 0.0, dy: master.view.bounds.height - self.detailViewOffset)
}
let expanding = {
[unowned detail = self.detail, unowned master = self.master] in
detail.view.frame = master.view.bounds
}
let blur = {
[unowned master = self.master] in
let blurEffect = UIBlurEffect(style: .prominent)
master.effectView.effect = blurEffect
}
let noBlur = {
[unowned master = self.master] in
master.effectView.effect = nil
}
let panParameters = AnimationParameters(expandingAnimation: expanding, collapsingAnimation: collapsing, scrubsLinearly: true, expandingTimeParameters: springTimingParameters, collapsingTimeParameters: springTimingParameters)
let blurParameters = AnimationParameters(expandingAnimation: blur, collapsingAnimation: noBlur, scrubsLinearly: false, expandingTimeParameters: customExpandingTimingParameters, collapsingTimeParameters: customCollapsingTimingParameters)
let detailHeadParameters = AnimationParameters(expandingAnimation: detail.expandTopView, collapsingAnimation: detail.collapseTopView, scrubsLinearly: false, expandingTimeParameters: easeOutTimingParameters, collapsingTimeParameters: easeInTimingParameters)
coordinator = AnimationCoordinator(withMasterViewHeight: master.view.bounds.height, andDetailViewOffset: detailViewOffset, duration: 1.0, animationParameters: [panParameters, blurParameters, detailHeadParameters])
}
//MARK: - Detail view controller delegate
func handleTap() {
coordinator.handleTap()
}
func handlePan(gestureState: UIGestureRecognizer.State, translation: CGPoint, velocity: CGPoint) {
coordinator.handlePan(gestureState: gestureState, translation: translation, velocity: velocity)
}
}
| 52.407407 | 264 | 0.696584 |
ef2dc424414591f459d1f8021bf8c1a25f726b15 | 613 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class a<b : b, d : b where b.d == d> {
}
class i: d{ class func f {}
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
}
class k: c{ class func i {
}
}lass func c()
}
var x1 = 1
=1 as a=1
| 22.703704 | 79 | 0.649266 |
5b60b71e852e58d0a6f81e4e565255abd7a59e32 | 2,955 | //
// form.support.realtime.swift
// Realtime
//
// Created by Denis Koryttsev on 11/09/2018.
//
#if os(iOS)
import UIKit
extension UITableView {
public enum Operation {
case reload
case move(IndexPath)
case insert
case delete
case none
var isActive: Bool {
if case .none = self {
return false
}
return true
}
}
func scheduleOperation(_ operation: Operation, for indexPath: IndexPath, with animation: UITableView.RowAnimation) {
switch operation {
case .none: break
case .reload: reloadRows(at: [indexPath], with: animation)
case .move(let ip): moveRow(at: indexPath, to: ip)
case .insert: insertRows(at: [indexPath], with: animation)
case .delete: deleteRows(at: [indexPath], with: animation)
}
}
public class ScheduledUpdate {
internal private(set) var events: [IndexPath: UITableView.Operation]
var operations: [(IndexPath, UITableView.Operation)] = []
var isReadyToUpdate: Bool { return events.isEmpty && !operations.isEmpty }
public init(events: [IndexPath: UITableView.Operation]) {
precondition(!events.isEmpty, "Events must not be empty")
self.events = events
}
func fulfill(_ indexPath: IndexPath) -> Bool {
if let operation = events.removeValue(forKey: indexPath) {
operations.append((indexPath, operation))
return true
} else {
return false
}
}
func batchUpdatesIfFulfilled(in tableView: UITableView) {
while !operations.isEmpty {
let (ip, op) = operations.removeLast()
tableView.scheduleOperation(op, for: ip, with: .automatic)
}
}
}
}
/*extension AnyRealtimeCollection: DynamicSectionDataSource {}
extension Values: DynamicSectionDataSource {}
extension AssociatedValues: DynamicSectionDataSource {}
extension References: DynamicSectionDataSource {}
extension MapRealtimeCollection: DynamicSectionDataSource {}
extension FlattenRealtimeCollection: DynamicSectionDataSource {}*/
public struct RealtimeCollectionDataSource<Model>: DynamicSectionDataSource {
let base: AnyRealtimeCollection<Model>
public init(_ base: AnyRealtimeCollection<Model>) { self.base = base }
public init<RC>(_ collection: RC) where RC: RealtimeCollection, RC.Element == Model, RC.View.Element: DatabaseKeyRepresentable {
self.base = AnyRealtimeCollection(collection)
}
public var changes: AnyListenable<DynamicSectionEvent> { base.changes }
public var keepSynced: Bool {
get { base.keepSynced }
set { base.keepSynced = newValue }
}
public var count: Int { base.count }
public subscript(index: Int) -> Model { base[base.index(base.startIndex, offsetBy: index)] }
}
#endif
| 33.965517 | 132 | 0.64467 |
e4c635cba591b0192552f327ee42548fb9fde8c2 | 401 | //
// Pin.swift
// Cacher
//
// Created by Prajwal Lobo on 19/03/18.
// Copyright © 2018 Prajwal Lobo. All rights reserved.
//
import UIKit
import ObjectMapper
class Pin: BaseModel {
var likes : Int?
var user : User?
var link : String?
override func mapping(map: Map) {
likes <- map["likes"]
user <- map["user"]
link <- map["links.download"]
}
}
| 17.434783 | 55 | 0.581047 |
b9157ddf53c860a05b2e4c60d9a2fd359e594c99 | 2,140 | //
// THIconCell.swift
// BallRecord
//
// Created by 买超 on 2019/11/28.
// Copyright © 2019 maichao. All rights reserved.
//
import UIKit
class THIconCell: UITableViewCell {
var iconView = UIImageView()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = ""
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = COLOR_324057
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)
return label
}()
lazy var arrowView: UIImageView = {
let imgV = UIImageView()
imgV.image = UIImage(named: "cell_arrow_icon")
return imgV
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configUI()
configFrame()
configData()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension THIconCell {
func configUI() {
selectionStyle = .none
contentView.addSubview(iconView)
contentView.addSubview(arrowView)
contentView.addSubview(titleLabel)
}
func configFrame() {
iconView.snp.makeConstraints { (make) in
make.height.width.equalTo(50)
make.left.equalTo(16)
make.top.equalTo(10)
make.bottom.equalTo(-10)
}
arrowView.snp.makeConstraints { (make) in
make.right.equalTo(contentView).offset(-16)
make.centerY.equalTo(contentView)
make.width.height.equalTo(20)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(iconView.snp_right).offset(8)
make.right.equalTo(arrowView.snp_left).offset(-8)
make.centerY.equalTo(contentView)
make.height.equalTo(titleLabel)
}
iconView.setCorner(cornerRadius: 25)
}
func configData() {
}
}
| 26.097561 | 82 | 0.594393 |
09fc9e7271d74acca44774d7becdcd698fdae805 | 135 | final class PassthroughSubject<Output, Failure> where Failure : Error {
func send(_ input: Output) {
// nothing yet
}
} | 27 | 71 | 0.651852 |
ed0613a09810182c0abe7fda5755351ac89c81a0 | 2,091 | //
// BuilderTests.swift
// Builder pattern exampleTests
//
// Created by Gabrielle Earnshaw on 05/08/2018.
// Copyright © 2018 Gabrielle Earnshaw. All rights reserved.
//
import XCTest
@testable import Builder_pattern_example
class BuilderTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
// MARK: - Communication of intent examples
extension BuilderTests {
func test_itShouldSendAlert_whenDeviceIsFound() {
// given
let device = DeviceBuilder()
.build()
// when
// ...
// then
// Assert that alert was sent
}
func test_itShouldUseCorrectDeviceId_whenConnectionIsMade() {
// given
let expectedId = "abcde12345"
let device = DeviceBuilder()
.with(id: expectedId)
.build()
// when
// ...
// then
// Assert that the device ID was correct
}
func test_itShouldConnectToDevice_whenDeviceIsActivated() {
// given
let device = DeviceBuilder()
.makeActivated()
.build()
// when
// ...
// then
// Assert the connection code was called
}
}
// MARK: - Complex object graph examples
extension BuilderTests {
func test_itShouldAuthenticate_whenUserLogsIn() {
// given
let user = UserBuilder()
.build()
// when
// ...
// then
// Assert the user was authenticated
}
func test_itShouldFailLogin_whenPasswordNotCorrect() {
// given
let userName = "[email protected]"
let password = "Not the right password"
let account = AccountBuilder()
.with(userName: userName)
.with(password: password)
.build()
let user = UserBuilder()
.with(account: account)
.build()
// when
// ...
// then
// Assert that login failed
}
}
| 21.336735 | 65 | 0.542802 |
b95e398f68a03cf63cbabadeb774567718e06b19 | 3,135 | //
// ©2019 SEAT, S.A. All rights reserved.
//
// This is file is part of a propietary app or framework.
// Unauthorized reproduction, copying or modification of this file is strictly prohibited.
//
// This code is proprietary and confidential.
//
// All the 3rd-party libraries included in the project are regulated by their own licenses.
//
import SwiftUI
import NavigationRouter
/// Sample view for testing purposes
struct View1A: RoutableView {
// MARK: - Fields
/// View model
var viewModel: ViewModel1A
// MARK: - Initializers
/// Initializes a new instance with given view model
/// - Parameter viewModel: View model instance
init(viewModel: ViewModel1A) {
self.viewModel = viewModel
}
// MARK: - View builder
/// View body
public var body: some View {
VStack {
Text("This is the root view")
Spacer()
VStack {
RoutedLink(to: "/view1b") {
Text("Navigate in-module without authentication")
.accessibility(identifier:
"testNavigationInSameModuleWithoutAuthentication")
}
RoutedLink(to: "/view1c") {
Text("Navigate in-module with authentication")
.accessibility(identifier:
"testNavigationInSameModuleWithAuthentication")
}
}
VStack {
RoutedLink(to: "/view2a") {
Text("Navigate between modules without authentication")
.accessibility(identifier:
"testNavigationBetweenModulesWithoutAuthentication")
}
RoutedLink(to: "/view2b") {
Text("Navigate between modules with authentication")
.accessibility(identifier:
"testNavigationBetweenModulesWithAuthentication")
}
RoutedLink(to: "/view2c/5") {
Text("Navigate between modules with parameters")
.accessibility(identifier:
"testNavigationBetweenModulesWithParameters")
}
RoutedLink(to: "/view2d") {
Text("Navigate with interception (after)")
.accessibility(identifier:
"testInterceptionAfterNavigation")
}
RoutedLink(to: "/view2e") {
Text("Navigate with interception (before)")
.accessibility(identifier:
"testInterceptionBeforeNavigation")
}
}
VStack {
RoutedLink(to: "/view3a") {
Text("Navigate to View3A")
.accessibility(identifier: "testView3A")
}
}
Spacer()
}.navigationBarTitle("Module 1 - Root view")
}
}
| 34.450549 | 91 | 0.504625 |
18231f2a8e67c7a393855cb0a8ee9ceb1b16e209 | 483 | //
// KeyModel.swift
// Scrabble v1
//
// Created by Andrés Aguilar on 4/12/20.
// Copyright © 2020 Andrés Aguilar. All rights reserved.
//
import Foundation
class TileModel {
func getTiles() -> [Tile]{
var tilesArray = [Tile]()
for _ in 0...6 {
let tile = Tile()
tile.letter = "B"
tilesArray.append(tile)
}
return tilesArray
}
}
| 16.655172 | 57 | 0.463768 |
01c342d612e27d4a4405ead71671f1a846d0e885 | 34 |
@_exported import ChartPresenter
| 11.333333 | 32 | 0.852941 |
e001859243fe062bdd55cbd59efdef1742218f8f | 2,733 | // Copyright 2021-present Xsolla (USA), Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at q
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing and permissions and
import UIKit
extension UIImage
{
// colorize image with given tint color
func tint(tintColor: UIColor, preserveLuminosity: Bool = false) -> UIImage
{
let modifiedImage = modifiedImage
{ context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
context.setBlendMode(.normal)
UIColor.black.setFill()
context.fill(rect)
// draw original image
context.setBlendMode(.normal)
if let cgImage = self.cgImage
{
context.draw(cgImage, in: rect)
// tint image (loosing alpha)
context.setBlendMode(preserveLuminosity ? .color : .normal)
tintColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(cgImage, in: rect)
}
}
return modifiedImage ?? self
}
private func modifiedImage( draw: (CGContext, CGRect) -> Void) -> UIImage?
{
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext! = UIGraphicsGetCurrentContext()
assert(context != nil)
// correctly rotate image
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
draw(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIImage
{
var template: UIImage
{
return self.withRenderingMode(.alwaysTemplate)
}
}
extension ImageAsset
{
var template: UIImage
{
return image.template
}
func tinted(_ color: UIColor) -> UIImage
{
return image.tint(tintColor: color)
}
}
| 30.032967 | 99 | 0.603732 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.