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
|
---|---|---|---|---|---|
4a1171526575e09657f408bcd017ea7c164eadf9 | 1,654 | //
// FacebookAttachmentPayload.swift
// VaporFacebookBot
//
// Created by Koray Koska on 24/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookAttachmentPayload: JSONConvertible {
public var url: String?
public var coordinatesLat: Double?
public var coordinatesLong: Double?
public init(url: String) {
self.url = url
}
public init(coordinatesLat: Double, coordinatesLong: Double) {
self.coordinatesLat = coordinatesLat
self.coordinatesLong = coordinatesLong
}
public convenience init(json: JSON) throws {
let url = json["url"]?.string
let coordinatesLat = json["coordinates"]?["lat"]?.double
let coordinatesLong = json["coordinates"]?["long"]?.double
if let coordinatesLat = coordinatesLat, let coordinatesLong = coordinatesLong {
self.init(coordinatesLat: coordinatesLat, coordinatesLong: coordinatesLong)
} else if let url = url {
self.init(url: url)
} else {
throw Abort(.badRequest, metadata: "FacebookAttachmentPayload must contain either a url or coordinates.lat and coordinates.long")
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
if let url = url {
try json.set("url", url)
} else if let coordinatesLat = coordinatesLat, let coordinatesLong = coordinatesLong {
var coordinates = JSON()
try coordinates.set("lat", coordinatesLat)
try coordinates.set("long", coordinatesLong)
try json.set("coordinates", coordinates)
}
return json
}
}
| 29.017544 | 141 | 0.639661 |
dd7f0f28edf6e8c1689d01db5520da8589418e48 | 5,868 | /// Represents any type of schema builder
public protocol Builder: class {
var entity: Entity.Type { get}
var fields: [RawOr<Field>] { get set }
var foreignKeys: [RawOr<ForeignKey>] { get set }
}
extension Builder {
public func field(_ field: Field) {
fields.append(.some(field))
}
public func id() {
let field = Field(
name: entity.idKey,
type: .id(type: entity.idType),
primaryKey: true
)
self.field(field)
}
public func foreignId<E: Entity>(
for entityType: E.Type,
optional: Bool = false,
unique: Bool = false,
foreignIdKey: String = E.foreignIdKey,
foreignKeyName: String? = nil
) {
let field = Field(
name: foreignIdKey,
type: .id(type: E.idType),
optional: optional,
unique: unique
)
self.field(field)
if autoForeignKeys {
self.foreignKey(
foreignIdKey,
references: E.idKey,
on: E.self,
named: foreignKeyName
)
}
}
public func int(
_ name: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .int,
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func string(
_ name: String,
length: Int? = nil,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .string(length: length),
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func double(
_ name: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .double,
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func bool(
_ name: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .bool,
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func bytes(
_ name: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .bytes,
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func date(
_ name: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .date,
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
public func custom(
_ name: String,
type: String,
optional: Bool = false,
unique: Bool = false,
default: NodeRepresentable? = nil
) {
let field = Field(
name: name,
type: .custom(type: type),
optional: optional,
unique: unique,
default: `default`
)
self.field(field)
}
// MARK: Relations
public func parent<E: Entity>(
_ entity: E.Type = E.self,
optional: Bool = false,
unique: Bool = false,
foreignIdKey: String = E.foreignIdKey
) {
foreignId(
for: E.self,
optional: optional,
unique: unique,
foreignIdKey: foreignIdKey
)
}
// MARK: Foreign Key
public func foreignKey(_ foreignKey: ForeignKey) {
foreignKeys.append(.some(foreignKey))
}
/// Adds a foreign key constraint from a local
/// column to a column on the foreign entity.
public func foreignKey<E: Entity>(
_ foreignIdKey: String,
references idKey: String,
on foreignEntity: E.Type = E.self,
named name: String? = nil
) {
let foreignKey = ForeignKey(
entity: entity,
field: foreignIdKey,
foreignField: idKey,
foreignEntity: foreignEntity,
name: name
)
self.foreignKey(foreignKey)
}
/// Adds a foreign key constraint from a local
/// column to a column on the foreign entity.
public func foreignKey<E: Entity>(
for: E.Type = E.self
) {
self.foreignKey(
E.foreignIdKey,
references: E.idKey,
on: E.self
)
}
// MARK: Raw
public func raw(_ string: String) {
fields.append(.raw(string, []))
}
}
public var autoForeignKeys = true
// MARK: Deprecated
extension Builder {
@available(*, deprecated, message: "Please use foreignKey(_: String, references: String, on: Entity, named: String)")
public func foreignKey<E: Entity>(
foreignIdKey: String = E.foreignIdKey,
referencesIdKey: String = E.idKey,
on foreignEntity: E.Type = E.self,
name: String? = nil
) {
self.foreignKey(
foreignIdKey,
references: referencesIdKey,
on: foreignEntity,
named: name
)
}
}
| 24.348548 | 121 | 0.505112 |
291dafcef98324147e8b98ff3cba90d1717518c0 | 646 | //
// HistoryTableViewCell.swift
// VirtualTourist
//
// Created by Xing Hui Lu on 3/8/16.
// Copyright © 2016 Xing Hui Lu. All rights reserved.
//
import UIKit
class HistoryTableViewCell: UITableViewCell {
@IBOutlet weak var changeType: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var dateOfChange: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.275862 | 65 | 0.679567 |
f81fc18d18bb5b0c5dc2e3d1c0829d351ef0cce0 | 1,023 | //
// UserPostData.swift
// Photostream
//
// Created by Mounir Ybanez on 06/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
protocol UserPostData {
var id: String { set get }
var message: String { set get }
var timestamp: Double { set get }
var photoUrl: String { set get }
var photoWidth: Int { set get }
var photoHeight: Int { set get }
var likes: Int { set get }
var comments: Int { set get }
var isLiked: Bool { set get }
var userId: String { set get }
var avatarUrl: String { set get }
var displayName: String { set get }
}
struct UserPostDataItem: UserPostData {
var id: String = ""
var message: String = ""
var timestamp: Double = 0
var photoUrl: String = ""
var photoWidth: Int = 0
var photoHeight: Int = 0
var likes: Int = 0
var comments: Int = 0
var isLiked: Bool = false
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
}
| 22.23913 | 56 | 0.597263 |
1e4350ea3c13ee463c1f4809ecd97061d1fbb873 | 5,065 | import UIKit
protocol ActionTitleTextDialogDelegate: AnyObject {
func didPressButton(
in actionTitleTextDialog: ActionTitleTextDialog
)
}
/// ActionTitleTextDialog used for PlaceholderView as contentView
final class ActionTitleTextDialog: UIView {
weak var delegate: ActionTitleTextDialogDelegate?
/// Icon content
var icon: UIImage {
get {
return iconView.image
}
set {
iconView.image = newValue
}
}
/// Textual content (title)
var title: String {
get {
return titleLabel.styledText ?? ""
}
set {
titleLabel.styledText = newValue
}
}
/// Textual content (subtitle)
var text: String {
get {
return textLabel.styledText ?? ""
}
set {
textLabel.styledText = newValue
}
}
/// Title for button
var buttonTitle: String {
set {
button.setStyledTitle(newValue, for: .normal)
}
get {
return button.styledTitle(for: .normal) ?? ""
}
}
override var accessibilityIdentifier: String? {
didSet {
guard let accessibilityIdentifier = accessibilityIdentifier else {
iconView.accessibilityIdentifier = nil
titleLabel.accessibilityIdentifier = nil
textLabel.accessibilityIdentifier = nil
button.accessibilityIdentifier = nil
return
}
iconView.accessibilityIdentifier = accessibilityIdentifier + ".iconView"
titleLabel.accessibilityIdentifier = accessibilityIdentifier + ".titleLabel"
textLabel.accessibilityIdentifier = accessibilityIdentifier + ".textLabel"
button.accessibilityIdentifier = accessibilityIdentifier + ".button"
}
}
// MARK: - UI properties
/// Image view, no image by default.
private(set) lazy var iconView = IconView()
private(set) lazy var titleLabel = UILabel()
private(set) lazy var textLabel = UILabel()
private(set) lazy var button: UIButton = {
$0.addTarget(
self,
action: #selector(buttonDidPress),
for: .touchUpInside
)
return $0
}(UIButton(type: .custom))
// MARK: - Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
deinit {
unsubscribeFromNotifications()
}
// MARK: - Setup view
private func setupView() {
layoutMargins = UIEdgeInsets(
top: Space.double,
left: Space.triple,
bottom: 0,
right: Space.triple
)
setupSubviews()
setupConstraints()
subscribeOnNotifications()
}
private func setupSubviews() {
textLabel.setContentCompressionResistancePriority(.highest, for: .vertical)
[
iconView,
titleLabel,
textLabel,
button,
].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
addSubview($0)
}
}
private func setupConstraints() {
let constraints = [
iconView.top.constraint(equalTo: topMargin),
iconView.centerX.constraint(equalTo: centerX),
iconView.leading.constraint(greaterThanOrEqualTo: leadingMargin),
titleLabel.leading.constraint(equalTo: leadingMargin),
titleLabel.trailing.constraint(equalTo: trailingMargin),
titleLabel.top.constraint(equalTo: iconView.bottom, constant: Space.double),
textLabel.leading.constraint(equalTo: leadingMargin),
textLabel.trailing.constraint(equalTo: trailingMargin),
textLabel.top.constraint(equalTo: titleLabel.bottom, constant: Space.single),
button.leading.constraint(greaterThanOrEqualTo: leadingMargin),
button.centerX.constraint(equalTo: centerX),
button.top.constraint(equalTo: textLabel.bottom, constant: Space.quadruple),
button.bottom.constraint(equalTo: bottomMargin),
]
NSLayoutConstraint.activate(constraints)
}
// MARK: - Notifications
private func subscribeOnNotifications() {
NotificationCenter.default.addObserver(
self,
selector: #selector(contentSizeCategoryDidChange),
name: UIContentSizeCategory.didChangeNotification,
object: nil
)
}
private func unsubscribeFromNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc
private func contentSizeCategoryDidChange() {
iconView.applyStyles()
titleLabel.applyStyles()
textLabel.applyStyles()
button.applyStyles()
}
@objc
private func buttonDidPress() {
delegate?.didPressButton(in: self)
}
}
| 27.82967 | 89 | 0.605133 |
b972860d7e4982df5c2d54ad744362a1562b75e2 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class S<T{func a<h{func b<T where h.g=a{{a{}{{var a{{let g=i{var b{{class B{struct Q{extension
| 44 | 94 | 0.734848 |
e04b8dd80e3cf3f3aac652571b91df6eb1c5ab59 | 1,661 | //
// MCEnvironmentType.swift
// MoyaChain
//
// Created by W&Z on 2019/6/27.
//
import Foundation
import Moya
public protocol ChainConfig {
/// The target's base `URL`.
var baseURL: URL { get }
/// The path to be appended to `baseURL` to form the full `URL`.
var path: String { get }
/// The HTTP method used in the request.
var method: Moya.Method { get }
/// Provides stub data for use in testing.
var sampleData: Data { get }
/// The type of HTTP task to be performed.
var task: Task { get }
/// The type of validation to perform on the request. Default is `.none`.
var validationType: ValidationType { get }
/// The headers to be used in the request.
var headers: [String: String]? { get }
}
extension ChainConfig{
public var validationType: ValidationType{
return .none
}
}
extension ChainConfig {
func asTargetType() -> Environment {
return Environment(env: self)
}
}
public struct Environment : TargetType {
public let baseURL: URL
public let path: String
public let method: Moya.Method
public let sampleData: Data
public let task: Task
public let headers: [String : String]?
public let validationType: ValidationType
init( env:ChainConfig) {
self.baseURL = env.baseURL
self.path = env.path
self.method = env.method
self.sampleData = env.sampleData
self.task = env.task
self.headers = env.headers
self.validationType = env.validationType
}
}
| 20.506173 | 77 | 0.597833 |
e425f494791c3afe607296cf2f410898244f3f07 | 689 | //
// polygon.swift
// PuckSpeedRadar
//
// Created by Aris Samad-Yahaya on 3/27/21.
//
import Foundation
class Polygon {
var xpoints: [Int];
var ypoints: [Int];
init() {
xpoints = [];
ypoints = [];
}
func addPoint(_ x: Int, _ y: Int) {
xpoints.append(x);
ypoints.append(y);
}
func getX(_ index: Int) -> Int {
return xpoints[index];
}
func getY(_ index: Int) -> Int {
return ypoints[index];
}
func size() -> Int {
return xpoints.count;
}
func getXPoints() -> [Int] {
let newArray = xpoints;
return newArray;
}
func getYPoints() -> [Int] {
let newArray = ypoints;
return newArray;
}
}
| 14.659574 | 44 | 0.554427 |
011146c946b005c692edcee5229efbdef1b9ee60 | 2,587 | //
// Constants.swift
// OkToDo
//
// Created by Oleksandr Kurtsev on 01/12/2021.
//
import UIKit
struct Colors {
static let niceBlue = UIColor(red: 71/255, green: 108/255, blue: 137/255, alpha: 1)
static let niceDark = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
static let mainWhite = UIColor(red: 242/255, green: 243/255, blue: 244/255, alpha: 1)
static let placeholder = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.25)
static let dateField = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.05)
}
struct Fonts {
static let avenir16 = UIFont(name: "AvenirNextCondensed-DemiBold", size: 16)
static let avenir20 = UIFont(name: "AvenirNextCondensed-DemiBold", size: 20)
static let avenir50 = UIFont(name: "AvenirNextCondensed-DemiBold", size: 50)
}
let kSaveString = "Save"
let kEditString = "Edit"
let kDeleteString = "Delete"
let kCancelString = "Cancel"
let kMyTasksString = "My tasks:"
let kCategoriesString = "Categories"
let kTextColorString = "Text Color"
let kBackColorString = "Back Color"
let kCategoryPlaceholder = "Enter a category name"
let kNewTaskString = "Create a new task"
let kAddNewCategoryString = "Add a new category"
let kCategoryEmptyString = "Category not selected"
let kEmptyTasksString = "You don't have any tasks yet"
let kAlertTitleOK = "OK"
let kAlertError = "Error"
let kAlertTitleConfirm = "Confirm"
let kAlertTitleCancel = "Cancel"
let kAlertTitleGallery = "Gallery"
let kAlertTitleCongr = "Congratulations"
let kAlertNewTaskMessage = "You added a new task"
let kTaskChangedMessage = "You have changed your task"
let kConfirmCancelMessage = "Your changes will be lost. Do you really want to continue?"
let kConfirmDeleteTask = "Are you sure you want to delete the task? This action is irrevocable."
let kConfirmDeleteCategory = "Are you sure you want to delete a category? All your tasks with this category will become category-free."
let kTaskLengthError = "Task name cannot be less than 3 characters long. Please correct it and try again."
let kCategoryLengthError = "Category name cannot be less than 3 characters long. Please correct it and try again."
let kPlaceholderName = "Write the name of the task"
let kPlaceholderCategory = "Select a task category"
let kPlaceholderDate = "Select a date:"
let kTaskImagePlaceholder = "ImagePlaceholder"
| 44.603448 | 136 | 0.682644 |
8fa6b39d00231c6e4e4704d52c4f1e139da0f1bc | 1,974 | //
// GCSwitch.swift
// GCoreVideoCalls
//
// Created by Evgenij Polubin on 28.03.2022.
//
import UIKit
final class GCSwitch: UISwitch {
init(onImage: UIImage?, offImage: UIImage?) {
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
layer.cornerRadius = 16
backgroundColor = .redOrange
addTarget(self, action: #selector(toggle), for: .valueChanged)
addImages(onImage: onImage, offImage: offImage)
transform = CGAffineTransform(scaleX: 1.25, y: 1.25)
}
@objc func toggle() {
isOn ? (backgroundColor = .greenCyan) : (backgroundColor = .redOrange)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addImages(onImage: UIImage?, offImage: UIImage?) {
guard let onImage = onImage,
let offImage = offImage
else { return }
let onImageView = UIImageView(image: onImage)
onImageView.translatesAutoresizingMaskIntoConstraints = false
onImageView.contentMode = .scaleAspectFit
let offImageView = UIImageView(image: offImage)
offImageView.translatesAutoresizingMaskIntoConstraints = false
offImageView.contentMode = .scaleAspectFit
addSubview(onImageView)
addSubview(offImageView)
NSLayoutConstraint.activate([
onImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 3),
onImageView.rightAnchor.constraint(equalTo: offImageView.leftAnchor, constant: -12),
onImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
onImageView.widthAnchor.constraint(equalTo: offImageView.widthAnchor),
offImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
offImageView.rightAnchor.constraint(equalTo: rightAnchor, constant: -3),
])
}
}
| 34.034483 | 96 | 0.651469 |
dd64fdf61936696b6e6e461595cd3db896661be7 | 790 | //
// TxReplaceResourceCell.swift
// Cosmostation
//
// Created by 정용주 on 2020/10/28.
// Copyright © 2020 wannabit. All rights reserved.
//
import UIKit
class TxReplaceResourceCell: UITableViewCell {
@IBOutlet weak var txIcon: UIImageView!
@IBOutlet weak var txTitleLabel: UILabel!
@IBOutlet weak var starnameLabel: UILabel!
@IBOutlet weak var starnameFeeAmountLabel: UILabel!
@IBOutlet weak var starnameFeeDenomLabel: UILabel!
@IBOutlet weak var resourceCntLabel: UILabel!
@IBOutlet weak var resourceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
starnameFeeAmountLabel.font = UIFontMetrics(forTextStyle: .caption1).scaledFont(for: Font_12_caption1)
}
}
| 27.241379 | 110 | 0.711392 |
569f708b20e06fe3d8a96fc612fbbf1e2de1473c | 529 | //
// ViewController.swift
// SalesManItemCategory_Category
//
// Created by Arabrellaxy on 11/20/2018.
// Copyright (c) 2018 Arabrellaxy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 21.16 | 80 | 0.6862 |
4a286dc0ba819a361fccf18912dbf2a49f92a83f | 7,633 | //
// IGRPhotoTweakView+NSLayoutConstraint.swift
// Pods
//
// Created by Vitalii Parovishnyk on 4/25/17.
//
//
import Foundation
extension IGRPhotoTweakView {
internal func setupMaskLayoutConstraints() {
//MARK: Top
self.topMask.translatesAutoresizingMaskIntoConstraints = false
var top = NSLayoutConstraint(item: self.topMask!,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
var leading = NSLayoutConstraint(item: self.topMask!,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
var trailing = NSLayoutConstraint(item: self.topMask!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.cropView,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
trailing.priority = .defaultHigh
var bottom = NSLayoutConstraint(item: self.topMask!,
attribute: .bottom,
relatedBy: .equal,
toItem: self.cropView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
bottom.priority = .defaultHigh
self.addConstraints([top, leading, trailing, bottom])
//MARK: Left
self.leftMask.translatesAutoresizingMaskIntoConstraints = false
top = NSLayoutConstraint(item: self.leftMask!,
attribute: .top,
relatedBy: .equal,
toItem: self.cropView,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
top.priority = .defaultHigh
leading = NSLayoutConstraint(item: self.leftMask!,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
trailing = NSLayoutConstraint(item: self.leftMask!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.cropView,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
trailing.priority = .defaultHigh
bottom = NSLayoutConstraint(item: self.leftMask!,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
self.addConstraints([top, leading, trailing, bottom])
//MARK: Right
self.rightMask.translatesAutoresizingMaskIntoConstraints = false
top = NSLayoutConstraint(item: self.rightMask!,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0.0)
leading = NSLayoutConstraint(item: self.rightMask!,
attribute: .leading,
relatedBy: .equal,
toItem: self.cropView,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
leading.priority = .defaultHigh
trailing = NSLayoutConstraint(item: self.rightMask!,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
bottom = NSLayoutConstraint(item: self.rightMask!,
attribute: .bottom,
relatedBy: .equal,
toItem: self.cropView,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
bottom.priority = .defaultHigh
self.addConstraints([top, leading, trailing, bottom])
//MARK: Bottom
self.bottomMask.translatesAutoresizingMaskIntoConstraints = false
top = NSLayoutConstraint(item: self.bottomMask!,
attribute: .top,
relatedBy: .equal,
toItem: self.cropView,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
top.priority = .defaultHigh
leading = NSLayoutConstraint(item: self.bottomMask!,
attribute: .leading,
relatedBy: .equal,
toItem: self.cropView,
attribute: .leading,
multiplier: 1.0,
constant: 0.0)
leading.priority = .defaultHigh
trailing = NSLayoutConstraint(item: self.bottomMask!,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0)
bottom = NSLayoutConstraint(item: self.bottomMask!,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0)
self.addConstraints([top, leading, trailing, bottom])
}
}
| 44.377907 | 73 | 0.358182 |
48030728d2e869196330edd59e334572cd37264e | 455 | // 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
var _=B
class a{
struct b{
class n{struct Q{
class
case,
| 30.333333 | 79 | 0.749451 |
21c99eee8fc0bbadf5009bad6e007d1c31d544b8 | 1,937 | //
// Extensions.swift
// PFactors_Example
//
// Created by Stephan Jancar on 20.10.17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import BigInt
extension Int {
func toUint() -> UInt64 {
if self >= 0 { return UInt64(self) }
let u = UInt64(self - Int.min) + UInt64(Int.max) + 1
return u
}
}
extension BigUInt {
func Build3Blocks() -> [String] {
var arr : [String] = []
let valstr = String(self)
var (str3,pos) = ("",0)
for c in valstr.reversed() {
(str3,pos) = (String(c) + str3,pos+1)
if pos % 3 == 0 {
arr.append(str3)
(str3,pos) = ("",0)
}
}
if str3 != "" { arr.append(str3) }
return arr
}
func FormatStr(maxrows : Int, rowlen : Int = 18) -> (String,rows: Int) {
if self == 0 { return ("0.",rows :1) }
let blocks = self.Build3Blocks()
var (outstr,len) = ("",0)
let blocksperrow = rowlen / 3
var rows = 1 + (blocks.count-1) / blocksperrow
var maxindex = maxrows * blocksperrow
if rows > maxrows {
rows = maxrows
maxindex = maxindex - 3 //Get place for ### Info
}
for i in 0..<rows {
for j in 0..<blocksperrow {
let index = i * blocksperrow + j
if index >= blocks.count { break }
if index >= maxindex {
var startstr = blocks[blocks.count-1]
if index < blocks.count - 2 {
startstr = startstr + "." + blocks[blocks.count-2]
}
outstr = startstr + ".###." + outstr
return (outstr,i)
}
let blockstr = blocks[index]
(outstr,len) = ( blockstr + "." + outstr,len+blockstr.count)
}
if i<rows-1 { outstr = "\n" + outstr }
}
return (outstr,rows)
}
}
extension String {
func asBigUInt() -> BigUInt {
var ret = BigUInt(0)
let chars = Array(self)
for c in chars {
switch c {
case "0", "1", "2", "3", "4" , "5", "6", "7", "8", "9":
let digit = BigUInt(String(c)) ?? 0
ret = ret * 10 + BigUInt(digit)
default:
break
}
}
return ret
}
}
| 22.523256 | 73 | 0.570986 |
4b8ee491600e3a0c372e0283cdd419e88d1e3053 | 282 | //
// SwiftUIDemoApp.swift
// SwiftUIDemo
//
// Created by Muukii on 2021/03/04.
// Copyright © 2021 muukii. All rights reserved.
//
import SwiftUI
@main
struct SwiftUIDemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 14.842105 | 49 | 0.599291 |
8a18de6ca8b3c91ff40aa644b1daedeb45debbf4 | 564 | //
// Created by Jamie Lynch on 23/03/2018.
// Copyright (c) 2018 Bugsnag. All rights reserved.
//
import Foundation
/**
* Sends a handled error to Bugsnag, which only includes a user's id
*/
internal class UserIdScenario: Scenario {
override func startBugsnag() {
self.config.autoTrackSessions = false;
super.startBugsnag()
}
override func run() {
Bugsnag.setUser("abc", withEmail: nil, andName: nil)
let error = NSError(domain: "UserIdScenario", code: 100, userInfo: nil)
Bugsnag.notifyError(error)
}
}
| 22.56 | 79 | 0.661348 |
76d0bfdcbfe01d8eaef0c804334299599d4bd071 | 9,611 | //
// UZTheme1.swift
// UizaSDK
//
// Created by Nam Kennic on 5/16/18.
// Copyright © 2018 Nam Kennic. All rights reserved.
//
import UIKit
import FrameLayoutKit
import AVKit
@objcMembers open class UZTheme1: NSObject, UZPlayerTheme {
public var id = "UZTheme1"
public weak var controlView: UZPlayerControlView?
public let topGradientLayer = CAGradientLayer()
public let bottomGradientLayer = CAGradientLayer()
public let frameLayout = StackFrameLayout(axis: .vertical, distribution: . top)
open var iconColor = UIColor.white
open var iconSize = CGSize(width: 24, height: 24)
open var skipIconSize = CGSize(width: 32, height: 32)
open var centerIconSize = CGSize(width: 92, height: 92)
open var seekThumbSize = CGSize(width: 24, height: 24)
open var buttonMinSize = CGSize(width: 32, height: 32)
public convenience init(iconSize: CGSize = CGSize(width: 24, height: 24), centerIconSize: CGSize = CGSize(width: 92, height: 92), seekThumbSize: CGSize = CGSize(width: 24, height: 24), iconColor: UIColor = .white) {
self.init()
self.iconSize = iconSize
self.centerIconSize = centerIconSize
self.iconColor = iconColor
self.seekThumbSize = seekThumbSize
}
public override init() {
}
open func updateUI() {
setupSkin()
setupLayout()
}
func setupSkin() {
guard let controlView = controlView else { return }
controlView.setDefaultThemeIcon()
// modify icon
let playlistIcon = UIImage(icon: .fontAwesomeSolid(.list), size: iconSize, textColor: iconColor, backgroundColor: .clear)
let helpIcon = UIImage(icon: .fontAwesomeSolid(.questionCircle), size: iconSize, textColor: iconColor, backgroundColor: .clear)
let ccIcon = UIImage(icon: .icofont(.cc), size: iconSize, textColor: iconColor, backgroundColor: .clear)
let playBigIcon = UIImage(icon: .fontAwesomeSolid(.playCircle), size: centerIconSize, textColor: iconColor, backgroundColor: .clear)
let pauseBigIcon = UIImage(icon: .fontAwesomeSolid(.pauseCircle), size: centerIconSize, textColor: iconColor, backgroundColor: .clear)
let playIcon = UIImage(icon: .googleMaterialDesign(.playArrow), size: iconSize, textColor: iconColor, backgroundColor: .clear)
let pauseIcon = UIImage(icon: .googleMaterialDesign(.pause), size: iconSize, textColor: iconColor, backgroundColor: .clear)
let nextIcon = UIImage(icon: .fontAwesomeSolid(.stepForward), size: skipIconSize, textColor: iconColor, backgroundColor: .clear)
let previousIcon = UIImage(icon: .fontAwesomeSolid(.stepBackward), size: skipIconSize, textColor: iconColor, backgroundColor: .clear)
controlView.playlistButton.setImage(playlistIcon, for: .normal)
controlView.helpButton.setImage(helpIcon, for: .normal)
controlView.ccButton.setImage(ccIcon, for: .normal)
controlView.playpauseCenterButton.setImage(playBigIcon, for: .normal)
controlView.playpauseCenterButton.setImage(pauseBigIcon, for: .selected)
controlView.playpauseButton.setImage(playIcon, for: .normal)
controlView.playpauseButton.setImage(pauseIcon, for: .selected)
controlView.nextButton.setImage(nextIcon, for: .normal)
controlView.previousButton.setImage(previousIcon, for: .normal)
controlView.nextButton.isHidden = true
controlView.previousButton.isHidden = true
if #available(iOS 9.0, *) {
let pipStartIcon = AVPictureInPictureController.pictureInPictureButtonStartImage(compatibleWith: nil).colorize(with: iconColor)
let pipStopIcon = AVPictureInPictureController.pictureInPictureButtonStopImage(compatibleWith: nil).colorize(with: iconColor)
controlView.pipButton.setImage(pipStartIcon, for: .normal)
controlView.pipButton.setImage(pipStopIcon, for: .selected)
controlView.pipButton.imageView?.contentMode = .scaleAspectFit
controlView.pipButton.isHidden = !AVPictureInPictureController.isPictureInPictureSupported()
}
// controlView.airplayButton.setupDefaultIcon(iconSize: iconSize, offColor: iconColor)
controlView.castingButton.setupDefaultIcon(iconSize: iconSize, offColor: iconColor)
controlView.titleLabel.textColor = .white
controlView.titleLabel.font = UIFont.systemFont(ofSize: 14)
let timeLabelFont = UIFont(name: "Arial", size: 12)
let timeLabelColor = UIColor.white
let timeLabelShadowColor = UIColor.black
let timeLabelShadowOffset = CGSize(width: 0, height: 1)
controlView.currentTimeLabel.textColor = timeLabelColor
controlView.currentTimeLabel.font = timeLabelFont
controlView.currentTimeLabel.shadowColor = timeLabelShadowColor
controlView.currentTimeLabel.shadowOffset = timeLabelShadowOffset
controlView.totalTimeLabel.textColor = timeLabelColor
controlView.totalTimeLabel.font = timeLabelFont
controlView.totalTimeLabel.shadowColor = timeLabelShadowColor
controlView.totalTimeLabel.shadowOffset = timeLabelShadowOffset
controlView.remainTimeLabel.textColor = timeLabelColor
controlView.remainTimeLabel.font = timeLabelFont
controlView.remainTimeLabel.shadowColor = timeLabelShadowColor
controlView.remainTimeLabel.shadowOffset = timeLabelShadowOffset
}
func setupLayout() {
guard let controlView = controlView else { return }
controlView.allControlViews.forEach { (view) in
frameLayout.addSubview(view)
}
frameLayout.isUserInteractionEnabled = true
topGradientLayer.colors = [UIColor(white: 0.0, alpha: 0.8).cgColor, UIColor(white: 0.0, alpha: 0.0).cgColor]
bottomGradientLayer.colors = [UIColor(white: 0.0, alpha: 0.0).cgColor, UIColor(white: 0.0, alpha: 0.8).cgColor]
controlView.containerView.layer.addSublayer(topGradientLayer)
controlView.containerView.layer.addSublayer(bottomGradientLayer)
frameLayout + HStackLayout {
$0 + [controlView.backButton, controlView.titleLabel]
($0 + 0).flexible()
($0 + [controlView.pipButton, controlView.castingButton, controlView.playlistButton, controlView.settingsButton]).forEach { (layout) in
layout.minSize = buttonMinSize
}
$0.spacing = 10
}
frameLayout + HStackLayout {
($0 + [controlView.previousButton, controlView.playpauseCenterButton, controlView.nextButton]).forEach { (layout) in
layout.alignment = (.center, .center)
}
$0.spacing = 10
$0.alignment = (.center, .center)
$0.distribution = .center
$0.flexible()
}
frameLayout + HStackLayout {
$0 + HStackLayout {
$0 + controlView.currentTimeLabel
($0 + controlView.timeSlider).flexible()
$0 + controlView.remainTimeLabel
$0.spacing = 10
$0.flexible()
$0.ignoreHiddenView = false
}
($0 + [controlView.backwardButton, controlView.forwardButton, controlView.fullscreenButton]).forEach { (layout) in
layout.minSize = buttonMinSize
}
$0.spacing = 10
}
frameLayout.padding(top: 10, left: 10, bottom: 0, right: 10)
controlView.containerView.addSubview(frameLayout)
}
open func layoutControls(rect: CGRect) {
frameLayout.frame = rect
frameLayout.layoutIfNeeded()
controlView?.loadingIndicatorView?.center = controlView?.center ?? .zero
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
topGradientLayer.frame = frameLayout.firstFrameLayout?.frame.inset(by: UIEdgeInsets(top: -frameLayout.edgeInsets.top, left: -frameLayout.edgeInsets.left, bottom: -frameLayout.edgeInsets.bottom, right: -frameLayout.edgeInsets.right)) ?? .zero
bottomGradientLayer.frame = frameLayout.lastFrameLayout?.frame.inset(by: UIEdgeInsets(top: -frameLayout.edgeInsets.top, left: -frameLayout.edgeInsets.left, bottom: -frameLayout.edgeInsets.bottom, right: -frameLayout.edgeInsets.right)) ?? .zero
CATransaction.commit()
guard let controlView = controlView else { return }
let viewSize = controlView.bounds.size
if !controlView.liveBadgeView.isHidden {
let badgeSize = controlView.liveBadgeView.sizeThatFits(viewSize)
controlView.liveBadgeView.frame = CGRect(x: (viewSize.width - badgeSize.width)/2, y: 10, width: badgeSize.width, height: badgeSize.height)
}
if !controlView.enlapseTimeLabel.isHidden {
let labelSize = controlView.enlapseTimeLabel.sizeThatFits(viewSize)
controlView.enlapseTimeLabel.frame = CGRect(x: 10, y: viewSize.height - labelSize.height - 10, width: labelSize.width, height: labelSize.height)
}
}
open func cleanUI() {
topGradientLayer.removeFromSuperlayer()
bottomGradientLayer.removeFromSuperlayer()
}
open func allButtons() -> [UIButton] {
return []
}
open func showLoader() {
guard let controlView = controlView else { return }
if controlView.loadingIndicatorView == nil {
if #available(iOS 13.0, *) {
controlView.loadingIndicatorView = UIActivityIndicatorView(style: .medium)
}
else {
controlView.loadingIndicatorView = UIActivityIndicatorView(style: .white)
}
controlView.addSubview(controlView.loadingIndicatorView!)
}
controlView.loadingIndicatorView?.isHidden = false
controlView.loadingIndicatorView?.startAnimating()
}
open func hideLoader() {
controlView?.loadingIndicatorView?.isHidden = true
controlView?.loadingIndicatorView?.stopAnimating()
}
open func update(withResource: UZPlayerResource?, video: UZVideoItem?, playlist: [UZVideoItem]?) {
let isEmptyPlaylist = (playlist?.count ?? 0) < 2
controlView?.nextButton.isHidden = isEmptyPlaylist
controlView?.previousButton.isHidden = isEmptyPlaylist
}
open func alignLogo() {
// align logo manually here if needed
}
public func updateLiveViewCount(_ viewCount: Int) {
controlView?.liveBadgeView.views = viewCount
}
}
| 41.248927 | 245 | 0.752679 |
ebf8cea2cc620a9cca4c71feb48b1da9d5e0dd53 | 1,714 | //
// StartMenuViewModel.swift
// CoronaContact
//
import Resolver
import UIKit
class StartMenuViewModel: ViewModel {
weak var coordinator: StartMenuCoordinator?
weak var viewController: StartMenuViewController?
@Injected private var repository: HealthRepository
private var subscriptions: Set<AnySubscription> = []
var isFunctionsSectionHidden: Bool { repository.hasAttestedSickness }
var isSelfTestFunctionAvailable: Bool {
!(repository.isProbablySick || repository.hasAttestedSickness)
}
var hasAttestedSickness: Bool { repository.hasAttestedSickness }
init(with coordinator: StartMenuCoordinator) {
self.coordinator = coordinator
repository.$userHealthStatus
.subscribe { [weak self] _ in
self?.updateView()
}
.add(to: &subscriptions)
}
func closeMenu() {
coordinator?.finish()
}
func checkSymptoms() {
coordinator?.selfTesting()
}
func reportPositiveDoctorsDiagnosis() {
coordinator?.sicknessCertificate()
}
func revokeSickness() {
coordinator?.revokeSickness()
}
func shareApp() {
coordinator?.shareApp()
}
func aboutApp() {
coordinator?.openOnboarding()
}
func website(_ page: ExternalWebsite) {
page.openInSafariVC()
}
func openSavedIDs() {
coordinator?.openSavedIDs()
}
func openSourceLicenses() {
coordinator?.openLicences()
}
func dataPrivacy() {
coordinator?.openPrivacy()
}
func imprint() {
coordinator?.openImprint()
}
func updateView() {
viewController?.updateView()
}
}
| 21.425 | 73 | 0.635939 |
e92354b9873c5c2b50b8b4d9a4c1980128853da9 | 2,820 | //
// ViewController.swift
// L11-UIViewController
//
// Created by Антон Сафронов on 24.05.2021.
//
import UIKit
class ViewController: UIViewController {
lazy var textField: UITextField = {
let textF = UITextField()
textF.borderStyle = .roundedRect
textF.textAlignment = .center
textF.placeholder = "Текст"
return textF
}()
lazy var shareButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Share", for: .normal)
button.backgroundColor = .red
button.setTitleColor(.black, for: .normal)
button.layer.cornerRadius = 8
button.addTarget(self, action: #selector(share), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .orange
view.addSubview(textField)
view.addSubview(shareButton)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
setTextFieldConstraints()
setButtonConstraints()
}
func setTextFieldConstraints() {
textField.translatesAutoresizingMaskIntoConstraints = false
textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
textField.topAnchor.constraint(equalTo: view.topAnchor, constant: view.bounds.height/2).isActive = true
textField.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setButtonConstraints() {
shareButton.translatesAutoresizingMaskIntoConstraints = false
shareButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true
shareButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40).isActive = true
shareButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40).isActive = true
shareButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
}
@objc func share() {
if textField.text?.count == 0 {
textField.placeholder = "Напечатайте что-нибудь"
return
}
let items: [String] = ["Text fot Share"]
let myActivity = ShareActivity(title: "myActivity", image: nil) { items in
print(items)
}
let ac = UIActivityViewController(activityItems: items, applicationActivities: [myActivity])
ac.excludedActivityTypes = [.postToFlickr, .postToVimeo, .saveToCameraRoll]
present(ac, animated: true, completion: nil)
}
}
| 34.390244 | 126 | 0.659929 |
161344b2d66f8b8bab3bac55d81affea8bd052ec | 1,001 | //
// IOSSwiftBoilerTests.swift
// IOSSwiftBoilerTests
//
// Created by Godson Ukpere on 3/17/16.
// Copyright © 2016 Godson Ukpere. All rights reserved.
//
import XCTest
@testable import IOSSwiftBoiler
class IOSSwiftBoilerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 27.054054 | 111 | 0.647353 |
9b4ab5a86d5b7d031cc8322582ee00e734cb7e78 | 642 | // Copyright 2020 Penguin Authors
//
// 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.
struct Penguin {
var text = "Hello, World!"
}
| 35.666667 | 75 | 0.73676 |
f82f9a638fbfdd49a0e5d1bcd824d2a4a6360d47 | 977 | //
// LabShare_FrontTests.swift
// LabShare-FrontTests
//
// Created by Alexander Frazis on 28/8/20.
// Copyright © 2020 CITS3200. All rights reserved.
//
import XCTest
@testable import LabShare_Front
class LabShare_FrontTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.914286 | 111 | 0.675537 |
186e1d9ec7c71bb509f2a779b1855bdb326ca38b | 416 | //
// hold.swift
// Flare
//
// Created by Umberto Sonnino on 2/18/19.
// Copyright © 2019 2Dimensions. All rights reserved.
//
import Foundation
import Foundation
class HoldInterpolator: Interpolator {
static let _instance = HoldInterpolator()
class var instance: HoldInterpolator {
return _instance
}
func getEasedMix(mix: Float) -> Float {
return 0.0
}
}
| 16.64 | 54 | 0.641827 |
291a2661921343d07b7da21a9c273faf02b6ab8a | 1,266 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// SettingsHeaderViewTheme.swift
import Foundation
import MacaroonUIKit
struct SingleGrayTitleHeaderViewTheme: LayoutSheet, StyleSheet {
let backgroundColor: Color
let title: TextStyle
let bottomInset: LayoutMetric
let horizontalInset: LayoutMetric
init(_ family: LayoutFamily) {
self.backgroundColor = AppColors.Shared.System.background
self.title = [
.textAlignment(.left),
.textOverflow(FittingText()),
.textColor(AppColors.Components.Text.gray),
.font(Fonts.DMSans.regular.make(13))
]
self.bottomInset = 8
self.horizontalInset = 24
}
}
| 30.142857 | 75 | 0.695893 |
e9077edb1ee11122ef43ce70fdd85514adf1bcd6 | 1,246 | //
// UpdateContactRequest.swift
// Pods
//
// Created by Pavel Dvorovenko on 1/16/17.
//
//
import Foundation
public final class UpdateContactRequest{
public var firstName : String?
public var lastName : String?
public var phone: String?
public var email: String?
public var zipCode : String?
public var birthdate: String?
public var gender = "Unknown"
public var emailOptIn = false
public var txtOptIn = false
public var pushNotificationOptin = false
public var inboxMessageOptin = false
public var preferredReward : String?
public init(contact: BEContact?) {
self.firstName = contact?.firstName
self.lastName = contact?.lastName
self.phone = contact?.phone?.stringByReplacingOccurrencesOfString("-", withString: "")
self.email = contact?.email
self.zipCode = contact?.zipCode
self.birthdate = contact?.birthday
if let gender = contact?.gender {
self.gender = gender
}
if let optIn = contact?.emailOptin {
self.emailOptIn = optIn > 0
}
if let optIn = contact?.pushNotificationOptin {
self.pushNotificationOptin = optIn > 0
}
self.inboxMessageOptin = self.pushNotificationOptin
self.preferredReward = contact?.preferredReward
}
}
| 27.086957 | 90 | 0.702247 |
2fd85b3cf019623ad011daa710dd70a60e7a2394 | 912 | //
// Donate+Tests.swift
// NCOV_Map
//
// Created by Emil Karimov on 18/02/2020.
// Copyright © 2020 ESKARIA. All rights reserved.
//
import XCTest
@testable import NCOV_Map
class DonateTests: XCTestCase {
override func 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.
}
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.823529 | 111 | 0.640351 |
de377303a4162fbffca96569444cf9862d862b00 | 6,300 | //
// AsyncUDP+Receive.swift
// AsyncNetwork
//
// Created by Kevin Hoogheem on 3/5/17.
//
//
// 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.
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Foundation
import Dispatch
public extension AsyncUDP {
/// Continous Receive of the UDP Packets
///
/// - Throws: Throws SocketError if error condition
public func beginReceiving() throws {
var errorCode: SocketError?
let block = DispatchWorkItem {
if self.flags.contains(.receiveContinous) == false {
if self.flags.contains(.didBind) == false {
errorCode = SocketError(.notBound(msg: "Must bind a socket prior to receiving."))
return
}
//Remove Receive once if set
self.flags.remove(.receiveOnce)
_ = self.flags.insert(.receiveContinous)
self.socketQueue.async {
self.doReceive()
}
}
}
if isCurrentQueue == true {
block.perform()
} else {
socketQueue.sync(execute: block)
}
if let errors = errorCode {
throw errors
}
}
/// Receives One UDP Message at a time
///
/// - Throws: Throws SocketError if error condition
public func receiveOnce() throws {
var errorCode: SocketError?
let block = DispatchWorkItem {
if self.flags.contains(.receiveContinous) == true {
errorCode = SocketError(.alreadyReceiving(msg: "Already Receiving Data. Must pause prior to calling receiveOnce"))
return
}
if self.flags.contains(.receiveOnce) == false {
if self.flags.contains(.didCreateSockets) == false {
errorCode = SocketError(.notBound(msg: "You must bind the Socket prior to Receiving"))
return
}
self.flags.remove(.receiveContinous)
_ = self.flags.insert(.receiveOnce)
//Continue to Receive
self.socketQueue.async {
self.doReceive()
}
}
}
if isCurrentQueue == true {
block.perform()
} else {
socketQueue.sync(execute: block)
}
if let errors = errorCode {
throw errors
}
}
}
//MARK: - Suspend/Receive
internal extension AsyncUDP {
internal func suspendReceive() {
if flags.contains(.recvSourceSuspend) == false {
if let source = receiveSource {
source.suspend()
_ = flags.insert(.recvSourceSuspend)
}
}
}
internal func resumeReceive() {
if flags.contains(.recvSourceSuspend) == true {
if let source = receiveSource {
source.resume()
flags.remove(.recvSourceSuspend)
}
}
}
internal func doReceive() {
if (flags.contains(.receiveContinous) || flags.contains(.receiveOnce)) == false {
if socketBytesAvailable > 0 {
suspendReceive()
}
return
}
//No Data
if socketBytesAvailable == 0 {
resumeReceive()
return
}
assert(socketBytesAvailable > 0, "Invalid Logic")
var readData:(data: [UInt8], sender: InternetAddress)
do {
readData = try self.socket!.receivefrom(maxBytes: maxReceiveSize)
} catch {
//print("Receive \(error)")
return
}
var waitingForSocket: Bool = false
var notifyDelegate: Bool = false
if readData.data.count == 0 {
waitingForSocket = true
} else if (readData.data.count < 0) {
if errno == EAGAIN {
waitingForSocket = true
} else {
closeSocketFinal()
return
}
} else {
if UInt(readData.data.count) > socketBytesAvailable {
socketBytesAvailable = 0
} else {
socketBytesAvailable -= UInt(readData.data.count)
}
let responseDgram = Data(bytes: readData.data)
//no errors go ahead and notify
notifyRecieveDelegate(data: responseDgram, fromAddress: readData.sender)
notifyDelegate = true
}
if waitingForSocket == true {
resumeReceive()
} else {
if notifyDelegate == true {
flags.remove(UdpSocketFlags.receiveOnce)
}
if flags.contains(UdpSocketFlags.receiveContinous) == true {
doReceive()
}
}
}
internal func doReceiveEOF() {
closeSocketFinal()
}
internal func notifyRecieveDelegate(data: Data, fromAddress address: InternetAddress) {
for observer in observers {
//Observer decides which queue it will send back on
observer.socketDidReceive(self, data: data, fromAddress: address)
}
}
}
| 26.470588 | 131 | 0.563651 |
5bbe95d6312381efcffd36a332fd5aae784458be | 2,559 | //
// CubicFit.swift
// maths
//
// Created by Adam Fowler on 18/04/2017.
// Code based on this page https://rosettacode.org/wiki/Polynomial_regression
//
import Foundation
public class PolynomialFunction {
// fit()
// Find the coefficients of a polynomial function that approximates the graph that contains the list of points supplied
public static func fit(xPoints: Vector, yPoints: Vector, order: Int) -> Vector {
assert(order < xPoints.count)
var summedXPowers : [Double] = []
var summedXYPowers : [Double] = []
let xPowers = xPoints.copy()
for _ in 1...order * 2 {
summedXPowers.append(xPowers.Sum())
xPowers.operate(xPoints, operation:{a,b in return a*b})
}
let xyPowers = xPoints.copy()
summedXYPowers.append(yPoints.Sum())
for _ in 0..<order {
summedXYPowers.append(Vector(xyPowers, yPoints, operation:{a,b in return a*b}).Sum())
xyPowers.operate(xPoints, operation:{a,b in return a*b})
}
let matrix = Matrix(xSize: order+1, ySize: order+1)
matrix[0][0] = Double(xPoints.count)
for i in 0..<order+1 {
for j in 0..<order+1 {
if i + j != 0 {
matrix[j][i] = summedXPowers[i+j-1]
}
}
}
let inverse = matrix.inverse()
return inverse! * Vector(summedXYPowers)
}
// compute()
// Return polynomial result, given x
public static func compute(coeffs: Vector, x: Double) -> Double {
var power = 1.0
var value = 0.0
for i in 0..<coeffs.count {
value += coeffs[i] * power
power *= x
}
return value
}
// solveNewtonRaphson()
// solve a polynomial equation f(x) = 0 using Newton Raphson method
public static func solveNewtonRaphson(coeffs: Vector, initialValue: Double, threshold: Double) -> Double {
var derivativeCoeffs : [Double] = coeffs.elements
derivativeCoeffs.remove(at:0)
for i in 0..<derivativeCoeffs.count {
derivativeCoeffs[i] *= Double(i+1)
}
let derivative = Vector(derivativeCoeffs)
var x = initialValue
while(true) {
let newX = x - compute(coeffs: coeffs, x: x) / compute(coeffs: derivative, x: x)
if abs(newX - x) < threshold {
break
}
x = newX
print(x)
}
return x
}
}
| 30.831325 | 123 | 0.553732 |
9b6f38a9f0f4ec1d124c71f6b21018ed7d30d9af | 1,255 | //
// MSUnderlineTextField.swift
// MVVM Demo
//
// Created by Malav Soni on 11/11/19.
// Copyright © 2019 Malav Soni. All rights reserved.
//
import UIKit
class MSUnderlineTextField: MSTextField {
private var bottomLineLayer:CAShapeLayer!
private var activeTextFieldColor:UIColor = UIColor.appTintColor
private var inActiveTextFieldColor:UIColor = UIColor.appLightGreyColor
var bottomLineHeight:CGFloat = 1
override func commonInit() {
super.commonInit()
self.setupBottomBorder()
self.delegate = self
}
override func layoutSubviews() {
super.layoutSubviews()
self.setupBottomBorder()
}
private func setupBottomBorder() -> Void{
if bottomLineLayer == nil{
bottomLineLayer = CAShapeLayer.init()
self.layer.addSublayer(bottomLineLayer)
}
bottomLineLayer.frame = CGRect.init(x: 0, y: self.frame.size.height - bottomLineHeight, width: self.frame.size.width, height: bottomLineHeight)
self.bottomLineLayer.backgroundColor = self.isFirstResponder ? self.activeTextFieldColor.cgColor : self.inActiveTextFieldColor.cgColor
bottomLineLayer.cornerRadius = self.bottomLineHeight / 2.0
}
}
| 29.880952 | 151 | 0.69004 |
f981e896ee7a155c71d6a75a4b160113f10dce1d | 726 | import UIKit
public protocol ReusableView: class {}
public extension ReusableView where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
public extension UITableView {
func register<Cell: UITableViewCell>(_ type: Cell.Type) {
register(Cell.self, forCellReuseIdentifier: Cell.reuseIdentifier)
}
}
public extension UITableView {
func dequeueReusableCell<Cell: UITableViewCell>(for indexPath: IndexPath) -> Cell {
guard let cell = dequeueReusableCell(withIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else { fatalError("Could not dequeue reusable cell") }
return cell
}
}
extension UITableViewCell: ReusableView { }
| 29.04 | 162 | 0.72865 |
e9a1cdfb88956270ba18ded96b33e78de742f0cc | 946 | /**
* Question Link: https://leetcode.com/problems/gas-station/
* Primary idea: use currentSum and total to keep track of the gas and cost,
* change start index when currentSum is less than 0
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class GasStation {
func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
let totalGas = gas.reduce(0) { $0 + $1 }, totalCost = cost.reduce(0) { $0 + $1 }
guard totalGas >= totalCost else {
return -1
}
var start = 0, gasSum = 0, costSum = 0
for (i, currentGas) in gas.enumerated() {
let currentCost = cost[i]
gasSum += currentGas
costSum += currentCost
if gasSum < costSum {
start = i + 1
gasSum = 0
costSum = 0
}
}
return start
}
} | 27.823529 | 88 | 0.491543 |
8a59f6fc7d63ca7c59720a1aaecf4e473269181f | 295 | // 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 < {
enum e {
{
}
var f = V
let a {
func f<T where A: Array {
{
}
}
protocol A : A.b
{
{
{
}
}
{
{
{
{
}
}
}
}
{
}
func b
| 9.21875 | 87 | 0.616949 |
9c14383a11a7d2aa7169bc27055d6cbd73f47f10 | 1,028 | //
// ViewController.swift
// MiddlewareCenter
//
// Created by catchzeng on 09/07/2018.
// Copyright (c) 2018 catchzeng. All rights reserved.
//
import UIKit
import MiddlewareCenter
class ViewController: UIViewController {
let center = MiddlewareCenter()
override func viewDidLoad() {
super.viewDidLoad()
center.use(BeforeUpload())
center.use(StartUpload())
center.use(EndUpload())
center.handle(ctx: nil)
}
}
public class StartUpload: Middleware {
public override func execute() {
print("before StartUpload.")
next?.execute()
print("after StartUpload.")
}
}
public class BeforeUpload: Middleware {
public override func execute() {
print("before upload.")
next?.execute()
print("after upload.")
}
}
public class EndUpload: Middleware {
public override func execute() {
print("before EndUpload.")
next?.execute()
print("after EndUpload.")
}
}
| 20.56 | 54 | 0.61284 |
292dc41d1ac9e28197f62fe41be2699589b0181a | 685 | //
// UIColorExtensions.swift
// EasyCheckout
//
// Created by parry on 8/3/16.
// Copyright © 2016 MCP. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
} | 29.782609 | 116 | 0.60292 |
75d93db85e8c763e49f193d2b3e33721c9f5f2f1 | 856 | //
// CustomFavoriteDetail.swift
// Ways
//
// Created by Felipe Luna Tersi on 12/09/19.
// Copyright © 2019 IBM. All rights reserved.
//
import UIKit
class CustomFavoriteDetail: UIViewController {
var custom: Customization!
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var titleFav: UILabel!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var costs: UILabel!
@IBOutlet weak var descriptionFav: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let oCustom = self.custom {
titleFav.text = oCustom.title
costs.text = "R$ \(oCustom.costs)"
time.text = oCustom.time
photo.image = oCustom.photo
descriptionFav.text = oCustom.description
}
// Do any additional setup after loading the view.
}
}
| 24.457143 | 58 | 0.632009 |
0837b9cec65f92e246762a1a6dd85b374028a7b5 | 358 | import XCTest
@testable import DI
final class DITests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(DI().text, "Hello, World!")
}
}
| 29.833333 | 91 | 0.581006 |
799117910ac7b39843747dd935b1673f2c7a516c | 4,979 | //
// IssueType.swift
// Asclepius
// Module: R4
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
A code that describes the type of issue.
URL: http://hl7.org/fhir/issue-type
ValueSet: http://hl7.org/fhir/ValueSet/issue-type
*/
public enum IssueType: String, AsclepiusPrimitiveType {
/// Content invalid against the specification or a profile.
case invalid
/// A structural issue in the content such as wrong namespace, unable to parse the content completely, invalid
/// syntax, etc.
case structure
/// A required element is missing.
case required
/// An element or header value is invalid.
case value
/// A content validation rule failed - e.g. a schematron rule.
case invariant
/// An authentication/authorization/permissions issue of some kind.
case security
/// The client needs to initiate an authentication process.
case login
/// The user or system was not able to be authenticated (either there is no process, or the proferred token is
/// unacceptable).
case unknown
/// User session expired; a login may be required.
case expired
/// The user does not have the rights to perform this action.
case forbidden
/// Some information was not or might not have been returned due to business rules, consent or privacy rules, or
/// access permission constraints. This information may be accessible through alternate processes.
case suppressed
/// Processing issues. These are expected to be final e.g. there is no point resubmitting the same content
/// unchanged.
case processing
/// The interaction, operation, resource or profile is not supported.
case notSupported = "not-supported"
/// An attempt was made to create a duplicate record.
case duplicate
/// Multiple matching records were found when the operation required only one match.
case multipleMatches = "multiple-matches"
/// The reference provided was not found. In a pure RESTful environment, this would be an HTTP 404 error, but this
/// code may be used where the content is not found further into the application architecture.
case notFound = "not-found"
/// The reference pointed to content (usually a resource) that has been deleted.
case deleted
/// Provided content is too long (typically, this is a denial of service protection type of error).
case tooLong = "too-long"
/// The code or system could not be understood, or it was not valid in the context of a particular ValueSet.code.
case codeInvalid = "code-invalid"
/// An extension was found that was not acceptable, could not be resolved, or a modifierExtension was not
/// recognized.
case `extension`
/// The operation was stopped to protect server resources; e.g. a request for a value set expansion on all of SNOMED
/// CT.
case tooCostly = "too-costly"
/// The content/operation failed to pass some business rule and so could not proceed.
case businessRule = "business-rule"
/// Content could not be accepted because of an edit conflict (i.e. version aware updates). (In a pure RESTful
/// environment, this would be an HTTP 409 error, but this code may be used where the conflict is discovered further
/// into the application architecture.).
case conflict
/// Transient processing issues. The system receiving the message may be able to resubmit the same content once an
/// underlying issue is resolved.
case transient
/// A resource/record locking failure (usually in an underlying database).
case lockError = "lock-error"
/// The persistent store is unavailable; e.g. the database is down for maintenance or similar action, and the
/// interaction or operation cannot be processed.
case noStore = "no-store"
/// An unexpected internal error has occurred.
case exception
/// An internal timeout has occurred.
case timeout
/// Not all data sources typically accessed could be reached or responded in time, so the returned information might
/// not be complete (applies to search interactions and some operations).
case incomplete
/// The system is not prepared to handle this request due to load management.
case throttled
/// A message unrelated to the processing success of the completed operation (examples of the latter include things
/// like reminders of password expiry, system maintenance times, etc.).
case informational
}
| 37.43609 | 118 | 0.727254 |
75fd36e021187514b5f20ffcef7c2036daeb325f | 10,282 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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
/// Bindable is like an observer, but knows to manage the subscription by itself.
public protocol BindableProtocol {
/// Type of the received elements.
associatedtype Element
/// Establish a one-way binding between the signal and the receiver.
/// - Warning: You are recommended to use `bind(to:)` on the signal when binding.
func bind(signal: Signal<Element, Never>) -> Disposable
}
extension SignalProtocol where Error == Never {
/// Establish a one-way binding between the source and the bindable.
/// - Parameter bindable: A binding target that will receive signal events.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<B: BindableProtocol>(to bindable: B) -> Disposable where B.Element == Element {
return bindable.bind(signal: toSignal())
}
/// Establish a one-way binding between the source and the bindable.
/// - Parameter bindable: A binding target that will receive signal events.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<B: BindableProtocol>(to bindable: B) -> Disposable where B.Element: OptionalProtocol, B.Element.Wrapped == Element {
return map { B.Element($0) }.bind(to: bindable)
}
}
extension BindableProtocol where Self: SignalProtocol, Self.Error == Never {
/// Establish a two-way binding between the source and the bindable.
/// - Parameter target: A binding target that will receive events from
/// the receiver and a source that will send events to the receiver.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bidirectionalBind<B: BindableProtocol & SignalProtocol>(to target: B) -> Disposable where B.Element == Element, B.Error == Error {
let scheduler = ExecutionContext.nonRecursive()
let d1 = receive(on: scheduler).bind(to: target)
let d2 = target.receive(on: scheduler).bind(to: self)
return CompositeDisposable([d1, d2])
}
}
extension SignalProtocol where Error == Never {
/// Bind the receiver to the target using the given setter closure. Closure is
/// called whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// Also conforms to `BindingExecutionContextProvider` that provides that context on which to execute the setter.
/// - setter: A closure that gets called on each next signal event both with the target and the sent element.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, setter: @escaping (Target, Element) -> Void) -> Disposable
where Target: BindingExecutionContextProvider {
return bind(to: target, context: target.bindingExecutionContext, setter: setter)
}
/// Bind the receiver to the target using the given setter closure. Closure is
/// called whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// - context: An execution context on which to execute the setter.
/// - setter: A closure that gets called on each next signal event both with the target and the sent element.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, context: ExecutionContext, setter: @escaping (Target, Element) -> Void) -> Disposable {
return prefix(untilOutputFrom: target.deallocated).observeNext { [weak target] element in
context.execute {
if let target = target {
setter(target, element)
}
}
}
}
/// Bind the receiver to target's property specified by the key path. The property is
/// updated whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// - keyPath: A key path to the property that will be updated with each sent element.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, keyPath: ReferenceWritableKeyPath<Target, Element>) -> Disposable where Target: BindingExecutionContextProvider {
return bind(to: target) { target, element in
target[keyPath: keyPath] = element
}
}
/// Bind the receiver to target's property specified by the key path. The property is
/// updated whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// - keyPath: A key path to the property that will be updated with each sent element.
/// - context: An execution context on which to execute the setter.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, keyPath: ReferenceWritableKeyPath<Target, Element>, context: ExecutionContext) -> Disposable {
return bind(to: target, context: context) { target, element in
target[keyPath: keyPath] = element
}
}
}
extension SignalProtocol where Error == Never, Element == Void {
/// Bind the receiver to the target using the given setter closure. Closure is
/// called whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// Also conforms to `BindingExecutionContextProvider` that provides that context on which to execute the setter.
/// - setter: A closure that gets called on each next signal event with the target.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, setter: @escaping (Target) -> Void) -> Disposable
where Target: BindingExecutionContextProvider {
return bind(to: target, context: target.bindingExecutionContext, setter: setter)
}
/// Bind the receiver to the target using the given setter closure. Closure is
/// called whenever the signal emits `next` event.
///
/// Binding lives until either the signal completes or the target is deallocated.
/// That means that the returned disposable can be safely ignored.
///
/// - Parameters:
/// - target: A binding target. Conforms to `Deallocatable` so it can inform the binding
/// when it gets deallocated. Upon target deallocation, the binding gets automatically disposed.
/// - context: An execution context on which to execute the setter.
/// - setter: A closure that gets called on each next signal event with the target.
/// - Returns: A disposable that can cancel the binding.
@discardableResult
public func bind<Target: Deallocatable>(to target: Target, context: ExecutionContext, setter: @escaping (Target) -> Void) -> Disposable {
return prefix(untilOutputFrom: target.deallocated).observeNext { [weak target] _ in
context.execute {
if let target = target {
setter(target)
}
}
}
}
}
/// Provides an execution context used to deliver binding events.
public protocol BindingExecutionContextProvider {
/// An execution context used to deliver binding events.
var bindingExecutionContext: ExecutionContext { get }
}
| 52.192893 | 176 | 0.696849 |
64b149267373b36189198ce8b4181fbb258a6cb2 | 293 | //
// bookListVC.swift
// U17Test
//
// Created by hjun on 2020/9/4.
// Copyright © 2020 hjun. All rights reserved.
//
import UIKit
class bookListVC: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
}
| 13.952381 | 47 | 0.627986 |
39d176aaf56c4d847315594ece9d8c43758a1846 | 1,781 | //
// Copyright 2018-2019 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import Amplify
import AWSPluginsCore
public class InterpretTextOperation: AmplifyOperation<PredictionsInterpretRequest,
Void,
InterpretResult,
PredictionsError>,
PredictionsInterpretOperation {
let multiService: InterpretTextMultiService
init(_ request: PredictionsInterpretRequest,
multiService: InterpretTextMultiService,
listener: EventListener?) {
self.multiService = multiService
super.init(categoryType: .predictions,
eventName: HubPayload.EventName.Predictions.interpret,
request: request,
listener: listener)
}
override public func main() {
if isCancelled {
finish()
return
}
multiService.setTextToInterpret(text: request.textToInterpret)
switch request.options.defaultNetworkPolicy {
case .offline:
multiService.fetchOfflineResult(callback: { event in
self.onServiceEvent(event: event)
})
case .auto:
multiService.fetchMultiServiceResult(callback: { event in
self.onServiceEvent(event: event)
})
}
}
// MARK: -
private func onServiceEvent(event: PredictionsEvent<InterpretResult, PredictionsError>) {
if isCancelled {
finish()
return
}
switch event {
case .completed(let result):
dispatch(event: .completed(result))
finish()
case .failed(let error):
dispatch(event: .failed(error))
finish()
}
}
}
| 25.811594 | 93 | 0.610893 |
eb210af584dafa1fe1e4fe65aeb2fd65abcf9021 | 3,565 | //
// MouseInfoController.swift
// Flatland
//
// Created by Stuart Rankin on 11/9/20.
// Copyright © 2020 Stuart Rankin. All rights reserved.
//
import Foundation
import AppKit
/// Controller for the Mouse Info UI.
class MouseInfoController: NSViewController, MouseInfoProtocol
{
public weak var MainDelegate: MainProtocol? = nil
override func viewDidLoad()
{
super.viewDidLoad()
SetLocation(Latitude: "", Longitude: "")
LocationLabel.stringValue = ""
self.view.wantsLayer = true
self.view.layer?.backgroundColor = NSColor.gray.cgColor
self.view.layer?.borderWidth = 3.0
self.view.layer?.cornerRadius = 5.0
self.view.layer?.borderColor = NSColor.white.cgColor
LatitudeValue.textColor = NSColor(calibratedRed: 0.05, green: 0.05, blue: 0.2, alpha: 1.0)
LongitudeValue.textColor = NSColor(calibratedRed: 0.05, green: 0.05, blue: 0.2, alpha: 1.0)
LocationManager = Locations()
LocationManager?.Main = MainDelegate
}
/// Set the main delegate. Ensure the location manager has the same delegate.
/// - Parameter Main: The main delegate.
func SetMainDelegate(_ Main: MainProtocol?)
{
MainDelegate = Main
LocationManager?.Main = Main
}
var LocationManager: Locations? = nil
/// "Sets" the location.
/// - Parameter Latitude: String representation of the latitude.
/// - Parameter Longitude: String representation of the longitude.
func SetLocation(Latitude: String, Longitude: String)
{
LatitudeValue.stringValue = Latitude
LongitudeValue.stringValue = Longitude
}
/// Sets the location. If the proper user setting is enabled, nearby locations will be searched for.
/// - Parameter Latitude: The latitude of the location.
/// - Parameter Longitude: The longitude of the location.
/// - Parameter Caller: The caller of the function.
func SetLocation(Latitude: Double, Longitude: Double, Caller: String = "")
{
LatitudeValue.stringValue = Utility.PrettyLatitude(Latitude, Precision: 3)
LongitudeValue.stringValue = Utility.PrettyLongitude(Longitude, Precision: 3)
if Settings.GetBool(.SearchForLocation)
{
let LookForTypes: [LocationTypes] = [.City, .Home, .UNESCO, .UserPOI]
if var NearBy = LocationManager?.WhatIsCloseTo(Latitude: Latitude, Longitude: Longitude,
CloseIs: 100.0, ForLocations: LookForTypes)
{
if NearBy.count > 0
{
NearBy.sort(by: {$0.Distance < $1.Distance})
let DisplayCount = min(NearBy.count, 3)
var CloseBy = ""
for Index in 0 ..< DisplayCount
{
CloseBy.append(NearBy[Index].Name)
if Index < DisplayCount - 1
{
CloseBy.append("\n")
}
}
LocationLabel.stringValue = CloseBy
}
else
{
LocationLabel.stringValue = ""
}
}
else
{
LocationLabel.stringValue = ""
}
}
}
@IBOutlet weak var LocationLabel: NSTextField!
@IBOutlet weak var LatitudeValue: NSTextField!
@IBOutlet weak var LongitudeValue: NSTextField!
}
| 36.752577 | 104 | 0.579523 |
fcfc781bdbf58d5727511ecb3523a8369001770f | 2,727 | /* *************************************************************************************************
StringIndent.swift
© 2020 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
************************************************************************************************ */
import Foundation
extension String {
public struct Indent: Comparable,
CustomStringConvertible,
Equatable,
Hashable {
public var character: Character.Space
/// Returns an instance of `Indent` that represents the space whose widths is `count`.
public static func spaces(count: Int) -> Indent { return .init(.space, count: count) }
/// Returns an instance of `Indent` that represents the horizontal tabs.
public static func tabs(count: Int) -> Indent { return .init(.horizontalTab, count: count) }
/// Default indent.
public static let `default`: Indent = .spaces(count: 2)
private var _count: Int = 0
public var count: Int {
get {
return self._count
}
set {
self._count = newValue > 0 ? newValue : 0
}
}
public init(_ character: Character.Space, count: Int) {
self.character = character
self.count = count
}
public var description: String {
return String(repeating: self.character.rawValue, count: self.count)
}
public func description(indentLevel: Int) -> String {
precondition(indentLevel >= 0)
return String(repeating: self.character.rawValue, count: indentLevel * self.count)
}
public static func <(lhs: Indent, rhs: Indent) -> Bool {
return lhs.description < rhs.description
}
}
}
extension StringProtocol where SubSequence == Substring {
/// Returns a Boolean value indicating whether the string begins with the specified indent.
internal func _hasIndent(_ indent: String.Indent) -> Bool {
return self.hasPrefix(indent.description)
}
internal func _dropIndentWithCounting(_ indent: String.Indent) -> (Self.SubSequence, count: Int) {
var count: Int = 0
var string: Self.SubSequence = self[self.startIndex..<self.endIndex]
while true {
if !string._hasIndent(indent) { break }
count += 1
string = string.dropFirst(indent.count)
}
return (string, count)
}
internal func _dropIndent(_ indent: String.Indent) -> Self.SubSequence? {
let droppedAndCount = self._dropIndentWithCounting(indent)
return droppedAndCount.count > 0 ? droppedAndCount.0 : nil
}
internal func _indentLevel(for indent: String.Indent) -> Int {
return self._dropIndentWithCounting(indent).count
}
}
| 33.256098 | 100 | 0.605061 |
de2052393fdf818a216db1a989356a2702351e2b | 2,253 | //
// SceneDelegate.swift
// SimpleTable
//
// Created by Michael on 2020/12/14.
// Copyright © 2020 TheAvengers. 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.
}
}
| 41.722222 | 143 | 0.743897 |
891ec7ecd791cb079792482720a01ea24eed648e | 4,613 | //
// AppDelegate.swift
// Payconiq
//
// Created by mohamed mohamed El Dehairy on 1/19/19.
// Copyright © 2019 mohamed El Dehairy. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Payconiq")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 49.074468 | 285 | 0.687622 |
b9615adf134cab18d4b759e774dc299024b5e54e | 484 | //
// Node.swift
// LinkedList
//
// Created by Begzod on 25/06/21.
//
import Foundation
class Node<Value> {
let value: Value
var next: Node?
init(_ value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
extension Node: CustomStringConvertible {
var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> \(next.description)"
}
}
| 15.612903 | 48 | 0.539256 |
bf8b6b2b042839a24c0c470da2f18e31985275a2 | 12,900 | import UIKit
/// [MondrianLayout]
/// A descriptor that lays out a single content and positions within the parent according to vertical and horizontal positional length.
public struct RelativeBlock:
_LayoutBlockType,
_DimensionConstraintType
{
public struct ConstrainedValue: Equatable, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public var min: CGFloat?
public var exact: CGFloat?
public var max: CGFloat?
var isEmpty: Bool {
return min == nil && exact == nil && max == nil
}
var isExactOnly: Bool {
return exact != nil && min == nil && max == nil
}
public init(
integerLiteral value: Int
) {
self.init(min: nil, exact: CGFloat(value), max: nil)
}
public init(
floatLiteral value: Double
) {
self.init(min: nil, exact: CGFloat(value), max: nil)
}
public init(
min: CGFloat? = nil,
exact: CGFloat? = nil,
max: CGFloat? = nil
) {
self.min = min
self.exact = exact
self.max = max
}
public mutating func accumulate(keyPath: WritableKeyPath<Self, CGFloat?>, _ other: CGFloat?) {
self[keyPath: keyPath] =
other.map { (self[keyPath: keyPath] ?? 0) + $0 } ?? self[keyPath: keyPath]
}
public mutating func accumulate(_ other: Self) {
accumulate(keyPath: \.min, other.min)
accumulate(keyPath: \.exact, other.exact)
accumulate(keyPath: \.max, other.max)
}
/// greater than or equal
public static func min(_ value: CGFloat) -> Self {
return .init(min: value, exact: nil, max: nil)
}
/// equal
public static func exact(_ value: CGFloat) -> Self {
return .init(min: nil, exact: value, max: nil)
}
/// less than or equal
public static func max(_ value: CGFloat) -> Self {
return .init(min: nil, exact: nil, max: value)
}
}
public var _layoutBlockNode: _LayoutBlockNode {
return .relative(self)
}
public var name: String = "Relative"
public var dimensionConstraints: DimensionDescriptor = .init()
public let content: _LayoutBlockNode
var top: ConstrainedValue
var bottom: ConstrainedValue
var trailing: ConstrainedValue
var leading: ConstrainedValue
init(
top: ConstrainedValue? = nil,
leading: ConstrainedValue? = nil,
bottom: ConstrainedValue? = nil,
trailing: ConstrainedValue? = nil,
content: () -> _LayoutBlockNode
) {
self.top = top ?? .init()
self.leading = leading ?? .init()
self.bottom = bottom ?? .init()
self.trailing = trailing ?? .init()
self.content = content()
}
public func setupConstraints(parent: _LayoutElement, in context: LayoutBuilderContext) {
context.add(constraints: dimensionConstraints.makeConstraints(for: parent))
func perform(current: _LayoutElement) {
var proposedConstraints: [NSLayoutConstraint] = []
// setting up constraints according to values
proposedConstraints +=
([
top.exact.map {
current.topAnchor.constraint(equalTo: parent.topAnchor, constant: $0)
},
trailing.exact.map {
current.trailingAnchor.constraint(equalTo: parent.trailingAnchor, constant: -$0)
},
leading.exact.map {
current.leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: $0)
},
bottom.exact.map {
current.bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -$0)
},
top.min.map {
current.topAnchor.constraint(greaterThanOrEqualTo: parent.topAnchor, constant: $0)
},
trailing.min.map {
current.trailingAnchor.constraint(lessThanOrEqualTo: parent.trailingAnchor, constant: -$0)
},
leading.min.map {
current.leadingAnchor.constraint(greaterThanOrEqualTo: parent.leadingAnchor, constant: $0)
},
bottom.min.map {
current.bottomAnchor.constraint(lessThanOrEqualTo: parent.bottomAnchor, constant: -$0)
},
top.max.map {
current.topAnchor.constraint(lessThanOrEqualTo: parent.topAnchor, constant: $0)
},
trailing.max.map {
current.trailingAnchor.constraint(greaterThanOrEqualTo: parent.trailingAnchor, constant: -$0)
},
leading.max.map {
current.leadingAnchor.constraint(lessThanOrEqualTo: parent.leadingAnchor, constant: $0)
},
bottom.max.map {
current.bottomAnchor.constraint(greaterThanOrEqualTo: parent.bottomAnchor, constant: -$0)
},
] as [NSLayoutConstraint?]).compactMap { $0 }
constraintsToFitInsideContainer: do {
/**
If a edge does not have minimum or exact value, the element might be overflowed.
*/
if bottom.min == nil, bottom.exact == nil {
proposedConstraints.append(
current.bottomAnchor.constraint(lessThanOrEqualTo: parent.bottomAnchor)
)
}
if top.min == nil, top.exact == nil {
proposedConstraints.append(
current.topAnchor.constraint(greaterThanOrEqualTo: parent.topAnchor)
)
}
if leading.min == nil, leading.exact == nil {
proposedConstraints.append(
current.trailingAnchor.constraint(lessThanOrEqualTo: parent.trailingAnchor)
)
}
if trailing.min == nil, trailing.exact == nil {
proposedConstraints.append(
current.trailingAnchor.constraint(lessThanOrEqualTo: parent.trailingAnchor)
)
}
}
constraintsToPositionCenter: do {
/**
Vertically or horizontally, if there are no specifiers, that causes an ambiguous layout.
As a default behavior, in that case, adds centering layout constraints.
*/
vertical: do {
let edges = [bottom, top]
if edges.allSatisfy({ $0.exact == nil }) {
proposedConstraints.append(
current.centerYAnchor.constraint(equalTo: parent.centerYAnchor).setPriority(
.defaultHigh
)
)
}
}
horizontal: do {
let edges = [leading, trailing]
if edges.allSatisfy({ $0.exact == nil }) {
proposedConstraints.append(
current.centerXAnchor.constraint(equalTo: parent.centerXAnchor).setPriority(
.defaultHigh
)
)
}
}
}
proposedConstraints.forEach {
$0.setInternalIdentifier(name)
}
context.add(constraints: proposedConstraints)
}
switch content {
case .layoutGuide(let block):
context.register(layoutGuideBlock: block)
perform(current: .init(layoutGuide: block.layoutGuide))
case .view(let block):
context.register(viewBlock: block)
perform(current: .init(view: block.view))
case .vStack(let c as _LayoutBlockType),
.hStack(let c as _LayoutBlockType),
.zStack(let c as _LayoutBlockType),
.background(let c as _LayoutBlockType),
.relative(let c as _LayoutBlockType),
.overlay(let c as _LayoutBlockType),
.vGrid(let c as _LayoutBlockType):
let newLayoutGuide = context.makeLayoutGuide(identifier: "RelativeBlock.\(c.name)")
c.setupConstraints(parent: .init(layoutGuide: newLayoutGuide), in: context)
perform(current: .init(layoutGuide: newLayoutGuide))
}
}
}
extension _LayoutBlockNodeConvertible {
/**
`.relative` modifier describes that the content attaches to specified edges with padding.
Not specified edges do not have constraints to the edge. so the sizing depends on intrinsic content size.
You might use this modifier to pin to edge as an overlay content.
```swift
ZStackBlock {
VStackBlock {
...
}
.relative(bottom: 8, right: 8)
}
```
*/
private func relative(
top: RelativeBlock.ConstrainedValue,
leading: RelativeBlock.ConstrainedValue,
bottom: RelativeBlock.ConstrainedValue,
trailing: RelativeBlock.ConstrainedValue
) -> RelativeBlock {
if case .relative(let relativeBlock) = self._layoutBlockNode {
var new = relativeBlock
new.top.accumulate(top)
new.leading.accumulate(leading)
new.trailing.accumulate(trailing)
new.bottom.accumulate(bottom)
return new
} else {
return .init(top: top, leading: leading, bottom: bottom, trailing: trailing) {
self._layoutBlockNode
}
}
}
/**
`.relative` modifier describes that the content attaches to specified edges with padding.
Not specified edges do not have constraints to the edge. so the sizing depends on intrinsic content size.
You might use this modifier to pin to edge as an overlay content.
*/
public func relative(_ value: RelativeBlock.ConstrainedValue) -> RelativeBlock {
return relative(top: value, leading: value, bottom: value, trailing: value)
}
/**
`.relative` modifier describes that the content attaches to specified edges with padding.
Not specified edges do not have constraints to the edge. so the sizing depends on intrinsic content size.
You might use this modifier to pin to edge as an overlay content.
*/
@_disfavoredOverload
public func relative(_ value: CGFloat) -> RelativeBlock {
return relative(.exact(value))
}
/**
`.relative` modifier describes that the content attaches to specified edges with padding.
Not specified edges do not have constraints to the edge. so the sizing depends on intrinsic content size.
You might use this modifier to pin to edge as an overlay content.
*/
public func relative(_ edgeInsets: UIEdgeInsets) -> RelativeBlock {
return relative(
top: .init(floatLiteral: Double(edgeInsets.top)),
leading: .init(floatLiteral: Double(edgeInsets.left)),
bottom: .init(floatLiteral: Double(edgeInsets.bottom)),
trailing: .init(floatLiteral: Double(edgeInsets.right))
)
}
/**
`.relative` modifier describes that the content attaches to specified edges with padding.
Not specified edges do not have constraints to the edge. so the sizing depends on intrinsic content size.
You might use this modifier to pin to edge as an overlay content.
Ambiguous position would be fixed by centering.
For example:
- lays out centered vertically if you only set horizontal values vice versa.
- also only setting minimum value in the axis.
*/
public func relative(_ edges: Edge.Set, _ value: RelativeBlock.ConstrainedValue) -> RelativeBlock {
return relative(
top: edges.contains(.top) ? value : .init(),
leading: edges.contains(.leading) ? value : .init(),
bottom: edges.contains(.bottom) ? value : .init(),
trailing: edges.contains(.trailing) ? value : .init()
)
}
@_disfavoredOverload
public func relative(_ edges: Edge.Set, _ value: CGFloat) -> RelativeBlock {
return relative(edges, .exact(value))
}
/**
.padding modifier is similar with .relative but something different.
Different with that, Not specified edges pin to edge with 0 padding.
Ambiguous position would be fixed by centering.
*/
public func padding(_ value: RelativeBlock.ConstrainedValue) -> RelativeBlock {
return relative(top: value, leading: value, bottom: value, trailing: value)
}
/**
.padding modifier is similar with .relative but something different.
Different with that, Not specified edges pin to edge with 0 padding.
Ambiguous position would be fixed by centering.
*/
@_disfavoredOverload
public func padding(_ value: CGFloat) -> RelativeBlock {
return padding(.exact(value))
}
/**
.padding modifier is similar with .relative but something different.
Different with that, Not specified edges pin to edge with 0 padding.
- the values would be used as `exact`.
*/
public func padding(_ edgeInsets: UIEdgeInsets) -> RelativeBlock {
return relative(edgeInsets)
}
/**
.padding modifier is similar with .relative but something different.
Different with that, Not specified edges pin to edge with 0 padding.
*/
public func padding(_ edges: Edge.Set, _ value: RelativeBlock.ConstrainedValue) -> RelativeBlock {
return relative(
top: edges.contains(.top) ? value : 0,
leading: edges.contains(.leading) ? value : 0,
bottom: edges.contains(.bottom) ? value : 0,
trailing: edges.contains(.trailing) ? value : 0
)
}
/**
.padding modifier is similar with .relative but something different.
Different with that, Not specified edges pin to edge with 0 padding.
*/
@_disfavoredOverload
public func padding(_ edges: Edge.Set, _ value: CGFloat) -> RelativeBlock {
return padding(edges, .exact(value))
}
}
| 30.714286 | 135 | 0.654961 |
389f814ebc7583b551afa66d742aecc1286840e3 | 545 | //
// Reducer.swift
// HelloSwift
//
// Created by 田中改 on 2020/03/12.
// Copyright © 2020 Aratoon. All rights reserved.
//
import ReSwift
func eventList(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case _ as FetchEventsStart: state.loading = true
case let action as FetchEventsFinish: do {
state.events = action.events
state.loading = false
}
case _ as FetchEventsFinish: state.loading = false
default: break
}
return state
}
| 20.961538 | 62 | 0.642202 |
33d435fcb324a58e435461c1650032e6be14e93f | 6,420 | import Foundation
public extension String {
/// Returns the receiver casted to an `NSString`
var nsString: NSString {
return self as NSString
}
/// Returns a string object containing the characters of the receiver that lie within a given range.
///
/// - Parameter nsRange: A range. The range must not exceed the bounds of the receiver.
/// - Returns: A string object containing the characters of the receiver that lie within aRange.
func substring(with nsRange: NSRange) -> String {
return nsString.substring(with: nsRange) as String
}
}
public extension String {
/// Attempts conversion of the receiver to a boolean value, according to the following rules:
///
/// - true: `"true", "yes", "1"` (allowing case variations)
/// - false: `"false", "no", "0"` (allowing case variations)
///
/// If none of the following rules is verified, `nil` is returned.
///
/// - returns: an optional boolean which will have the converted value, or `nil` if the conversion failed.
func toBool() -> Bool? {
switch lowercased() {
case "true", "yes", "1": return true
case "false", "no", "0": return false
default: return nil
}
}
}
public extension String {
/// Returns a localized string using the receiver as the key.
var localized: String {
return NSLocalizedString(self, comment: self)
}
func localized(with arguments: [CVarArg]) -> String {
return String(format: localized, arguments: arguments)
}
func localized(with arguments: CVarArg...) -> String {
return String(format: localized, arguments: arguments)
}
}
public extension String {
/// Creates a string from the `dump` output of the given value.
init<T>(dumping x: T) {
self.init()
dump(x, to: &self)
}
}
extension String {
/// Replaces occurrences of multiple `Character`s with corresponding `String` values using the given mapping, while
/// skipping (filtering out) an optional set of characters from the output. Being backed by a `Scanner`, a single
/// pass is made over the receiver.
///
/// - Parameters:
/// - replacementMap: A dictionary containing the replacement mapping `Character` -> `String`.
/// - charactersToBeSkipped: An optional set of characters to skip (i.e. filter out from the input).
/// - Returns: A modified version of the receiver with the replacement mapping applied.
public func replacingOccurrencesOfCharacters(
in replacementMap: [Character: String],
skippingCharactersIn charactersToBeSkipped: CharacterSet? = nil
) -> String {
guard !replacementMap.isEmpty else { return self }
let matchSet = CharacterSet(charactersIn: replacementMap.keys.reduce(into: "") { $0 += String($1) })
.union(charactersToBeSkipped ?? CharacterSet())
var final = ""
let scanner = Scanner(string: self)
scanner.charactersToBeSkipped = charactersToBeSkipped
while !scanner.isAtEnd {
// copy everything until finding a character to be replaced or skipped
var collector: NSString? = ""
if scanner.scanUpToCharacters(from: matchSet, into: &collector), let collector = collector {
final.append(collector as String)
}
// exit early if we're already at the end
guard !scanner.isAtEnd else { break }
// find and replace matching character if needed
replacementMap
.first { match, _ in scanner.scanString(String(match), into: nil) }
.flatMap { _, replacement in final.append(replacement) }
}
return final
}
}
extension String {
public static let nonBreakingSpace = String(Character.nonBreakingSpace)
public static let nonBreakingHyphen = String(Character.nonBreakingHyphen)
public static let wordJoiner = String(Character.wordJoiner)
public static let emDash = String(Character.emDash)
public static let enDash = String(Character.enDash)
/// Returns a non line breaking version of `self`. Line breaking characters occurrences are replaced with
/// corresponding non line breaking variants when existent. Otherwise, word joiner characters are attached to them
/// to make them non line breaking. Existing newlines can be replaced by any given string, via the optional
/// `newlineCharacterReplacement` parameter (defaults to `nil`, which preserves newlines).
///
/// The character mapping is:
/// - space (" ") -> non breaking space (`U+2028`)
/// - hyphen ("-") -> non breaking hyphen (`U+00A0`)
/// - em dash ("—") -> word joiner (`U+2060`) + em dash + word joiner (`U+2060`)
/// - en dash ("–") -> word joiner (`U+2060`) + en dash + word joiner (`U+2060`)
/// - question mark ("?") -> question mark + word joiner (`U+2060`)
/// - closing brace ("}") -> closing brace + word joiner (`U+2060`)
///
/// The `newlineCharacterReplacement` acts upon the characters specified in `CharacterSet.newlines`
/// (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`), some example values are:
/// - `nil` -> newlines are preserved
/// - `""` -> newlines are stripped
/// - `String.nonBreakingSpace` -> output a single line
///
/// - Parameter newlineCharacterReplacement: The replacement string to use for newline characters (defaults to
/// `nil`).
/// - Returns: A modified version of the receiver without line breaking characters.
public func nonLineBreaking(replacingNewlinesWith newlineCharacterReplacement: String? = nil) -> String {
let newlineReplacementMap = newlineCharacterReplacement
.flatMap { replacement in Dictionary(uniqueKeysWithValues: Character.newlines.map { ($0, replacement) }) }
?? [:]
return replacingOccurrencesOfCharacters(
in: [
" ": String.nonBreakingSpace,
"-": String.nonBreakingHyphen,
.emDash: String([.wordJoiner, .emDash, .wordJoiner]),
.enDash: String([.wordJoiner, .enDash, .wordJoiner]),
"?": "?" + .wordJoiner,
"}": "}" + .wordJoiner
]
.merging(newlineReplacementMap) { $1 },
skippingCharactersIn: nil
)
}
}
| 40.377358 | 119 | 0.634891 |
481f378ed1124ec4f8bf8b98812840e2012447fb | 1,040 | //
// BlockedUser.swift
// App
//
// Created by Li Fumin on 2018/7/29.
//
import Foundation
import Vapor
import FluentPostgreSQL
struct BlockedUser: PostgreSQLModel{
var id: Int?
var ownerID: Int
var blockedUserID: Int
var blockedUserName: String?
var createdAt: Date?
var updatedAt: Date?
static var createdAtKey: TimestampKey? { return \.createdAt }
static var updatedAtKey: TimestampKey? { return \.updatedAt }
init(ownerID: Int, blockedUserID: Int) {
self.ownerID = ownerID
self.blockedUserID = blockedUserID
}
}
extension BlockedUser: Content {}
extension BlockedUser: Migration {
static func prepare(on connection: PostgreSQLConnection) -> Future<Void>{
return Database.create(self, on: connection) { builder in
try addProperties(to: builder)
builder.reference(from: \.ownerID, to: \User.id)
}
}
}
extension BlockedUser {
var owner: Parent<BlockedUser,User> {
return parent(\.ownerID)
}
}
| 21.666667 | 77 | 0.656731 |
d54aeeb25402fbfb6b337db36ccbcebad1b12a05 | 2,287 | //
// TimeAgoExtension.swift
// MobiHair Customer
//
// Created by Duong Viet Cuong on 10/19/17.
// Copyright © 2017 newsoft. All rights reserved.
//
import UIKit
class TimeHelper:NSObject{
static func timeAgoSince(_ datex: Date?) -> String {
if let date = datex{
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let year = components.year, year >= 2 {
return "\(year) năm trước"
}
if let year = components.year, year >= 1 {
return "Năm ngoái"
}
if let month = components.month, month >= 2 {
return "\(month) tháng trước"
}
if let month = components.month, month >= 1 {
return "Tháng trước"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) tuần trước"
}
if let week = components.weekOfYear, week >= 1 {
return "Tuần trước"
}
if let day = components.day, day >= 2 {
return "\(day) ngày trước"
}
if let day = components.day, day >= 1 {
return "Ngày hôm qua"
}
if let hour = components.hour, hour >= 2 {
return "\(hour) giờ trước"
}
if let hour = components.hour, hour >= 1 {
return "Trước đây 1 tiếng"
}
if let minute = components.minute, minute >= 2 {
return "\(minute) phút trước đây"
}
if let minute = components.minute, minute >= 1 {
return "1 phút trước"
}
if let second = components.second, second >= 3 {
return "\(second) giây trước"
}
}
return "Gần đây"
}
}
| 29.320513 | 109 | 0.43944 |
efad97dee601e2617eca8fa18886a9507829d762 | 2,526 | //
// AppDelegate.swift
// GlobalTime
//
// Created by Pedro Trujillo on 11/17/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let newGlobalTimeVC = root_main_GlobalTimeTableViewController()
let globalTimeNavigationController = UINavigationController(rootViewController: newGlobalTimeVC)
window?.rootViewController = globalTimeNavigationController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.107143 | 285 | 0.747427 |
228e26e05bb23d26d67dab585bc5ae61923dbdfe | 1,422 | //
// GigimoviesUITests.swift
// GigimoviesUITests
//
// Created by Guido Fabio on 31/08/2021.
//
import XCTest
class GigimoviesUITests: 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: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.069767 | 182 | 0.657525 |
9c09ef212df655cf29782ca5c56ec3f7a9207d17 | 2,878 | //
// WeightedGraph+shortestPath.swift
// traveling-salesman-problem
//
// Created by David Nadoba on 09/02/2017.
// Copyright © 2017 David Nadoba. All rights reserved.
//
import Foundation
extension WeightedGraph {
/// finds the shortes path which visits all vertices and starts and returns to the given start vertex
///
/// - Parameter start: start and end vertex
/// - Returns: summed weight, all visited vertices in the correct order and all edges in the correct order
func shortestPath(from start: V) -> (W, [V], [E])? {
guard contains(start) else {
return nil
}
let requiredPathLength = vertexCount
guard requiredPathLength >= 2 else {
return nil
}
let nextEdges = edges(from: start)
let (complexity, result) = shortesPath(start: start, path: [start], edges: [], nextEdges: nextEdges, requiredPathLength: requiredPathLength, weightSummed: W.zero, complexity: 0)
print("calculated shortest path on \(self) with complexity: \(complexity)")
return result
}
private func shortesPath(start: V, path: [V], edges: [E], nextEdges: Set<E>, requiredPathLength: Int, weightSummed: W, complexity: Int) -> (Int, (W, [V], [E])?) {
let newComplexity = complexity + 1
//path is not posible
if path.count == requiredPathLength {
//route not possible
guard let edgeToStart = nextEdges.first(where: { $0.destination == start }) else {
return (newComplexity, nil)
}
var newPath = path
newPath.append(start)
var newEdges = edges
newEdges.append(edgeToStart)
let newWeight = weightSummed + edgeToStart.weight
return (newComplexity, (newWeight, newPath, newEdges))
}
//only try edges with destination which we did not already visit
let posibleEdges = nextEdges.filter { (nextEdge: E) -> Bool in
return !path.contains { $0 == nextEdge.destination }
}
let results = posibleEdges.map { (edge) -> (Int, (W, [V], [E])?) in
let nextVertex = edge.destination
var newPath = path
newPath.append(nextVertex)
var newEdges = edges
newEdges.append(edge)
let nextEdges = self.edges(from: nextVertex)
let newWeight = weightSummed + edge.weight
return shortesPath(start: start, path: newPath, edges: newEdges, nextEdges: nextEdges, requiredPathLength: requiredPathLength, weightSummed: newWeight, complexity: 0)
}
let summedComplexity = results.map({$0.0}).reduce(newComplexity, +)
let possiblePaths = results.compactMap({$0.1})
return (summedComplexity, possiblePaths.min{$0.0 < $1.0})
}
}
| 41.710145 | 185 | 0.608756 |
75b2c3b8ae6422921b495b5f8b0e8d022765b511 | 21,041 | //
// NeopixelModuleViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 24/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
import SSZipArchive
class NeopixelModuleViewController: ModuleViewController {
// Constants
private var defaultPalette: [String] = []
private let kLedWidth: CGFloat = 44
private let kLedHeight: CGFloat = 44
private let kDefaultLedColor = UIColor(hex: 0xffffff)
// UI
@IBOutlet weak var statusView: UIView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var paletteCollection: UICollectionView!
@IBOutlet weak var boardScrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var contentViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var contentViewHeightConstrait: NSLayoutConstraint!
@IBOutlet weak var colorPickerButton: UIButton!
@IBOutlet weak var boardControlsView: UIView!
@IBOutlet weak var rotationView: UIView!
// Data
private let neopixel = NeopixelModuleManager()
private var board: NeopixelModuleManager.Board?
private var ledViews: [UIView] = []
private var currentColor: UIColor = UIColor.redColor()
private var contentRotationAngle: CGFloat = 0
private var boardMargin = UIEdgeInsetsZero
private var boardCenterScrollOffset = CGPointZero
private var isSketchTooltipAlreadyShown = false
override func viewDidLoad() {
super.viewDidLoad()
// Init
neopixel.delegate = self
board = NeopixelModuleManager.Board.loadStandardBoard(0)
// Read palette from resources
let path = NSBundle.mainBundle().pathForResource("NeopixelDefaultPalette", ofType: "plist")!
defaultPalette = NSArray(contentsOfFile: path) as! [String]
// UI
statusView.layer.borderColor = UIColor.whiteColor().CGColor
statusView.layer.borderWidth = 1
boardScrollView.layer.borderColor = UIColor.whiteColor().CGColor
boardScrollView.layer.borderWidth = 1
colorPickerButton.layer.cornerRadius = 4
colorPickerButton.layer.masksToBounds = true
createBoardUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Show tooltip alert
if Preferences.neopixelIsSketchTooltipEnabled && !isSketchTooltipAlreadyShown{
let localizationManager = LocalizationManager.sharedInstance
let alertController = UIAlertController(title: localizationManager.localizedString("dialog_notice"), message: localizationManager.localizedString("neopixel_sketch_tooltip"), preferredStyle: .Alert)
let okAction = UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: .Default, handler:nil)
alertController.addAction(okAction)
let dontshowAction = UIAlertAction(title: localizationManager.localizedString("dialog_dontshowagain"), style: .Destructive) { (action) in
Preferences.neopixelIsSketchTooltipEnabled = false
}
alertController.addAction(dontshowAction)
self.presentViewController(alertController, animated: true, completion: nil)
isSketchTooltipAlreadyShown = true
}
//
updateStatusUI()
neopixel.start()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
neopixel.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "boardSelectorSegue" {
if let controller = segue.destinationViewController.popoverPresentationController {
controller.delegate = self
let boardSelectorViewController = segue.destinationViewController as! NeopixelBoardSelectorViewController
boardSelectorViewController.onClickStandardBoard = { [unowned self] standardBoardIndex in
var currentType: UInt16!
if let type = self.board?.type {
currentType = type
}
else {
currentType = NeopixelModuleManager.kDefaultType
}
let board = NeopixelModuleManager.Board.loadStandardBoard(standardBoardIndex, type: currentType)
self.changeBoard(board)
}
boardSelectorViewController.onClickCustomLineStrip = { [unowned self] in
self.showLineStripDialog()
}
}
}
else if segue.identifier == "boardTypeSegue" {
if let controller = segue.destinationViewController.popoverPresentationController {
controller.delegate = self
let typeSelectorViewController = segue.destinationViewController as! NeopixelTypeSelectorViewController
if let type = board?.type {
typeSelectorViewController.currentType = type
}
else {
typeSelectorViewController.currentType = NeopixelModuleManager.kDefaultType
}
typeSelectorViewController.onClickSetType = { [unowned self] type in
if var board = self.board {
board.type = type
self.changeBoard(board)
}
}
}
}
else if segue.identifier == "colorPickerSegue" {
if let controller = segue.destinationViewController.popoverPresentationController {
controller.delegate = self
if let colorPickerViewController = segue.destinationViewController as? NeopixelColorPickerViewController {
colorPickerViewController.delegate = self
}
}
}
}
/*
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
createBoardUI()
}
*/
private func changeBoard(board: NeopixelModuleManager.Board) {
self.board = board
createBoardUI()
neopixel.resetBoard()
updateStatusUI()
}
private func showLineStripDialog() {
// Show dialog
let localizationManager = LocalizationManager.sharedInstance
let alertController = UIAlertController(title: nil, message: "Selet line strip length", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Select", style: .Default) { (_) in
let stripLengthTextField = alertController.textFields![0] as UITextField
if let text = stripLengthTextField.text, let stripLength = Int(text) {
let board = NeopixelModuleManager.Board(name: "1x\(stripLength)", width: UInt8(stripLength), height:UInt8(1), components: UInt8(3), stride: UInt8(stripLength), type: NeopixelModuleManager.kDefaultType)
self.changeBoard(board)
}
}
okAction.enabled = false
alertController.addAction(okAction)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "Enter Length"
textField.keyboardType = .NumberPad
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue()) { (notification) in
okAction.enabled = textField.text != ""
}
}
alertController.addAction(UIAlertAction(title: localizationManager.localizedString("dialog_cancel"), style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true) { () -> Void in
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateBoardPositionValues()
setDefaultPositionAndScaleAnimated(true)
}
private func updateStatusUI() {
connectButton.enabled = neopixel.isSketchDetected != true || (neopixel.isReady() && (neopixel.board == nil && !neopixel.isWaitingResponse))
let isBoardConfigured = neopixel.isBoardConfigured()
boardScrollView.alpha = isBoardConfigured ? 1.0:0.2
boardControlsView.alpha = isBoardConfigured ? 1.0:0.2
var statusMessage: String?
if !neopixel.isReady() {
statusMessage = "Waiting for Uart..."
}
else if neopixel.isSketchDetected == nil {
statusMessage = "Ready to Connect"
}
else if neopixel.isSketchDetected! {
if neopixel.board == nil {
if neopixel.isWaitingResponse {
statusMessage = "Waiting for Setup"
}
else {
statusMessage = "Ready to Setup"
}
}
else {
statusMessage = "Connected"
}
}
else {
statusMessage = "Not detected"
}
statusLabel.text = statusMessage
}
private func createBoardUI() {
// Remove old views
for ledView in ledViews {
ledView.removeFromSuperview()
}
for subview in rotationView.subviews {
subview.removeFromSuperview()
}
// Create views
let ledBorderColor = UIColor.whiteColor().colorWithAlphaComponent(0.2).CGColor
let ledCircleMargin: CGFloat = 1
var k = 0
ledViews = []
if let board = board {
boardScrollView.layoutIfNeeded()
updateBoardPositionValues()
//let boardMargin = UIEdgeInsetsMake(verticalMargin, horizontalMargin, verticalMargin, horizontalMargin)
for j in 0..<board.height {
for i in 0..<board.width {
let button = UIButton(frame: CGRectMake(CGFloat(i)*kLedWidth+boardMargin.left, CGFloat(j)*kLedHeight+boardMargin.top, kLedWidth, kLedHeight))
button.layer.borderColor = ledBorderColor
button.layer.borderWidth = 1
button.tag = k
button.addTarget(self, action: #selector(NeopixelModuleViewController.ledPressed(_:)), forControlEvents: [.TouchDown])
rotationView.addSubview(button)
let colorView = UIView(frame: CGRectMake(ledCircleMargin, ledCircleMargin, kLedWidth-ledCircleMargin*2, kLedHeight-ledCircleMargin*2))
colorView.userInteractionEnabled = false
colorView.layer.borderColor = ledBorderColor
colorView.layer.borderWidth = 2
colorView.layer.cornerRadius = kLedWidth/2
colorView.layer.masksToBounds = true
colorView.backgroundColor = kDefaultLedColor
ledViews.append(colorView)
button.addSubview(colorView)
k += 1
}
}
contentViewWidthConstraint.constant = CGFloat(board.width) * kLedWidth + boardMargin.left + boardMargin.right
contentViewHeightConstrait.constant = CGFloat(board.height) * kLedHeight + boardMargin.top + boardMargin.bottom
boardScrollView.minimumZoomScale = 0.1
boardScrollView.maximumZoomScale = 10
setDefaultPositionAndScaleAnimated(false)
boardScrollView.layoutIfNeeded()
}
boardScrollView.setZoomScale(1, animated: false)
}
private func updateBoardPositionValues() {
if let board = board {
boardScrollView.layoutIfNeeded()
//let marginScale: CGFloat = 5
//boardMargin = UIEdgeInsetsMake(boardScrollView.bounds.height * marginScale, boardScrollView.bounds.width * marginScale, boardScrollView.bounds.height * marginScale, boardScrollView.bounds.width * marginScale)
boardMargin = UIEdgeInsetsMake(2000, 2000, 2000, 2000)
let boardWidthPoints = CGFloat(board.width) * kLedWidth
let boardHeightPoints = CGFloat(board.height) * kLedHeight
let horizontalMargin = max(0, (boardScrollView.bounds.width - boardWidthPoints)/2)
let verticalMargin = max(0, (boardScrollView.bounds.height - boardHeightPoints)/2)
boardCenterScrollOffset = CGPointMake(boardMargin.left - horizontalMargin, boardMargin.top - verticalMargin)
}
}
private func setDefaultPositionAndScaleAnimated(animated: Bool) {
boardScrollView.setZoomScale(1, animated: animated)
boardScrollView.setContentOffset(boardCenterScrollOffset, animated: animated)
}
func ledPressed(sender: UIButton) {
let isBoardConfigured = neopixel.isBoardConfigured()
if let board = board where isBoardConfigured {
let x = sender.tag % Int(board.width)
let y = sender.tag / Int(board.width)
DLog("led: (\(x)x\(y))")
ledViews[sender.tag].backgroundColor = currentColor
neopixel.setPixelColor(currentColor, x: UInt8(x), y: UInt8(y))
}
}
// MARK: - Actions
@IBAction func onClickConnect(sender: AnyObject) {
neopixel.connectNeopixel()
updateStatusUI()
}
@IBAction func onDoubleTapScrollView(sender: AnyObject) {
setDefaultPositionAndScaleAnimated(true)
}
@IBAction func onClickClear(sender: AnyObject) {
for ledView in ledViews {
ledView.backgroundColor = currentColor
}
neopixel.clearBoard(currentColor)
}
@IBAction func onChangeBrightness(sender: UISlider) {
neopixel.setBrighness(sender.value)
}
@IBAction func onClickHelp(sender: UIBarButtonItem) {
let localizationManager = LocalizationManager.sharedInstance
let helpViewController = storyboard!.instantiateViewControllerWithIdentifier("HelpExportViewController") as! HelpExportViewController
helpViewController.setHelp(localizationManager.localizedString("neopixel_help_text"), title: localizationManager.localizedString("neopixel_help_title"))
helpViewController.fileTitle = "Neopixel Sketch"
let cacheDirectoryURL = try! NSFileManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if let sketchPath = cacheDirectoryURL.URLByAppendingPathComponent("Neopixel.zip").path {
let isSketchZipAvailable = NSFileManager.defaultManager().fileExistsAtPath(sketchPath)
if !isSketchZipAvailable {
// Create zip from code if not exists
if let sketchFolder = NSBundle.mainBundle().pathForResource("Neopixel", ofType: nil) {
let result = SSZipArchive.createZipFileAtPath(sketchPath, withContentsOfDirectory: sketchFolder)
DLog("Neopiel zip created: \(result)")
}
else {
DLog("Error creating zip file")
}
}
// Setup file download
helpViewController.fileURL = NSURL(fileURLWithPath: sketchPath)
}
let helpNavigationController = UINavigationController(rootViewController: helpViewController)
helpNavigationController.modalPresentationStyle = .Popover
helpNavigationController.popoverPresentationController?.barButtonItem = sender
presentViewController(helpNavigationController, animated: true, completion: nil)
}
@IBAction func onClickRotate(sender: AnyObject) {
contentRotationAngle += CGFloat(M_PI_2)
rotationView.transform = CGAffineTransformMakeRotation(contentRotationAngle)
setDefaultPositionAndScaleAnimated(true)
}
}
// MARK: - UICollectionViewDataSource
extension NeopixelModuleViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return defaultPalette.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let reuseIdentifier = "ColorCell"
let colorCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) //as! AdminMenuCollectionViewCell
let colorHex = defaultPalette[indexPath.row]
let color = UIColor(CSS: colorHex)
colorCell.backgroundColor = color
let isSelected = currentColor.isEqual(color)
colorCell.layer.borderWidth = isSelected ? 4:2
colorCell.layer.borderColor = (isSelected ? UIColor.whiteColor(): color.darker(0.5)).CGColor
colorCell.layer.cornerRadius = 4
colorCell.layer.masksToBounds = true
return colorCell
}
}
// MARK: - UICollectionViewDelegate
extension NeopixelModuleViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
DLog("colors selected: \(indexPath.item)")
let colorHex = defaultPalette[indexPath.row]
let color = UIColor(CSS: colorHex)
currentColor = color
updatePickerColorButton(false)
collectionView.reloadData()
}
}
// MARK: - UIScrollViewDelegate
extension NeopixelModuleViewController: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return contentView
}
func scrollViewDidZoom(scrollView: UIScrollView) {
// let zoomScale = scrollView.zoomScale
// contentViewWidthConstraint.constant = zoomScale*200
// contentViewHeightConstrait.constant = zoomScale*200
}
}
// MARK: - NeopixelModuleManagerDelegate
extension NeopixelModuleViewController: NeopixelModuleManagerDelegate {
func onNeopixelSetupFinished(success: Bool) {
if (success) {
neopixel.clearBoard(kDefaultLedColor)
}
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.updateStatusUI()
});
}
func onNeopixelSketchDetected(detected: Bool) {
if detected {
if let board = board {
neopixel.setupNeopixel(board)
}
}
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.updateStatusUI()
});
}
func onNeopixelUartIsReady() {
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.updateStatusUI()
});
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension NeopixelModuleViewController : UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(PC: UIPresentationController) -> UIModalPresentationStyle {
// This *forces* a popover to be displayed on the iPhone
if traitCollection.verticalSizeClass != .Compact {
return .None
}
else {
return .FullScreen
}
}
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
DLog("selector dismissed")
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension NeopixelModuleViewController : NeopixelColorPickerViewControllerDelegate {
func onColorPickerChooseColor(color: UIColor) {
colorPickerButton.backgroundColor = color
updatePickerColorButton(true)
currentColor = color
paletteCollection.reloadData()
}
private func updatePickerColorButton(isSelected: Bool) {
colorPickerButton.layer.borderWidth = isSelected ? 4:2
colorPickerButton.layer.borderColor = (isSelected ? UIColor.whiteColor(): colorPickerButton.backgroundColor!.darker(0.5)).CGColor
}
} | 40.001901 | 222 | 0.637612 |
dba3c9638c90c66493ce19f71ca51287becc172a | 2,178 | //
// AppDelegate.swift
// watchOS Test Host
//
// Created by Tony Stone on 9/24/17.
// Copyright © 2017 Tony Stone. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.340426 | 285 | 0.754821 |
2240804e93ee81e6ccd230aa1896a14aff0eec9a | 4,498 | //
// DQEmoticonPageCell.swift
// SinaWeibo
//
// Created by admin on 2016/10/8.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
let emoticonPageControlHeight: CGFloat = 30
class DQEmoticonPageCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
addChildButton()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
contentView.addGestureRecognizer(longPress)
}
@objc private func longPress(gesture: UILongPressGestureRecognizer) {
let point = gesture.location(in: contentView)
guard let btn = findEmoticonButton(point: point) else {
popView.removeFromSuperview()
return
}
if btn.isHidden == true {
popView.removeFromSuperview()
return
}
switch gesture.state {
case .began,.changed:
let keyboardWindow = UIApplication.shared.windows.last!
let rect = btn.superview!.convert(btn.frame, to: window)
//let rect = btn.convert(btn.bounds, to: window)
popView.center.x = rect.midX
popView.frame.origin.y = rect.maxY - popView.bounds.height
//给表情按钮设置模型
popView.emoticonButton.emoticon = btn.emoticon
keyboardWindow.addSubview(popView)
popView.showEmoticon()
// btn.isHidden = true
default:
popView.removeFromSuperview()
// btn.isHidden = false
}
}
private func findEmoticonButton(point: CGPoint) -> DQEmoticonButton? {
for btn in buttonArray {
if btn.frame.contains(point) {
return btn
}
}
return nil
}
private func addChildButton() {
let buttonWidth = ScreenWidth / 7
let buttonHeight = (emoticonKeyboardHeight - emoticonToolBarHeight - emoticonPageControlHeight) / 3
for i in 0..<emoticonPageMaxCount {
let button = DQEmoticonButton()
let colIndex = i % 7
let rawIndex = i / 7
let buttonX = CGFloat(colIndex) * buttonWidth
let buttonY = CGFloat(rawIndex) * buttonHeight
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)
// button.backgroundColor = randomColor()
button.adjustsImageWhenHighlighted = false
button.titleLabel?.font = UIFont.systemFont(ofSize: 32)
contentView.addSubview(button)
buttonArray.append(button)
button.addTarget(self, action: #selector(emoticonButtonClick(btn:)), for: .touchUpInside)
}
//删除按钮
let deleteButton = UIButton()
deleteButton.frame = CGRect(x: ScreenWidth - buttonWidth, y: buttonHeight * 2, width: buttonWidth, height: buttonHeight)
deleteButton.setImage(#imageLiteral(resourceName: "compose_emotion_delete"), for: .normal)
deleteButton.adjustsImageWhenHighlighted = false
deleteButton.addTarget(self, action: #selector(deleteButtonClick), for: .touchUpInside)
contentView.addSubview(deleteButton)
}
@objc private func emoticonButtonClick(btn: DQEmoticonButton) {
DQEmoticonTools.sharedTools.saveRecentEmoticons(emoticon: btn.emoticon!)
NotificationCenter.default.post(name: NSNotification.Name(KSelectEmoticon), object: btn.emoticon)
}
@objc private func deleteButtonClick() {
NotificationCenter.default.post(name: NSNotification.Name(KSelectEmoticon), object: nil)
}
lazy var buttonArray: [DQEmoticonButton] = [DQEmoticonButton]()
lazy var popView: DQEmoticonPopView = {
return DQEmoticonPopView.loadPopoView()
}()
var emoticons: [DQEmoticon]? {
didSet{
for button in buttonArray {
button.isHidden = true
}
for value in emoticons!.enumerated() {
let btn = buttonArray[value.offset]
btn.isHidden = false
btn.emoticon = value.element
}
}
}
}
| 32.832117 | 128 | 0.601378 |
9bddd1c868fa809a25ed65bc54f20552d7ca20c6 | 423 | //
// LabelCollectionViewCellModel.swift
// SwiftTest
//
// Created by Najmuz Sakib on 31/1/19.
// Copyright © 2019 Najmuz Sakib. All rights reserved.
//
import UIKit
struct LabelCollectionViewCellModel {
var title: String
var edgeInsets: UIEdgeInsets
init(title:String = "", edgeInsets:UIEdgeInsets = UIEdgeInsets.zero) {
self.title = title
self.edgeInsets = edgeInsets
}
}
| 20.142857 | 74 | 0.673759 |
bf681d8cfefff599da285d3c9d6ed1a5e8fb5548 | 566 | //
// Date.swift
// JSONBuilder
//
// Created by Axel Etcheverry on 03/02/2017.
//
//
import Foundation
let iso8601Formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
extension Date: JSONSerializable {
public func jsonSerialize() -> Any {
return iso8601Formatter.string(from: self)
}
}
| 20.962963 | 56 | 0.690813 |
bf5e283738367e909f34423fb201742a117f86d2 | 839 | //
// BaseAPI.swift
// MOETeachers
//
// Created by Valera on 8/31/18.
// Copyright © 2018 IdeoDigital. All rights reserved.
//
//import Moya
import Foundation
protocol BaseAPI {
static var shouldUseStubs: Bool { get }
}
extension BaseAPI {
var baseURL: URL {
return URL(string: "\(AppContext.shared.environment.baseURLString)")!
}
func stubbedResponseFromJSONFile(filename: String, inDirectory subpath: String = "", bundle: Bundle = Bundle.main ) -> Data {
guard let path = bundle.path(forResource: filename, ofType: "json", inDirectory: subpath) else { return Data() }
if let dataString = try? String(contentsOfFile: path), let data = dataString.data(using: String.Encoding.utf8){
return data
} else {
return Data()
}
}
}
| 25.424242 | 129 | 0.630513 |
deb22e89188044ee9ac7e617a57191023d0502de | 581 | //
// UIViewController+Alert.swift
// AppEmpresas
//
// Created by Matheus Lima on 28/09/20.
//
import Foundation
import UIKit
extension UIViewController {
func alert(message: String, title: String = "", okAction: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
okAction()
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
| 27.666667 | 103 | 0.662651 |
286f97b4bf761ecb1606277a379a5e0ab0870f91 | 5,158 | //
// Feed+sql.swift
// chopchop
//
// Created by Maor Eini on 18/03/2017.
// Copyright © 2017 Maor Eini. All rights reserved.
//
//
// FeedItem+sql.swift
// chopchop
//
// Created by Maor Eini on 18/03/2017.
// Copyright © 2017 Maor Eini. All rights reserved.
//
import Foundation
//var feedItemId: String
//var userId: String
//var date: String
//var author: String
//var imageUrl: String
//var location: String
//var likesCount: Int
//var isLikeClicked: Bool
//var lastUpdate : Date?
extension FeedItem{
static let FEED_TABLE = "FEED"
static let FEED_ID = "ID"
static let FEED_USER_ID = "USER_ID"
static let FEED_AUTHOR = "AUTHOR"
static let FEED_DATE = "DATE"
static let FEED_IMAGE_URL = "IMAGE_URL"
static let FEED_LOCATION = "FEED_LOCATION"
static let FEED_LIKES_COUNT = "LIKES_COUNT"
static let FEED_IS_LIKE_CLICKED = "IS_LIKE_CLICKED"
static let FEED_LAST_UPDATE = "FEED_LAST_UPDATE"
static func createTable(database:OpaquePointer?)->Bool{
var errormsg: UnsafeMutablePointer<Int8>? = nil
let res = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS " + FEED_TABLE + " ( " + FEED_ID + " TEXT PRIMARY KEY, "
+ FEED_USER_ID + " TEXT, "
+ FEED_AUTHOR + " TEXT, "
+ FEED_DATE + " TEXT, "
+ FEED_IMAGE_URL + " TEXT, "
+ FEED_LOCATION + " TEXT, "
+ FEED_LIKES_COUNT + " TEXT, "
+ FEED_IS_LIKE_CLICKED + " TEXT, "
+ FEED_LAST_UPDATE + " DOUBLE)", nil, nil, &errormsg);
if(res != 0){
print("error creating table");
return false
}
return true
}
func addFeedItemToLocalDb(database:OpaquePointer?){
var sqlite3_stmt: OpaquePointer? = nil
if (sqlite3_prepare_v2(database,"INSERT OR REPLACE INTO " + FeedItem.FEED_TABLE
+ "(" + FeedItem.FEED_ID + ","
+ FeedItem.FEED_USER_ID + ","
+ FeedItem.FEED_AUTHOR + ","
+ FeedItem.FEED_DATE + ","
+ FeedItem.FEED_IMAGE_URL + ","
+ FeedItem.FEED_LOCATION + ","
+ FeedItem.FEED_LIKES_COUNT + ","
+ FeedItem.FEED_IS_LIKE_CLICKED + ","
+ FeedItem.FEED_LAST_UPDATE + ") VALUES (?,?,?,?,?,?,?,?,?);",-1, &sqlite3_stmt,nil) == SQLITE_OK){
let id = self.id.cString(using: .utf8)
let userId = self.userId.cString(using: .utf8)
let author = self.author.cString(using: .utf8)
let date = self.date.timeIntervalSince1970
let imageUrl = self.imageUrl.cString(using: .utf8)
let location = self.location.cString(using: .utf8)
let likesCount = Int32(self.likesCount)
let isLikeClicked = Int32((self.isLikeClicked) ? 1 : 0)
sqlite3_bind_text(sqlite3_stmt, 1, id,-1,nil);
sqlite3_bind_text(sqlite3_stmt, 2, userId,-1,nil);
sqlite3_bind_text(sqlite3_stmt, 3, author,-1,nil);
sqlite3_bind_double(sqlite3_stmt, 4, date);
sqlite3_bind_text(sqlite3_stmt, 5, imageUrl,-1,nil);
sqlite3_bind_text(sqlite3_stmt, 6, location,-1,nil);
sqlite3_bind_int(sqlite3_stmt, 7, likesCount);
sqlite3_bind_int(sqlite3_stmt, 8, isLikeClicked);
if (lastUpdate == nil){
lastUpdate = Date()
}
sqlite3_bind_double(sqlite3_stmt, 9, lastUpdate!.toFirebase());
if(sqlite3_step(sqlite3_stmt) == SQLITE_DONE){
print("new row added succefully")
}
}
sqlite3_finalize(sqlite3_stmt)
}
static func getAllFeedItemsFromLocalDb(database:OpaquePointer?)->[FeedItem]{
var FeedItems = [FeedItem]()
var sqlite3_stmt: OpaquePointer? = nil
if (sqlite3_prepare_v2(database,"SELECT * from FEED ORDER BY date DESC;",-1,&sqlite3_stmt,nil) == SQLITE_OK){
while(sqlite3_step(sqlite3_stmt) == SQLITE_ROW) {
let id = String(validatingUTF8:sqlite3_column_text(sqlite3_stmt,0))
let userId = String(validatingUTF8:sqlite3_column_text(sqlite3_stmt,1))
let author = String(validatingUTF8:sqlite3_column_text(sqlite3_stmt,2))
let date = sqlite3_column_double(sqlite3_stmt,3)
let imageUrl = String(validatingUTF8:sqlite3_column_text(sqlite3_stmt,4))
let location = String(validatingUTF8:sqlite3_column_text(sqlite3_stmt,5))
let likesCount = Int(sqlite3_column_int(sqlite3_stmt,6))
let isLikeClicked = (Int(sqlite3_column_int(sqlite3_stmt,7)) == 1) ? true : false;
let feedItem = FeedItem(id: id!, userId: userId!, author: author!,date: Date(timeIntervalSince1970: date), imageUrl: imageUrl!, location: location!, likesCount: likesCount, isLikeClicked: isLikeClicked)
FeedItems.append(feedItem)
}
}
sqlite3_finalize(sqlite3_stmt)
return FeedItems
}
}
| 38.492537 | 218 | 0.597325 |
ace30ed41b47067ed74dc84d4eb0c566f5216124 | 865 | //
// LikeViewController.swift
// TabBarApp
//
// Created by Halil Özel on 27.07.2018.
// Copyright © 2018 Halil Özel. All rights reserved.
//
import UIKit
class LikeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.027778 | 106 | 0.67052 |
16941fe1b8a7f7f0e4058d3dfd852c4ba5a4adb5 | 2,960 | //
// UIImage+Editor.swift
// DTCamera
//
// Created by Dan Jiang on 2019/8/7.
// Copyright © 2019 Dan Thought Studio. All rights reserved.
//
import UIKit
extension UIImage {
func cgImageCorrectedOrientation() -> CGImage? {
guard imageOrientation != .up else {
// This is default orientation, don't need to do anything
return cgImage
}
guard let cgImage = self.cgImage else {
// CGImage is not available
return nil
}
guard let colorSpace = cgImage.colorSpace,
let ctx = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil // Not able to create CGContext
}
var transform: CGAffineTransform = .identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat.pi / 2.0)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: CGFloat.pi / -2.0)
case .up, .upMirrored:
break
@unknown default:
break
}
// Flip image one more time if needed to, this is to prevent flipped image
switch imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .up, .down, .left, .right:
break
@unknown default:
break
}
ctx.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
return ctx.makeImage()
}
func correctedOrientation() -> UIImage? {
guard let newCGImage = cgImageCorrectedOrientation() else { return nil }
return UIImage(cgImage: newCGImage)
}
}
| 34.823529 | 95 | 0.548311 |
22d35dc4a61a0a33bc3057b141028527f8870434 | 5,504 | // Copyright 2016 Razeware Inc. (see LICENSE.txt for details)
/*:
## Dictionaries
### Question 1
Which of the following statements are valid?
*/
//let dict1: [Int, Int] = [:] // Invalid: type should be [Int: Int] not [Int, Int]
//let dict2 = [:] // Invalid: type cannot be inferred
let dict3: [Int: Int] = [:] // Valid
//: Given
let dict4 = ["One": 1, "Two": 2, "Three": 3]
//: Which of the following are valid:
//dict4[1] // Invalid: key should be String, not Int
dict4["One"] // Valid
//dict4["Zero"] = 0 // Invalid: dict4 is a constant
//dict4[0] = "Zero" // Invalid: key should be a String and value should be an Int - and dict4 is a constant anyway
//: Given
var dict5 = ["NY": "New York", "CA": "California"]
//: Which of the following are valid?
dict5["NY"] // Valid
dict5["WA"] = "Washington" // Valid
dict5["CA"] = nil // Valid
/*:
### Question 2
Write a function that swaps the values of two keys in a dictionary.
This is the signature of the function:
```
func swappingValuesForKeys(_ key1: String, _ key2: String, in dictionary: [String: Int]) -> [String: Int]
```
*/
func swappingValuesForKeys(_ key1: String, _ key2: String, in dictionary: [String: Int]) -> [String: Int] {
var newDictionary = dictionary
let oldValue = newDictionary[key1]
newDictionary[key1] = newDictionary[key2]
newDictionary[key2] = oldValue
return newDictionary
}
/*:
### Question 3
Given a dictionary with 2-letter state codes as keys and the full state name as values, write a function that prints all the states whose name is longer than 8 characters. For example, for this dictionary ["NY": "New York", "CA": "California"] the output would be "California".
*/
func printLongStateNames(in dictionary: [String: String]) {
for (_, value) in dictionary {
if value.characters.count > 8 {
print(value)
}
}
}
/*:
### Question 4
Write a function that combines two dictionaries into one. If a certain key appears in both dictionaries, ignore the pair from the first dictionary.
This is the signature of the function:
```
func combine(dict1: [String: String], with dict2: [String: String]) -> [String: String]
```
*/
func merging(_ dict1: [String: String], with dict2: [String: String]) -> [String: String] {
var newDictionary = dict1
for (key, value) in dict2 {
newDictionary[key] = value
}
return newDictionary
}
/*:
### Question 5
Declare a function `letterStats` that calculates which characters occur in a string, as well as how often each of these characters occur.
Return the result as a dictionary. This is the function signature:
```
func occurrencesOfCharacters(in text: String) -> [Character: Int]
```
*/
func occurrencesOfCharacters(in text: String) -> [Character: Int] {
var occurrences: [Character: Int] = [:]
for character in text.characters {
if let count = occurrences[character] {
occurrences[character] = count + 1
} else {
occurrences[character] = 1
}
}
return occurrences
}
/*:
### Question 6
Write a function that returns true if all of the values of a dictionary [String: Int] are unique. Use a dictionary to test uniqueness.
This is the function signature:
```
func isInvertible(_ dictionary: [String: Int]) -> Bool
```
*/
func isInvertible(_ dictionary: [String: Int]) -> Bool {
var isValuePresent: [Int: Bool] = [:]
for value in dictionary.values {
if isValuePresent[value] != nil {
return false // duplicate value detected
}
isValuePresent[value] = true
}
return true
}
/*:
### Question 7
Write an `invert` function that takes a dictionary [String: Int] and creates a new inverted dictionary [Int: String] where the values are the keys and the keys are the values. Note that for this function to work properly, the dictionary must be invertible. You can check this by using the function you created above to do ```precondition(isInvertible(input), "this dictionary can't be inverted")``` at the beginning of your function body. Your program will halt if this precondition is not met.
This is the function signature:
```
func invert(_ input: [String: Int]) -> [Int: String]
```
```
func invert(_ input: [String: Int]) -> [Int: String]
```
*/
func invert(_ input: [String: Int]) -> [Int: String] {
precondition(isInvertible(input), "this dictionary can't be inverted")
var output: [Int: String] = [:]
for (key, value) in input {
output[value] = key
}
return output
}
let testInvert = ["Eggs": 1000, "Bacon": 1001]
invert(testInvert)
/*:
### Question 8
Write a function that takes a dictionary [String: Int16] and prints the keys and values
alphabetically sorted by keys.
This is the function signature:
```
func printSortedKeysAndValues(_ input: [String: Int16])
```
*/
let testSort: [String: Int16] = ["Zebra": 3, "Aligator": 2, "Baboon": 3, "Cat": 10, "Dog": 8, "Elephant": 20, "Finch": 2, "Giraffe": 30]
func printSortedKeysAndValues(_ input: [String: Int16]) {
for k in Array(input.keys).sorted() {
print("\(k): \(input[k]!)")
}
}
printSortedKeysAndValues(testSort)
/*:
### Question 9.
Given the dictionary:
*/
var nameTitleLookup: [String: String?] = ["Mary": "Engineer", "Patrick": "Intern", "Ray": "Hacker"]
/*:
Set the value of the key "Patrick" to `nil` and completely remove the key and value for "Ray".
*/
nameTitleLookup.updateValue(nil, forKey: "Patrick")
nameTitleLookup.removeValue(forKey: "Ray")
nameTitleLookup["Ray"] = nil // The same as removeValue
nameTitleLookup
| 30.577778 | 497 | 0.680051 |
48eb05b1e65715c0de967a5a28e186c6809354a8 | 109 | import Foundation
extension String {
var asURL: URL {
return URL(fileURLWithPath: self)
}
}
| 13.625 | 41 | 0.642202 |
e5c74cf1cf22364c872799c6540c5c4027639425 | 2,289 | // --------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------
import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
/// User-configurable options for the `PostRequiredArrayParameter` operation.
public struct PostRequiredArrayParameterOptions: RequestOptions {
/// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// Highly recommended for correlating client-side activites with requests received by the server.
public let clientRequestId: String?
/// A token used to make a best-effort attempt at canceling a request.
public let cancellationToken: CancellationToken?
/// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
public var dispatchQueue: DispatchQueue?
/// A `PipelineContext` object to associate with the request.
public var context: PipelineContext?
/// Initialize a `PostRequiredArrayParameterOptions` structure.
/// - Parameters:
/// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
/// - cancellationToken: A token used to make a best-effort attempt at canceling a request.
/// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
/// - context: A `PipelineContext` object to associate with the request.
public init(
clientRequestId: String? = nil,
cancellationToken: CancellationToken? = nil,
dispatchQueue: DispatchQueue? = nil,
context: PipelineContext? = nil
) {
self.clientRequestId = clientRequestId
self.cancellationToken = cancellationToken
self.dispatchQueue = dispatchQueue
self.context = context
}
}
| 44.882353 | 122 | 0.6872 |
fefc2cde14332a98b0839e70fb018436ff126cc6 | 321 | public struct BluesScale: Scale {
public let key: Note
public var notes: [Note] { [
key,
key + .minorThird,
key + .perfectFourth,
key + .diminishedFifth,
key + .perfectFifth,
key + .minorSeventh
] }
public init(key: Note) {
self.key = key
}
}
| 18.882353 | 33 | 0.523364 |
8989a89aab1a3e27d996a91e8c156f07d4abfa5b | 627 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func use<T>(_: T) {}
// CHECK-LABEL: sil hidden @$S22generic_local_property3foo1x1yyx_SitlF
func foo<T>(x: T, y: Int) {
var mutable: Int {
get {
use(x)
return y
}
set {
use(x)
}
}
var readonly: Int {
get {
use(x)
return y
}
}
// CHECK-LABEL: function_ref getter of readonly #1 in foo<A>(x:y:)
_ = readonly
// CHECK-LABEL: function_ref getter of mutable #1 in foo<A>(x:y:)
_ = mutable
// CHECK-LABEL: function_ref setter of mutable #1 in foo<A>(x:y:)
mutable = y
}
| 20.225806 | 84 | 0.591707 |
bbcc744e4f5f541243c56f20c4c2c971094a64af | 9,940 | import Foundation
private extension DispatchTime {
var elapsed: Double {
let nanoTime = DispatchTime.now().uptimeNanoseconds - self.uptimeNanoseconds
return Double(nanoTime) / 1_000_000
}
}
/**
The logger class is used within the library to output logs of what is going on. Multi-threading and task management is very
complicated and having logs can help immensely when it comes to debugging purposes
Everytime the log function is called, a number of tags are automatically produced that are attached to the message. These are:
* the function name that the log is called from
* The thread that the log is called from (UI or BG - for background)
* The filename
* The log level (see `LogLevel`)
This class is also made public so the API is meant to be stable
There're also a number of predefined tags that the logs from within the library use. See `LogTags` for a list.
*/
public class Logger {
/// Shared logger object
public static let shared: Logger = {
let logger = Logger(synchronousOutput: true)
// logger.addTransport { print($0) }
return logger
}()
private let startTime = DispatchTime.now()
private let queue = DispatchQueue(label: "Tasker.Logger", qos: .utility)
private let dispatchGroup = DispatchGroup()
private var _enabled: Bool = true
private var _outputTags: Bool = false
private let synchronousOutput: Bool
private var transports: [(String) -> Void] = []
private var allowedTags = Set<String>()
private var ignoredTags = Set<String>()
private var historyBuffer: RingBuffer<String>?
/**
Initializes a Logger object
- parameter logHistorySize: How many entried to keep in the history
*/
public init(logHistorySize: Int? = nil, synchronousOutput: Bool = false) {
if let logHistorySize = logHistorySize {
self.historyBuffer = RingBuffer(capacity: logHistorySize)
}
self.synchronousOutput = synchronousOutput
self.enabled = true
}
/**
Transports are called asynchronously, if you need to wait till all logging output has been sent to
all transports then this function blocks until that happens
*/
public func waitTillAllLogsTransported() {
self.dispatchGroup.wait()
}
/// Set to true if you want the tags to be printed as well
public var outputTags: Bool {
get {
self.queue.sync {
self._outputTags
}
}
set {
self.queue.async { [weak self] in
self?._outputTags = newValue
}
}
}
/// If this is false then it ignores all logs
public var enabled: Bool {
get {
self.queue.sync {
self._enabled
}
}
set {
self.queue.async { [weak self] in
self?._enabled = newValue
}
}
}
/**
Adding a transport allows you to tell the logger where the output goes to. You may add as
many as you like.
- parameter transport: function that is called with each log invocaton
*/
public func addTransport(_ transport: @escaping (String) -> Void) {
self.queue.async { [weak self] in
self?.transports.append(transport)
}
}
public func removeTransports() {
self.queue.async { [weak self] in
self?.transports.removeAll()
}
}
/// Filters log messages unless they are tagged with `tag`
public func filterUnless(tag: String) {
self.queue.async { [weak self] in
self?.allowedTags.insert(tag)
}
}
/// Filters log messages unless they are tagged with any of `tags`
public func filterUnless(tags: [String]) {
self.queue.async { [weak self] in
if let union = self?.allowedTags.union(tags) {
self?.allowedTags = union
}
}
}
/// Filters log messages if they are tagged with `tag`
public func filterIf(tag: String) {
self.queue.async { [weak self] in
self?.ignoredTags.insert(tag)
}
}
/// Filters log messages if they are tagged with any of `tags`
public func filterIf(tags: [String]) {
self.queue.async { [weak self] in
if let union = self?.ignoredTags.union(tags) {
self?.ignoredTags = union
}
}
}
/**
Logs any `T` by using string interpolation
- parameter object: autoclosure statment to be logged
- parameter tag: a tag to apply to this log
*/
public func log<T>(
level: LogLevel = .info,
_ object: @autoclosure () -> T,
tag: String,
force: Bool = false,
_ file: String = #file,
_ function: String = #function,
_ line: Int = #line
) {
self.log(level: level, object(), tags: [tag], force: force, file, function, line)
}
public func log<T, S>(
level: LogLevel = .info,
from _: S?,
_ object: @autoclosure () -> T,
tags: [String] = [],
force: Bool = false,
_ file: String = #file,
_ function: String = #function,
_ line: Int = #line
) {
self.log(
level: level,
object: object(),
tags: tags,
force: force,
context: String(describing: S.self),
file: file,
function: function,
line: line
)
}
/**
Logs any `T` by using string interpolation
- parameter object: autoclosure statment to be logged
- parameter tags: a set of tags to apply to this log
*/
public func log<T>(
level: LogLevel = .info,
_ object: @autoclosure () -> T,
tags: [String] = [],
force: Bool = false,
_ file: String = #file,
_ function: String = #function,
_ line: Int = #line
) {
self.log(
level: level,
object: object(),
tags: tags,
force: force,
context: nil,
file: file,
function: function,
line: line
)
}
private func log<T>(
level: LogLevel = .info,
object: @autoclosure () -> T,
tags explicitTags: [String],
force: Bool,
context: String?,
file: String,
function: String,
line: Int
) {
#if !DEBUG
guard level != .debug else {
return
}
#endif
let thread = Thread.isMainThread ? "UI" : "BG"
let threadID = pthread_mach_thread_np(pthread_self())
let timestamp = self.startTime.elapsed
let string = "\(object())"
if self.synchronousOutput {
self.queue.sync {
self.synclog(
thread: thread,
threadID: threadID,
timestamp: timestamp,
level: level,
string: string,
tags: explicitTags,
force: force,
file: file,
function: function,
line: line,
context: context
)
}
return
}
self.dispatchGroup.enter()
self.queue.async { [weak self] in
self?.synclog(
thread: thread,
threadID: threadID,
timestamp: timestamp,
level: level,
string: string,
tags: explicitTags,
force: force,
file: file,
function: function,
line: line,
context: context
)
self?.dispatchGroup.leave()
}
}
private func synclog(
thread: String,
threadID: mach_port_t,
timestamp: Double,
level: LogLevel = .info,
string: String,
tags explicitTags: [String] = [],
force: Bool = false,
file: String = #file,
function: String = #function,
line: Int = #line,
context: String?
) {
guard (self._enabled && self.transports.count > 0) || force else {
return
}
let functionName = function.components(separatedBy: "(").first ?? ""
let fileName: String = {
let name = URL(fileURLWithPath: file)
.deletingPathExtension().lastPathComponent
let value = name.isEmpty ? "Unknown file" : name
return value
}()
var allTags = [functionName, thread, fileName, level.rawValue]
allTags.append(contentsOf: explicitTags)
if let context = context {
allTags.append(context)
}
var shouldOutputToTransports = true
if self.ignoredTags.count > 0 && self.ignoredTags.intersection(allTags).count > 0 {
shouldOutputToTransports = false
}
if self.allowedTags.count > 0 && self.allowedTags.intersection(allTags).count == 0 {
shouldOutputToTransports = false
}
guard shouldOutputToTransports || force else {
return
}
var tagsString = ""
if explicitTags.count > 0, self._outputTags {
tagsString = ",\(explicitTags.joined(separator: ","))"
}
let output = "[\(level.rawValue):\(String(format: "%.2f", timestamp))]"
+ "[\(thread):\(threadID),\(fileName):\(line),\(functionName)\(tagsString)]"
+ " => \(string)"
self.historyBuffer?.append(output)
if shouldOutputToTransports {
for transport in self.transports {
transport(output)
}
}
if force {
print(output)
}
}
}
| 29.671642 | 127 | 0.544567 |
dbb97b189cf242b17f80654c55a70497528d2f63 | 6,810 | //
// Tests_XCTestCase.swift
// HLYWebViewJSBridge_Tests
//
// Created by Lingye Han on 2020/5/9.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import XCTest
import WebKit
import HLYWebViewJSBridge
@testable import HLYWebViewJSBridge_Example
let timeout: Double = 3
class Tests_XCTestCase: XCTestCase {
var wkWebView: WKWebView!
var bridgeRefs = [HLYWebViewJSBridge]()
override func setUp() {
super.setUp()
let rootVC = (UIApplication.shared.delegate as! AppDelegate).window!.rootViewController!
wkWebView = WKWebView(frame: rootVC.view.bounds)
wkWebView.backgroundColor = UIColor.red
rootVC.view.addSubview(wkWebView)
wkWebView.navigationDelegate = self
HLYWebViewJSBridge.enableLogging()
}
override func tearDown() {
super.tearDown()
wkWebView.removeFromSuperview()
}
func testRegisterHandler() {
let bridge = self.bridge()
XCTAssertNotNil(bridge)
let expectation = self.expectation(description: "Register Handler")
bridge.registerHandler("nativeFunc") { (data, responseCallback) in
XCTAssertEqual(data as? String, "Hello world")
expectation.fulfill()
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testCallHandler() {
let bridge = self.bridge()
let callbackInvoked = expectation(description: "Callback invoked")
bridge.callHandler("echoHandler", data: "echo hello!") { (responseData) in
XCTAssertEqual(responseData as? String, "echo hello!");
callbackInvoked.fulfill()
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testEchoHandlerAfterSetup() {
let bridge = self.bridge()
let callbackInvoked = expectation(description: "Callback invoked")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.150) {
bridge.callHandler("echoHandler", data:"testEchoHandler") { (responseData) in
XCTAssertEqual(responseData as! String, "testEchoHandler")
callbackInvoked.fulfill()
}
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testObjectEncoding() {
let bridge = self.bridge()
func echoObject(_ object: Any) {
let callbackInvoked = expectation(description: "Callback invoked")
bridge.callHandler("echoHandler", data: object) { (responseData) in
if (object is NSDictionary) {
XCTAssertEqual(responseData as! NSDictionary, object as! NSDictionary)
} else if (object is NSArray) {
XCTAssertEqual(responseData as! NSArray, object as! NSArray)
}
callbackInvoked.fulfill()
}
}
echoObject("A string sent over the wire");
echoObject("A string with '\"'/\\");
echoObject([1, 2, 3]);
echoObject(["a": 1, "b": 2]);
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testJavascriptReceiveResponse() {
let bridge = self.bridge()
let callbackInvoked = expectation(description: "Callback invoked")
bridge.registerHandler("objcEchoToJs") { (data, responseCallback) in
XCTAssertEqual(data as! NSDictionary, ["foo": "bar"]);
responseCallback!(data)
}
bridge.callHandler("jsRcvResponseTest", data: nil) { (responseData) in
XCTAssertEqual(responseData as! String, "Response from JS");
callbackInvoked.fulfill()
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testJavascriptReceiveResponseWithoutSafetyTimeout() {
let bridge = self.bridge()
bridge.disableJavscriptAlertBoxSafetyTimeout()
let callbackInvoked = expectation(description: "Callback invoked")
bridge.registerHandler("objcEchoToJs") { (data, responseCallback) in
XCTAssertEqual(data as! NSDictionary, ["foo": "bar"]);
responseCallback!(data);
}
bridge.callHandler("jsRcvResponseTest", data:nil) { (responseData) in
XCTAssertEqual(responseData as! String, "Response from JS");
callbackInvoked.fulfill()
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
func testRemoveHandler() {
let bridge = self.bridge()
let callbackNotInvoked = expectation(description: "Callback invoked")
var count = 0
bridge.registerHandler("objcEchoToJs") { (data, callback) in
count += 1
callback!(data)
}
bridge.callHandler("jsRcvResponseTest", data: nil) { (responseData) in
XCTAssertEqual(responseData as! String, "Response from JS");
bridge.removeHandler("objcEchoToJs")
bridge.callHandler("jsRcvResponseTest", data: nil) { (responseData) in
// Since we have removed the "objcEchoToJs" handler, and since the
// echo.html javascript won't call the response callback until it has
// received a response from "objcEchoToJs", we should never get here
XCTAssert(false)
}
bridge.callHandler("echoHandler", data: nil) { (responseData) in
XCTAssertEqual(count, 1)
callbackNotInvoked.fulfill()
}
}
loadJSBridgeTestHTML()
waitForExpectations(timeout: timeout, handler: nil)
}
private func bridge() -> HLYWebViewJSBridge {
let bridge = HLYWebViewJSBridge.bridge(wkWebView)
bridgeRefs.append(bridge)
return bridge
}
private func loadJSBridgeTestHTML() {
let request = URLRequest(url: Bundle.main.url(forResource: "JSBridgeTest", withExtension: "html")!)
wkWebView.load(request)
}
}
extension Tests_XCTestCase: WKNavigationDelegate {
// func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// print("\(#function)")
// }
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("\(#function)")
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
print("\(#function)")
decisionHandler(.allow)
}
}
| 35.103093 | 163 | 0.627019 |
c1b6cd470c31c21bf7e04c356d7d0fa959f804fe | 1,730 | //
// Promise+Web3+Personal+UnlockAccount.swift
// web3swift
//
// Created by Alexander Vlasov on 18.06.2018.
// Copyright © 2018 Bankex Foundation. All rights reserved.
//
import Foundation
import BigInt
import PromiseKit
import EthereumAddress
extension web3.Personal {
func unlockAccountPromise(account: EthereumAddress, password:String = "web3swift", seconds: UInt64 = 300) -> Promise<Bool> {
let addr = account.address
return unlockAccountPromise(account: addr, password: password, seconds: seconds)
}
func unlockAccountPromise(account: String, password:String = "web3swift", seconds: UInt64 = 300) -> Promise<Bool> {
let queue = web3.requestDispatcher.queue
do {
if self.web3.provider.attachedKeystoreManager == nil {
let request = JSONRPCRequestFabric.prepareRequest(.unlockAccount, parameters: [account.lowercased(), password, seconds])
return self.web3.dispatch(request).map(on: queue) {response in
guard let value: Bool = response.getValue() else {
if response.error != nil {
throw Web3Error.nodeError(desc: response.error!.message)
}
throw Web3Error.nodeError(desc: "Invalid value from Ethereum node")
}
return value
}
}
throw Web3Error.inputError(desc: "Can not unlock a local keystore")
} catch {
let returnPromise = Promise<Bool>.pending()
queue.async {
returnPromise.resolver.reject(error)
}
return returnPromise.promise
}
}
}
| 37.608696 | 136 | 0.601156 |
e6679fe2546ce7e75f1a32499e6f8b31ea906330 | 37,250 | // @generated
// Do not edit this generated file
// swiftlint:disable all
// swiftformat:disable all
import Foundation
// MARK: - StarWarsEnumModel
/// One of the films in the Star Wars Trilogy
enum EpisodeStarWarsEnumModel: RawRepresentable, Codable {
typealias RawValue = String
/// Released in 1977.
case newhope
/// Released in 1980.
case empire
/// Released in 1983
case jedi
/// Auto generated constant for unknown enum values
case _unknown(RawValue)
public init?(rawValue: RawValue) {
switch rawValue {
case "NEWHOPE": self = .newhope
case "EMPIRE": self = .empire
case "JEDI": self = .jedi
default: self = ._unknown(rawValue)
}
}
public var rawValue: RawValue {
switch self {
case .newhope: return "NEWHOPE"
case .empire: return "EMPIRE"
case .jedi: return "JEDI"
case let ._unknown(value): return value
}
}
static func == (lhs: EpisodeStarWarsEnumModel, rhs: EpisodeStarWarsEnumModel) -> Bool {
switch (lhs, rhs) {
case (.newhope, .newhope): return true
case (.empire, .empire): return true
case (.jedi, .jedi): return true
case let (._unknown(lhsValue), ._unknown(rhsValue)): return lhsValue == rhsValue
default: return false
}
}
}
/// Language
enum LanguageStarWarsEnumModel: RawRepresentable, Codable {
typealias RawValue = String
case en
case sl
/// Auto generated constant for unknown enum values
case _unknown(RawValue)
public init?(rawValue: RawValue) {
switch rawValue {
case "EN": self = .en
case "SL": self = .sl
default: self = ._unknown(rawValue)
}
}
public var rawValue: RawValue {
switch self {
case .en: return "EN"
case .sl: return "SL"
case let ._unknown(value): return value
}
}
static func == (lhs: LanguageStarWarsEnumModel, rhs: LanguageStarWarsEnumModel) -> Bool {
switch (lhs, rhs) {
case (.en, .en): return true
case (.sl, .sl): return true
case let (._unknown(lhsValue), ._unknown(rhsValue)): return lhsValue == rhsValue
default: return false
}
}
}
// MARK: - StarWarsModel
struct MutationStarWarsModel: Codable {
let mutate: Optional<Bool>
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case mutate
}
}
struct DroidStarWarsModel: Codable {
private let internalId: Optional<String>
private let internalName: Optional<String>
func id() throws -> String {
try value(for: \Self.internalId, codingKey: CodingKeys.internalId)
}
func name() throws -> String {
try value(for: \Self.internalName, codingKey: CodingKeys.internalName)
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
internalId = try container.decodeOptionalIfPresent(String.self, forKey: .internalId)
internalName = try container.decodeOptionalIfPresent(String.self, forKey: .internalName)
}
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case internalId = "id"
case internalName = "name"
}
}
struct HumanStarWarsModel: Codable {
private let internalId: Optional<String>
func id() throws -> String {
try value(for: \Self.internalId, codingKey: CodingKeys.internalId)
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
internalId = try container.decodeOptionalIfPresent(String.self, forKey: .internalId)
}
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case internalId = "id"
}
}
struct QueryStarWarsModel: Codable {
let character: Optional<CharacterUnionStarWarsUnionModel?>
let characters: Optional<[CharacterStarWarsInterfaceModel]>
let droid: Optional<DroidStarWarsModel?>
let droids: Optional<[DroidStarWarsModel]>
let greeting: Optional<String>
let human: Optional<HumanStarWarsModel?>
let humans: Optional<[HumanStarWarsModel]>
let luke: Optional<HumanStarWarsModel?>
let time: Optional<DateTimeInterval>
let whoami: Optional<String>
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case character
case characters
case droid
case droids
case greeting
case human
case humans
case luke
case time
case whoami
}
}
struct SubscriptionStarWarsModel: Codable {
let number: Optional<Int>
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case number
}
}
// MARK: - Input Objects
struct GreetingStarWarsInputModel: Codable {
let language: LanguageStarWarsEnumModel?
let name: String
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case language
case name
}
}
struct GreetingOptionsStarWarsInputModel: Codable {
let prefix: String?
// MARK: - CodingKeys
private enum CodingKeys: String, CodingKey {
case prefix
}
}
// MARK: - StarWarsInterfaceModel
enum CharacterStarWarsInterfaceModel: Codable {
case droid(DroidStarWarsModel)
case human(HumanStarWarsModel)
enum Typename: String, Decodable {
case droid = "Droid"
case human = "Human"
}
private enum CodingKeys: String, CodingKey {
case __typename
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let singleValueContainer = try decoder.singleValueContainer()
let type = try container.decode(Typename.self, forKey: .__typename)
switch type {
case .droid:
let value = try singleValueContainer.decode(DroidStarWarsModel.self)
self = .droid(value)
case .human:
let value = try singleValueContainer.decode(HumanStarWarsModel.self)
self = .human(value)
}
}
func encode(to _: Encoder) throws {
fatalError("Not implemented yet")
}
}
// MARK: - StarWarsUnionModel
enum CharacterUnionStarWarsUnionModel: Codable {
case human(HumanStarWarsModel)
case droid(DroidStarWarsModel)
enum Typename: String, Decodable {
case human = "Human"
case droid = "Droid"
}
private enum CodingKeys: String, CodingKey {
case __typename
case id
case name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let singleValueContainer = try decoder.singleValueContainer()
let type = try container.decode(Typename.self, forKey: .__typename)
switch type {
case .human:
let value = try singleValueContainer.decode(HumanStarWarsModel.self)
self = .human(value)
case .droid:
let value = try singleValueContainer.decode(DroidStarWarsModel.self)
self = .droid(value)
}
}
func encode(to _: Encoder) throws {
fatalError("Not implemented yet")
}
}
// MARK: - GraphQLRequesting
/// CharacterStarWarsQuery
struct CharacterStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "character"
let rootSelectionKeys: Set<String> = ["CharacterCharacterUnionFragment"]
// MARK: - Arguments
/// id of the character
let id: String
private enum CodingKeys: String, CodingKey {
/// id of the character
case id = "characterId"
}
init(
id: String
) {
self.id = id
}
// MARK: - Operation Definition
let requestQuery: String = {
"""
character(
id: $characterId
) {
...CharacterCharacterUnionFragment
}
"""
}()
let requestArguments: String = {
"""
$characterId: ID!
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// CharactersStarWarsQuery
struct CharactersStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "characters"
let rootSelectionKeys: Set<String> = ["CharactersCharacterFragment"]
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
characters {
...CharactersCharacterFragment
}
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// DroidStarWarsQuery
struct DroidStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "droid"
let rootSelectionKeys: Set<String> = ["DroidDroidFragment"]
// MARK: - Arguments
/// id of the character
let id: String
private enum CodingKeys: String, CodingKey {
/// id of the character
case id = "droidId"
}
init(
id: String
) {
self.id = id
}
// MARK: - Operation Definition
let requestQuery: String = {
"""
droid(
id: $droidId
) {
...DroidDroidFragment
}
"""
}()
let requestArguments: String = {
"""
$droidId: ID!
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// DroidsStarWarsQuery
struct DroidsStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "droids"
let rootSelectionKeys: Set<String> = ["DroidsDroidFragment"]
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
droids {
...DroidsDroidFragment
}
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// GreetingStarWarsQuery
struct GreetingStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "greeting"
let rootSelectionKeys: Set<String> = []
// MARK: - Arguments
let input: GreetingStarWarsInputModel?
private enum CodingKeys: String, CodingKey {
case input = "greetingInput"
}
init(
input: GreetingStarWarsInputModel?
) {
self.input = input
}
// MARK: - Operation Definition
let requestQuery: String = {
"""
greeting(
input: $greetingInput
)
"""
}()
let requestArguments: String = {
"""
$greetingInput: Greeting
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// HumanStarWarsQuery
struct HumanStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "human"
let rootSelectionKeys: Set<String> = ["HumanHumanFragment"]
// MARK: - Arguments
/// id of the character
let id: String
private enum CodingKeys: String, CodingKey {
/// id of the character
case id = "humanId"
}
init(
id: String
) {
self.id = id
}
// MARK: - Operation Definition
let requestQuery: String = {
"""
human(
id: $humanId
) {
...HumanHumanFragment
}
"""
}()
let requestArguments: String = {
"""
$humanId: ID!
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// HumansStarWarsQuery
struct HumansStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "humans"
let rootSelectionKeys: Set<String> = ["HumansHumanFragment"]
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
humans {
...HumansHumanFragment
}
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// LukeStarWarsQuery
struct LukeStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "luke"
let rootSelectionKeys: Set<String> = ["LukeHumanFragment"]
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
luke {
...LukeHumanFragment
}
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// TimeStarWarsQuery
struct TimeStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "time"
let rootSelectionKeys: Set<String> = []
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
time
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
/// WhoamiStarWarsQuery
struct WhoamiStarWarsQuery: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .query
let requestName: String = "whoami"
let rootSelectionKeys: Set<String> = []
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
whoami
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
struct StarWarsQuery: GraphQLRequesting {
let requestType: GraphQLRequestType = .query
let requestName: String = ""
var rootSelectionKeys: Set<String> {
return requests.reduce(into: Set<String>()) { result, request in
request.rootSelectionKeys.forEach {
result.insert($0)
}
}
}
let character: CharacterStarWarsQuery?
let characters: CharactersStarWarsQuery?
let droid: DroidStarWarsQuery?
let droids: DroidsStarWarsQuery?
let greeting: GreetingStarWarsQuery?
let human: HumanStarWarsQuery?
let humans: HumansStarWarsQuery?
let luke: LukeStarWarsQuery?
let time: TimeStarWarsQuery?
let whoami: WhoamiStarWarsQuery?
private var requests: [GraphQLRequesting] {
let requests: [GraphQLRequesting?] = [
character,
characters,
droid,
droids,
greeting,
human,
humans,
luke,
time,
whoami
]
return requests.compactMap { $0 }
}
init(
character: CharacterStarWarsQuery? = nil,
characters: CharactersStarWarsQuery? = nil,
droid: DroidStarWarsQuery? = nil,
droids: DroidsStarWarsQuery? = nil,
greeting: GreetingStarWarsQuery? = nil,
human: HumanStarWarsQuery? = nil,
humans: HumansStarWarsQuery? = nil,
luke: LukeStarWarsQuery? = nil,
time: TimeStarWarsQuery? = nil,
whoami: WhoamiStarWarsQuery? = nil
) {
self.character = character
self.characters = characters
self.droid = droid
self.droids = droids
self.greeting = greeting
self.human = human
self.humans = humans
self.luke = luke
self.time = time
self.whoami = whoami
}
func encode(to encoder: Encoder) throws {
try requests.forEach {
try $0.encode(to: encoder)
}
}
var requestQuery: String {
requests
.map { $0.requestQuery }
.joined(separator: "\n")
}
var requestArguments: String {
requests
.map { $0.requestArguments }
.joined(separator: "\n")
}
func requestFragments(with selections: GraphQLSelections) -> String {
requests.map {
selections.requestFragments(for: $0.requestName, rootSelectionKeys: rootSelectionKeys)
}.joined(separator: "\n")
}
}
/// MutateStarWarsMutation
struct MutateStarWarsMutation: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .mutation
let requestName: String = "mutate"
let rootSelectionKeys: Set<String> = []
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
mutate
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
struct StarWarsMutation: GraphQLRequesting {
let requestType: GraphQLRequestType = .mutation
let requestName: String = ""
var rootSelectionKeys: Set<String> {
return requests.reduce(into: Set<String>()) { result, request in
request.rootSelectionKeys.forEach {
result.insert($0)
}
}
}
let mutate: MutateStarWarsMutation?
private var requests: [GraphQLRequesting] {
let requests: [GraphQLRequesting?] = [
mutate
]
return requests.compactMap { $0 }
}
init(
mutate: MutateStarWarsMutation? = nil
) {
self.mutate = mutate
}
func encode(to encoder: Encoder) throws {
try requests.forEach {
try $0.encode(to: encoder)
}
}
var requestQuery: String {
requests
.map { $0.requestQuery }
.joined(separator: "\n")
}
var requestArguments: String {
requests
.map { $0.requestArguments }
.joined(separator: "\n")
}
func requestFragments(with selections: GraphQLSelections) -> String {
requests.map {
selections.requestFragments(for: $0.requestName, rootSelectionKeys: rootSelectionKeys)
}.joined(separator: "\n")
}
}
/// NumberStarWarsSubscription
struct NumberStarWarsSubscription: GraphQLRequesting {
// MARK: - GraphQLRequestType
let requestType: GraphQLRequestType = .subscription
let requestName: String = "number"
let rootSelectionKeys: Set<String> = []
func encode(to _: Encoder) throws {}
init(
) {}
// MARK: - Operation Definition
let requestQuery: String = {
"""
number
"""
}()
let requestArguments: String = {
"""
"""
}()
func requestFragments(with selections: GraphQLSelections) -> String {
selections.requestFragments(for: requestName, rootSelectionKeys: rootSelectionKeys)
}
}
struct StarWarsSubscription: GraphQLRequesting {
let requestType: GraphQLRequestType = .subscription
let requestName: String = ""
var rootSelectionKeys: Set<String> {
return requests.reduce(into: Set<String>()) { result, request in
request.rootSelectionKeys.forEach {
result.insert($0)
}
}
}
let number: NumberStarWarsSubscription?
private var requests: [GraphQLRequesting] {
let requests: [GraphQLRequesting?] = [
number
]
return requests.compactMap { $0 }
}
init(
number: NumberStarWarsSubscription? = nil
) {
self.number = number
}
func encode(to encoder: Encoder) throws {
try requests.forEach {
try $0.encode(to: encoder)
}
}
var requestQuery: String {
requests
.map { $0.requestQuery }
.joined(separator: "\n")
}
var requestArguments: String {
requests
.map { $0.requestArguments }
.joined(separator: "\n")
}
func requestFragments(with selections: GraphQLSelections) -> String {
requests.map {
selections.requestFragments(for: $0.requestName, rootSelectionKeys: rootSelectionKeys)
}.joined(separator: "\n")
}
}
struct CharacterQueryResponse: Codable {
let character: CharacterUnionStarWarsUnionModel?
}
struct CharactersQueryResponse: Codable {
let characters: [CharacterStarWarsInterfaceModel]
}
struct DroidQueryResponse: Codable {
let droid: DroidStarWarsModel?
}
struct DroidsQueryResponse: Codable {
let droids: [DroidStarWarsModel]
}
struct GreetingQueryResponse: Codable {
let greeting: String
}
struct HumanQueryResponse: Codable {
let human: HumanStarWarsModel?
}
struct HumansQueryResponse: Codable {
let humans: [HumanStarWarsModel]
}
struct LukeQueryResponse: Codable {
let luke: HumanStarWarsModel?
}
struct TimeQueryResponse: Codable {
let time: DateTimeInterval
}
struct WhoamiQueryResponse: Codable {
let whoami: String
}
struct MutateMutationResponse: Codable {
let mutate: Bool
}
struct NumberSubscriptionResponse: Codable {
let number: Int
}
// MARK: - GraphQLSelection
enum DroidSelection: String, GraphQLSelection {
case id
case name
}
enum HumanSelection: String, GraphQLSelection {
case id
}
struct StarWarsQuerySelections: GraphQLSelections {
let droid: Set<DroidSelection>
let human: Set<HumanSelection>
init(
droid: Set<DroidSelection> = .allFields,
human: Set<HumanSelection> = .allFields
) {
self.droid = droid
self.human = human
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let droidDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droid.requestFragments(requestName: capitalizedRequestName))
}
"""
let humanDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(human.requestFragments(requestName: capitalizedRequestName))
}
"""
let characterDeclaration = """
fragment \(capitalizedRequestName)CharacterFragment on Character {
__typename
...\(capitalizedRequestName)DroidFragment
...\(capitalizedRequestName)HumanFragment
}
"""
let characterUnionDeclaration = """
fragment \(capitalizedRequestName)CharacterUnionFragment on CharacterUnion {
__typename
...\(capitalizedRequestName)HumanFragment
...\(capitalizedRequestName)DroidFragment
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)DroidFragment": droidDeclaration,
"\(capitalizedRequestName)HumanFragment": humanDeclaration,
"\(capitalizedRequestName)CharacterFragment": characterDeclaration,
"\(capitalizedRequestName)CharacterUnionFragment": characterUnionDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct HumanStarWarsQuerySelections: GraphQLSelections {
let humanSelections: Set<HumanSelection>
init(
humanSelections: Set<HumanSelection> = .allFields
) {
self.humanSelections = humanSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let humanSelectionsDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(humanSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)HumanFragment": humanSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct DroidStarWarsQuerySelections: GraphQLSelections {
let droidSelections: Set<DroidSelection>
init(
droidSelections: Set<DroidSelection> = .allFields
) {
self.droidSelections = droidSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let droidSelectionsDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droidSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)DroidFragment": droidSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct CharacterStarWarsQuerySelections: GraphQLSelections {
let droidSelections: Set<DroidSelection>
let humanSelections: Set<HumanSelection>
init(
droidSelections: Set<DroidSelection> = .allFields,
humanSelections: Set<HumanSelection> = .allFields
) {
self.droidSelections = droidSelections
self.humanSelections = humanSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let characterUnionSelectionsDeclaration = """
fragment \(capitalizedRequestName)CharacterUnionFragment on CharacterUnion {
__typename
...\(capitalizedRequestName)HumanFragment
...\(capitalizedRequestName)DroidFragment
}
"""
let droidSelectionsDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droidSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let humanSelectionsDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(humanSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)CharacterUnionFragment": characterUnionSelectionsDeclaration,
"\(capitalizedRequestName)DroidFragment": droidSelectionsDeclaration,
"\(capitalizedRequestName)HumanFragment": humanSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct LukeStarWarsQuerySelections: GraphQLSelections {
let humanSelections: Set<HumanSelection>
init(
humanSelections: Set<HumanSelection> = .allFields
) {
self.humanSelections = humanSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let humanSelectionsDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(humanSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)HumanFragment": humanSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct HumansStarWarsQuerySelections: GraphQLSelections {
let humanSelections: Set<HumanSelection>
init(
humanSelections: Set<HumanSelection> = .allFields
) {
self.humanSelections = humanSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let humanSelectionsDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(humanSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)HumanFragment": humanSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct DroidsStarWarsQuerySelections: GraphQLSelections {
let droidSelections: Set<DroidSelection>
init(
droidSelections: Set<DroidSelection> = .allFields
) {
self.droidSelections = droidSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let droidSelectionsDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droidSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)DroidFragment": droidSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct CharactersStarWarsQuerySelections: GraphQLSelections {
let droidSelections: Set<DroidSelection>
let humanSelections: Set<HumanSelection>
init(
droidSelections: Set<DroidSelection> = .allFields,
humanSelections: Set<HumanSelection> = .allFields
) {
self.droidSelections = droidSelections
self.humanSelections = humanSelections
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let characterSelectionsDeclaration = """
fragment \(capitalizedRequestName)CharacterFragment on Character {
__typename
...\(capitalizedRequestName)DroidFragment
...\(capitalizedRequestName)HumanFragment
}
"""
let droidSelectionsDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droidSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let humanSelectionsDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(humanSelections.requestFragments(requestName: capitalizedRequestName))
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)CharacterFragment": characterSelectionsDeclaration,
"\(capitalizedRequestName)DroidFragment": droidSelectionsDeclaration,
"\(capitalizedRequestName)HumanFragment": humanSelectionsDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct GreetingStarWarsQuerySelections: GraphQLSelections {
func requestFragments(for _: String, rootSelectionKeys _: Set<String>) -> String {
""
}
}
// MARK: - Selections
struct WhoamiStarWarsQuerySelections: GraphQLSelections {
func requestFragments(for _: String, rootSelectionKeys _: Set<String>) -> String {
""
}
}
// MARK: - Selections
struct TimeStarWarsQuerySelections: GraphQLSelections {
func requestFragments(for _: String, rootSelectionKeys _: Set<String>) -> String {
""
}
}
struct StarWarsMutationSelections: GraphQLSelections {
let droid: Set<DroidSelection>
let human: Set<HumanSelection>
init(
droid: Set<DroidSelection> = .allFields,
human: Set<HumanSelection> = .allFields
) {
self.droid = droid
self.human = human
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let droidDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droid.requestFragments(requestName: capitalizedRequestName))
}
"""
let humanDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(human.requestFragments(requestName: capitalizedRequestName))
}
"""
let characterDeclaration = """
fragment \(capitalizedRequestName)CharacterFragment on Character {
__typename
...\(capitalizedRequestName)DroidFragment
...\(capitalizedRequestName)HumanFragment
}
"""
let characterUnionDeclaration = """
fragment \(capitalizedRequestName)CharacterUnionFragment on CharacterUnion {
__typename
...\(capitalizedRequestName)HumanFragment
...\(capitalizedRequestName)DroidFragment
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)DroidFragment": droidDeclaration,
"\(capitalizedRequestName)HumanFragment": humanDeclaration,
"\(capitalizedRequestName)CharacterFragment": characterDeclaration,
"\(capitalizedRequestName)CharacterUnionFragment": characterUnionDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct MutateStarWarsMutationSelections: GraphQLSelections {
func requestFragments(for _: String, rootSelectionKeys _: Set<String>) -> String {
""
}
}
struct StarWarsSubscriptionSelections: GraphQLSelections {
let droid: Set<DroidSelection>
let human: Set<HumanSelection>
init(
droid: Set<DroidSelection> = .allFields,
human: Set<HumanSelection> = .allFields
) {
self.droid = droid
self.human = human
}
func requestFragments(for requestName: String, rootSelectionKeys: Set<String>) -> String {
let capitalizedRequestName = requestName.prefix(1).uppercased() + requestName.dropFirst()
let droidDeclaration = """
fragment \(capitalizedRequestName)DroidFragment on Droid {
\(droid.requestFragments(requestName: capitalizedRequestName))
}
"""
let humanDeclaration = """
fragment \(capitalizedRequestName)HumanFragment on Human {
\(human.requestFragments(requestName: capitalizedRequestName))
}
"""
let characterDeclaration = """
fragment \(capitalizedRequestName)CharacterFragment on Character {
__typename
...\(capitalizedRequestName)DroidFragment
...\(capitalizedRequestName)HumanFragment
}
"""
let characterUnionDeclaration = """
fragment \(capitalizedRequestName)CharacterUnionFragment on CharacterUnion {
__typename
...\(capitalizedRequestName)HumanFragment
...\(capitalizedRequestName)DroidFragment
}
"""
let selectionDeclarationMap = [
"\(capitalizedRequestName)DroidFragment": droidDeclaration,
"\(capitalizedRequestName)HumanFragment": humanDeclaration,
"\(capitalizedRequestName)CharacterFragment": characterDeclaration,
"\(capitalizedRequestName)CharacterUnionFragment": characterUnionDeclaration
]
let fragmentMaps = rootSelectionKeys
.map {
requestFragments(
selectionDeclarationMap: selectionDeclarationMap,
rootSelectionKey: $0
)
}
.reduce([String: String]()) { old, new in
old.merging(new, uniquingKeysWith: { _, new in new })
}
return fragmentMaps.values.joined(separator: "\n")
}
}
// MARK: - Selections
struct NumberStarWarsSubscriptionSelections: GraphQLSelections {
func requestFragments(for _: String, rootSelectionKeys _: Set<String>) -> String {
""
}
} | 24.474376 | 93 | 0.689128 |
2301168813fed13dd2227e18958894b2c14f5af0 | 43,065 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS GENERATED BY EASY BINDINGS, DO NOT MODIFY IT
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_mNominalSize : AnyObject {
var mNominalSize : Int { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_mFontName : AnyObject {
var mFontName : String { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_mFontVersion : AnyObject {
var mFontVersion : Int { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_mDescriptiveString : AnyObject {
var mDescriptiveString : String { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_versionString : AnyObject {
var versionString : String? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_sizeString : AnyObject {
var sizeString : String? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_descriptor : AnyObject {
var descriptor : BoardFontDescriptor? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_textCount : AnyObject {
var textCount : Int? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_canRemoveFont : AnyObject {
var canRemoveFont : Bool? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_componentNamesCount : AnyObject {
var componentNamesCount : Int? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
protocol FontInProject_componentValuesCount : AnyObject {
var componentValuesCount : Int? { get }
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Entity: FontInProject
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class FontInProject : EBManagedObject,
FontInProject_mNominalSize,
FontInProject_mFontName,
FontInProject_mFontVersion,
FontInProject_mDescriptiveString,
FontInProject_versionString,
FontInProject_sizeString,
FontInProject_descriptor,
FontInProject_textCount,
FontInProject_canRemoveFont,
FontInProject_componentNamesCount,
FontInProject_componentValuesCount {
//····················································································································
// To many property: mTexts
//····················································································································
final let mTexts_property = StoredArrayOf_BoardText (usedForSignature: false)
//····················································································································
//····················································································································
final var mTexts : EBReferenceArray <BoardText> {
get { return self.mTexts_property.propval }
set { self.mTexts_property.setProp (newValue) }
}
//····················································································································
// Atomic property: mNominalSize
//····················································································································
final let mNominalSize_property : EBStoredProperty_Int
//····················································································································
final func reset_mNominalSize_toDefaultValue () {
self.mNominalSize = 0
}
//····················································································································
final var mNominalSize : Int {
get { return self.mNominalSize_property.propval }
set { self.mNominalSize_property.setProp (newValue) }
}
//····················································································································
// Atomic property: mFontName
//····················································································································
final let mFontName_property : EBStoredProperty_String
//····················································································································
final func reset_mFontName_toDefaultValue () {
self.mFontName = ""
}
//····················································································································
final var mFontName : String {
get { return self.mFontName_property.propval }
set { self.mFontName_property.setProp (newValue) }
}
//····················································································································
// Atomic property: mFontVersion
//····················································································································
final let mFontVersion_property : EBStoredProperty_Int
//····················································································································
final func reset_mFontVersion_toDefaultValue () {
self.mFontVersion = 0
}
//····················································································································
final var mFontVersion : Int {
get { return self.mFontVersion_property.propval }
set { self.mFontVersion_property.setProp (newValue) }
}
//····················································································································
// Atomic property: mDescriptiveString
//····················································································································
final let mDescriptiveString_property : EBStoredProperty_String
//····················································································································
final func reset_mDescriptiveString_toDefaultValue () {
self.mDescriptiveString = ""
}
//····················································································································
final var mDescriptiveString : String {
get { return self.mDescriptiveString_property.propval }
set { self.mDescriptiveString_property.setProp (newValue) }
}
//····················································································································
// To many property: mComponentNames
//····················································································································
final let mComponentNames_property = StoredArrayOf_ComponentInProject (usedForSignature: false)
//····················································································································
//····················································································································
final var mComponentNames : EBReferenceArray <ComponentInProject> {
get { return self.mComponentNames_property.propval }
set { self.mComponentNames_property.setProp (newValue) }
}
//····················································································································
// To many property: mComponentValues
//····················································································································
final let mComponentValues_property = StoredArrayOf_ComponentInProject (usedForSignature: false)
//····················································································································
//····················································································································
final var mComponentValues : EBReferenceArray <ComponentInProject> {
get { return self.mComponentValues_property.propval }
set { self.mComponentValues_property.setProp (newValue) }
}
//····················································································································
// Transient property: versionString
//····················································································································
final let versionString_property = EBTransientProperty_String ()
//····················································································································
final var versionString : String? {
switch self.versionString_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: sizeString
//····················································································································
final let sizeString_property = EBTransientProperty_String ()
//····················································································································
final var sizeString : String? {
switch self.sizeString_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: descriptor
//····················································································································
final let descriptor_property = EBTransientProperty_BoardFontDescriptor ()
//····················································································································
final var descriptor : BoardFontDescriptor? {
switch self.descriptor_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: textCount
//····················································································································
final let textCount_property = EBTransientProperty_Int ()
//····················································································································
final var textCount : Int? {
switch self.textCount_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: canRemoveFont
//····················································································································
final let canRemoveFont_property = EBTransientProperty_Bool ()
//····················································································································
final var canRemoveFont : Bool? {
switch self.canRemoveFont_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: componentNamesCount
//····················································································································
final let componentNamesCount_property = EBTransientProperty_Int ()
//····················································································································
final var componentNamesCount : Int? {
switch self.componentNamesCount_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// Transient property: componentValuesCount
//····················································································································
final let componentValuesCount_property = EBTransientProperty_Int ()
//····················································································································
final var componentValuesCount : Int? {
switch self.componentValuesCount_property.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}
//····················································································································
// init
//····················································································································
required init (_ ebUndoManager : EBUndoManager?) {
self.mNominalSize_property = EBStoredProperty_Int (defaultValue: 0, undoManager: ebUndoManager)
self.mFontName_property = EBStoredProperty_String (defaultValue: "", undoManager: ebUndoManager)
self.mFontVersion_property = EBStoredProperty_Int (defaultValue: 0, undoManager: ebUndoManager)
self.mDescriptiveString_property = EBStoredProperty_String (defaultValue: "", undoManager: ebUndoManager)
super.init (ebUndoManager)
//--- To many property: mTexts (has opposite relationship)
self.mTexts_property.ebUndoManager = self.ebUndoManager
self.mTexts_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mFont_property.setProp (me) } },
resetter: { inObject in inObject.mFont_property.setProp (nil) }
)
//--- To many property: mComponentNames (has opposite relationship)
self.mComponentNames_property.ebUndoManager = self.ebUndoManager
self.mComponentNames_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mNameFont_property.setProp (me) } },
resetter: { inObject in inObject.mNameFont_property.setProp (nil) }
)
//--- To many property: mComponentValues (has opposite relationship)
self.mComponentValues_property.ebUndoManager = self.ebUndoManager
self.mComponentValues_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mValueFont_property.setProp (me) } },
resetter: { inObject in inObject.mValueFont_property.setProp (nil) }
)
//--- Atomic property: versionString
self.versionString_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mFontVersion_property.selection) {
case (.single (let v0)) :
return .single (transient_FontInProject_versionString (v0))
case (.multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mFontVersion_property.addEBObserver (self.versionString_property)
//--- Atomic property: sizeString
self.sizeString_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mDescriptiveString_property.selection) {
case (.single (let v0)) :
return .single (transient_FontInProject_sizeString (v0))
case (.multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mDescriptiveString_property.addEBObserver (self.sizeString_property)
//--- Atomic property: descriptor
self.descriptor_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mNominalSize_property.selection, unwSelf.mDescriptiveString_property.selection) {
case (.single (let v0), .single (let v1)) :
return .single (transient_FontInProject_descriptor (v0, v1))
case (.multiple, .multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mNominalSize_property.addEBObserver (self.descriptor_property)
self.mDescriptiveString_property.addEBObserver (self.descriptor_property)
//--- Atomic property: textCount
self.textCount_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mTexts_property.count_property.selection) {
case (.single (let v0)) :
return .single (transient_FontInProject_textCount (v0))
case (.multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mTexts_property.addEBObserver (self.textCount_property)
//--- Atomic property: canRemoveFont
self.canRemoveFont_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mComponentNames_property.count_property.selection, unwSelf.mComponentValues_property.count_property.selection) {
case (.single (let v0), .single (let v1)) :
return .single (transient_FontInProject_canRemoveFont (v0, v1))
case (.multiple, .multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mComponentNames_property.addEBObserver (self.canRemoveFont_property)
self.mComponentValues_property.addEBObserver (self.canRemoveFont_property)
//--- Atomic property: componentNamesCount
self.componentNamesCount_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mComponentNames_property.count_property.selection) {
case (.single (let v0)) :
return .single (transient_FontInProject_componentNamesCount (v0))
case (.multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mComponentNames_property.addEBObserver (self.componentNamesCount_property)
//--- Atomic property: componentValuesCount
self.componentValuesCount_property.mReadModelFunction = { [weak self] in
if let unwSelf = self {
switch (unwSelf.mComponentValues_property.count_property.selection) {
case (.single (let v0)) :
return .single (transient_FontInProject_componentValuesCount (v0))
case (.multiple) :
return .multiple
default :
return .empty
}
}else{
return .empty
}
}
self.mComponentValues_property.addEBObserver (self.componentValuesCount_property)
//--- Install undoers and opposite setter for relationships
self.mTexts_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mFont_property.setProp (me) } },
resetter: { inObject in inObject.mFont_property.setProp (nil) }
)
self.mComponentNames_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mNameFont_property.setProp (me) } },
resetter: { inObject in inObject.mNameFont_property.setProp (nil) }
)
self.mComponentValues_property.setOppositeRelationShipFunctions (
setter: { [weak self] inObject in if let me = self { inObject.mValueFont_property.setProp (me) } },
resetter: { inObject in inObject.mValueFont_property.setProp (nil) }
)
//--- Register properties for handling signature
//--- Extern delegates
}
//····················································································································
override func removeAllObservers () {
super.removeAllObservers ()
// self.mFontVersion_property.removeEBObserver (self.versionString_property)
// self.mDescriptiveString_property.removeEBObserver (self.sizeString_property)
// self.mNominalSize_property.removeEBObserver (self.descriptor_property)
// self.mDescriptiveString_property.removeEBObserver (self.descriptor_property)
// self.mTexts_property.removeEBObserver (self.textCount_property)
// self.mComponentNames_property.removeEBObserver (self.canRemoveFont_property)
// self.mComponentValues_property.removeEBObserver (self.canRemoveFont_property)
// self.mComponentNames_property.removeEBObserver (self.componentNamesCount_property)
// self.mComponentValues_property.removeEBObserver (self.componentValuesCount_property)
//--- Unregister properties for handling signature
}
//····················································································································
// Extern delegates
//····················································································································
//····················································································································
// populateExplorerWindow
//····················································································································
#if BUILD_OBJECT_EXPLORER
override func populateExplorerWindow (_ y : inout CGFloat, view : NSView) {
super.populateExplorerWindow (&y, view:view)
createEntryForPropertyNamed (
"mNominalSize",
object: self.mNominalSize_property,
y: &y,
view: view,
observerExplorer: &self.mNominalSize_property.mObserverExplorer,
valueExplorer: &self.mNominalSize_property.mValueExplorer
)
createEntryForPropertyNamed (
"mFontName",
object: self.mFontName_property,
y: &y,
view: view,
observerExplorer: &self.mFontName_property.mObserverExplorer,
valueExplorer: &self.mFontName_property.mValueExplorer
)
createEntryForPropertyNamed (
"mFontVersion",
object: self.mFontVersion_property,
y: &y,
view: view,
observerExplorer: &self.mFontVersion_property.mObserverExplorer,
valueExplorer: &self.mFontVersion_property.mValueExplorer
)
createEntryForPropertyNamed (
"mDescriptiveString",
object: self.mDescriptiveString_property,
y: &y,
view: view,
observerExplorer: &self.mDescriptiveString_property.mObserverExplorer,
valueExplorer: &self.mDescriptiveString_property.mValueExplorer
)
createEntryForTitle ("Properties", y: &y, view: view)
createEntryForPropertyNamed (
"versionString",
object: self.versionString_property,
y: &y,
view: view,
observerExplorer: &self.versionString_property.mObserverExplorer,
valueExplorer: &self.versionString_property.mValueExplorer
)
createEntryForPropertyNamed (
"sizeString",
object: self.sizeString_property,
y: &y,
view: view,
observerExplorer: &self.sizeString_property.mObserverExplorer,
valueExplorer: &self.sizeString_property.mValueExplorer
)
createEntryForPropertyNamed (
"descriptor",
object: self.descriptor_property,
y: &y,
view: view,
observerExplorer: &self.descriptor_property.mObserverExplorer,
valueExplorer: &self.descriptor_property.mValueExplorer
)
createEntryForPropertyNamed (
"textCount",
object: self.textCount_property,
y: &y,
view: view,
observerExplorer: &self.textCount_property.mObserverExplorer,
valueExplorer: &self.textCount_property.mValueExplorer
)
createEntryForPropertyNamed (
"canRemoveFont",
object: self.canRemoveFont_property,
y: &y,
view: view,
observerExplorer: &self.canRemoveFont_property.mObserverExplorer,
valueExplorer: &self.canRemoveFont_property.mValueExplorer
)
createEntryForPropertyNamed (
"componentNamesCount",
object: self.componentNamesCount_property,
y: &y,
view: view,
observerExplorer: &self.componentNamesCount_property.mObserverExplorer,
valueExplorer: &self.componentNamesCount_property.mValueExplorer
)
createEntryForPropertyNamed (
"componentValuesCount",
object: self.componentValuesCount_property,
y: &y,
view: view,
observerExplorer: &self.componentValuesCount_property.mObserverExplorer,
valueExplorer: &self.componentValuesCount_property.mValueExplorer
)
createEntryForTitle ("Transients", y: &y, view: view)
createEntryForToManyRelationshipNamed (
"mTexts",
object: mTexts_property,
y: &y,
view: view,
valueExplorer:&mTexts_property.mValueExplorer
)
createEntryForToManyRelationshipNamed (
"mComponentNames",
object: mComponentNames_property,
y: &y,
view: view,
valueExplorer:&mComponentNames_property.mValueExplorer
)
createEntryForToManyRelationshipNamed (
"mComponentValues",
object: mComponentValues_property,
y: &y,
view: view,
valueExplorer:&mComponentValues_property.mValueExplorer
)
createEntryForTitle ("ToMany Relationships", y: &y, view: view)
createEntryForTitle ("ToOne Relationships", y: &y, view: view)
}
#endif
//····················································································································
// clearObjectExplorer
//····················································································································
#if BUILD_OBJECT_EXPLORER
override func clearObjectExplorer () {
//--- To many property: mTexts
self.mTexts_property.mValueExplorer = nil
//--- Atomic property: mNominalSize
self.mNominalSize_property.mObserverExplorer = nil
self.mNominalSize_property.mValueExplorer = nil
//--- Atomic property: mFontName
self.mFontName_property.mObserverExplorer = nil
self.mFontName_property.mValueExplorer = nil
//--- Atomic property: mFontVersion
self.mFontVersion_property.mObserverExplorer = nil
self.mFontVersion_property.mValueExplorer = nil
//--- Atomic property: mDescriptiveString
self.mDescriptiveString_property.mObserverExplorer = nil
self.mDescriptiveString_property.mValueExplorer = nil
//--- To many property: mComponentNames
self.mComponentNames_property.mValueExplorer = nil
//--- To many property: mComponentValues
self.mComponentValues_property.mValueExplorer = nil
//---
super.clearObjectExplorer ()
}
#endif
//····················································································································
// cleanUpToManyRelationships
//····················································································································
override func cleanUpToManyRelationships () {
self.mTexts.removeAll ()
self.mComponentNames.removeAll ()
self.mComponentValues.removeAll ()
//---
super.cleanUpToManyRelationships ()
}
//····················································································································
// cleanUpToOneRelationships
//····················································································································
override func cleanUpToOneRelationships () {
//---
super.cleanUpToOneRelationships ()
}
//····················································································································
// saveIntoDictionary
//····················································································································
override func saveIntoDictionary (_ ioDictionary : NSMutableDictionary) {
super.saveIntoDictionary (ioDictionary)
//--- To many property: mTexts
self.store (
managedObjectArray: self.mTexts_property.propval.values,
relationshipName: "mTexts",
intoDictionary: ioDictionary
)
//--- Atomic property: mNominalSize
self.mNominalSize_property.storeIn (dictionary: ioDictionary, forKey: "mNominalSize")
//--- Atomic property: mFontName
self.mFontName_property.storeIn (dictionary: ioDictionary, forKey: "mFontName")
//--- Atomic property: mFontVersion
self.mFontVersion_property.storeIn (dictionary: ioDictionary, forKey: "mFontVersion")
//--- Atomic property: mDescriptiveString
self.mDescriptiveString_property.storeIn (dictionary: ioDictionary, forKey: "mDescriptiveString")
//--- To many property: mComponentNames
self.store (
managedObjectArray: self.mComponentNames_property.propval.values,
relationshipName: "mComponentNames",
intoDictionary: ioDictionary
)
//--- To many property: mComponentValues
self.store (
managedObjectArray: self.mComponentValues_property.propval.values,
relationshipName: "mComponentValues",
intoDictionary: ioDictionary
)
}
//····················································································································
// setUpWithDictionary
//····················································································································
override func setUpWithDictionary (_ inDictionary : NSDictionary,
managedObjectArray : inout [EBManagedObject]) {
super.setUpWithDictionary (inDictionary, managedObjectArray: &managedObjectArray)
//--- To many property: mTexts
/* self.mTexts_property.setProp (readEntityArrayFromDictionary (
inRelationshipName: "mTexts",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [BoardText]) */
do{
let array = readEntityArrayFromDictionary (
inRelationshipName: "mTexts",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [BoardText]
self.mTexts_property.setProp (EBReferenceArray (array))
}
//--- To many property: mComponentNames
/* self.mComponentNames_property.setProp (readEntityArrayFromDictionary (
inRelationshipName: "mComponentNames",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [ComponentInProject]) */
do{
let array = readEntityArrayFromDictionary (
inRelationshipName: "mComponentNames",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [ComponentInProject]
self.mComponentNames_property.setProp (EBReferenceArray (array))
}
//--- To many property: mComponentValues
/* self.mComponentValues_property.setProp (readEntityArrayFromDictionary (
inRelationshipName: "mComponentValues",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [ComponentInProject]) */
do{
let array = readEntityArrayFromDictionary (
inRelationshipName: "mComponentValues",
inDictionary: inDictionary,
managedObjectArray: &managedObjectArray
) as! [ComponentInProject]
self.mComponentValues_property.setProp (EBReferenceArray (array))
}
}
//····················································································································
// setUpAtomicPropertiesWithDictionary
//····················································································································
override func setUpAtomicPropertiesWithDictionary (_ inDictionary : NSDictionary) {
super.setUpAtomicPropertiesWithDictionary (inDictionary)
//--- Atomic property: mNominalSize
self.mNominalSize_property.readFrom (dictionary: inDictionary, forKey: "mNominalSize")
//--- Atomic property: mFontName
self.mFontName_property.readFrom (dictionary: inDictionary, forKey: "mFontName")
//--- Atomic property: mFontVersion
self.mFontVersion_property.readFrom (dictionary: inDictionary, forKey: "mFontVersion")
//--- Atomic property: mDescriptiveString
self.mDescriptiveString_property.readFrom (dictionary: inDictionary, forKey: "mDescriptiveString")
}
//····················································································································
// appendPropertyNamesTo
//····················································································································
override func appendPropertyNamesTo (_ ioString : inout String) {
super.appendPropertyNamesTo (&ioString)
//--- Atomic properties
ioString += "mNominalSize\n"
ioString += "mFontName\n"
ioString += "mFontVersion\n"
ioString += "mDescriptiveString\n"
//--- To one relationships
//--- To many relationships
ioString += "mTexts\n"
ioString += "mComponentNames\n"
ioString += "mComponentValues\n"
}
//····················································································································
// appendPropertyValuesTo
//····················································································································
override func appendPropertyValuesTo (_ ioData : inout Data) {
super.appendPropertyValuesTo (&ioData)
//--- Atomic properties
self.mNominalSize.appendPropertyValueTo (&ioData)
ioData.append (ascii: .lineFeed)
self.mFontName.appendPropertyValueTo (&ioData)
ioData.append (ascii: .lineFeed)
self.mFontVersion.appendPropertyValueTo (&ioData)
ioData.append (ascii: .lineFeed)
self.mDescriptiveString.appendPropertyValueTo (&ioData)
ioData.append (ascii: .lineFeed)
//--- To one relationships
//--- To many relationships
do{
var optionalFirstIndex : Int? = nil
var rangeCount = 0
for object in self.mTexts.values {
if let firstIndex = optionalFirstIndex {
if object.savingIndex == (firstIndex + 1) {
rangeCount += 1
optionalFirstIndex = object.savingIndex
}else if rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
rangeCount = 0
optionalFirstIndex = object.savingIndex
}else{
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}else{
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}
if optionalFirstIndex != nil, rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
}
ioData.append (ascii: .lineFeed)
}
do{
var optionalFirstIndex : Int? = nil
var rangeCount = 0
for object in self.mComponentNames.values {
if let firstIndex = optionalFirstIndex {
if object.savingIndex == (firstIndex + 1) {
rangeCount += 1
optionalFirstIndex = object.savingIndex
}else if rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
rangeCount = 0
optionalFirstIndex = object.savingIndex
}else{
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}else{
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}
if optionalFirstIndex != nil, rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
}
ioData.append (ascii: .lineFeed)
}
do{
var optionalFirstIndex : Int? = nil
var rangeCount = 0
for object in self.mComponentValues.values {
if let firstIndex = optionalFirstIndex {
if object.savingIndex == (firstIndex + 1) {
rangeCount += 1
optionalFirstIndex = object.savingIndex
}else if rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
rangeCount = 0
optionalFirstIndex = object.savingIndex
}else{
ioData.append (ascii: .space)
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}else{
ioData.append (base62Encoded: object.savingIndex)
optionalFirstIndex = object.savingIndex
}
}
if optionalFirstIndex != nil, rangeCount > 0 {
ioData.append (ascii: .colon)
ioData.append (base62Encoded: rangeCount)
}
ioData.append (ascii: .lineFeed)
}
}
//····················································································································
// setUpWithTextDictionary
//····················································································································
override func setUpWithTextDictionary (_ inDictionary : [String : NSRange],
_ inObjectArray : [EBManagedObject],
_ inData : Data,
_ inParallelObjectSetupContext : ParallelObjectSetupContext) {
super.setUpWithTextDictionary (inDictionary, inObjectArray, inData, inParallelObjectSetupContext)
inParallelObjectSetupContext.addOperation {
//--- Atomic properties
if let range = inDictionary ["mNominalSize"], let value = Int.unarchiveFromDataRange (inData, range) {
self.mNominalSize = value
}
if let range = inDictionary ["mFontName"], let value = String.unarchiveFromDataRange (inData, range) {
self.mFontName = value
}
if let range = inDictionary ["mFontVersion"], let value = Int.unarchiveFromDataRange (inData, range) {
self.mFontVersion = value
}
if let range = inDictionary ["mDescriptiveString"], let value = String.unarchiveFromDataRange (inData, range) {
self.mDescriptiveString = value
}
//--- To one relationships
//--- To many relationships
if let range = inDictionary ["mTexts"], range.length > 0 {
var relationshipArray = EBReferenceArray <BoardText> ()
let indexArray = inData.base62EncodedIntArray (fromRange: range)
for idx in indexArray {
relationshipArray.append (inObjectArray [idx] as! BoardText)
}
inParallelObjectSetupContext.addToManySetupDeferredOperation { self.mTexts = relationshipArray }
}
if let range = inDictionary ["mComponentNames"], range.length > 0 {
var relationshipArray = EBReferenceArray <ComponentInProject> ()
let indexArray = inData.base62EncodedIntArray (fromRange: range)
for idx in indexArray {
relationshipArray.append (inObjectArray [idx] as! ComponentInProject)
}
inParallelObjectSetupContext.addToManySetupDeferredOperation { self.mComponentNames = relationshipArray }
}
if let range = inDictionary ["mComponentValues"], range.length > 0 {
var relationshipArray = EBReferenceArray <ComponentInProject> ()
let indexArray = inData.base62EncodedIntArray (fromRange: range)
for idx in indexArray {
relationshipArray.append (inObjectArray [idx] as! ComponentInProject)
}
inParallelObjectSetupContext.addToManySetupDeferredOperation { self.mComponentValues = relationshipArray }
}
}
//--- End of addOperation
}
//····················································································································
// accessibleObjects
//····················································································································
override func accessibleObjects (objects : inout [EBManagedObject]) {
super.accessibleObjects (objects: &objects)
//--- To many property: mTexts
for managedObject in self.mTexts.values {
objects.append (managedObject)
}
//--- To many property: mComponentNames
for managedObject in self.mComponentNames.values {
objects.append (managedObject)
}
//--- To many property: mComponentValues
for managedObject in self.mComponentValues.values {
objects.append (managedObject)
}
}
//····················································································································
// accessibleObjectsForSaveOperation
//····················································································································
override func accessibleObjectsForSaveOperation (objects : inout [EBManagedObject]) {
super.accessibleObjectsForSaveOperation (objects: &objects)
//--- To many property: mTexts
for managedObject in self.mTexts.values {
objects.append (managedObject)
}
//--- To many property: mComponentNames
for managedObject in self.mComponentNames.values {
objects.append (managedObject)
}
//--- To many property: mComponentValues
for managedObject in self.mComponentValues.values {
objects.append (managedObject)
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 42.470414 | 136 | 0.50382 |
11be01b14bbc21a8cfa6b3921c85db611d922b92 | 811 | //
// UIView+IBInspectable.swift
// Mindshift
//
// Created by Mohamed Afsar on 02/06/21.
// Copyright © 2021 Freshworks Studio Inc. All rights reserved.
//
import UIKit
internal extension UIView {
@IBInspectable
var shadowColor: UIColor? {
get {
if let cgColor = self.layer.shadowColor {
return UIColor(cgColor: cgColor)
}
return nil
}
set {
self.layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable
var borderColor: UIColor? {
get {
if let cgColor = self.layer.borderColor {
return UIColor(cgColor: cgColor)
}
return nil
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
}
| 21.342105 | 64 | 0.531443 |
39530610514da10e271e3350f37c179d06ad291d | 1,747 | //
// ThirdView.swift
// CDSwiftUI-EnvironmentObject
//
// Created by Chris on 2/28/20.
// Copyright © 2020 Christophe Dellac. All rights reserved.
//
import SwiftUI
struct ThirdView: View {
// Getting the shared user stored in the Environment
// Please note that we are not passing this property in any way from the main view, to this view
// It is all magic, from the Shared Environment Object, managed by SwiftUI
@EnvironmentObject var user: User
var body: some View {
VStack {
Text("This is our last subview, and the age is \(user.age). Please use the slider below to change the age")
.multilineTextAlignment(.center)
.lineLimit(2)
.frame(height: 60)
// Using this stepper, let's change the value of our property inside our EnvironmentObject
Stepper(onIncrement: {
// We update the value as a regular value, we don't need to use any $ as it is not a binding
self.user.age += 1
}, onDecrement: {
self.user.age -= 1
}) {
Text("Age: \(user.age)")
}
Text("Now, you can go back to the main view to make sure that the age has changed in the Environment Object, not only in this View 😎")
.multilineTextAlignment(.center)
.lineLimit(3)
.frame(height: 80)
.padding()
}
.navigationBarTitle("Third View", displayMode: .inline)
.padding()
}
}
struct ThirdView_Previews: PreviewProvider {
static var previews: some View {
ThirdView()
.environmentObject(User(age: 70))
}
}
| 32.962264 | 146 | 0.576417 |
e54fe07af49f147e7928aa2deea40f2d9d0e852d | 18,837 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import SotoCore
/// Error enum for ElastiCache
public struct ElastiCacheErrorType: AWSErrorType {
enum Code: String {
case aPICallRateForCustomerExceededFault = "APICallRateForCustomerExceeded"
case authorizationAlreadyExistsFault = "AuthorizationAlreadyExists"
case authorizationNotFoundFault = "AuthorizationNotFound"
case cacheClusterAlreadyExistsFault = "CacheClusterAlreadyExists"
case cacheClusterNotFoundFault = "CacheClusterNotFound"
case cacheParameterGroupAlreadyExistsFault = "CacheParameterGroupAlreadyExists"
case cacheParameterGroupNotFoundFault = "CacheParameterGroupNotFound"
case cacheParameterGroupQuotaExceededFault = "CacheParameterGroupQuotaExceeded"
case cacheSecurityGroupAlreadyExistsFault = "CacheSecurityGroupAlreadyExists"
case cacheSecurityGroupNotFoundFault = "CacheSecurityGroupNotFound"
case cacheSecurityGroupQuotaExceededFault = "QuotaExceeded.CacheSecurityGroup"
case cacheSubnetGroupAlreadyExistsFault = "CacheSubnetGroupAlreadyExists"
case cacheSubnetGroupInUse = "CacheSubnetGroupInUse"
case cacheSubnetGroupNotFoundFault = "CacheSubnetGroupNotFoundFault"
case cacheSubnetGroupQuotaExceededFault = "CacheSubnetGroupQuotaExceeded"
case cacheSubnetQuotaExceededFault = "CacheSubnetQuotaExceededFault"
case clusterQuotaForCustomerExceededFault = "ClusterQuotaForCustomerExceeded"
case defaultUserAssociatedToUserGroupFault = "DefaultUserAssociatedToUserGroup"
case defaultUserRequired = "DefaultUserRequired"
case duplicateUserNameFault = "DuplicateUserName"
case globalReplicationGroupAlreadyExistsFault = "GlobalReplicationGroupAlreadyExistsFault"
case globalReplicationGroupNotFoundFault = "GlobalReplicationGroupNotFoundFault"
case insufficientCacheClusterCapacityFault = "InsufficientCacheClusterCapacity"
case invalidARNFault = "InvalidARN"
case invalidCacheClusterStateFault = "InvalidCacheClusterState"
case invalidCacheParameterGroupStateFault = "InvalidCacheParameterGroupState"
case invalidCacheSecurityGroupStateFault = "InvalidCacheSecurityGroupState"
case invalidGlobalReplicationGroupStateFault = "InvalidGlobalReplicationGroupState"
case invalidKMSKeyFault = "InvalidKMSKeyFault"
case invalidParameterCombinationException = "InvalidParameterCombination"
case invalidParameterValueException = "InvalidParameterValue"
case invalidReplicationGroupStateFault = "InvalidReplicationGroupState"
case invalidSnapshotStateFault = "InvalidSnapshotState"
case invalidSubnet = "InvalidSubnet"
case invalidUserGroupStateFault = "InvalidUserGroupState"
case invalidUserStateFault = "InvalidUserState"
case invalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault"
case noOperationFault = "NoOperationFault"
case nodeGroupNotFoundFault = "NodeGroupNotFoundFault"
case nodeGroupsPerReplicationGroupQuotaExceededFault = "NodeGroupsPerReplicationGroupQuotaExceeded"
case nodeQuotaForClusterExceededFault = "NodeQuotaForClusterExceeded"
case nodeQuotaForCustomerExceededFault = "NodeQuotaForCustomerExceeded"
case replicationGroupAlreadyExistsFault = "ReplicationGroupAlreadyExists"
case replicationGroupAlreadyUnderMigrationFault = "ReplicationGroupAlreadyUnderMigrationFault"
case replicationGroupNotFoundFault = "ReplicationGroupNotFoundFault"
case replicationGroupNotUnderMigrationFault = "ReplicationGroupNotUnderMigrationFault"
case reservedCacheNodeAlreadyExistsFault = "ReservedCacheNodeAlreadyExists"
case reservedCacheNodeNotFoundFault = "ReservedCacheNodeNotFound"
case reservedCacheNodeQuotaExceededFault = "ReservedCacheNodeQuotaExceeded"
case reservedCacheNodesOfferingNotFoundFault = "ReservedCacheNodesOfferingNotFound"
case serviceLinkedRoleNotFoundFault = "ServiceLinkedRoleNotFoundFault"
case serviceUpdateNotFoundFault = "ServiceUpdateNotFoundFault"
case snapshotAlreadyExistsFault = "SnapshotAlreadyExistsFault"
case snapshotFeatureNotSupportedFault = "SnapshotFeatureNotSupportedFault"
case snapshotNotFoundFault = "SnapshotNotFoundFault"
case snapshotQuotaExceededFault = "SnapshotQuotaExceededFault"
case subnetInUse = "SubnetInUse"
case subnetNotAllowedFault = "SubnetNotAllowedFault"
case tagNotFoundFault = "TagNotFound"
case tagQuotaPerResourceExceeded = "TagQuotaPerResourceExceeded"
case testFailoverNotAvailableFault = "TestFailoverNotAvailableFault"
case userAlreadyExistsFault = "UserAlreadyExists"
case userGroupAlreadyExistsFault = "UserGroupAlreadyExists"
case userGroupNotFoundFault = "UserGroupNotFound"
case userGroupQuotaExceededFault = "UserGroupQuotaExceeded"
case userNotFoundFault = "UserNotFound"
case userQuotaExceededFault = "UserQuotaExceeded"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ElastiCache
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The customer has exceeded the allowed rate of API calls.
public static var aPICallRateForCustomerExceededFault: Self { .init(.aPICallRateForCustomerExceededFault) }
/// The specified Amazon EC2 security group is already authorized for the specified cache security group.
public static var authorizationAlreadyExistsFault: Self { .init(.authorizationAlreadyExistsFault) }
/// The specified Amazon EC2 security group is not authorized for the specified cache security group.
public static var authorizationNotFoundFault: Self { .init(.authorizationNotFoundFault) }
/// You already have a cluster with the given identifier.
public static var cacheClusterAlreadyExistsFault: Self { .init(.cacheClusterAlreadyExistsFault) }
/// The requested cluster ID does not refer to an existing cluster.
public static var cacheClusterNotFoundFault: Self { .init(.cacheClusterNotFoundFault) }
/// A cache parameter group with the requested name already exists.
public static var cacheParameterGroupAlreadyExistsFault: Self { .init(.cacheParameterGroupAlreadyExistsFault) }
/// The requested cache parameter group name does not refer to an existing cache parameter group.
public static var cacheParameterGroupNotFoundFault: Self { .init(.cacheParameterGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum number of cache security groups.
public static var cacheParameterGroupQuotaExceededFault: Self { .init(.cacheParameterGroupQuotaExceededFault) }
/// A cache security group with the specified name already exists.
public static var cacheSecurityGroupAlreadyExistsFault: Self { .init(.cacheSecurityGroupAlreadyExistsFault) }
/// The requested cache security group name does not refer to an existing cache security group.
public static var cacheSecurityGroupNotFoundFault: Self { .init(.cacheSecurityGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the allowed number of cache security groups.
public static var cacheSecurityGroupQuotaExceededFault: Self { .init(.cacheSecurityGroupQuotaExceededFault) }
/// The requested cache subnet group name is already in use by an existing cache subnet group.
public static var cacheSubnetGroupAlreadyExistsFault: Self { .init(.cacheSubnetGroupAlreadyExistsFault) }
/// The requested cache subnet group is currently in use.
public static var cacheSubnetGroupInUse: Self { .init(.cacheSubnetGroupInUse) }
/// The requested cache subnet group name does not refer to an existing cache subnet group.
public static var cacheSubnetGroupNotFoundFault: Self { .init(.cacheSubnetGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the allowed number of cache subnet groups.
public static var cacheSubnetGroupQuotaExceededFault: Self { .init(.cacheSubnetGroupQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of subnets in a cache subnet group.
public static var cacheSubnetQuotaExceededFault: Self { .init(.cacheSubnetQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of clusters per customer.
public static var clusterQuotaForCustomerExceededFault: Self { .init(.clusterQuotaForCustomerExceededFault) }
/// The default user assigned to the user group.
public static var defaultUserAssociatedToUserGroupFault: Self { .init(.defaultUserAssociatedToUserGroupFault) }
/// You must add default user to a user group.
public static var defaultUserRequired: Self { .init(.defaultUserRequired) }
/// A user with this username already exists.
public static var duplicateUserNameFault: Self { .init(.duplicateUserNameFault) }
/// The Global datastore name already exists.
public static var globalReplicationGroupAlreadyExistsFault: Self { .init(.globalReplicationGroupAlreadyExistsFault) }
/// The Global datastore does not exist
public static var globalReplicationGroupNotFoundFault: Self { .init(.globalReplicationGroupNotFoundFault) }
/// The requested cache node type is not available in the specified Availability Zone. For more information, see InsufficientCacheClusterCapacity in the ElastiCache User Guide.
public static var insufficientCacheClusterCapacityFault: Self { .init(.insufficientCacheClusterCapacityFault) }
/// The requested Amazon Resource Name (ARN) does not refer to an existing resource.
public static var invalidARNFault: Self { .init(.invalidARNFault) }
/// The requested cluster is not in the available state.
public static var invalidCacheClusterStateFault: Self { .init(.invalidCacheClusterStateFault) }
/// The current state of the cache parameter group does not allow the requested operation to occur.
public static var invalidCacheParameterGroupStateFault: Self { .init(.invalidCacheParameterGroupStateFault) }
/// The current state of the cache security group does not allow deletion.
public static var invalidCacheSecurityGroupStateFault: Self { .init(.invalidCacheSecurityGroupStateFault) }
/// The Global datastore is not available or in primary-only state.
public static var invalidGlobalReplicationGroupStateFault: Self { .init(.invalidGlobalReplicationGroupStateFault) }
/// The KMS key supplied is not valid.
public static var invalidKMSKeyFault: Self { .init(.invalidKMSKeyFault) }
/// Two or more incompatible parameters were specified.
public static var invalidParameterCombinationException: Self { .init(.invalidParameterCombinationException) }
/// The value for a parameter is invalid.
public static var invalidParameterValueException: Self { .init(.invalidParameterValueException) }
/// The requested replication group is not in the available state.
public static var invalidReplicationGroupStateFault: Self { .init(.invalidReplicationGroupStateFault) }
/// The current state of the snapshot does not allow the requested operation to occur.
public static var invalidSnapshotStateFault: Self { .init(.invalidSnapshotStateFault) }
/// An invalid subnet identifier was specified.
public static var invalidSubnet: Self { .init(.invalidSubnet) }
/// The user group is not in an active state.
public static var invalidUserGroupStateFault: Self { .init(.invalidUserGroupStateFault) }
/// The user is not in active state.
public static var invalidUserStateFault: Self { .init(.invalidUserStateFault) }
/// The VPC network is in an invalid state.
public static var invalidVPCNetworkStateFault: Self { .init(.invalidVPCNetworkStateFault) }
/// The operation was not performed because no changes were required.
public static var noOperationFault: Self { .init(.noOperationFault) }
/// The node group specified by the NodeGroupId parameter could not be found. Please verify that the node group exists and that you spelled the NodeGroupId value correctly.
public static var nodeGroupNotFoundFault: Self { .init(.nodeGroupNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum allowed number of node groups (shards) in a single replication group. The default maximum is 90
public static var nodeGroupsPerReplicationGroupQuotaExceededFault: Self { .init(.nodeGroupsPerReplicationGroupQuotaExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of cache nodes in a single cluster.
public static var nodeQuotaForClusterExceededFault: Self { .init(.nodeQuotaForClusterExceededFault) }
/// The request cannot be processed because it would exceed the allowed number of cache nodes per customer.
public static var nodeQuotaForCustomerExceededFault: Self { .init(.nodeQuotaForCustomerExceededFault) }
/// The specified replication group already exists.
public static var replicationGroupAlreadyExistsFault: Self { .init(.replicationGroupAlreadyExistsFault) }
/// The targeted replication group is not available.
public static var replicationGroupAlreadyUnderMigrationFault: Self { .init(.replicationGroupAlreadyUnderMigrationFault) }
/// The specified replication group does not exist.
public static var replicationGroupNotFoundFault: Self { .init(.replicationGroupNotFoundFault) }
/// The designated replication group is not available for data migration.
public static var replicationGroupNotUnderMigrationFault: Self { .init(.replicationGroupNotUnderMigrationFault) }
/// You already have a reservation with the given identifier.
public static var reservedCacheNodeAlreadyExistsFault: Self { .init(.reservedCacheNodeAlreadyExistsFault) }
/// The requested reserved cache node was not found.
public static var reservedCacheNodeNotFoundFault: Self { .init(.reservedCacheNodeNotFoundFault) }
/// The request cannot be processed because it would exceed the user's cache node quota.
public static var reservedCacheNodeQuotaExceededFault: Self { .init(.reservedCacheNodeQuotaExceededFault) }
/// The requested cache node offering does not exist.
public static var reservedCacheNodesOfferingNotFoundFault: Self { .init(.reservedCacheNodesOfferingNotFoundFault) }
/// The specified service linked role (SLR) was not found.
public static var serviceLinkedRoleNotFoundFault: Self { .init(.serviceLinkedRoleNotFoundFault) }
/// The service update doesn't exist
public static var serviceUpdateNotFoundFault: Self { .init(.serviceUpdateNotFoundFault) }
/// You already have a snapshot with the given name.
public static var snapshotAlreadyExistsFault: Self { .init(.snapshotAlreadyExistsFault) }
/// You attempted one of the following operations: Creating a snapshot of a Redis cluster running on a cache.t1.micro cache node. Creating a snapshot of a cluster that is running Memcached rather than Redis. Neither of these are supported by ElastiCache.
public static var snapshotFeatureNotSupportedFault: Self { .init(.snapshotFeatureNotSupportedFault) }
/// The requested snapshot name does not refer to an existing snapshot.
public static var snapshotNotFoundFault: Self { .init(.snapshotNotFoundFault) }
/// The request cannot be processed because it would exceed the maximum number of snapshots.
public static var snapshotQuotaExceededFault: Self { .init(.snapshotQuotaExceededFault) }
/// The requested subnet is being used by another cache subnet group.
public static var subnetInUse: Self { .init(.subnetInUse) }
/// At least one subnet ID does not match the other subnet IDs. This mismatch typically occurs when a user sets one subnet ID to a regional Availability Zone and a different one to an outpost. Or when a user sets the subnet ID to an Outpost when not subscribed on this service.
public static var subnetNotAllowedFault: Self { .init(.subnetNotAllowedFault) }
/// The requested tag was not found on this resource.
public static var tagNotFoundFault: Self { .init(.tagNotFoundFault) }
/// The request cannot be processed because it would cause the resource to have more than the allowed number of tags. The maximum number of tags permitted on a resource is 50.
public static var tagQuotaPerResourceExceeded: Self { .init(.tagQuotaPerResourceExceeded) }
/// The TestFailover action is not available.
public static var testFailoverNotAvailableFault: Self { .init(.testFailoverNotAvailableFault) }
/// A user with this ID already exists.
public static var userAlreadyExistsFault: Self { .init(.userAlreadyExistsFault) }
/// The user group with this ID already exists.
public static var userGroupAlreadyExistsFault: Self { .init(.userGroupAlreadyExistsFault) }
/// The user group was not found or does not exist
public static var userGroupNotFoundFault: Self { .init(.userGroupNotFoundFault) }
/// The number of users exceeds the user group limit.
public static var userGroupQuotaExceededFault: Self { .init(.userGroupQuotaExceededFault) }
/// The user does not exist or could not be found.
public static var userNotFoundFault: Self { .init(.userNotFoundFault) }
/// The quota of users has been exceeded.
public static var userQuotaExceededFault: Self { .init(.userQuotaExceededFault) }
}
extension ElastiCacheErrorType: Equatable {
public static func == (lhs: ElastiCacheErrorType, rhs: ElastiCacheErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ElastiCacheErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 73.29572 | 281 | 0.769018 |
6278f2b7f893cb77585f2d2144623d5ef6852fbc | 1,021 | import Foundation
class Parrot {
private let parrotType: ParrotTypeEnum
private let numberOfCoconuts: Int
private let voltage: Double
private let isNailed: Bool
init(_ parrotType: ParrotTypeEnum, numberOfCoconuts: Int, voltage: Double, isNailed: Bool) {
self.parrotType = parrotType
self.numberOfCoconuts = numberOfCoconuts
self.voltage = voltage
self.isNailed = isNailed
}
var speed: Double {
switch parrotType {
case .european:
return baseSpeed
case .african:
return max(0, baseSpeed - loadFactor * Double(numberOfCoconuts));
case .norwegianBlue:
return (isNailed) ? 0 : baseSpeed(voltage: voltage)
}
}
private func baseSpeed(voltage: Double) -> Double {
return min(24.0, voltage*baseSpeed)
}
private var loadFactor: Double {
return 9.0
}
private var baseSpeed: Double {
return 12.0
}
}
| 24.902439 | 96 | 0.602351 |
23137c7b4695b0f4867d89ce5611ba57c0dc7079 | 2,008 | //
// extensions.swift
// Dante Patient
//
// Created by Xinhao Liang on 7/2/19.
// Copyright © 2019 Xinhao Liang. All rights reserved.
//
import UIKit
class Banner: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
self.layer.shadowOpacity = 0.4
self.layer.shadowRadius = 5
self.layer.cornerRadius = 5
}
}
class CardComponent: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.layer.cornerRadius = 20
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: 0, height: 1.0)
self.layer.shadowRadius = 8
}
}
extension UIView {
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
if #available(iOS 11.0, *) {
layer.cornerRadius = radius
layer.maskedCorners = CACornerMask(rawValue: corners.rawValue)
} else {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
func addShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: 0, height: 0.8)
self.layer.shadowRadius = 8
}
func fadeIn() {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 1.0
}, completion: nil)
}
func fadeOut() {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.alpha = 0.0
}, completion: nil)
}
}
| 30.424242 | 136 | 0.61753 |
201d0a00538f7deb6d67cd3bff33bdaf5ddb087b | 837 | //
// Result.swift
// SyntaxKit
//
// Represents a match by the parser.
//
// Created by Sam Soffes on 10/11/14.
// Copyright © 2014-2015 Sam Soffes. All rights reserved.
//
import Foundation
internal struct Result: Equatable {
// MARK: - Properties
let patternIdentifier: String
var range: NSRange
let result: NSTextCheckingResult?
let attribute: AnyObject?
// MARK: - Initializers
init(identifier: String, range: NSRange, result: NSTextCheckingResult? = nil, attribute: AnyObject? = nil) {
self.patternIdentifier = identifier
self.range = range
self.result = result
self.attribute = attribute
}
}
internal func == (lhs: Result, rhs: Result) -> Bool {
return lhs.patternIdentifier == rhs.patternIdentifier &&
Range(lhs.range) == Range(rhs.range)
}
| 23.25 | 112 | 0.660693 |
147d57e22943f9b58daafdcc58bc99d438af053c | 2,139 | //
// AppDelegate.swift
// My-MosaicLayout
//
// Created by Panda on 16/3/9.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.510638 | 285 | 0.753623 |
b995e630e607d086270b2b008f556895155482d3 | 2,394 | //
// GatherUITests+Timer.swift
// UITests
//
// Created by Radu Dan on 16.12.2021.
//
import XCTest
import Localizable
import FoundationTools
extension GatherUITests {
/// **Scenario 1: Starting time**
///
/// **GIVEN** I am in the "Gather" screen
/// **WHEN** I tap on "Start"
/// **THEN** the timer starts
/// **AND** the "Start" button's title changes to "Pause"
///
/// **Scenario 2: Cancelling time**
///
/// **GIVEN** I am in the "Gather" screen
/// **WHEN** I tap on "Cancel"
/// **THEN** the timer resets to the initial time
/// **AND** the right button's title is "Start"
///
/// **Scenario 3: Pausing time**
///
/// ** GIVEN** I am in the "Gather" screen
/// **AND** the timer is started
/// **WHEN** I tap on "Pause"
/// **THEN** the timer pauses
/// **AND** the "Pause" button's title to "Resume"
///
/// **Scenario 4: Resuming time**
///
/// **GIVEN** I am in the "Gather" screen
/// **AND** the timer is paused
/// **WHEN** I tap on "Resume"
/// **THEN** the timer resumes
/// **AND** the "Resume" button's title changes to "Pause"
///
/// **Scenario 5: Completing time**
///
/// **GIVEN** I am in the "Gather" screen
/// **AND** the timer is started
/// **WHEN** the timer reaches "00:00"
/// **THEN** the timer resets to the initial time
/// **AND** the right button's title is "Start"
/// **AND** a popup dialog informing the time is up
func testTimerInteraction() {
assertTime(is: "00:02", state: .stopped)
actionTimerButton.tap()
assertTime(is: "00:01", state: .started)
actionTimerButton.tap()
assertTimerState(is: .paused)
actionTimerButton.tap()
assertTimeIsUp()
assertTime(is: "00:02", state: .stopped)
actionTimerButton.tap()
assertTime(is: "00:01", state: .started)
cancelTimerButton.tap()
assertTime(is: "00:02", state: .stopped)
}
// MARK: - Helpers
private func assertTimeIsUp(line: UInt = #line) {
let alert = app.alerts[LocalizedString.timeIsUpTitle]
XCTAssertTrue(alert.waitToAppear(), line: line)
alert.buttons[LocalizedString.ok].tap()
}
}
| 27.517241 | 62 | 0.540518 |
79e10cf9002fa3707b06668d8c6f69eaffc930b3 | 6,458 | //
// ID3v2TextEncoding.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public enum ID3v2TextEncoding {
case latin1
case utf16
case utf16LE
case utf16BE
case utf8
// MARK: Instance Properties
var rawValue: UInt8 {
switch self {
case .latin1:
return 0
case .utf16, .utf16LE:
return 1
case .utf16BE:
return 2
case .utf8:
return 3
}
}
// MARK: Initializers
public init?(rawValue: UInt8) {
switch rawValue {
case 0:
self = .latin1
case 1:
self = .utf16
case 2:
self = .utf16BE
case 3:
self = .utf8
default:
return nil
}
}
// MARK: Instance Methods
public func decode(_ data: [UInt8]) -> (text: String, endIndex: Int, terminated: Bool)? {
guard !data.isEmpty else {
return (text: "", endIndex: 0, terminated: false)
}
switch self {
case .latin1:
if let terminator = data.index(of: 0) {
guard let text = String(bytes: data.prefix(terminator), encoding: String.Encoding.isoLatin1) else {
return nil
}
return (text: text, endIndex: terminator + 1, terminated: true)
} else {
guard let text = String(bytes: data, encoding: String.Encoding.isoLatin1) else {
return nil
}
return (text: text, endIndex: data.count, terminated: false)
}
case .utf16, .utf16LE, .utf16BE:
guard data.count > 1 else {
return nil
}
let stringEncoding: String.Encoding
if self == ID3v2TextEncoding.utf16 {
stringEncoding = String.Encoding.utf16
} else if (data[0] == 255) && (data[1] == 254) {
stringEncoding = String.Encoding.utf16
} else if (data[0] == 254) && (data[1] == 255) {
stringEncoding = String.Encoding.utf16
} else if self == ID3v2TextEncoding.utf16LE {
stringEncoding = String.Encoding.utf16LittleEndian
} else if self == ID3v2TextEncoding.utf16BE {
stringEncoding = String.Encoding.utf16BigEndian
} else {
stringEncoding = String.Encoding.utf16
}
var endIndex = 0
while let terminator = data[endIndex..<(data.count - 1)].index(of: 0) {
if terminator & 1 == 0 {
endIndex = terminator + 2
if data[endIndex - 1] == 0 {
guard let text = String(bytes: data.prefix(terminator), encoding: stringEncoding) else {
return nil
}
return (text: text, endIndex: endIndex, terminated: true)
}
if endIndex >= data.count - 1 {
break
}
} else {
endIndex = terminator + 1
}
}
guard let text = String(bytes: data, encoding: stringEncoding) else {
return nil
}
return (text: text, endIndex: data.count, terminated: false)
case .utf8:
if let terminator = data.index(of: 0) {
guard let text = String(bytes: data.prefix(terminator), encoding: String.Encoding.utf8) else {
return nil
}
return (text: text, endIndex: terminator + 1, terminated: true)
} else {
guard let text = String(bytes: data, encoding: String.Encoding.utf8) else {
return nil
}
return (text: text, endIndex: data.count, terminated: false)
}
}
}
public func encode(_ string: String, termination: Bool) -> [UInt8] {
var data: [UInt8] = []
switch self {
case .latin1:
if !string.isEmpty {
data.append(contentsOf: ID3v1Latin1TextEncoding().encode(string))
}
case .utf16, .utf16BE:
if self == ID3v2TextEncoding.utf16 {
data.append(contentsOf: [254, 255])
}
if !string.isEmpty {
let unicode = string.utf16
for code in unicode {
data.append(contentsOf: [UInt8((code >> 8) & 255), UInt8(code & 255)])
}
}
if termination {
data.append(0)
}
case .utf16LE:
data.append(contentsOf: [255, 254])
if !string.isEmpty {
let unicode = string.utf16
for code in unicode {
data.append(contentsOf: [UInt8(code & 255), UInt8((code >> 8) & 255)])
}
}
if termination {
data.append(0)
}
case .utf8:
if !string.isEmpty {
data.append(contentsOf: string.utf8)
}
}
if termination {
data.append(0)
}
return data
}
}
| 29.760369 | 115 | 0.52013 |
752091c716680d52ac74547d59510b21a584c1fd | 2,921 | //
// Data.swift
// TravelApp
//
// Created by Anik on 25/11/20.
//
import SwiftUI
import MapKit
struct Data {
static let places = [
Place(index: 0, name: "Boracay, Philipphines", date: "31.10.2020 - 6.11.2020", imageName: "boracay", location: CLLocationCoordinate2D(latitude: 11.9672475, longitude: 121.9252489), departureDayLeft: "1 Days until departure", activities: activities1),
Place(index: 1, name: "Dominican Republic", date: "1.9.2020 - 26.9.2020", imageName: "dominican", location: CLLocationCoordinate2D(latitude: 18.154504, longitude: -68.7120643), departureDayLeft: "15 Days until departure", activities: activities2),
Place(index: 2, name: "Ecuador", date: "11.10.2020 - 16.10.2020", imageName: "ecuador_galapagos", location: CLLocationCoordinate2D(latitude: -0.76105, longitude: -90.333942), departureDayLeft: "1 Months until departure", activities: activities3)
]
static let activities1 = [
Activity(title: "FOUR SEASONS", imageName: "two_star", address: "Boracay Banwa it Malay, Lalawigan ng Aklan", duration: "7 Nights", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "SNORKLING", imageName: "snorkelers", address: "White Beach Boracay, Lalawigan ng Aklan", duration: "2 Hours", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "SURFING", imageName: "surfing", address: "Bulabog Beach, Malay, Philippines, Lalawigan ng Aklan", duration: "3 Hours", occupancy: "2 People", needBooking: true, price: "$29", previousPrice: "$59")
]
static let activities2 = [
Activity(title: "MELIA CARIBE", imageName: "melia", address: "Playas De Bavaro, Punta Cana 230001 Dominican Republic", duration: "7 Nights", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "ZIP LINE", imageName: "zip_line", address: "Nuestra Senora de la Altagracia", duration: "2 Hours", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "4x4 ATV", imageName: "ATV", address: "Bavaro Racing, Tours Point", duration: "8 Hours", occupancy: "2 People", needBooking: true, price: "$99", previousPrice: "$149")
]
static let activities3 = [
Activity(title: "VILLA TAINA", imageName: "melia", address: "Cabarete 57000 Dominican Republic", duration: "7 Nights", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "BIRD WATCHING", imageName: "bird", address: "Galápagos Islands, Ecuador", duration: "2 Hours", occupancy: "2 People", needBooking: false, price: "$0", previousPrice: "$0"),
Activity(title: "SNORKLING", imageName: "snorkelers", address: "Tortuga Bay, Ecuador", duration: "8 Hours", occupancy: "2 People", needBooking: true, price: "$49", previousPrice: "$79")
]
}
| 78.945946 | 258 | 0.683328 |
08cc5ad5f9e165ef08fcf9595dcf9c1975ae2c80 | 1,869 | import XCTest
import SwiftSyntax
import variable_injector_core
final class VariableInjectorTests: XCTestCase {
let testSource = """
import Foundation
class Environment {
static var serverURL: String = "$(SERVER_URL)"
var apiVersion: String = "$(API_VERSION)"
var notReplaceIt: String = "Do not replace it"
}
"""
func testVariableSubstitution() throws {
let stubEnvironment = ["SERVER_URL": "http://ci.injected.server.url.com"]
let sourceFile = try SyntaxParser.parse(source: testSource)
let envVarRewriter = EnvironmentVariableLiteralRewriter(environment: stubEnvironment)
let result = envVarRewriter.visit(sourceFile)
var contents: String = ""
result.write(to: &contents)
let expected = testSource.replacingOccurrences(of: "$(SERVER_URL)", with: "http://ci.injected.server.url.com")
XCTAssertEqual(expected, contents)
}
func testVariableSubstitutionWithExclusion() throws {
let stubEnvironment = ["SERVER_URL": "http://ci.injected.server.url.com", "API_VERSION": "v1"]
let sourceFile = try SyntaxParser.parse(source: testSource)
let envVarRewriter = EnvironmentVariableLiteralRewriter(environment: stubEnvironment, ignoredLiteralValues: ["SERVER_URL"])
let result = envVarRewriter.visit(sourceFile)
var contents: String = ""
result.write(to: &contents)
let expected = testSource.replacingOccurrences(of: "$(API_VERSION)", with: "v1")
XCTAssertEqual(expected, contents)
}
static var allTests = [
("testVariableSubstitution", testVariableSubstitution),
("testVariableSubstitutionWithExclusion", testVariableSubstitutionWithExclusion),
]
}
| 35.264151 | 131 | 0.652755 |
202eaf90edd9255bb883c0ba08d10da3c27bd477 | 572 | #if MIXBOX_ENABLE_IN_APP_SERVICES
import MixboxDi
extension Optional: DefaultGeneratorProvider {
public static func defaultGenerator(dependencyResolver: DependencyResolver) throws -> Generator<Self> {
switch dependencyResolver.defaultGeneratorResolvingStrategy() {
case .empty:
return EmptyOptionalGenerator()
case .random:
return try RandomOptionalGenerator(
anyGenerator: dependencyResolver.resolve(),
isNoneGenerator: ConstantGenerator(false)
)
}
}
}
#endif
| 28.6 | 107 | 0.678322 |
e852352eafac60d709e380abd92e8ebaf6434b95 | 1,663 | //
// ViewController.swift
// Project1
//
// Created by RAJ RAVAL on 06/08/19.
// Copyright © 2019 Buck. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var pictures = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Storm Viewer"
navigationController?.navigationBar.prefersLargeTitles = true
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items.sorted() {
if item.hasPrefix("nssl") {
//This is a picture to load!
pictures.append(item)
}
}
print(pictures)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
cell.textLabel?.text = pictures[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = pictures[indexPath.row]
vc.selectedImageCount = indexPath.row + 1
navigationController?.pushViewController(vc, animated: true)
}
}
}
| 30.796296 | 110 | 0.638605 |
7211cb83bcd2b571c87a39dc81b5c92d619109c9 | 2,098 | //
// Matcher.swift
// Entitas-Swift
//
// Created by Maxim Zaks on 04.06.17.
// Copyright © 2017 Maxim Zaks. All rights reserved.
//
import Foundation
public struct Matcher {
let allOf: Set<CID>
let anyOf: Set<CID>
let noneOf: Set<CID>
public func matches(_ e: Entity) -> Bool {
for id in allOf {
if e.has(id) == false {
return false
}
}
for id in noneOf {
if e.has(id) == true {
return false
}
}
if anyOf.isEmpty {
return true
}
for id in anyOf {
if e.has(id) == true {
return true
}
}
return false
}
public init(all: Set<CID>, any: Set<CID>, none: Set<CID>) {
allOf = all
anyOf = any
noneOf = none
assert(allOf.isEmpty == false || anyOf.isEmpty == false, "Your matcher does not have elements in allOf or in anyOf set")
assert(isDisjoint, "Your matcher is not disjoint")
}
public init(all: Set<CID>) {
self.init(all: all, any:[], none: [])
}
public init(all: Set<CID>, any: Set<CID>) {
self.init(all: all, any:any, none: [])
}
public init(any: Set<CID>) {
self.init(all: [], any:any, none: [])
}
public init(any: Set<CID>, none: Set<CID>) {
self.init(all: [], any:any, none: none)
}
public init(all: Set<CID>, none: Set<CID>) {
self.init(all: all, any:[], none: none)
}
private var isDisjoint : Bool {
return allOf.isDisjoint(with: anyOf) && allOf.isDisjoint(with: noneOf) && anyOf.isDisjoint(with: noneOf)
}
}
extension Matcher: Hashable {
public var hashValue: Int {
return allOf.hashValue ^ anyOf.hashValue ^ noneOf.hashValue
}
public static func ==(a: Matcher, b: Matcher) -> Bool {
return a.allOf == b.allOf && a.anyOf == b.anyOf && a.noneOf == b.noneOf
}
}
extension Component {
public static var matcher: Matcher {
return Matcher(all:[Self.cid])
}
}
| 26.225 | 128 | 0.532888 |
90e9f1ce61293125d532db190c228c17940aed63 | 2,100 | //
// PageBar.swift
// redis-pro
//
// Created by chengpanwang on 2021/4/12.
//
import SwiftUI
import Logging
struct PageBar: View {
@EnvironmentObject var globalContext:GlobalContext
@ObservedObject var page:Page
var action:() throws -> Void = {}
let logger = Logger(label: "page-bar")
var body: some View {
HStack(alignment:.center, spacing: 4) {
Spacer()
Text("Total: \(page.total)")
.font(.footnote)
.lineLimit(1)
.multilineTextAlignment(.trailing)
Picker("", selection: $page.size) {
Text("10").tag(10)
Text("50").tag(50)
Text("100").tag(100)
Text("200").tag(200)
}
.onChange(of: page.size, perform: { value in
logger.info("on page size change: \(value)")
page.firstPage()
doAction()
})
.font(.footnote)
.frame(width: 65)
HStack(alignment:.center) {
MIcon(icon: "chevron.left", action: onPrevPageAction).disabled(!page.hasPrevPage && !globalContext.loading)
Text("\(page.current)/\(page.totalPage)")
.font(.footnote)
.multilineTextAlignment(.center)
.lineLimit(1)
MIcon(icon: "chevron.right", action: onNextPageAction).disabled(!page.hasNextPage && !globalContext.loading)
}
.layoutPriority(1)
}
}
func onNextPageAction() -> Void {
page.nextPage()
doAction()
}
func onPrevPageAction() -> Void {
page.prevPage()
doAction()
}
func doAction() -> Void {
logger.info("page bar change action, page: \(page)")
do {
try action()
} catch {
globalContext.showError(error)
}
}
}
struct PageBar_Previews: PreviewProvider {
static var previews: some View {
PageBar(page: Page())
}
}
| 27.272727 | 124 | 0.502381 |
3839ac1c16b247d54503b3ad15ae221df68296bb | 2,328 | //
// PostScreenViewModel.swift
// Socia
//
// Created by Mehmet Ateş on 13.03.2022.
//
import Foundation
import UIKit
class PostSaveScreenViewModel: ObservableObject{
private var sgService = SGServices()
private var fsService = FSServices()
@Published var inProcess = false
@Published var isSuccess = false
func failedProcess(system: AuthSystem, err: SaveError){
system.anErrorTaked = true
system.errorMessage = err.localizedDescription
self.inProcess = false
}
func savePost(image: UIImage, desc: String, system: AuthSystem){
self.inProcess = true
guard let currentUser = system.currentUser else { return }
DispatchQueue.main.async {
let postID = UUID().uuidString
self.sgService.uploadPhoto(image: image, imagePath: "posts/\(postID).jpg", username: currentUser.username) { saveRes in
switch saveRes{
case .failure(let err):
self.failedProcess(system: system, err: err)
return
case .success(let photoUrl):
var willUser = currentUser
willUser.posts?.append(postID)
self.fsService.savePost(postID: postID, desc: desc, imagePath: photoUrl, username: currentUser.username) { saveRes2 in
switch saveRes2{
case .failure(let err):
self.failedProcess(system: system, err: err)
return
case .success(_):
self.fsService.updateUser(saveData: willUser.toMap()) { saveRes3 in
switch saveRes3{
case .failure(let err):
self.failedProcess(system: system, err: err)
return
case .success(_):
self.inProcess = false
self.isSuccess = true
system.setCurrentUser()
}
}
}
}
}
}
}
}
}
| 36.952381 | 138 | 0.484536 |
11d2c047d32aa6ce6eea7908b190063e2adc4b98 | 1,852 | //
// TestViewController.swift
//
//
// Created by mefilt on 31/01/2019.
//
import Foundation
import UIKit
final class TestViewController: ModalScrollViewController {
@IBOutlet var tableView: ModalTableView!
private var needUpdateInsets: Bool = true
private var languages: [Language] = []
override func viewDidLoad() {
super.viewDidLoad()
var newList = Language.list
newList.append(contentsOf: Language.list)
self.languages = newList
self.tableView.reloadData()
}
override var scrollView: UIScrollView {
return self.tableView
}
override func visibleScrollViewHeight(for size: CGSize) -> CGFloat {
return 288
}
}
extension TestViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Content") else { return UITableViewCell() }
let language = languages[indexPath.row]
let iconImageView = cell.viewWithTag(100) as? UIImageView
let nameLabelView = cell.viewWithTag(200) as? UILabel
iconImageView?.image = UIImage(named: language.icon)
nameLabelView?.text = language.title
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return languages.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 56
}
}
extension TestViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.dismiss(animated: true, completion: nil)
}
}
| 23.74359 | 115 | 0.682505 |
4ba87ca6c0045cbb456103e112d7f721a0758221 | 434 | //
// TypeRegistrationTestCase.swift
// DependencyInjectionTests
//
// Created by Jeff Kereakoglow on 7/3/17.
// Copyright © 2017 Alexis Digital. All rights reserved.
//
import XCTest
@testable import DependencyInjection
class TypeRegistrationTestCase: XCTestCase {
override func setUp() {
super.setUp()
destroyAppRegistry()
initializeAppContainer(withRegistrationModule: RegistryModule())
}
}
| 20.666667 | 72 | 0.721198 |
89c02698f7c62b28df011fc9d37f0d6aa3b1482c | 579 | //
// ExclusivePair.swift
// Sluthware
//
// Created by Pat Sluth on 2018-06-20.
// Copyright © 2018 patsluth. All rights reserved.
//
import Foundation
public struct Pair<A, B>
{
var a: A
var b: B
public init(_ a: A, _ b: B)
{
self.a = a
self.b = b
}
public init?(_ a: A?, _ b: B?)
{
guard let a = a, let b = b else { return nil }
self.init(a, b)
}
}
extension Pair: Equatable
where A: Equatable, B: Equatable
{
public static func == (lhs: Pair<A, B>, rhs: Pair<A, B>) -> Bool
{
return (lhs.a == rhs.a && lhs.b == rhs.b)
}
}
| 10.924528 | 65 | 0.561313 |
e6404e402995d9dd6fd476ccee9bab13af2cbbac | 1,152 | //
// Session.swift
// Nearby Places
//
// Created by Madson Cardoso on 1/28/16.
// Copyright © 2016 Madson Cardoso. All rights reserved.
//
import UIKit
let API_URL = "https://api.foursquare.com"
let CLIENT_ID = "NUVZBMY2QT0RDM2W1FVDMOYMX23QGTPOMGUO255YHJQBIOHG"
let CLIENT_SECRET = "F5EG4GT2VQZY5SNCETJRYL0YO3XLV5DZVTQ2GVLQNEXMWBAF"
let CLIENT_VERSION = "20200101"
class FoursquareAPI : AFHTTPSessionManager {
static let sharedInstance = FoursquareAPI()
init() {
let url = NSURL(string: API_URL)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
super.init(baseURL: url, sessionConfiguration: config)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.requestSerializer = AFJSONRequestSerializer()
}
// MARK: - Helpers
class func defaultParams() -> [String: AnyObject] {
var params = [String: AnyObject]()
params["client_id"] = CLIENT_ID
params["client_secret"] = CLIENT_SECRET
params["v"] = CLIENT_VERSION
return params
}
}
| 25.6 | 76 | 0.654514 |
0a69104bb43ce9d456b8bc7299dab47f3205f375 | 9,130 | import Foundation
import PathKit
/// Model that represents a .xcodeproj project.
public final class XcodeProj: Equatable {
// MARK: - Properties
/// Project workspace
public var workspace: XCWorkspace
/// .pbxproj representatino
public var pbxproj: PBXProj
/// Shared data.
public var sharedData: XCSharedData?
// MARK: - Init
public init(path: Path) throws {
var pbxproj: PBXProj!
var workspace: XCWorkspace!
var sharedData: XCSharedData?
if !path.exists { throw XCodeProjError.notFound(path: path) }
let pbxprojPaths = path.glob("*.pbxproj")
if pbxprojPaths.isEmpty {
throw XCodeProjError.pbxprojNotFound(path: path)
}
let pbxprojPath = pbxprojPaths.first!
let (pbxProjData, pbxProjDictionary) = try XcodeProj.readPBXProj(path: pbxprojPath)
let context = ProjectDecodingContext(
pbxProjValueReader: { key in
pbxProjDictionary[key]
}
)
let plistDecoder = XcodeprojPropertyListDecoder(context: context)
pbxproj = try plistDecoder.decode(PBXProj.self, from: pbxProjData)
try pbxproj.updateProjectName(path: pbxprojPaths.first!)
let xcworkspacePaths = path.glob("*.xcworkspace")
if xcworkspacePaths.isEmpty {
workspace = XCWorkspace()
} else {
workspace = try XCWorkspace(path: xcworkspacePaths.first!)
}
let sharedDataPath = path + "xcshareddata"
sharedData = try? XCSharedData(path: sharedDataPath)
self.pbxproj = pbxproj
self.workspace = workspace
self.sharedData = sharedData
}
public convenience init(pathString: String) throws {
try self.init(path: Path(pathString))
}
/// Initializes the XCodeProj
///
/// - Parameters:
/// - workspace: project internal workspace.
/// - pbxproj: project .pbxproj.
public init(workspace: XCWorkspace, pbxproj: PBXProj, sharedData: XCSharedData? = nil) {
self.workspace = workspace
self.pbxproj = pbxproj
self.sharedData = sharedData
}
// MARK: - Equatable
public static func == (lhs: XcodeProj, rhs: XcodeProj) -> Bool {
return lhs.workspace == rhs.workspace &&
lhs.pbxproj == rhs.pbxproj &&
lhs.sharedData == rhs.sharedData
}
// MARK: - Private
private static func readPBXProj(path: Path) throws -> (Data, [String: Any]) {
let plistXML = try Data(contentsOf: path.url)
var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml
let serialized = try PropertyListSerialization.propertyList(
from: plistXML,
options: .mutableContainersAndLeaves,
format: &propertyListFormat
)
// swiftlint:disable:next force_cast
let pbxProjDictionary = serialized as! [String: Any]
return (plistXML, pbxProjDictionary)
}
}
// MARK: - <Writable>
extension XcodeProj: Writable {
/// Writes project to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if project should be overridden. Default is true.
/// If false will throw error if project already exists at the given path.
public func write(path: Path, override: Bool = true) throws {
try write(path: path, override: override, outputSettings: PBXOutputSettings())
}
/// Writes project to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if project should be overridden. Default is true.
/// - Parameter outputSettings: Controls the writing of various files.
/// If false will throw error if project already exists at the given path.
public func write(path: Path, override: Bool = true, outputSettings: PBXOutputSettings) throws {
try path.mkpath()
try writeWorkspace(path: path, override: override)
try writePBXProj(path: path, override: override, outputSettings: outputSettings)
try writeSchemes(path: path, override: override)
try writeBreakPoints(path: path, override: override)
}
/// Returns workspace file path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Returns: worspace file path relative to the given path.
public static func workspacePath(_ path: Path) -> Path {
return path + "project.xcworkspace"
}
/// Writes workspace to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if workspace should be overridden. Default is true.
/// If false will throw error if workspace already exists at the given path.
public func writeWorkspace(path: Path, override: Bool = true) throws {
try workspace.write(path: XcodeProj.workspacePath(path), override: override)
}
/// Returns project file path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Returns: project file path relative to the given path.
public static func pbxprojPath(_ path: Path) -> Path {
return path + "project.pbxproj"
}
/// Writes project to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if project should be overridden. Default is true.
/// - Parameter outputSettings: Controls the writing of various files.
/// If false will throw error if project already exists at the given path.
public func writePBXProj(path: Path, override: Bool = true, outputSettings: PBXOutputSettings) throws {
try pbxproj.write(path: XcodeProj.pbxprojPath(path), override: override, outputSettings: outputSettings)
}
/// Returns shared data path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Returns: shared data path relative to the given path.
public static func sharedDataPath(_ path: Path) -> Path {
return path + "xcshareddata"
}
/// Returns schemes folder path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Returns: schemes folder path relative to the given path.
public static func schemesPath(_ path: Path) -> Path {
return XcodeProj.sharedDataPath(path) + "xcschemes"
}
/// Returns scheme file path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Parameter schemeName: scheme name
/// - Returns: scheme file path relative to the given path.
public static func schemePath(_ path: Path, schemeName: String) -> Path {
return XcodeProj.schemesPath(path) + "\(schemeName).xcscheme"
}
/// Writes all project schemes to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if project should be overridden. Default is true.
/// If true will remove all existing schemes before writing.
/// If false will throw error if scheme already exists at the given path.
public func writeSchemes(path: Path, override: Bool = true) throws {
guard let sharedData = sharedData else { return }
let schemesPath = XcodeProj.schemesPath(path)
if override, schemesPath.exists {
try schemesPath.delete()
}
try schemesPath.mkpath()
for scheme in sharedData.schemes {
try scheme.write(path: XcodeProj.schemePath(path, schemeName: scheme.name), override: override)
}
}
/// Returns debugger folder path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Parameter schemeName: scheme name
/// - Returns: debugger folder path relative to the given path.
public static func debuggerPath(_ path: Path) -> Path {
return XcodeProj.sharedDataPath(path) + "xcdebugger"
}
/// Returns breakpoints plist path relative to the given path.
///
/// - Parameter path: `.xcodeproj` file path
/// - Parameter schemeName: scheme name
/// - Returns: breakpoints plist path relative to the given path.
public static func breakPointsPath(_ path: Path) -> Path {
return XcodeProj.debuggerPath(path) + "Breakpoints_v2.xcbkptlist"
}
/// Writes all project breakpoints to the given path.
///
/// - Parameter path: path to `.xcodeproj` file.
/// - Parameter override: if project should be overridden. Default is true.
/// If true will remove all existing debugger data before writing.
/// If false will throw error if breakpoints file exists at the given path.
public func writeBreakPoints(path: Path, override: Bool = true) throws {
guard let sharedData = sharedData else { return }
let debuggerPath = XcodeProj.debuggerPath(path)
if override, debuggerPath.exists {
try debuggerPath.delete()
}
try debuggerPath.mkpath()
try sharedData.breakpoints?.write(path: XcodeProj.breakPointsPath(path), override: override)
}
}
| 39.184549 | 112 | 0.654436 |
16de6b83684b154e64c4c7513256328ecc576649 | 4,158 | //
// SignUpViewController.swift
// AnimojiStudio
// Snehal Mulchandani - [email protected]
// Created by Snehal Mulchandani on 4/21/21.
//
import UIKit
//sign up through this VC
class SignUpViewController: ShowsErrorHideKeyboardGIFBackgroundViewController, SignUpViewControllerAuthDelegate, UITextFieldDelegate, SignUpViewControllerFirestoreDelegate {
var signUpDelegate:FirebaseSignUpDelegate = FirebaseAuthService() //change to same as below?
var userServiceDelegate:FirestoreUserServiceDelegate!
@IBOutlet weak var phoneNumberTextField: UITextField!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var shootingStarImageView: UIImageView!
//set up GIFs and hiding keyboard when needed
override func viewDidLoad() {
userServiceDelegate = FirestoreUserService()
self.backgroundImageName = "Background"
self.loadGif(for: "shootingStar", image: shootingStarImageView)
self.keyboardsToHide = [phoneNumberTextField]
super.viewDidLoad()
}
/*override func viewDidAppear(_ animated: Bool) {
hideNavigationBar(animated: animated)
}*/
//when sign up pressed handle inputs
@IBAction func signUpButtonPressed(_ sender: Any) {
//verify/preprocess inputs
if(phoneNumberTextField.text!.isEmpty){
showError(error: "Please enter your phone number")
}
else if(phoneNumberTextField.text!.count == 7){
showError(error: "Please enter your area code")
}
else if (phoneNumberTextField.text!.count != 10){
showError(error: "Please enter your 10 digit US phone number")
}
else{
signUpDelegate.verifyPhone(phoneNumber: "+1" + phoneNumberTextField.text!, viewController: self)//check if ! messes up for empty
}
}
//pass to delegate once input
func getVerificationCode(){
let alert = UIAlertController(title: "Verify Phone Number", message: "Provide verification code", preferredStyle: .alert)
let continueAction = UIAlertAction(title: "Ok", style: .default) { (actionPerformed) in
guard let verificationCode = alert.textFields?.first?.text, !verificationCode.isEmpty else{
self.showError(error: "Verification code not input")
return
}
self.signUpDelegate.signInWithVerificationCode(verificationCode: verificationCode, viewController: self)
}
alert.addAction(continueAction)
alert.addTextField { (textField) in
//textField.keyboardType = .default
textField.textContentType = .oneTimeCode
textField.placeholder = "Verification Code"
textField.delegate = self
}
present(alert, animated: false)
}
func signInSuccess(userID: String?) {
//check if user exists, push to account creation else tab bar w/map
if let userID = userID{
userServiceDelegate.userExists(delegate: self, UserID: userID)
}
}
func userExists() {
//send to tab bar view w/ map
goToViewController(identifier: "InAppTabBar")
}
func userDoesntExist() {
// go to user info page
goToViewController(identifier: "UserInfoVC")
}
//easy function to switch VC
func goToViewController(identifier: String){
//https://stackoverflow.com/questions/24038215/how-to-navigate-from-one-view-controller-to-another-using-swift
let vc = UIStoryboard.init(name: "Main", bundle: .main).instantiateViewController(identifier: identifier)
self.navigationController?.pushViewController(vc, animated: true)
}
}
//to communicate to delegate without exposing whole VC interface
protocol SignUpViewControllerAuthDelegate: CanShowErrorProtocol {
func getVerificationCode()
func signInSuccess(userID: String?)
}
//to communicate to delegate without exposing whole VC interface
protocol SignUpViewControllerFirestoreDelegate {
func userExists()
func userDoesntExist()
//change to userExists and userDoesn'tExist
}
| 36.79646 | 173 | 0.682059 |
33cc24dcd40a28774bfa33330fd84a0558f46ed1 | 18,713 | //
// AuthenticationController.swift
// auth0_flutter
//
// Created by Juan Alvarez on 9/24/19.
//
import Foundation
import Auth0
class AuthenticationController: NSObject, FlutterPlugin {
enum MethodName: String {
case login
case loginWithOTP
case loginDefaultDirectory
case createUser
case resetPassword
case startEmailPasswordless
case startPhoneNumberPasswordless
case loginEmailPasswordless
case loginPhoneNumberPasswordless
case userInfoWithAccessToken
case loginFacebook
case tokenExchangeWithParameters
case tokenExchangeWithCode
case appleTokenExchange
case renew
case revoke
case delegation
}
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "plugins.auth0_flutter.io/authentication", binaryMessenger: registrar.messenger())
let instance = AuthenticationController()
registrar.addMethodCallDelegate(instance, channel: channel)
}
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments ?? [:]
do {
guard let method = MethodName(rawValue: call.method) else {
sendResult(result, data: nil, error: Auth0PluginError.unknownMethod(call.method))
return
}
let data = try JSONSerialization.data(withJSONObject: arguments, options: [])
let authParams = try AuthParameters.decode(data: data)
let auth = authentication(clientId: authParams.clientId, domain: authParams.domain)
if authParams.loggingEnabled {
_ = auth.logging(enabled: authParams.loggingEnabled)
}
switch method {
case .login:
let params = try LoginWithUsernameOrEmailParameters.decode(data: data)
auth.login(usernameOrEmail: params.usernameOrEmail,
password: params.password,
realm: params.realm,
audience: params.audience,
scope: params.scope,
parameters: params.parametersDict())
.start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .loginWithOTP:
let params = try LoginWithOTPParameters.decode(data: data)
auth.login(withOTP: params.otp, mfaToken: params.mfaToken).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .loginDefaultDirectory:
let params = try LoginWithDefaultDirectoryParameters.decode(data: data)
auth.loginDefaultDirectory(withUsername: params.username,
password: params.password,
audience: params.audience,
scope: params.scope,
parameters: params.parametersDict())
.start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .createUser:
let params = try CreateUserParameters.decode(data: data)
auth.createUser(email: params.email,
username: params.username,
password: params.password,
connection: params.connection,
userMetadata: params.userMetadataDict(),
rootAttributes: params.rootAttributesDict())
.start { (authResult) in
switch authResult {
case .success(let user):
sendResult(result, data: databaseUserToJSON(user), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .resetPassword:
let params = try ResetPasswordParameters.decode(data: data)
auth.resetPassword(email: params.email, connection: params.connection).start { (authResult) in
switch authResult {
case .success(_):
sendResult(result, data: nil, error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .startEmailPasswordless:
let params = try StartEmailPasswordlessParameters.decode(data: data)
auth.startPasswordless(email: params.email, type: params.type, connection: params.connection, parameters: params.parametersDict()).start { (authResult) in
switch authResult {
case .success(_):
sendResult(result, data: nil, error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .startPhoneNumberPasswordless:
let params = try StartPhoneNumberPasswordlessParameters.decode(data: data)
auth.startPasswordless(phoneNumber: params.phoneNumber, type: params.type, connection: params.connection).start { (authResult) in
switch authResult {
case .success(_):
sendResult(result, data: nil, error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .loginEmailPasswordless:
let params = try LoginEmailPasswordlessParameters.decode(data: data)
auth.login(email: params.email, code: params.code, audience: params.audience, scope: params.scope, parameters: params.parametersDict()).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .loginPhoneNumberPasswordless:
let params = try LoginPhoneNumberPasswordlessParameters.decode(data: data)
auth.login(phoneNumber: params.phoneNumber, code: params.code, audience: params.audience, scope: params.scope, parameters: params.parametersDict()).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .userInfoWithAccessToken:
let params = try UserInfoWithAccessTokenParameters.decode(data: data)
auth.userInfo(withAccessToken: params.accessToken).start { (authResult) in
switch authResult {
case .success(let userInfo):
sendResult(result, data: userInfo.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .loginFacebook:
let params = try LoginFacebookParameters.decode(data: data)
auth.login(facebookSessionAccessToken: params.sessionAccessToken, profile: params.profileDict(), scope: params.scope, audience: params.audience).start { authResult in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .tokenExchangeWithParameters:
let params = try TokenExchangeWithParamsParameters.decode(data: data)
auth.tokenExchange(withParameters: params.parametersDict()).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .tokenExchangeWithCode:
let params = try TokenExchangeWithCodeParameters.decode(data: data)
auth.tokenExchange(withCode: params.code, codeVerifier: params.code, redirectURI: params.redirectURI).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .appleTokenExchange:
let params = try AppleTokenExchangeParameters.decode(data: data)
auth.tokenExchange(withAppleAuthorizationCode: params.authCode, scope: params.scope, audience: params.audience).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .renew:
let params = try RenewParameters.decode(data: data)
auth.renew(withRefreshToken: params.refreshToken, scope: params.scope).start { (authResult) in
switch authResult {
case .success(let credentials):
sendResult(result, data: credentials.toJSON(), error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .revoke:
let params = try RevokeParameters.decode(data: data)
auth.revoke(refreshToken: params.refreshToken).start { (authResult) in
switch authResult {
case .success(_):
sendResult(result, data: nil, error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
case .delegation:
let params = try DelegationParameters.decode(data: data)
auth.delegation(withParameters: params.parametersDict()).start { (authResult) in
switch authResult {
case .success(let dict):
sendResult(result, data: dict, error: nil)
case .failure(let error):
sendResult(result, data: nil, error: CustomAuthenticationError(error as! AuthenticationError))
}
}
}
} catch {
sendResult(result, data: nil, error: error)
}
}
}
private struct AuthParameters: Decodable {
let clientId: String
let domain: String
let loggingEnabled: Bool
}
private struct LoginWithUsernameOrEmailParameters: Decodable {
let usernameOrEmail: String
let password: String
let realm: String
let audience: String?
let scope: String?
private let parameters: [String: AnyDecodable]?
func parametersDict() -> [String: Any]? {
return parameters?.mapValues { $0.value }
}
}
private struct LoginWithOTPParameters: Decodable {
let otp: String
let mfaToken: String
}
private struct LoginWithDefaultDirectoryParameters: Decodable {
let username: String
let password: String
let audience: String?
let scope: String?
private let parameters: [String: AnyDecodable]?
func parametersDict() -> [String: Any]? {
return parameters?.mapValues { $0.value }
}
}
private struct CreateUserParameters: Decodable {
let email: String
let username: String?
let password: String
let connection: String
private let userMetadata: [String: AnyDecodable]?
private let rootAttributes: [String: AnyDecodable]?
func userMetadataDict() -> [String: Any]? {
return userMetadata?.mapValues { $0.value }
}
func rootAttributesDict() -> [String: Any]? {
return rootAttributes?.mapValues { $0.value }
}
}
private struct ResetPasswordParameters: Decodable {
let email: String
let connection: String
}
extension PasswordlessType: Decodable {}
private struct StartEmailPasswordlessParameters: Decodable {
let email: String
let type: PasswordlessType
let connection: String
private let parameters: [String: AnyDecodable]
func parametersDict() -> [String: Any] {
return parameters.mapValues { $0.value }
}
}
private struct StartPhoneNumberPasswordlessParameters: Decodable {
let phoneNumber: String
let type: PasswordlessType
let connection: String
}
private struct LoginPhoneNumberPasswordlessParameters: Decodable {
let phoneNumber: String
let code: String
let audience: String?
let scope: String?
private let parameters: [String: AnyDecodable]
func parametersDict() -> [String: Any] {
return parameters.mapValues { $0.value }
}
}
private struct LoginEmailPasswordlessParameters: Decodable {
let email: String
let code: String
let audience: String?
let scope: String?
private let parameters: [String: AnyDecodable]
func parametersDict() -> [String: Any] {
return parameters.mapValues { $0.value }
}
}
private struct UserInfoWithAccessTokenParameters: Decodable {
let accessToken: String
}
private struct LoginFacebookParameters: Decodable {
let sessionAccessToken: String
private let profile: [String: AnyDecodable]
let scope: String
let audience: String?
func profileDict() -> [String: Any] {
return profile.mapValues { $0.value }
}
}
private struct TokenExchangeWithParamsParameters: Decodable {
private let parameters: [String: AnyDecodable]
func parametersDict() -> [String: Any] {
return parameters.mapValues { $0.value }
}
}
private struct TokenExchangeWithCodeParameters: Decodable {
let code: String
let codeVerifier: String
let redirectURI: String
}
private struct AppleTokenExchangeParameters: Decodable {
let authCode: String
let scope: String?
let audience: String?
}
private struct RenewParameters: Decodable {
let refreshToken: String
let scope: String?
}
private struct RevokeParameters: Decodable {
let refreshToken: String
}
private struct DelegationParameters: Decodable {
private let parameters: [String: AnyDecodable]
func parametersDict() -> [String: Any] {
return parameters.mapValues { $0.value }
}
}
| 44.448931 | 191 | 0.536365 |
1a5041cf7147615cb69f022b783e2817054a9d0b | 367 | //
// ViewController.swift
// MultipleViewControllers
//
// Created by Halil Özel on 8.10.2018.
// Copyright © 2018 Halil Özel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| 17.47619 | 80 | 0.678474 |
e95e33407e83f3825fe25af705c6d510c7e5abd9 | 7,378 | //
// Ext_UIView.swift
// jarvis-storefront-ios
//
// Created by Prakash Jha on 03/10/19.
//
import UIKit
//import SDWebImage
import jarvis_utility_ios
enum GradientDirection {
case leftToRight
case rightToLeft
case topToBottom
case bottomToTop
}
extension UIView {
public func sfRoundCorner(_ aBorder: CGFloat, _ borderColor: UIColor?, _ rad: CGFloat, _ shouldClip: Bool) {
self.layer.masksToBounds = true
self.layer.cornerRadius = rad
self.clipsToBounds = shouldClip
self.layer.borderWidth = aBorder
if borderColor != nil {
self.layer.borderColor = borderColor!.cgColor
}
}
public func sfRoundCorner(_ radius: CGFloat) {
self.layer.masksToBounds = true
self.layer.cornerRadius = radius
}
public func sfMakeShadow(shadowRadius: CGFloat, shadowOpacity: Float, shadowColor:CGColor, shadowOffset: CGSize) {
self.layer.masksToBounds = false
self.layer.shadowRadius = shadowRadius
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowColor = shadowColor
self.layer.shadowOffset = shadowOffset
}
func drawGradient(colors: [CGColor], direction: GradientDirection) {
if let subLayers = self.layer.sublayers {
for layer in subLayers {
if layer is CAGradientLayer {
return
}
}
}
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors
switch direction {
case .leftToRight:
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
case .rightToLeft:
gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
case .bottomToTop:
gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
default:
break
}
self.layer.insertSublayer(gradient, at: 0)
}
func drawGradientByRemovingOld(colors: [CGColor], direction: GradientDirection) {
removeGradientIfAny()
drawGradient(colors: colors, direction: direction)
}
func removeGradientIfAny() {
if let subLayers = self.layer.sublayers {
for layer in subLayers {
if layer is CAGradientLayer {
layer.removeFromSuperlayer()
}
}
}
}
}
extension Bundle {
class var sfBundle : Bundle{
return Bundle.init(for: SFConfig.self)
}
class func nibWith(name: String) -> UINib? {
return UINib(nibName : name, bundle : Bundle.sfBundle)
}
}
extension UIImage {
class func imageNamed(name: String) -> UIImage? {
return UIImage(named: name, in: Bundle.sfBundle, compatibleWith: nil)
}
}
extension UIImageView {
func setImageFrom(url: URL?, placeHolderImg: UIImage?, completion: JRImageCacheCompletionBlock?) {
self.jr_setImage(with: url, placeholderImage: placeHolderImg, options: .retryFailed,
completed: completion)
}
}
extension UIColor {
public class func themeBlueColor() -> UIColor {
return UIColor(red: 0/255.0, green: 186.0/255.0, blue: 242.0/255.0, alpha: 1.0)
}
}
extension String {
public func replaceFirst(of pattern:String,
with replacement:String) -> String {
if let range = self.range(of: pattern) {
return self.replacingCharacters(in: range, with: replacement)
}else{
return self
}
}
}
extension Double {
public func getFormattedAmount() -> String {
let numberStr = String(format: "%.2f", CGFloat(self))
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
let number: NSNumber? = formatter.number(from: numberStr)
if let number = number {
if Double(truncating: number)/Double(Int(truncating: number)) > 1.0 {
formatter.minimumFractionDigits = 2
}
if let formattedStr = formatter.string(from: number) {
return formattedStr
}
return String(describing: number)
}
return numberStr
}
}
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
extension UILabel {
func applyLetterSpacing(latterSpacing: CGFloat = 0) {
let characterSpacing: CGFloat = latterSpacing
let string = NSMutableAttributedString(string: self.text!)
if string.length > 0 {
string.addAttribute(.kern, value: characterSpacing, range: NSRange(location: 0, length: string.length - 1))
self.attributedText = string
}
}
}
extension UICollectionView {
func moveCellToCenter() {
let visibleCenterPositionOfScrollView = Float(self.contentOffset.x + (self.bounds.size.width / 2))
var closestCellIndex = -1
var closestDistance: Float = .greatestFiniteMagnitude
for i in 0..<self.visibleCells.count {
let cell = self.visibleCells[i]
let cellWidth = cell.bounds.size.width
let cellCenter = Float(cell.frame.origin.x + cellWidth / 2)
// Now calculate closest cell
let distance: Float = fabsf(visibleCenterPositionOfScrollView - cellCenter)
if distance < closestDistance {
closestDistance = distance
closestCellIndex = self.indexPath(for: cell)!.row
}
}
if closestCellIndex != -1 {
self.scrollToItem(at: IndexPath(row: closestCellIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
extension Dictionary where Key == String { // where Key: String, Value: Any
public func sfStringFor(key: String) -> String {
return self.sfActualValueFor(key: key, inInt: true)
}
public func sfIntFor(key: String) -> Int {
if let mInt = self[key] as? Int { return mInt }
let value = Int(self.sfActualValueFor(key: key, inInt: true))
return value != nil ? value! : 0
}
public func sfDoubleFor(key: String) -> Double {
let value = Double(self.sfActualValueFor(key: key, inInt: false))
return value != nil ? value! : 0.0
}
public func sfBooleanFor(key: String) -> Bool {
return self.sfStringFor(key: key).lowercased() == "true" || self.sfIntFor(key: key) >= 1
}
private func sfActualValueFor(key: String, inInt: Bool) -> String {
let str1 = self[key]
if str1 == nil { return "" }
if let str = str1 as? String {
return (str.lowercased() == "nil" || str.lowercased() == "null") ? "" : str
}
if let num = str1 as? NSNumber {
return inInt ? String(format:"%i", num.int32Value) : String(format:"%f", num.doubleValue)
}
return ""
}
}
| 31.529915 | 122 | 0.591488 |
64c7d249ef6fc7ff09cb14db2b23e865e65869ef | 13,103 | //===--- IntroSort.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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: %empty-directory(%t)
// RUN: %target-build-swift -g -Onone -DUSE_STDLIBUNITTEST %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// Note: This introsort was the standard library's sort algorithm until Swift 5.
import Swift
import StdlibUnittest
extension MutableCollection {
/// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]`.
/// Stable.
///
/// The indices passed as `a`, `b`, and `c` do not need to be consecutive, but
/// must be in strict increasing order.
///
/// - Precondition: `a < b && b < c`
/// - Postcondition: `self[a] <= self[b] && self[b] <= self[c]`
@inlinable
public // @testable
mutating func _sort3(
_ a: Index, _ b: Index, _ c: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// There are thirteen possible permutations for the original ordering of
// the elements at indices `a`, `b`, and `c`. The comments in the code below
// show the relative ordering of the three elements using a three-digit
// number as shorthand for the position and comparative relationship of
// each element. For example, "312" indicates that the element at `a` is the
// largest of the three, the element at `b` is the smallest, and the element
// at `c` is the median. This hypothetical input array has a 312 ordering for
// `a`, `b`, and `c`:
//
// [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ]
// ^ ^ ^
// a b c
//
// - If each of the three elements is distinct, they could be ordered as any
// of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321.
// - If two elements are equivalent and one is distinct, they could be
// ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211,
// 122, 212, or 221.
// - If all three elements are equivalent, they are already in order: 111.
switch try (areInIncreasingOrder(self[b], self[a]),
areInIncreasingOrder(self[c], self[b])) {
case (false, false):
// 0 swaps: 123, 112, 122, 111
break
case (true, true):
// 1 swap: 321
// swap(a, c): 312->123
swapAt(a, c)
case (true, false):
// 1 swap: 213, 212 --- 2 swaps: 312, 211
// swap(a, b): 213->123, 212->122, 312->132, 211->121
swapAt(a, b)
if try areInIncreasingOrder(self[c], self[b]) {
// 132 (started as 312), 121 (started as 211)
// swap(b, c): 132->123, 121->112
swapAt(b, c)
}
case (false, true):
// 1 swap: 132, 121 --- 2 swaps: 231, 221
// swap(b, c): 132->123, 121->112, 231->213, 221->212
swapAt(b, c)
if try areInIncreasingOrder(self[b], self[a]) {
// 213 (started as 231), 212 (started as 221)
// swap(a, b): 213->123, 212->122
swapAt(a, b)
}
}
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Reorders the collection and returns an index `p` such that every element
/// in `range.lowerBound..<p` is less than every element in
/// `p..<range.upperBound`.
///
/// - Precondition: The count of `range` must be >= 3 i.e.
/// `distance(from: range.lowerBound, to: range.upperBound) >= 3`
@inlinable
internal mutating func _partition(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Index {
var lo = range.lowerBound
var hi = index(before: range.upperBound)
// Sort the first, middle, and last elements, then use the middle value
// as the pivot for the partition.
let half = distance(from: lo, to: hi) / 2
let mid = index(lo, offsetBy: half)
try _sort3(lo, mid, hi, by: areInIncreasingOrder)
// FIXME: Stashing the pivot element instead of using the index won't work
// for move-only types.
let pivot = self[mid]
// Loop invariants:
// * lo < hi
// * self[i] < pivot, for i in range.lowerBound..<lo
// * pivot <= self[i] for i in hi..<range.upperBound
Loop: while true {
FindLo: do {
formIndex(after: &lo)
while lo != hi {
if try !areInIncreasingOrder(self[lo], pivot) { break FindLo }
formIndex(after: &lo)
}
break Loop
}
FindHi: do {
formIndex(before: &hi)
while hi != lo {
if try areInIncreasingOrder(self[hi], pivot) { break FindHi }
formIndex(before: &hi)
}
break Loop
}
swapAt(lo, hi)
}
return lo
}
@inlinable
public // @testable
mutating func _introSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let n = distance(from: range.lowerBound, to: range.upperBound)
guard n > 1 else { return }
// Set max recursion depth to 2*floor(log(N)), as suggested in the introsort
// paper: http://www.cs.rpi.edu/~musser/gp/introsort.ps
let depthLimit = 2 * n._binaryLogarithm()
try _introSortImpl(
within: range,
by: areInIncreasingOrder,
depthLimit: depthLimit)
}
@inlinable
internal mutating func _introSortImpl(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool,
depthLimit: Int
) rethrows {
// Insertion sort is better at handling smaller regions.
if distance(from: range.lowerBound, to: range.upperBound) < 20 {
try _insertionSort(within: range, by: areInIncreasingOrder)
} else if depthLimit == 0 {
try _heapSort(within: range, by: areInIncreasingOrder)
} else {
// Partition and sort.
// We don't check the depthLimit variable for underflow because this
// variable is always greater than zero (see check above).
let partIdx = try _partition(within: range, by: areInIncreasingOrder)
try _introSortImpl(
within: range.lowerBound..<partIdx,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
try _introSortImpl(
within: partIdx..<range.upperBound,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
}
}
@inlinable
internal mutating func _siftDown(
_ idx: Index,
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var idx = idx
var countToIndex = distance(from: range.lowerBound, to: idx)
var countFromIndex = distance(from: idx, to: range.upperBound)
// Check if left child is within bounds. If not, stop iterating, because
// there are no children of the given node in the heap.
while countToIndex + 1 < countFromIndex {
let left = index(idx, offsetBy: countToIndex + 1)
var largest = idx
if try areInIncreasingOrder(self[largest], self[left]) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = index(after: left)
if try areInIncreasingOrder(self[largest], self[right]) {
largest = right
}
}
// If a child is bigger than the current node, swap them and continue
// sifting down.
if largest != idx {
swapAt(idx, largest)
idx = largest
countToIndex = distance(from: range.lowerBound, to: idx)
countFromIndex = distance(from: idx, to: range.upperBound)
} else {
break
}
}
}
@inlinable
internal mutating func _heapify(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// Here we build a heap starting from the lowest nodes and moving to the
// root. On every step we sift down the current node to obey the max-heap
// property:
// parent >= max(leftChild, rightChild)
//
// We skip the rightmost half of the array, because these nodes don't have
// any children.
let root = range.lowerBound
let half = distance(from: range.lowerBound, to: range.upperBound) / 2
var node = index(root, offsetBy: half)
while node != root {
formIndex(before: &node)
try _siftDown(node, within: range, by: areInIncreasingOrder)
}
}
@inlinable
public // @testable
mutating func _heapSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var hi = range.upperBound
let lo = range.lowerBound
try _heapify(within: range, by: areInIncreasingOrder)
formIndex(before: &hi)
while hi != lo {
swapAt(lo, hi)
try _siftDown(lo, within: lo..<hi, by: areInIncreasingOrder)
formIndex(before: &hi)
}
}
}
//===--- Tests ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
var suite = TestSuite("IntroSort")
// The routine is based on http://www.cs.dartmouth.edu/~doug/mdmspe.pdf
func makeQSortKiller(_ len: Int) -> [Int] {
var candidate: Int = 0
var keys = [Int: Int]()
func Compare(_ x: Int, y : Int) -> Bool {
if keys[x] == nil && keys[y] == nil {
if (x == candidate) {
keys[x] = keys.count
} else {
keys[y] = keys.count
}
}
if keys[x] == nil {
candidate = x
return true
}
if keys[y] == nil {
candidate = y
return false
}
return keys[x]! > keys[y]!
}
var ary = [Int](repeating: 0, count: len)
var ret = [Int](repeating: 0, count: len)
for i in 0..<len { ary[i] = i }
ary = ary.sorted(by: Compare)
for i in 0..<len {
ret[ary[i]] = i
}
return ret
}
suite.test("sorted/complexity") {
var ary: [Int] = []
// Check performance of sorting an array of repeating values.
var comparisons_100 = 0
ary = Array(repeating: 0, count: 100)
ary._introSort(within: 0..<ary.count) { comparisons_100 += 1; return $0 < $1 }
var comparisons_1000 = 0
ary = Array(repeating: 0, count: 1000)
ary._introSort(within: 0..<ary.count) { comparisons_1000 += 1; return $0 < $1 }
expectTrue(comparisons_1000/comparisons_100 < 20)
// Try to construct 'bad' case for quicksort, on which the algorithm
// goes quadratic.
comparisons_100 = 0
ary = makeQSortKiller(100)
ary._introSort(within: 0..<ary.count) { comparisons_100 += 1; return $0 < $1 }
comparisons_1000 = 0
ary = makeQSortKiller(1000)
ary._introSort(within: 0..<ary.count) { comparisons_1000 += 1; return $0 < $1 }
expectTrue(comparisons_1000/comparisons_100 < 20)
}
suite.test("sort3/simple")
.forEach(in: [
[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
]) {
var input = $0
input._sort3(0, 1, 2, by: <)
expectEqual([1, 2, 3], input)
}
func isSorted<T>(_ a: [T], by areInIncreasingOrder: (T, T) -> Bool) -> Bool {
return !zip(a.dropFirst(), a).contains(where: areInIncreasingOrder)
}
suite.test("sort3/stable")
.forEach(in: [
[1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 1, 1]
]) {
// decorate with offset, but sort by value
var input = Array($0.enumerated())
input._sort3(0, 1, 2) { $0.element < $1.element }
// offsets should still be ordered for equal values
expectTrue(isSorted(input) {
if $0.element == $1.element {
return $0.offset < $1.offset
}
return $0.element < $1.element
})
}
suite.test("heapSort") {
// Generates the next permutation of `num` as a binary integer, using long
// arithmetics approach.
//
// - Precondition: All values in `num` are either 0 or 1.
func addOne(to num: [Int]) -> [Int] {
// `num` represents a binary integer. To add one, we toggle any bits until
// we've set a clear bit.
var num = num
for i in num.indices {
if num[i] == 1 {
num[i] = 0
} else {
num[i] = 1
break
}
}
return num
}
// Test binary number size.
let numberLength = 11
var binaryNumber = Array(repeating: 0, count: numberLength)
// We are testing sort on all permutations off 0-1s of size `numberLength`
// except the all 1's case (its equals to all 0's case).
while !binaryNumber.allSatisfy({ $0 == 1 }) {
var buffer = binaryNumber
buffer._heapSort(within: buffer.startIndex..<buffer.endIndex, by: <)
expectTrue(isSorted(buffer, by: <))
binaryNumber = addOne(to: binaryNumber)
}
}
runAllTests()
| 32.922111 | 81 | 0.597726 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.