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
|
---|---|---|---|---|---|
71c5b05626343b871b20ae059d4aac0b3297dddc | 998 | //
// Namespace.swift
// MVVMFramework
//
// Created by lisilong on 2018/12/5.
// Copyright ยฉ 2018 lisilong. All rights reserved.
//
import UIKit
public protocol NamespaceWrappable {
associatedtype WrapperType
var td: WrapperType { get set }
static var td: WrapperType.Type { get }
}
public extension NamespaceWrappable {
var td: NamespaceWrapper<Self> {
get {
return NamespaceWrapper(value: self)
}
set {}
}
static var td: NamespaceWrapper<Self>.Type {
return NamespaceWrapper.self
}
}
public struct NamespaceWrapper<Base> {
public var wrappedValue: Base
public init(value: Base) {
self.wrappedValue = value
}
}
extension UIView: NamespaceWrappable {}
extension String: NamespaceWrappable {}
extension UIViewController: NamespaceWrappable {}
extension Bool: NamespaceWrappable {}
extension NSMutableAttributedString: NamespaceWrappable {}
extension UITapGestureRecognizer: NamespaceWrappable {}
| 23.209302 | 58 | 0.705411 |
d6b655a9705fd53d7e9bd545f0c00331c982363f | 332 | //
// PathsStorage.swift
// KinescopeSDK
//
// Created by Artemii Shabanov on 08.04.2021.
//
import Foundation
protocol PathsStorage {
func save(relativeUrl: String, id: String)
func readUrl(by id: String) -> String?
func fetchIds() -> [String]
@discardableResult
func deleteUrl(by id: String) -> String?
}
| 19.529412 | 46 | 0.671687 |
5daa7237dac9548ace62e127e64e6aedd40b37bb | 11,826 | //
// FlagIcons.swift
// LastDay
//
// Created by Mateusz Malczak on 17/09/16.
// Copyright ยฉ 2016 The Pirate Cat. All rights reserved.
//
import Foundation
import UIKit
/**
SpriteSheet class represents an image map
*/
open class SpriteSheet {
typealias GridSize = (cols: Int, rows: Int)
typealias ImageSize = (width: Int, height: Int)
/**
Struct stores information about a grid size, sprite size and country codes included in sprite sheet
*/
struct SheetInfo {
fileprivate(set) var gridSize: GridSize
fileprivate(set) var spriteSize: ImageSize
fileprivate(set) var codes: [String]
}
fileprivate(set) var info: SheetInfo
fileprivate(set) var image: UIImage
fileprivate(set) var colorSpace: CGColorSpace
fileprivate var imageData: UnsafeMutableRawPointer?
fileprivate var imageCache = [String:UIImage]()
fileprivate var cgImage: CGImage {
return image.cgImage!
}
var bitsPerComponent: Int {
return cgImage.bitsPerComponent
}
var bitsPerPixel: Int {
return bitsPerComponent * 4
}
var imageSize: CGSize {
return image.size
}
var spriteBytesPerRow: Int {
return 4 * info.spriteSize.width
}
var spriteBytesCount: Int {
return spriteBytesPerRow * info.spriteSize.height
}
var sheetBytesPerRow: Int {
return spriteBytesPerRow * info.gridSize.rows
}
var sheetBytesPerCol: Int {
return spriteBytesCount * info.gridSize.cols
}
var sheetBytesCount: Int {
return sheetBytesPerRow * Int(imageSize.height)
}
var bitmapInfo: CGBitmapInfo {
let imageBitmapInfo = cgImage.bitmapInfo
let imageAlphaInfo = cgImage.alphaInfo
return CGBitmapInfo(rawValue:
(imageBitmapInfo.rawValue & (CGBitmapInfo.byteOrderMask.rawValue)) |
(imageAlphaInfo.rawValue & (CGBitmapInfo.alphaInfoMask.rawValue)))
}
var bytes: UnsafeMutablePointer<UInt8> {
return imageData!.assumingMemoryBound(to: UInt8.self)
}
init?(sheetImage: UIImage, info sInfo: SheetInfo) {
image = sheetImage
info = sInfo
guard let cgImage = sheetImage.cgImage else {
return nil
}
guard let cgColorSpace = cgImage.colorSpace else {
return nil
}
colorSpace = cgColorSpace
let memory = sheetMemoryLayout()
let bytes = UnsafeMutableRawPointer.allocate(byteCount: memory.size,
alignment: memory.alignment)
let imageWidth = Int(imageSize.width)
let imageHeight = Int(imageSize.height)
guard let bmpCtx = CGContext(data: bytes,
width: imageWidth,
height: imageHeight,
bitsPerComponent: bitsPerComponent,
bytesPerRow: 4 * imageWidth,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) else {
bytes.deallocate()
return
}
imageData = bytes
bmpCtx.draw(cgImage,
in: CGRect(x: 0, y: 0,
width: imageSize.width,
height: imageSize.height))
}
open func getImageFor(_ code: String, deepCopy: Bool = false, scale: CGFloat = 2) -> UIImage? {
var cimg = imageCache[code] // cache is not thread safe
if nil == cimg || deepCopy {
let data = getBytesFor(code)
if deepCopy {
guard let bmpCtx = CGContext(data: nil,
width: info.spriteSize.width,
height: info.spriteSize.height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: spriteBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) else {
return nil
}
if let bmpData = bmpCtx.data {
var srcData = UnsafeMutablePointer<UInt8>(mutating: data.bytes)
var curData = bmpData.assumingMemoryBound(to: UInt8.self)
for _ in 0..<info.spriteSize.height {
curData.assign(from: srcData, count: spriteBytesPerRow)
curData = curData.advanced(by: spriteBytesPerRow)
srcData = srcData.advanced(by: sheetBytesPerRow)
}
if let bmpImage = bmpCtx.makeImage() {
return UIImage(cgImage: bmpImage, scale: scale, orientation: UIImage.Orientation.up).withRenderingMode(.alwaysOriginal)
}
}
return nil
}
let expectedSize = sheetBytesPerRow * info.spriteSize.height
let size = min(expectedSize, data.size)
guard let provider = CGDataProvider(dataInfo: nil,
data: data.bytes,
size: size,
releaseData: {_,_,_ in}) else {
return nil
}
guard let cgImage = CGImage(width: info.spriteSize.width,
height: info.spriteSize.height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: sheetBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo,
provider: provider,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent) else {
return nil
}
cimg = UIImage(cgImage: cgImage)
imageCache[code] = cimg
}
return cimg
}
open func getBytesFor(_ code: String) -> (bytes: UnsafePointer<UInt8>, size: Int) {
let idx = info.codes.firstIndex(of: code.lowercased()) ?? 0
let dx = idx % info.gridSize.cols
let dy = idx / info.gridSize.rows
let bytesOffset = sheetBytesPerCol * dy + spriteBytesPerRow * dx
let data = bytes.advanced(by: bytesOffset)
let totalMemory = sheetMemoryLayout().size
#if TRACK_MEMORY
print("""
/*********
code : \(code)
index : \(idx)
d(x/y) : \(dx) x \(dy) | \(idx % info.gridSize.cols) x \(idx/info.gridSize.rows)
bytes offset : \(bytesOffset)
Sheet
sprites : \(info.codes.count)
grid size : \(info.gridSize.cols) x \(info.gridSize.rows)
sprite size : \(info.spriteSize.width) x \(info.spriteSize.height)
bits/Component : \(bitsPerComponent)
bits/Pixel : \(bitsPerPixel)
Memory
total : \(totalMemory)
provider : \(sheetBytesPerRow * info.spriteSize.height)
sprite : \(spriteBytesCount)
left : \(totalMemory - bytesOffseTRACK_MEMORYt)
""")
#endif
return (UnsafePointer<UInt8>(data), totalMemory - bytesOffset)
}
open func flushCache() {
imageCache.removeAll()
}
func sheetMemoryLayout() -> (size: Int, alignment: Int) {
return (sheetBytesCount * MemoryLayout<UInt8>.stride,
MemoryLayout<UInt8>.alignment)
}
deinit {
imageCache.removeAll()
if let data = imageData {
data.deallocate()
}
imageData = nil
}
}
/**
Represents a flags icon sprite sheet
*/
open class FlagIcons {
public struct Country {
public let name: String;
public let code: String;
}
open class func loadDefault() -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoFile = assetsBundle.path(forResource: "flags", ofType: "json") {
return self.loadSheetFrom(infoFile)
}
return nil
}
open class func loadCountries() -> [Country]? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let dataFile = assetsBundle.path(forResource: "countries", ofType: "json") {
if let countriesSet: [[String:String]] = loadJSON(file: dataFile) {
return countriesSet.compactMap({countryInfo in
guard case let (name?, code?) = (countryInfo["name"], countryInfo["code"]) else {
return nil
}
return Country(name: name, code: code)
}).sorted(by: {country1, country2 in country1.name < country2.name})
}
}
return nil
}
open class func loadSheetFrom(_ file: String) -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoObj: [String:Any] = loadJSON(file: file) {
if let gridSizeObj = infoObj["gridSize"] as? [String:Int],
let spriteSizeObj = infoObj["spriteSize"] as? [String:Int] {
let gridSize = (gridSizeObj["cols"]!, gridSizeObj["rows"]!)
let spriteSize = (spriteSizeObj["width"]!, spriteSizeObj["height"]!)
if let codes = (infoObj["codes"] as? String)?.components(separatedBy: "|") {
if let sheetFileName = infoObj["sheetFile"] as? String,
let resourceUrl = assetsBundle.resourceURL {
let sheetFileUrl = resourceUrl.appendingPathComponent(sheetFileName)
if let image = UIImage(contentsOfFile: sheetFileUrl.path) {
let info = SpriteSheet.SheetInfo(gridSize: gridSize, spriteSize: spriteSize, codes: codes)
return SpriteSheet(sheetImage: image, info: info)
}
}
}
}
}
return nil
}
fileprivate class func loadJSON<T>(file: String) -> T? {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
return nil
}
let options = JSONSerialization.ReadingOptions(rawValue: 0)
return try? JSONSerialization.jsonObject(with: data, options: options) as? T
}
fileprivate class func assetsBundle() -> Bundle? {
let bundle = Bundle(for: self)
guard let assetsBundlePath = bundle.path(forResource: "assets", ofType: "bundle") else {
return nil
}
return Bundle(path: assetsBundlePath);
}
}
| 36.165138 | 143 | 0.502199 |
1a1eb61e1994776518a541d71dac090617aee66e | 8,639 | //
// InitialQuizViewController.swift
// GameJun
//
// Created by JEON JUNHA on 2021/05/03.
//
import UIKit
import SnapKit
class InitialQuizViewController: UIViewController {
let createButton = UIButton()
let startButton = UIButton()
let customQuizButton = UIButton()
var myTitle = ""
let gameView = UIView()
let movieTitleLabel = UILabel()
let answerButton = UIButton()
let nextButton = UIButton()
let myTitleButton = UIButton()
var movieTitle = String()
var movieTitles = [""]
let dismissButton = DismissButton()
let titleTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
setUI()
view.backgroundColor = .black
nextButton.isHidden = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@objc
func dissmissKeyboard() {
view.endEditing(true)
}
}
// MARK: - ์ด์ฑ ๋ณํ
extension InitialQuizViewController {
func initial(movieTitle: String) -> String {
var initial:String = "";
let title = movieTitle as NSString
for i in 0..<title.length{
let oneChar:UniChar = title.character(at:i)
if( oneChar >= 0xAC00 && oneChar <= 0xD7A3 ){
var firstCodeValue = ((oneChar - 0xAC00)/28)/21
firstCodeValue += 0x1100;
initial = initial.appending(String(format:"%C", firstCodeValue))
}else{
initial = initial.appending(String(format:"%C", oneChar))
}
}
return initial
}
}
extension InitialQuizViewController {
@objc
func tapMainButton(_ sender: UIButton) {
gameView.isHidden = false
switch sender {
case startButton:
nextButton.isHidden = false
movieTitles = InitialQuizManager.shared.movieTitle
movieTitle = movieTitles.randomElement() ?? ""
movieTitleLabel.text = initial(movieTitle: movieTitle)
nextButton.isHidden = true
titleTextField.isHidden = true
myTitleButton.isHidden = true
gameView.tag = 0
case createButton:
answerButton.isHidden = true
titleTextField.isHidden = false
nextButton.isHidden = true
myTitleButton.isHidden = false
gameView.tag = 1
default:
fatalError()
}
}
@objc
func tapGameButton(_ sender: UIButton) {
view.endEditing(true)
if gameView.tag == 0 {
switch sender {
case answerButton:
movieTitleLabel.text = movieTitle as String
answerButton.isHidden = true
nextButton.isHidden = false
case nextButton:
nextButton.isHidden = true
movieTitles.removeAll(where: { $0 == movieTitle as String })
if movieTitles.count == 0 {
nextButton.isHidden = false
movieTitleLabel.text = "๊ฒ์ ๋!"
answerButton.isHidden = true
nextButton.setTitle("ํ์ธ", for: .normal)
} else {
answerButton.isHidden = false
movieTitle = movieTitles.randomElement() ?? ""
movieTitleLabel.text = initial(movieTitle: movieTitle)
}
if nextButton.titleLabel?.text == "ํ์ธ" {
// gameView.isHidden = true
nextButton.setTitle("๋ค์ ๋ฌธ์ ", for: .normal)
self.dismiss(animated: true, completion: nil)
}
case myTitleButton:
myTitle = titleTextField.text ?? ""
movieTitleLabel.text = initial(movieTitle: myTitle)
default:
fatalError()
}
} else {
switch sender {
case answerButton:
movieTitleLabel.text = myTitle
answerButton.isHidden = true
titleTextField.isHidden = false
myTitleButton.isHidden = false
titleTextField.text = ""
case myTitleButton:
if titleTextField.text == "" {
movieTitleLabel.text = "์ ์์ด๋ฅผ ์
๋ ฅํ์ธ์"
} else {
myTitle = titleTextField.text ?? ""
movieTitleLabel.text = initial(movieTitle: myTitle)
myTitleButton.isHidden = true
titleTextField.isHidden = true
answerButton.isHidden = false
}
default:
fatalError()
}
}
}
@objc
func tapDismissButton(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Delegate
extension InitialQuizViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.tapGameButton(self.myTitleButton)
return true
}
}
// MARK: - UI
extension InitialQuizViewController {
final private func setUI() {
setBasics()
setLayout()
}
final private func setBasics() {
[startButton, createButton].forEach {
$0.addTarget(self, action: #selector(tapMainButton(_:)), for: .touchUpInside)
}
startButton.setTitle("ํ๋ ์ด!", for: .normal)
startButton.titleLabel?.font = .systemFont(ofSize: 60)
startButton.setImage(UIImage(named: "2"), for: .normal)
createButton.setTitle("๋ฌธ์ ๋ด๊ธฐ", for: .normal)
createButton.titleLabel?.font = .systemFont(ofSize: 60)
createButton.setImage(UIImage(named: "2"), for: .normal)
gameView.isHidden = true
gameView.backgroundColor = .black
[answerButton, nextButton, myTitleButton].forEach {
$0.titleLabel?.font = .systemFont(ofSize: 24)
$0.addTarget(self, action: #selector(tapGameButton(_:)), for: .touchUpInside)
$0.setImage(UIImage(named: "2"), for: .normal)
}
answerButton.setTitle("์ ๋ต ํ์ธ!", for: .normal)
nextButton.setTitle("ํ๋ฒ ๋!", for: .normal)
myTitleButton.setTitle("ํ๋ ์ด!", for: .normal)
movieTitleLabel.font = .systemFont(ofSize: 60)
movieTitleLabel.textAlignment = .center
movieTitleLabel.numberOfLines = 4
movieTitleLabel.textColor = .white
dismissButton.addTarget(self, action: #selector(tapDismissButton(_:)), for: .touchUpInside)
titleTextField.placeholder = "์ ์์ด ์
๋ ฅ!"
titleTextField.backgroundColor = .white
titleTextField.textAlignment = .center
titleTextField.textColor = .black
titleTextField.delegate = self
}
final private func setLayout() {
[startButton, createButton, gameView, dismissButton].forEach {
view.addSubview($0)
}
startButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview().offset(-120)
}
createButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.top.equalTo(startButton.snp.bottom).offset(80)
}
gameView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
[movieTitleLabel, answerButton, nextButton, titleTextField, myTitleButton].forEach {
gameView.addSubview($0)
}
movieTitleLabel.snp.makeConstraints {
$0.leading.trailing.equalToSuperview()
$0.centerX.equalToSuperview()
$0.top.equalTo(view.safeAreaLayoutGuide).offset(80)
}
titleTextField.snp.makeConstraints {
$0.centerX.equalToSuperview().offset(8)
$0.bottom.equalTo(answerButton.snp.top).offset(-20)
$0.width.equalTo(120)
}
answerButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview().offset(40)
}
myTitleButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview().offset(40)
}
nextButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview().offset(40)
}
dismissButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(20)
}
}
}
| 33.878431 | 99 | 0.568121 |
4a073935df5dfd03f9def74acd732706fc1cdbd4 | 33,234 | //
// AFDateHelper.swift
// https://github.com/melvitax/DateHelper
// Version 4.2.8
//
// Created by Melvin Rivera on 7/15/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
public extension Date {
// MARK: Convert from String
/*
Initializes a new Date() objext based on a date string, format, optional timezone and optional locale.
- Returns: A Date() object if successfully converted from string or nil.
*/
init?(fromString string: String, format:DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Foundation.Locale.current, isLenient: Bool = true) {
guard !string.isEmpty else {
return nil
}
var string = string
switch format {
case .dotNet:
let pattern = "\\\\?/Date\\((\\d+)(([+-]\\d{2})(\\d{2}))?\\)\\\\?/"
let regex = try! NSRegularExpression(pattern: pattern)
guard let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) else {
return nil
}
#if swift(>=4.0)
let dateString = (string as NSString).substring(with: match.range(at: 1))
#else
let dateString = (string as NSString).substring(with: match.rangeAt(1))
#endif
let interval = Double(dateString)! / 1000.0
self.init(timeIntervalSince1970: interval)
return
case .rss, .altRSS:
if string.hasSuffix("Z") {
string = string[..<string.index(string.endIndex, offsetBy: -1)].appending("GMT")
}
default:
break
}
let formatter = Date.cachedDateFormatters.cachedFormatter(
format.stringFormat,
timeZone: timeZone.timeZone,
locale: locale,
isLenient: isLenient)
guard let date = formatter.date(from: string) else {
return nil
}
self.init(timeInterval:0, since:date)
}
// MARK: Convert to String
/// Converts the date to string using the short date and time style.
func toString(style:DateStyleType = .short) -> String {
switch style {
case .short:
return self.toString(dateStyle: .short, timeStyle: .short, isRelative: false)
case .medium:
return self.toString(dateStyle: .medium, timeStyle: .medium, isRelative: false)
case .long:
return self.toString(dateStyle: .long, timeStyle: .long, isRelative: false)
case .full:
return self.toString(dateStyle: .full, timeStyle: .full, isRelative: false)
case .ordinalDay:
let formatter = Date.cachedDateFormatters.cachedNumberFormatter()
if #available(iOSApplicationExtension 9.0, *) {
formatter.numberStyle = .ordinal
}
return formatter.string(from: component(.day)! as NSNumber)!
case .weekday:
let weekdaySymbols = Date.cachedDateFormatters.cachedFormatter().weekdaySymbols!
let string = weekdaySymbols[component(.weekday)!-1] as String
return string
case .shortWeekday:
let shortWeekdaySymbols = Date.cachedDateFormatters.cachedFormatter().shortWeekdaySymbols!
return shortWeekdaySymbols[component(.weekday)!-1] as String
case .veryShortWeekday:
let veryShortWeekdaySymbols = Date.cachedDateFormatters.cachedFormatter().veryShortWeekdaySymbols!
return veryShortWeekdaySymbols[component(.weekday)!-1] as String
case .month:
let monthSymbols = Date.cachedDateFormatters.cachedFormatter().monthSymbols!
return monthSymbols[component(.month)!-1] as String
case .shortMonth:
let shortMonthSymbols = Date.cachedDateFormatters.cachedFormatter().shortMonthSymbols!
return shortMonthSymbols[component(.month)!-1] as String
case .veryShortMonth:
let veryShortMonthSymbols = Date.cachedDateFormatters.cachedFormatter().veryShortMonthSymbols!
return veryShortMonthSymbols[component(.month)!-1] as String
}
}
/// Converts the date to string based on a date format, optional timezone and optional locale.
func toString(format: DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Locale.current) -> String {
switch format {
case .dotNet:
let offset = Foundation.NSTimeZone.default.secondsFromGMT() / 3600
let nowMillis = 1000 * self.timeIntervalSince1970
return String(format: format.stringFormat, nowMillis, offset)
default:
break
}
let formatter = Date.cachedDateFormatters.cachedFormatter(format.stringFormat, timeZone: timeZone.timeZone, locale: locale)
return formatter.string(from: self)
}
/// Converts the date to string based on DateFormatter's date style and time style with optional relative date formatting, optional time zone and optional locale.
func toString(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, isRelative: Bool = false, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> String {
let formatter = Date.cachedDateFormatters.cachedFormatter(dateStyle, timeStyle: timeStyle, doesRelativeDateFormatting: isRelative, timeZone: timeZone, locale: locale)
return formatter.string(from: self)
}
/// Converts the date to string based on a relative time language. i.e. just now, 1 minute ago etc...
func toStringWithRelativeTime(strings:[RelativeTimeStringType:String]? = nil) -> String {
let time = self.timeIntervalSince1970
let now = Date().timeIntervalSince1970
let isPast = now - time > 0
let sec:Double = abs(now - time)
let min:Double = round(sec/60)
let hr:Double = round(min/60)
let d:Double = round(hr/24)
if sec < 60 {
if sec < 10 {
if isPast {
return strings?[.nowPast] ?? NSLocalizedString("just now", comment: "Date format")
} else {
return strings?[.nowFuture] ?? NSLocalizedString("in a few seconds", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.secondsPast] ?? NSLocalizedString("%.f seconds ago", comment: "Date format")
} else {
string = strings?[.secondsFuture] ?? NSLocalizedString("in %.f seconds", comment: "Date format")
}
return String(format: string, sec)
}
}
if min < 60 {
if min == 1 {
if isPast {
return strings?[.oneMinutePast] ?? NSLocalizedString("1 minute ago", comment: "Date format")
} else {
return strings?[.oneMinuteFuture] ?? NSLocalizedString("in 1 minute", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.minutesPast] ?? NSLocalizedString("%.f minutes ago", comment: "Date format")
} else {
string = strings?[.minutesFuture] ?? NSLocalizedString("in %.f minutes", comment: "Date format")
}
return String(format: string, min)
}
}
if hr < 24 {
if hr == 1 {
if isPast {
return strings?[.oneHourPast] ?? NSLocalizedString("last hour", comment: "Date format")
} else {
return strings?[.oneHourFuture] ?? NSLocalizedString("next hour", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.hoursPast] ?? NSLocalizedString("%.f hours ago", comment: "Date format")
} else {
string = strings?[.hoursFuture] ?? NSLocalizedString("in %.f hours", comment: "Date format")
}
return String(format: string, hr)
}
}
if d < 7 {
if d == 1 {
if isPast {
return strings?[.oneDayPast] ?? NSLocalizedString("yesterday", comment: "Date format")
} else {
return strings?[.oneDayFuture] ?? NSLocalizedString("tomorrow", comment: "Date format")
}
} else {
let string:String
if isPast {
string = strings?[.daysPast] ?? NSLocalizedString("%.f days ago", comment: "Date format")
} else {
string = strings?[.daysFuture] ?? NSLocalizedString("in %.f days", comment: "Date format")
}
return String(format: string, d)
}
}
if d < 28 {
if isPast {
if compare(.isLastWeek) {
return strings?[.oneWeekPast] ?? NSLocalizedString("last week", comment: "Date format")
} else {
let string = strings?[.weeksPast] ?? NSLocalizedString("%.f weeks ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .week))))
}
} else {
if compare(.isNextWeek) {
return strings?[.oneWeekFuture] ?? NSLocalizedString("next week", comment: "Date format")
} else {
let string = strings?[.weeksFuture] ?? NSLocalizedString("in %.f weeks", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .week))))
}
}
}
if compare(.isThisYear) {
if isPast {
if compare(.isLastMonth) {
return strings?[.oneMonthPast] ?? NSLocalizedString("last month", comment: "Date format")
} else {
let string = strings?[.monthsPast] ?? NSLocalizedString("%.f months ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .month))))
}
} else {
if compare(.isNextMonth) {
return strings?[.oneMonthFuture] ?? NSLocalizedString("next month", comment: "Date format")
} else {
let string = strings?[.monthsFuture] ?? NSLocalizedString("in %.f months", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .month))))
}
}
}
if isPast {
if compare(.isLastYear) {
return strings?[.oneYearPast] ?? NSLocalizedString("last year", comment: "Date format")
} else {
let string = strings?[.yearsPast] ?? NSLocalizedString("%.f years ago", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .year))))
}
} else {
if compare(.isNextYear) {
return strings?[.oneYearFuture] ?? NSLocalizedString("next year", comment: "Date format")
} else {
let string = strings?[.yearsFuture] ?? NSLocalizedString("in %.f years", comment: "Date format")
return String(format: string, Double(abs(since(Date(), in: .year))))
}
}
}
// MARK: Compare Dates
/// Compares dates to see if they are equal while ignoring time.
func compare(_ comparison:DateComparisonType) -> Bool {
switch comparison {
case .isToday:
return compare(.isSameDay(as: Date()))
case .isTomorrow:
let comparison = Date().adjust(.day, offset:1)
return compare(.isSameDay(as: comparison))
case .isYesterday:
let comparison = Date().adjust(.day, offset: -1)
return compare(.isSameDay(as: comparison))
case .isSameDay(let date):
return component(.year) == date.component(.year)
&& component(.month) == date.component(.month)
&& component(.day) == date.component(.day)
case .isThisWeek:
return self.compare(.isSameWeek(as: Date()))
case .isNextWeek:
let comparison = Date().adjust(.week, offset:1)
return compare(.isSameWeek(as: comparison))
case .isLastWeek:
let comparison = Date().adjust(.week, offset:-1)
return compare(.isSameWeek(as: comparison))
case .isSameWeek(let date):
if component(.week) != date.component(.week) {
return false
}
// Ensure time interval is under 1 week
return abs(self.timeIntervalSince(date)) < Date.weekInSeconds
case .isThisMonth:
return self.compare(.isSameMonth(as: Date()))
case .isNextMonth:
let comparison = Date().adjust(.month, offset:1)
return compare(.isSameMonth(as: comparison))
case .isLastMonth:
let comparison = Date().adjust(.month, offset:-1)
return compare(.isSameMonth(as: comparison))
case .isSameMonth(let date):
return component(.year) == date.component(.year) && component(.month) == date.component(.month)
case .isThisYear:
return self.compare(.isSameYear(as: Date()))
case .isNextYear:
let comparison = Date().adjust(.year, offset:1)
return compare(.isSameYear(as: comparison))
case .isLastYear:
let comparison = Date().adjust(.year, offset:-1)
return compare(.isSameYear(as: comparison))
case .isSameYear(let date):
return component(.year) == date.component(.year)
case .isInTheFuture:
return self.compare(.isLater(than: Date()))
case .isInThePast:
return self.compare(.isEarlier(than: Date()))
case .isEarlier(let date):
return (self as NSDate).earlierDate(date) == self
case .isLater(let date):
return (self as NSDate).laterDate(date) == self
case .isWeekday:
return !compare(.isWeekend)
case .isWeekend:
let range = Calendar.current.maximumRange(of: Calendar.Component.weekday)!
return (component(.weekday) == range.lowerBound || component(.weekday) == range.upperBound - range.lowerBound)
}
}
// MARK: Adjust dates
/// Creates a new date with adjusted components
func adjust(_ component:DateComponentType, offset:Int) -> Date {
var dateComp = DateComponents()
switch component {
case .second:
dateComp.second = offset
case .minute:
dateComp.minute = offset
case .hour:
dateComp.hour = offset
case .day:
dateComp.day = offset
case .weekday:
dateComp.weekday = offset
case .nthWeekday:
dateComp.weekdayOrdinal = offset
case .week:
dateComp.weekOfYear = offset
case .month:
dateComp.month = offset
case .year:
dateComp.year = offset
}
return Calendar.current.date(byAdding: dateComp, to: self)!
}
/// Return a new Date object with the new hour, minute and seconds values.
func adjust(hour: Int?, minute: Int?, second: Int?, day: Int? = nil, month: Int? = nil) -> Date {
var comp = Date.components(self)
comp.month = month ?? comp.month
comp.day = day ?? comp.day
comp.hour = hour ?? comp.hour
comp.minute = minute ?? comp.minute
comp.second = second ?? comp.second
return Calendar.current.date(from: comp)!
}
// MARK: Date for...
func dateFor(_ type:DateForType, calendar:Calendar = Calendar.current) -> Date {
switch type {
case .startOfDay:
return adjust(hour: 0, minute: 0, second: 0)
case .endOfDay:
return adjust(hour: 23, minute: 59, second: 59)
case .startOfWeek:
return calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
case .endOfWeek:
let offset = 7 - component(.weekday)!
return adjust(.day, offset: offset)
case .startOfMonth:
return adjust(hour: 0, minute: 0, second: 0, day: 1)
case .endOfMonth:
let month = (component(.month) ?? 0) + 1
return adjust(hour: 0, minute: 0, second: 0, day: 0, month: month)
case .tomorrow:
return adjust(.day, offset:1)
case .yesterday:
return adjust(.day, offset:-1)
case .nearestMinute(let nearest):
let minutes = (component(.minute)! + nearest/2) / nearest * nearest
return adjust(hour: nil, minute: minutes, second: nil)
case .nearestHour(let nearest):
let hours = (component(.hour)! + nearest/2) / nearest * nearest
return adjust(hour: hours, minute: 0, second: nil)
}
}
// MARK: Time since...
func since(_ date:Date, in component:DateComponentType) -> Int64 {
switch component {
case .second:
return Int64(timeIntervalSince(date))
case .minute:
let interval = timeIntervalSince(date)
return Int64(interval / Date.minuteInSeconds)
case .hour:
let interval = timeIntervalSince(date)
return Int64(interval / Date.hourInSeconds)
case .day:
let calendar = Calendar.current
let end = calendar.ordinality(of: .day, in: .era, for: self)
let start = calendar.ordinality(of: .day, in: .era, for: date)
return Int64(end! - start!)
case .weekday:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekday, in: .era, for: self)
let start = calendar.ordinality(of: .weekday, in: .era, for: date)
return Int64(end! - start!)
case .nthWeekday:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: self)
let start = calendar.ordinality(of: .weekdayOrdinal, in: .era, for: date)
return Int64(end! - start!)
case .week:
let calendar = Calendar.current
let end = calendar.ordinality(of: .weekOfYear, in: .era, for: self)
let start = calendar.ordinality(of: .weekOfYear, in: .era, for: date)
return Int64(end! - start!)
case .month:
let calendar = Calendar.current
let end = calendar.ordinality(of: .month, in: .era, for: self)
let start = calendar.ordinality(of: .month, in: .era, for: date)
return Int64(end! - start!)
case .year:
let calendar = Calendar.current
let end = calendar.ordinality(of: .year, in: .era, for: self)
let start = calendar.ordinality(of: .year, in: .era, for: date)
return Int64(end! - start!)
}
}
// MARK: Extracting components
func component(_ component:DateComponentType) -> Int? {
let components = Date.components(self)
switch component {
case .second:
return components.second
case .minute:
return components.minute
case .hour:
return components.hour
case .day:
return components.day
case .weekday:
return components.weekday
case .nthWeekday:
return components.weekdayOrdinal
case .week:
return components.weekOfYear
case .month:
return components.month
case .year:
return components.year
}
}
func numberOfDaysInMonth() -> Int {
let range = Calendar.current.range(of: Calendar.Component.day, in: Calendar.Component.month, for: self)!
return range.upperBound - range.lowerBound
}
func firstDayOfWeek() -> Int {
let distanceToStartOfWeek = Date.dayInSeconds * Double(self.component(.weekday)! - 1)
let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek
return Date(timeIntervalSinceReferenceDate: interval).component(.day)!
}
func lastDayOfWeek() -> Int {
let distanceToStartOfWeek = Date.dayInSeconds * Double(self.component(.weekday)! - 1)
let distanceToEndOfWeek = Date.dayInSeconds * Double(7)
let interval: TimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek
return Date(timeIntervalSinceReferenceDate: interval).component(.day)!
}
// MARK: Internal Components
internal static func componentFlags() -> Set<Calendar.Component> { return [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second, Calendar.Component.weekday, Calendar.Component.weekdayOrdinal, Calendar.Component.weekOfYear] }
internal static func components(_ fromDate: Date) -> DateComponents {
return Calendar.current.dateComponents(Date.componentFlags(), from: fromDate)
}
internal class concurrentFormatterCache {
private static let cachedDateFormattersQueue = DispatchQueue(
label: "date-formatter-queue",
attributes: .concurrent
)
private static let cachedNumberFormatterQueue = DispatchQueue(
label: "number-formatter-queue",
attributes: .concurrent
)
private static var cachedDateFormatters = [String: DateFormatter]()
private static var cachedNumberFormatter = NumberFormatter()
private func register(hashKey: String, formatter: DateFormatter) -> Void {
concurrentFormatterCache.cachedDateFormattersQueue.async(flags: .barrier) {
concurrentFormatterCache.cachedDateFormatters.updateValue(formatter, forKey: hashKey)
}
}
private func retrieve(hashKey: String) -> DateFormatter? {
let dateFormatter = concurrentFormatterCache.cachedDateFormattersQueue.sync { () -> DateFormatter? in
guard let result = concurrentFormatterCache.cachedDateFormatters[hashKey] else { return nil }
return result.copy() as? DateFormatter
}
return dateFormatter
}
private func retrieve() -> NumberFormatter {
let numberFormatter = concurrentFormatterCache.cachedNumberFormatterQueue.sync { () -> NumberFormatter in
// Should always be NumberFormatter
return concurrentFormatterCache.cachedNumberFormatter.copy() as! NumberFormatter
}
return numberFormatter
}
public func cachedFormatter(_ format: String = DateFormatType.standard.stringFormat,
timeZone: Foundation.TimeZone = Foundation.TimeZone.current,
locale: Locale = Locale.current, isLenient: Bool = true) -> DateFormatter {
let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
if Date.cachedDateFormatters.retrieve(hashKey: hashKey) == nil {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = timeZone
formatter.locale = locale
formatter.isLenient = trisLenientue
Date.cachedDateFormatters.register(hashKey: hashKey, formatter: formatter)
}
return Date.cachedDateFormatters.retrieve(hashKey: hashKey)!
}
/// Generates a cached formatter based on the provided date style, time style and relative date.
/// Formatters are cached in a singleton array using hashkeys.
public func cachedFormatter(_ dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, doesRelativeDateFormatting: Bool, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current, isLenient: Bool = true) -> DateFormatter {
let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
if Date.cachedDateFormatters.retrieve(hashKey: hashKey) == nil {
let formatter = DateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
formatter.doesRelativeDateFormatting = doesRelativeDateFormatting
formatter.timeZone = timeZone
formatter.locale = locale
formatter.isLenient = isLenient
Date.cachedDateFormatters.register(hashKey: hashKey, formatter: formatter)
}
return Date.cachedDateFormatters.retrieve(hashKey: hashKey)!
}
public func cachedNumberFormatter() -> NumberFormatter {
return Date.cachedDateFormatters.retrieve()
}
}
/// A cached static array of DateFormatters so that thy are only created once.
private static var cachedDateFormatters = concurrentFormatterCache()
// MARK: Intervals In Seconds
internal static let minuteInSeconds:Double = 60
internal static let hourInSeconds:Double = 3600
internal static let dayInSeconds:Double = 86400
internal static let weekInSeconds:Double = 604800
internal static let yearInSeconds:Double = 31556926
}
// MARK: Enums used
/**
The string format used for date string conversion.
````
case isoYear: i.e. 1997
case isoYearMonth: i.e. 1997-07
case isoDate: i.e. 1997-07-16
case isoDateTime: i.e. 1997-07-16T19:20+01:00
case isoDateTimeSec: i.e. 1997-07-16T19:20:30+01:00
case isoDateTimeMilliSec: i.e. 1997-07-16T19:20:30.45+01:00
case dotNet: i.e. "/Date(1268123281843)/"
case rss: i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
case altRSS: i.e. "09 Sep 2011 15:26:08 +0200"
case httpHeader: i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
case standard: "EEE MMM dd HH:mm:ss Z yyyy"
case custom(String): a custom date format string
````
*/
public enum DateFormatType {
/// The ISO8601 formatted year "yyyy" i.e. 1997
case isoYear
/// The ISO8601 formatted year and month "yyyy-MM" i.e. 1997-07
case isoYearMonth
/// The ISO8601 formatted date "yyyy-MM-dd" i.e. 1997-07-16
case isoDate
/// The ISO8601 formatted date and time "yyyy-MM-dd'T'HH:mmZ" i.e. 1997-07-16T19:20+01:00
case isoDateTime
/// The ISO8601 formatted date, time and sec "yyyy-MM-dd'T'HH:mm:ssZ" i.e. 1997-07-16T19:20:30+01:00
case isoDateTimeSec
/// The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ss.SSSZ" i.e. 1997-07-16T19:20:30.45+01:00
case isoDateTimeMilliSec
/// The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/"
case dotNet
/// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
case rss
/// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200"
case altRSS
/// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
case httpHeader
/// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy"
case standard
/// A custom date format string
case custom(String)
var stringFormat:String {
switch self {
case .isoYear: return "yyyy"
case .isoYearMonth: return "yyyy-MM"
case .isoDate: return "yyyy-MM-dd"
case .isoDateTime: return "yyyy-MM-dd'T'HH:mmZ"
case .isoDateTimeSec: return "yyyy-MM-dd'T'HH:mm:ssZ"
case .isoDateTimeMilliSec: return "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
case .dotNet: return "/Date(%d%f)/"
case .rss: return "EEE, d MMM yyyy HH:mm:ss ZZZ"
case .altRSS: return "d MMM yyyy HH:mm:ss ZZZ"
case .httpHeader: return "EEE, dd MM yyyy HH:mm:ss ZZZ"
case .standard: return "EEE MMM dd HH:mm:ss Z yyyy"
case .custom(let customFormat): return customFormat
}
}
}
extension DateFormatType: Equatable {
public static func ==(lhs: DateFormatType, rhs: DateFormatType) -> Bool {
switch (lhs, rhs) {
case (.custom(let lhsString), .custom(let rhsString)):
return lhsString == rhsString
default:
return lhs == rhs
}
}
}
/// The time zone to be used for date conversion
public enum TimeZoneType {
case local, `default`, utc, custom(Int)
var timeZone:TimeZone {
switch self {
case .local: return NSTimeZone.local
case .default: return NSTimeZone.default
case .utc: return TimeZone(secondsFromGMT: 0)!
case let .custom(gmt): return TimeZone(secondsFromGMT: gmt)!
}
}
}
// The string keys to modify the strings in relative format
public enum RelativeTimeStringType {
case nowPast, nowFuture, secondsPast, secondsFuture, oneMinutePast, oneMinuteFuture, minutesPast, minutesFuture, oneHourPast, oneHourFuture, hoursPast, hoursFuture, oneDayPast, oneDayFuture, daysPast, daysFuture, oneWeekPast, oneWeekFuture, weeksPast, weeksFuture, oneMonthPast, oneMonthFuture, monthsPast, monthsFuture, oneYearPast, oneYearFuture, yearsPast, yearsFuture
}
// The type of comparison to do against today's date or with the suplied date.
public enum DateComparisonType {
// Days
/// Checks if date today.
case isToday
/// Checks if date is tomorrow.
case isTomorrow
/// Checks if date is yesterday.
case isYesterday
/// Compares date days
case isSameDay(as:Date)
// Weeks
/// Checks if date is in this week.
case isThisWeek
/// Checks if date is in next week.
case isNextWeek
/// Checks if date is in last week.
case isLastWeek
/// Compares date weeks
case isSameWeek(as:Date)
// Months
/// Checks if date is in this month.
case isThisMonth
/// Checks if date is in next month.
case isNextMonth
/// Checks if date is in last month.
case isLastMonth
/// Compares date months
case isSameMonth(as:Date)
// Years
/// Checks if date is in this year.
case isThisYear
/// Checks if date is in next year.
case isNextYear
/// Checks if date is in last year.
case isLastYear
/// Compare date years
case isSameYear(as:Date)
// Relative Time
/// Checks if it's a future date
case isInTheFuture
/// Checks if the date has passed
case isInThePast
/// Checks if earlier than date
case isEarlier(than:Date)
/// Checks if later than date
case isLater(than:Date)
/// Checks if it's a weekday
case isWeekday
/// Checks if it's a weekend
case isWeekend
}
// The date components available to be retrieved or modifed
public enum DateComponentType {
case second, minute, hour, day, weekday, nthWeekday, week, month, year
}
// The type of date that can be used for the dateFor function.
public enum DateForType {
case startOfDay, endOfDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, tomorrow, yesterday, nearestMinute(minute:Int), nearestHour(hour:Int)
}
// Convenience types for date to string conversion
public enum DateStyleType {
/// Short style: "2/27/17, 2:22 PM"
case short
/// Medium style: "Feb 27, 2017, 2:22:06 PM"
case medium
/// Long style: "February 27, 2017 at 2:22:06 PM EST"
case long
/// Full style: "Monday, February 27, 2017 at 2:22:06 PM Eastern Standard Time"
case full
/// Ordinal day: "27th"
case ordinalDay
/// Weekday: "Monday"
case weekday
/// Short week day: "Mon"
case shortWeekday
/// Very short weekday: "M"
case veryShortWeekday
/// Month: "February"
case month
/// Short month: "Feb"
case shortMonth
/// Very short month: "F"
case veryShortMonth
}
| 41.803774 | 375 | 0.589246 |
762d469f12b497d2f0b76eec1dea9189d9cc2aa3 | 3,794 | //
// SwiftFlowTests.swift
// SwiftFlowTests
//
// Created by John Holdsworth on 31/03/2015.
// Copyright (c) 2015 John Holdsworth. All rights reserved.
//
import UIKit
import XCTest
import SwiftFlow
class SwiftFlowTests: 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()
}
var user: String?
func fetchURL( _ repo: String ) -> String? {
if let url = URL( string: "https://github.com/\(unwrap(user))/\(repo)" ) {
do {
let string = try NSString( contentsOf: url, encoding: String.Encoding.utf8.rawValue )
return string as String
} catch let error as NSError {
_throw( NSException( name: NSExceptionName(rawValue: "fetchURL: Could not fetch"),
reason: error.localizedDescription, userInfo: nil ) )
}
} else {
_throw( NSException( name: NSExceptionName(rawValue: "fetchURL"), reason: "Invalid URL", userInfo: nil) )
}
return nil
}
func testExample() {
// This is an example of a functional test case.
var gotException = false
_try {
_ = self.fetchURL( "SwiftFlow" )
}
_catch {
(exception) in
gotException = true
}
XCTAssert(gotException, "Pass")
gotException = false
_try {
_ = unwrap(self.user)
}
_catch {
(exception) in
gotException = true
}
XCTAssert(gotException, "Pass")
user = "johnno1962"
gotException = false
_try {
_ = unwrap(self.user)
}
_catch {
(exception) in
gotException = true
}
XCTAssert(!gotException, "Pass")
gotException = false
_try {
_ = self.fetchURL( "Cabbage" )
}
_catch {
(exception) in
gotException = true
}
XCTAssert(gotException, "Pass")
gotException = false
_try {
_ = self.fetchURL( "SwiftFlow" )
}
_catch {
(exception) in
gotException = true
}
XCTAssert(!gotException, "Pass")
var exceuted = false
_synchronized( {
exceuted = true
} )
XCTAssert(exceuted, "Pass")
exceuted = false
_synchronized( self ) {
exceuted = true
}
XCTAssert(exceuted, "Pass")
var i = 0; //
{
print("Task #1")
for _ in 0 ..< 10000000 {
}
print("\(i)")
i += 1
} & {
print("Task #2")
for _ in 0 ..< 20000000 {
}
print("\(i)")
i += 1
} & {
print("Task #3")
for _ in 0 ..< 30000000 {
}
print("\(i)")
i += 1
} | {
print("Completed \(i)")
};
{
return 99
} | {
(result:Int) in
print("\(result)")
};
{
return 88
} & {
return 99
} | {
(results:[Int?]) in
print("\(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.
}
}
}
| 24.012658 | 117 | 0.468898 |
f40f220bfc104e26e9989e9fed84415aa2580f1e | 947 | // RUN: %target-swift-frontend %s -emit-ir -g -o %t.ll
// RUN: FileCheck %s < %t.ll
func markUsed<T>(_ t: T) {}
var puzzleOutput: [String] = []
// CHECK-NOT: !DILocalVariable(name: "$letter$generator"
// CHECK: !DILocalVariable(name: "letter",
// CHECK-SAME: line: [[@LINE+1]]
for letter in ["g", "r", "e", "a", "t"] {
switch letter {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput.append(letter)
}
}
markUsed(puzzleOutput)
func count() {
// CHECK-NOT: !DILocalVariable(name: "$i$generator"
// CHECK: !DILocalVariable(name: "i",
// CHECK-SAME: line: [[@LINE+1]]
for i in 0...100 {
markUsed(i)
}
}
count()
// End-to-end test:
// RUN: llc %t.ll -filetype=obj -o - | llvm-dwarfdump - | FileCheck %s --check-prefix DWARF-CHECK
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name {{.*}} "letter"
//
// DWARF-CHECK: DW_TAG_variable
// DWARF-CHECK: DW_AT_name {{.*}} "i"
| 24.921053 | 97 | 0.591341 |
f512317a735486357cee475669dddf685536da9a | 7,458 | import Basic
import Build
import Utility
import POSIX
enum DestinationError: Swift.Error {
/// Couldn't find the Xcode installation.
case invalidInstallation(String)
/// The schema version is invalid.
case invalidSchemaVersion
}
extension DestinationError: CustomStringConvertible {
var description: String {
switch self {
case .invalidSchemaVersion:
return "unsupported destination file schema version"
case .invalidInstallation(let problem):
return problem
}
}
}
/// The compilation destination, has information about everything that's required for a certain destination.
public struct Destination {
/// The clang/LLVM triple describing the target OS and architecture.
///
/// The triple has the general format <arch><sub>-<vendor>-<sys>-<abi>, where:
/// - arch = x86_64, i386, arm, thumb, mips, etc.
/// - sub = for ex. on ARM: v5, v6m, v7a, v7m, etc.
/// - vendor = pc, apple, nvidia, ibm, etc.
/// - sys = none, linux, win32, darwin, cuda, etc.
/// - abi = eabi, gnu, android, macho, elf, etc.
///
/// for more information see //https://clang.llvm.org/docs/CrossCompilation.html
public let target: String
/// The SDK used to compile for the destination.
public let sdk: AbsolutePath
/// The binDir in the containing the compilers/linker to be used for the compilation.
public let binDir: AbsolutePath
/// The file extension for dynamic libraries (eg. `.so` or `.dylib`)
public let dynamicLibraryExtension: String
/// Additional flags to be passed to the C compiler.
public let extraCCFlags: [String]
/// Additional flags to be passed to the Swift compiler.
public let extraSwiftCFlags: [String]
/// Additional flags to be passed when compiling with C++.
public let extraCPPFlags: [String]
/// Returns the bin directory for the host.
///
/// - Parameter originalWorkingDirectory: The working directory when the program was launched.
private static func hostBinDir(
originalWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory
) -> AbsolutePath {
#if Xcode
// For Xcode, set bin directory to the build directory containing the fake
// toolchain created during bootstraping. This is obviously not production ready
// and only exists as a development utility right now.
//
// This also means that we should have bootstrapped with the same Swift toolchain
// we're using inside Xcode otherwise we will not be able to load the runtime libraries.
//
// FIXME: We may want to allow overriding this using an env variable but that
// doesn't seem urgent or extremely useful as of now.
return AbsolutePath(#file).parentDirectory
.parentDirectory.parentDirectory.appending(components: ".build", hostTargetTriple, "debug")
#else
guard let cwd = originalWorkingDirectory else {
return try! AbsolutePath(validating: CommandLine.arguments[0]).parentDirectory
}
return AbsolutePath(CommandLine.arguments[0], relativeTo: cwd).parentDirectory
#endif
}
/// The destination describing the host OS.
public static func hostDestination(
_ binDir: AbsolutePath? = nil,
originalWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory,
environment: [String:String] = Process.env
) throws -> Destination {
// Select the correct binDir.
let binDir = binDir ?? Destination.hostBinDir(
originalWorkingDirectory: originalWorkingDirectory)
#if os(macOS)
// Get the SDK.
let sdkPath: AbsolutePath
if let value = lookupExecutablePath(filename: getenv("SYSROOT")) {
sdkPath = value
} else {
// No value in env, so search for it.
let sdkPathStr = try Process.checkNonZeroExit(
arguments: ["xcrun", "--sdk", "macosx", "--show-sdk-path"], environment: environment).spm_chomp()
guard !sdkPathStr.isEmpty else {
throw DestinationError.invalidInstallation("default SDK not found")
}
sdkPath = AbsolutePath(sdkPathStr)
}
// Compute common arguments for clang and swift.
// This is currently just frameworks path.
let commonArgs = Destination.sdkPlatformFrameworkPath(environment: environment).map({ ["-F", $0.asString] }) ?? []
return Destination(
target: hostTargetTriple,
sdk: sdkPath,
binDir: binDir,
dynamicLibraryExtension: "dylib",
extraCCFlags: ["-arch", "x86_64", "-mmacosx-version-min=10.10"] + commonArgs,
extraSwiftCFlags: commonArgs,
extraCPPFlags: ["-lc++"]
)
#else
return Destination(
target: hostTargetTriple,
sdk: .root,
binDir: binDir,
dynamicLibraryExtension: "so",
extraCCFlags: ["-fPIC"],
extraSwiftCFlags: [],
extraCPPFlags: ["-lstdc++"]
)
#endif
}
/// Returns macosx sdk platform framework path.
public static func sdkPlatformFrameworkPath(environment: [String:String] = Process.env) -> AbsolutePath? {
if let path = _sdkPlatformFrameworkPath {
return path
}
let platformPath = try? Process.checkNonZeroExit(
arguments: ["xcrun", "--sdk", "macosx", "--show-sdk-platform-path"], environment: environment).spm_chomp()
if let platformPath = platformPath, !platformPath.isEmpty {
_sdkPlatformFrameworkPath = AbsolutePath(platformPath).appending(
components: "Developer", "Library", "Frameworks")
}
return _sdkPlatformFrameworkPath
}
/// Cache storage for sdk platform path.
private static var _sdkPlatformFrameworkPath: AbsolutePath? = nil
/// Target triple for the host system.
private static let hostTargetTriple = Triple.hostTriple.tripleString
#if os(macOS)
/// Returns the host's dynamic library extension.
public static let hostDynamicLibraryExtension = "dylib"
#else
/// Returns the host's dynamic library extension.
public static let hostDynamicLibraryExtension = "so"
#endif
}
extension Destination {
/// Load a Destination description from a JSON representation from disk.
public init(fromFile path: AbsolutePath, fileSystem: FileSystem = localFileSystem) throws {
let json = try JSON(bytes: fileSystem.readFileContents(path))
try self.init(json: json)
}
}
extension Destination: JSONMappable {
/// The current schema version.
static let schemaVersion = 1
public init(json: JSON) throws {
// Check schema version.
guard try json.get("version") == Destination.schemaVersion else {
throw DestinationError.invalidSchemaVersion
}
try self.init(
target: json.get("target"),
sdk: AbsolutePath(json.get("sdk")),
binDir: AbsolutePath(json.get("toolchain-bin-dir")),
dynamicLibraryExtension: json.get("dynamic-library-extension"),
extraCCFlags: json.get("extra-cc-flags"),
extraSwiftCFlags: json.get("extra-swiftc-flags"),
extraCPPFlags: json.get("extra-cpp-flags")
)
}
}
| 38.05102 | 122 | 0.647895 |
d6de5b1831b9848763198f38e7251a78c47306c0 | 828 | //
// CheesePizza.swift
//
//
// Created by Bastiรกn Vรฉliz Vega on 15-07-20.
//
import Foundation
class CheesePizza: PizzaWithIngredients {
var name: String
var dough: Dough?
var sauce: Sauce?
var veggies: [Veggies] = []
var cheese: Cheese?
var pepperoni: Pepperoni?
var clam: Clams?
var isReady: Bool = false
var ingredientsFactory: PizzaIngredientFactory
init(name: String, ingredientsFactory: PizzaIngredientFactory) {
self.name = name
self.ingredientsFactory = ingredientsFactory
}
func prepare() {
print("Preparing \(self.name)")
self.dough = self.ingredientsFactory.createDough()
self.sauce = self.ingredientsFactory.createSauce()
self.cheese = self.ingredientsFactory.createCheese()
self.isReady = true
}
}
| 23.657143 | 68 | 0.663043 |
0ef741eff7b4ef92b0570ef98e60b4d58bd67980 | 832 | //
// GreetingViewController.swift
// MVCpattern
//
// Created by Carlos Santiago Cruz on 25/10/18.
// Copyright ยฉ 2018 Carlos Santiago Cruz. All rights reserved.
//
import UIKit
class GreetingViewController: UIViewController {
var person: Person!
let showGreetingButton = UIButton()
let greetingLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.showGreetingButton.addTarget(self, action: Selector(("didTapButton")), for: .touchUpOutside)
let model = Person(firstName: "Carlos", lastName: "Santiago")
let view = GreetingViewController()
view.person = model
}
func didTapButton(button: UIButton) {
let greeting = "hello" + " " + self.person.firstName + " " + self.person.lastName
self.greetingLabel.text = greeting
}
}
| 29.714286 | 105 | 0.671875 |
bf3f834b3f6ef89c7b3ff18fd89b824dbc9a542f | 264 | //
// DinoRow.swift
// DinoBasic WatchKit Extension
//
// Created by Mario Esposito on 9/29/19.
// Copyright ยฉ 2019 The Garage Innovation. All rights reserved.
//
import WatchKit
class DinoRow: NSObject {
@IBOutlet weak var dinoName: WKInterfaceLabel!
}
| 18.857143 | 64 | 0.715909 |
9b44a36a501c21d918aec5cbace399b1ae1d9114 | 710 | //
// LoginViewController.swift
// #github-ios
//
// Created by Artur on 05/04/2017.
// Copyright ยฉ 2017 Artur Matusiak. All rights reserved.
//
import Foundation
import UIKit
class LoginViewController: UIViewController {
private var presenter: LoginPresentable!
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
self.presenter = LoginPresenter(view: self)
self.presenter.updateView()
self.initWebView()
}
private func initWebView() {
self.webView.loadRequest(URLRequest(url: URL(string: "https://github.com/login/oauth/authorize?client_id=\(GithubConfig.CLIENT_ID)")!));
}
}
| 21.515152 | 144 | 0.64507 |
d6032a13ad801fe12b23c2bc14e6236bf885bef6 | 3,132 | //
// FileParserTests.swift
// SaberTests
//
// Created by Andrew Pleshkov on 29/05/2018.
//
import XCTest
@testable import Saber
class FileParserTests: XCTestCase {
func testNestedDecls() {
let factory = ParsedDataFactory()
try! FileParser(contents:
"""
extension Foo {
typealias FooInt = Int
extension Bar {
// @saber.inject
func set() {}
}
}
extension Foo.Bar.Baz {
// @saber.inject
func set() {}
typealias BazInt = Int
}
"""
).parse(to: factory)
try! FileParser(contents:
"""
struct Foo {
struct Bar {
// @saber.cached
struct Baz {}
typealias BarInt = Int
}
}
"""
).parse(to: factory)
let data = factory.make()
XCTAssertEqual(data.types.count, 3)
XCTAssertEqual(
data.type(name: "Foo")?.name,
"Foo"
)
XCTAssertEqual(
data.ext(typeName: "Foo.Bar")?.methods,
[ParsedMethod(name: "set", annotations: [.inject])]
)
XCTAssertEqual(
data.type(name: "Foo.Bar.Baz")?.annotations,
[.cached]
)
XCTAssertEqual(
data.ext(typeName: "Foo.Bar.Baz")?.methods,
[ParsedMethod(name: "set", annotations: [.inject])]
)
XCTAssertEqual(
data.alias(name: "Foo.FooInt")?.type,
ParsedTypeUsage(name: "Int")
)
XCTAssertEqual(
data.alias(name: "Foo.Bar.BarInt")?.type,
ParsedTypeUsage(name: "Int")
)
XCTAssertEqual(
data.alias(name: "Foo.Bar.Baz.BazInt")?.type,
ParsedTypeUsage(name: "Int")
)
}
func testModuleName() {
let factory = ParsedDataFactory()
try! FileParser(contents:
"""
class Foo {}
typealias Bar = Foo
extension Foo {}
""", moduleName: "A"
).parse(to: factory)
let data = factory.make()
XCTAssertEqual(
data.type(name: "Foo")?.moduleName,
"A"
)
XCTAssertEqual(
data.alias(name: "Bar")?.moduleName,
"A"
)
XCTAssertEqual(
data.ext(typeName: "Foo")?.moduleName,
"A"
)
}
func testContainer() {
let factory = ParsedDataFactory()
try! FileParser(contents:
"""
// @saber.container(Foo)
// @saber.scope(Singleton)
protocol FooConfig {}
""", moduleName: "A"
).parse(to: factory)
let data = factory.make()
XCTAssertEqual(
data.containers["Foo"]?.scopeName,
"Singleton"
)
XCTAssertEqual(
data.containers["Foo"]?.moduleName,
"A"
)
}
}
| 25.884298 | 63 | 0.453065 |
39390fd06d35102d5aa8eda76f74ae263f7b6365 | 6,781 | //
// DiskCache.swift
// DiskCache
//
// Created by Julian Grosshauser on 27/06/15.
// Copyright ยฉ 2015 Julian Grosshauser. All rights reserved.
//
/**
Caches data on disk asynchronously
*/
public class DiskCache {
//MARK: Properties
private let fileManager = NSFileManager()
private let ioQueue: dispatch_queue_t
/**
Data will be cached at this path, e.g. `Library/Caches/com.domain.App.DiskCache`
*/
public let path: String
//MARK: Initialization
public init(identifier: String) {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
let cachePath = paths.first!
// use "DiskCache" as `bundleIdentifier` iff `mainBundle()`s `bundleIdentifier` is `nil`
let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier ?? "DiskCache"
let cacheIdentifier = "\(bundleIdentifier).\(identifier)"
path = cachePath.stringByAppendingPathComponent(cacheIdentifier)
let ioQueueLabel = "\(cacheIdentifier).queue"
ioQueue = dispatch_queue_create(ioQueueLabel, DISPATCH_QUEUE_SERIAL)
}
public convenience init() {
self.init(identifier: "DiskCache")
}
//MARK: Cache data
/**
Cache data asynchronously
- Parameter data: Data to cache
- Parameter forKey: Key for data
- Parameter completionHandler: Called on main thread after data is cached
- Throws: `DiskCacheError.EmptyKey` if `key` parameter is empty.
- Warning: Doesn't throw when error happens asynchronously. Check `.Success` or `.Failure` in `Result` parameter of `completionHandler` instead.
*/
public func cacheData(data: NSData, forKey key: String, completionHandler: (Result<Void> -> Void)?) throws {
if key.isEmpty {
throw DiskCacheError.EmptyKey
}
dispatch_async(ioQueue) {
if !self.fileManager.fileExistsAtPath(self.path) {
do {
try self.fileManager.createDirectoryAtPath(self.path, withIntermediateDirectories: true, attributes: nil)
} catch {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Failure(error))
return
}
}
}
let filePath = self.path.stringByAppendingPathComponent(key)
if self.fileManager.createFileAtPath(filePath, contents: data, attributes: nil) {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Success())
}
} else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Failure(DiskCacheError.WriteError))
}
}
}
}
//MARK: Retrieve data
/**
Retrieve data asynchronously
- Parameter key: Key for data
- Parameter completionHandler: Called on main thread with retrieved data or error as parameter
- Throws: `DiskCacheError.EmptyKey` if `key` parameter is empty.
- Warning: Doesn't throw when error happens asynchronously. Check `.Success` or `.Failure` in `Result` parameter of `completionHandler` instead.
*/
public func retrieveDataForKey(key: String, completionHandler: Result<NSData> -> Void) throws {
if key.isEmpty {
throw DiskCacheError.EmptyKey
}
dispatch_async(ioQueue) {
let filePath = self.path.stringByAppendingPathComponent(key)
if !self.fileManager.fileExistsAtPath(filePath) {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(.Failure(DiskCacheError.CacheMiss))
}
} else {
if let data = NSData(contentsOfFile: filePath) {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(.Success(data))
}
} else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(.Failure(DiskCacheError.ReadError))
}
}
}
}
}
//MARK: Remove data
/**
Remove all cached data asynchronously
- Parameter completionHandler: Called on main thread after all cached data got removed
- Note: `Result` parameter of `completionHandler` contains `.Success` or `.Failure`
*/
public func removeAllData(completionHandler completionHandler: (Result<Void> -> Void)?) {
dispatch_async(ioQueue) {
// if path doesn't exist we can exit early with success
if !self.fileManager.fileExistsAtPath(self.path) {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Success())
}
} else {
do {
try self.fileManager.removeItemAtPath(self.path)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Success())
}
} catch {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Failure(error))
}
}
}
}
}
/**
Remove cached data for key asynchronously
- Parameter key: Key for data
- Parameter completionHandler: Called on main thread after cached data got removed
- Throws: `DiskCacheError.EmptyKey` if `key` parameter is empty.
- Warning: Doesn't throw when error happens asynchronously. Check `.Success` or `.Failure` in `Result` parameter of `completionHandler` instead.
*/
public func removeDataForKey(key: String, completionHandler: (Result<Void> -> Void)?) throws {
if key.isEmpty {
throw DiskCacheError.EmptyKey
}
dispatch_async(ioQueue) {
let filePath = self.path.stringByAppendingPathComponent(key)
// if file doesn't exist we can exit early with success
if !self.fileManager.fileExistsAtPath(filePath) {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Success())
}
} else {
do {
try self.fileManager.removeItemAtPath(filePath)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Success())
}
} catch {
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(.Failure(error))
}
}
}
}
}
}
| 34.42132 | 148 | 0.58428 |
21c492bb9d8b08042c633967b0f47aaf993c2df1 | 7,602 | /*
* Copyright (c) 2017 Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import UIKit
import PSPDFKitUI
struct Preferences {
static var userDefaults: UserDefaults {
return PreferencesShared.userDefaults
}
static func migrateUserDefaultsToAppGroups() {
let userDefaults = UserDefaults.standard
let groupDefaults = UserDefaults(suiteName: Constants.DefaultKey.appGroupName)
if let groupDefaults = groupDefaults {
if !groupDefaults.bool(forKey: Constants.DefaultKey.migrationToAppGroups) {
for (key, value) in userDefaults.dictionaryRepresentation() {
groupDefaults.set(value, forKey: key)
}
groupDefaults.set(true, forKey: Constants.DefaultKey.migrationToAppGroups)
groupDefaults.synchronize()
print("Successfully migrated defaults")
} else {
print("No need to migrate defaults")
}
} else {
print("Unable to create NSUserDefaults with given app group")
}
}
static func currentLanguage() -> QuarterlyLanguage {
return PreferencesShared.currentLanguage()
}
static func currentQuarterly() -> String {
return PreferencesShared.currentQuarterly()
}
static func currentTheme() -> ReaderStyle.Theme {
guard let rawTheme = Preferences.userDefaults.string(forKey: Constants.DefaultKey.readingOptionsTheme),
let theme = ReaderStyle.Theme(rawValue: rawTheme) else {
if Preferences.getSettingsTheme() == Theme.Dark.rawValue {
return .dark
}
return .light
}
return theme
}
static func currentTypeface() -> ReaderStyle.Typeface {
guard let rawTypeface = Preferences.userDefaults.string(forKey: Constants.DefaultKey.readingOptionsTypeface),
let typeface = ReaderStyle.Typeface(rawValue: rawTypeface) else {
return .lato
}
return typeface
}
static func currentSize() -> ReaderStyle.Size {
guard let rawSize = Preferences.userDefaults.string(forKey: Constants.DefaultKey.readingOptionsSize),
let size = ReaderStyle.Size(rawValue: rawSize) else {
return .medium
}
return size
}
static func reminderStatus() -> Bool {
return Preferences.userDefaults.bool(forKey: Constants.DefaultKey.settingsReminderStatus)
}
static func reminderTime() -> String {
guard let time = Preferences.userDefaults.string(forKey: Constants.DefaultKey.settingsReminderTime) else {
return Constants.DefaultKey.settingsDefaultReminderTime
}
return time
}
static func latestReaderBundleTimestamp() -> String {
guard let timestamp = Preferences.userDefaults.string(forKey: Constants.DefaultKey.latestReaderBundleTimestamp) else {
return ""
}
return timestamp
}
static func getSettingsTheme() -> String {
guard let theme = Preferences.userDefaults.string(forKey: Constants.DefaultKey.settingsTheme) else {
if #available(iOS 13.0, *) {
if UITraitCollection.current.userInterfaceStyle == .dark {
return Theme.Dark.rawValue
}
}
return Theme.Light.rawValue
}
return theme
}
static func gcPopupStatus() -> Bool {
return Preferences.userDefaults.bool(forKey: Constants.DefaultKey.gcPopup)
}
static func getPreferredBibleVersionKey() -> String {
return Constants.DefaultKey.preferredBibleVersion + Preferences.currentLanguage().code
}
static func getPdfPageTransition() -> PageTransition {
let exists = Preferences.userDefaults.object(forKey: Constants.DefaultKey.pdfConfigurationPageTransition) != nil
let pageTransition = Preferences.userDefaults.integer(forKey: Constants.DefaultKey.pdfConfigurationPageTransition)
return exists ? PageTransition(rawValue: UInt(pageTransition))! : PageTransition.scrollContinuous
}
static func getPdfPageMode() -> PageMode {
let exists = Preferences.userDefaults.object(forKey: Constants.DefaultKey.pdfConfigurationPageMode) != nil
let pageMode = Preferences.userDefaults.integer(forKey: Constants.DefaultKey.pdfConfigurationPageMode)
return exists ? PageMode(rawValue: UInt(pageMode))! : PageMode.single
}
static func getPdfScrollDirection() -> ScrollDirection {
let exists = Preferences.userDefaults.object(forKey: Constants.DefaultKey.pdfConfigurationScrollDirection) != nil
let scrollDirection = Preferences.userDefaults.integer(forKey: Constants.DefaultKey.pdfConfigurationScrollDirection)
return exists ? ScrollDirection(rawValue: UInt(scrollDirection))! : ScrollDirection.vertical
}
static func getPdfSpreadFitting() -> PDFConfiguration.SpreadFitting {
let exists = Preferences.userDefaults.object(forKey: Constants.DefaultKey.pdfConfigurationSpreadFitting) != nil
let spreadFitting = Preferences.userDefaults.integer(forKey: Constants.DefaultKey.pdfConfigurationSpreadFitting)
return exists ? PDFConfiguration.SpreadFitting(rawValue: spreadFitting)! : PDFConfiguration.SpreadFitting.fit
}
static func saveQuarterlyGroup(quarterlyGroup: QuarterlyGroup) -> Void {
var existingGroups = Preferences.getQuarterlyGroups()
if let index = existingGroups.firstIndex(where: { $0.name == quarterlyGroup.name }) {
existingGroups.remove(at: index)
}
existingGroups.insert(quarterlyGroup, at: 0)
do {
let dictionary = try JSONEncoder().encode(existingGroups)
Preferences.userDefaults.set(dictionary, forKey: "\(Constants.DefaultKey.quarterlyGroups)\(currentLanguage().code)")
} catch {
return
}
}
static func getQuarterlyGroups() -> [QuarterlyGroup] {
if let quarterliesGroupData = Preferences.userDefaults.value(forKey: "\(Constants.DefaultKey.quarterlyGroups)\(currentLanguage().code)") as? Data {
do {
let quarterliesGroup: [QuarterlyGroup] = try JSONDecoder().decode(Array<QuarterlyGroup>.self, from: quarterliesGroupData)
return quarterliesGroup
} catch {}
}
return []
}
}
| 42.949153 | 155 | 0.679558 |
ff555663c56c4a97807db479745bca9d239c2b19 | 4,184 | import Foundation
import azureSwiftRuntime
public protocol ExpressRouteCircuitAuthorizationsCreateOrUpdate {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var circuitName : String { get set }
var authorizationName : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
var authorizationParameters : ExpressRouteCircuitAuthorizationProtocol? { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (ExpressRouteCircuitAuthorizationProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.ExpressRouteCircuitAuthorizations {
// CreateOrUpdate creates or updates an authorization in the specified express route circuit. This method may poll for
// completion. Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel
// polling and any outstanding HTTP requests.
internal class CreateOrUpdateCommand : BaseCommand, ExpressRouteCircuitAuthorizationsCreateOrUpdate {
public var resourceGroupName : String
public var circuitName : String
public var authorizationName : String
public var subscriptionId : String
public var apiVersion = "2018-01-01"
public var authorizationParameters : ExpressRouteCircuitAuthorizationProtocol?
public init(resourceGroupName: String, circuitName: String, authorizationName: String, subscriptionId: String, authorizationParameters: ExpressRouteCircuitAuthorizationProtocol) {
self.resourceGroupName = resourceGroupName
self.circuitName = circuitName
self.authorizationName = authorizationName
self.subscriptionId = subscriptionId
self.authorizationParameters = authorizationParameters
super.init()
self.method = "Put"
self.isLongRunningOperation = true
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{circuitName}"] = String(describing: self.circuitName)
self.pathParameters["{authorizationName}"] = String(describing: self.authorizationName)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
self.body = authorizationParameters
}
public override func encodeBody() throws -> Data? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let encoder = try CoderFactory.encoder(for: mimeType)
let encodedValue = try encoder.encode(authorizationParameters as? ExpressRouteCircuitAuthorizationData)
return encodedValue
}
throw DecodeError.unknownMimeType
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(ExpressRouteCircuitAuthorizationData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (ExpressRouteCircuitAuthorizationProtocol?, Error?) -> Void) -> Void {
client.executeAsyncLRO(command: self) {
(result: ExpressRouteCircuitAuthorizationData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 54.337662 | 191 | 0.679015 |
5d7455da9b86b955e41de0201085b7ad73446d30 | 887 | //
// CSVComponents.swift
// AgileLife
//
// Created by Ahri on 6/24/18.
// Copyright ยฉ 2018 TeaBee. All rights reserved.
//
import Foundation
enum CsvRow: Int, CustomStringConvertible {
case question = 0
case type = 1
case firstAnswerOpt = 2
case lastAnswerOpt = 7
case correctResponse = 8
case explanation = 9
var description: String {
return String(self.rawValue)
}
}
enum QuestionType: Int {
case multiChoice = 0,
multiSelect
}
struct Alphabet {
fileprivate static let all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static func from(index: Int) -> String {
guard index >= 0, index < Alphabet.all.count else {
return ""
}
let indexInAlphabet = Alphabet.all.index(Alphabet.all.startIndex, offsetBy: index)
return String(Alphabet.all[indexInAlphabet])
}
}
| 20.159091 | 90 | 0.630214 |
d5fb5ce4222a706d23f68c5038fa32c2d8ef2e01 | 1,196 | import UIKit
/// Conform to this protocol to control editing of table view cells.
///
/// The two methods correspond to the similarly named ones in `UITableViewDataSource`.
///
/// Implementation note: We avoid using the exact same method names as in `UITableViewDataSource`.
/// Doing so will confuse the Swift compiler when using a `UITableViewController` as the
/// editing delegate, since it already conforms to `UITableViewDataSource`, but the method
/// implementations in Swift might not match the @objc requirements of that protocol.
///
/// Set the `editingDelegate` property of your `TableViewDataSource` to control editing.
public protocol TableViewEditingDelegate: class {
func editing(tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
func editing(tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
}
extension TableViewEditingDelegate {
/// Default implementation. An editing delegate can choose to omit this method in the common
/// case where every item can be edited.
public func editing(tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
| 46 | 121 | 0.767559 |
67ff140ce052ae328ada12792b4aebbfa70f8b46 | 2,836 | //
// TextTapManager.swift
// Pods-SLEssentials_Tests
//
// Created by Vukasin on 07/09/2020.
//
import Foundation
public final class TextTapManager {
// MARK: - Properties
public var textTapHandler: ((NSAttributedString?) -> ())?
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: .zero)
var textStorage: NSTextStorage?
var attributedText: NSAttributedString?
// MARK: - Init
public init() {}
// MARK: - Public methods
public func setup(for label: UILabel, with attributedText: NSAttributedString) {
self.attributedText = attributedText
setupLayoutManager()
setupTextStorage(for: attributedText)
setupTextContainer(for: label)
setupTapGestureRecognizer(for: label)
}
// MARK: - Actions
@objc
func handleLabelTap(_ recognizer: UITapGestureRecognizer) {
guard let label = recognizer.view else { return }
let labelSize = label.bounds.size
textContainer.size = labelSize
let locationOfTouchInLabel = recognizer.location(in: label)
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x,
y: locationOfTouchInLabel.y - textContainerOffset.y)
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer,
in: textContainer,
fractionOfDistanceBetweenInsertionPoints: nil)
textChunk(at: indexOfCharacter, completion: textTapHandler)
}
// MARK: - Private methods
func setupLayoutManager() {
layoutManager.addTextContainer(textContainer)
}
func setupTextStorage(for attributedText: NSAttributedString) {
textStorage = NSTextStorage(attributedString: attributedText)
textStorage?.addLayoutManager(layoutManager)
}
func setupTextContainer(for label: UILabel) {
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
}
func setupTapGestureRecognizer(for label: UILabel) {
label.isUserInteractionEnabled = true
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleLabelTap(_:))))
}
func textChunk(at index: Int, completion: ((NSAttributedString?) -> ())?) {
guard let attributedText = attributedText else {
completion?(nil)
return
}
attributedText.enumerateAttributes(in: NSRange(location: 0, length: attributedText.length), options: []) { _, range, _ in
guard NSLocationInRange(index, range) else { return }
completion?(attributedText.attributedSubstring(from: range))
}
}
}
| 32.976744 | 123 | 0.752468 |
46444d94ca1a510cf67bec662036bd6a12e7858d | 6,085 | //
// RulesCommand.swift
// SwiftLint
//
// Created by Chris Eidhof on 20/05/15.
// Copyright ยฉ 2015 Realm. All rights reserved.
//
import Commandant
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Result
import SwiftLintFramework
import SwiftyTextTable
private func print(ruleDescription desc: RuleDescription) {
print("\(desc.consoleDescription)")
if !desc.triggeringExamples.isEmpty {
func indent(_ string: String) -> String {
return string.components(separatedBy: "\n")
.map { " \($0)" }
.joined(separator: "\n")
}
print("\nTriggering Examples (violation is marked with 'โ'):")
for (index, example) in desc.triggeringExamples.enumerated() {
print("\nExample #\(index + 1)\n\n\(indent(example))")
}
}
}
struct RulesCommand: CommandProtocol {
let verb = "rules"
let function = "Display the list of rules and their identifiers"
func run(_ options: RulesOptions) -> Result<(), CommandantError<()>> {
if let ruleID = options.ruleID {
guard let rule = masterRuleList.list[ruleID] else {
return .failure(.usageError(description: "No rule with identifier: \(ruleID)"))
}
print(ruleDescription: rule.description)
return .success(())
}
if options.onlyDisabledRules && options.onlyEnabledRules {
return .failure(.usageError(description: "You can't use --disabled and --enabled at the same time."))
}
let configuration = Configuration(options: options)
let rules = ruleList(for: options, configuration: configuration)
print(TextTable(ruleList: rules, configuration: configuration).render())
return .success(())
}
private func ruleList(for options: RulesOptions, configuration: Configuration) -> RuleList {
guard options.onlyEnabledRules || options.onlyDisabledRules else {
return masterRuleList
}
let filtered: [Rule.Type] = masterRuleList.list.compactMap { ruleID, ruleType in
let configuredRule = configuration.rules.first { rule in
return type(of: rule).description.identifier == ruleID
}
if options.onlyEnabledRules && configuredRule == nil {
return nil
} else if options.onlyDisabledRules && configuredRule != nil {
return nil
}
return ruleType
}
return RuleList(rules: filtered)
}
}
struct RulesOptions: OptionsProtocol {
fileprivate let ruleID: String?
let configurationFile: String
fileprivate let onlyEnabledRules: Bool
fileprivate let onlyDisabledRules: Bool
// swiftlint:disable line_length
static func create(_ configurationFile: String) -> (_ ruleID: String) -> (_ onlyEnabledRules: Bool) -> (_ onlyDisabledRules: Bool) -> RulesOptions {
return { ruleID in { onlyEnabledRules in { onlyDisabledRules in
self.init(ruleID: (ruleID.isEmpty ? nil : ruleID),
configurationFile: configurationFile,
onlyEnabledRules: onlyEnabledRules,
onlyDisabledRules: onlyDisabledRules)
}}}
}
static func evaluate(_ mode: CommandMode) -> Result<RulesOptions, CommandantError<CommandantError<()>>> {
return create
<*> mode <| configOption
<*> mode <| Argument(defaultValue: "",
usage: "the rule identifier to display description for")
<*> mode <| Switch(flag: "e",
key: "enabled",
usage: "only display enabled rules")
<*> mode <| Switch(flag: "d",
key: "disabled",
usage: "only display disabled rules")
}
}
// MARK: - SwiftyTextTable
extension TextTable {
init(ruleList: RuleList, configuration: Configuration) {
let columns = [
TextTableColumn(header: "identifier"),
TextTableColumn(header: "opt-in"),
TextTableColumn(header: "correctable"),
TextTableColumn(header: "enabled in your config"),
TextTableColumn(header: "kind"),
TextTableColumn(header: "configuration")
]
self.init(columns: columns)
let sortedRules = ruleList.list.sorted { $0.0 < $1.0 }
func truncate(_ string: String) -> String {
let stringWithNoNewlines = string.replacingOccurrences(of: "\n", with: "\\n")
let minWidth = "configuration".count - "...".count
let configurationStartColumn = 112
let truncatedEndIndex = stringWithNoNewlines.index(
stringWithNoNewlines.startIndex,
offsetBy: max(minWidth, Terminal.currentWidth() - configurationStartColumn),
limitedBy: stringWithNoNewlines.endIndex
)
if let truncatedEndIndex = truncatedEndIndex {
return stringWithNoNewlines[..<truncatedEndIndex] + "..."
}
return stringWithNoNewlines
}
for (ruleID, ruleType) in sortedRules {
let rule = ruleType.init()
let configuredRule = configuration.rules.first { rule in
return type(of: rule).description.identifier == ruleID
}
addRow(values: [
ruleID,
(rule is OptInRule) ? "yes" : "no",
(rule is CorrectableRule) ? "yes" : "no",
configuredRule != nil ? "yes" : "no",
ruleType.description.kind.rawValue,
truncate((configuredRule ?? rule).configurationDescription)
])
}
}
}
struct Terminal {
static func currentWidth() -> Int {
var size = winsize()
#if os(Linux)
_ = ioctl(CInt(STDOUT_FILENO), UInt(TIOCGWINSZ), &size)
#else
_ = ioctl(STDOUT_FILENO, TIOCGWINSZ, &size)
#endif
return Int(size.ws_col)
}
}
| 36.005917 | 152 | 0.589318 |
f5efff6a6cca7b5a94b38e81f1b4f95ba6f1b290 | 1,776 | //
// Data+Extension.swift
// Carrots
//
// Copyright (c) 2021 Tiago Henriques
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public extension Data {
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
var logDescription: String {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]) else { return "" }
return String(data: data, encoding: .utf8).map {
$0.components(separatedBy: .newlines)
.filter { !$0.isEmpty }
.map { " \($0)" }
.joined(separator: "\n")
} ?? ""
}
}
| 42.285714 | 135 | 0.690315 |
891703c87741afff95f4378aac62a36b311e9c8f | 3,795 | // Copyright (c) 2022 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import SwiftUI
struct TabNavView<
LibraryView: View,
DownloadsView: View,
MyTutorialsView: View,
SettingsView: View
> {
init(
libraryView: @escaping () -> LibraryView,
myTutorialsView: @escaping () -> MyTutorialsView,
downloadsView: @escaping () -> DownloadsView,
settingsView: @escaping () -> SettingsView
) {
self.libraryView = libraryView
self.myTutorialsView = myTutorialsView
self.downloadsView = downloadsView
self.settingsView = settingsView
}
@EnvironmentObject private var model: TabViewModel
@EnvironmentObject private var settingsManager: SettingsManager
private let libraryView: () -> LibraryView
private let myTutorialsView: () -> MyTutorialsView
private let downloadsView: () -> DownloadsView
private let settingsView: () -> SettingsView
}
// MARK: - View
extension TabNavView: View {
var body: some View {
TabView(selection: $model.selectedTab) {
tab(
content: libraryView,
text: .library,
imageName: "library",
tag: .library
)
tab(
content: downloadsView,
text: .downloads,
imageName: "downloadTabInactive",
tag: .downloads
)
tab(
content: myTutorialsView,
text: .myTutorials,
imageName: "myTutorials",
tag: .myTutorials
)
tab(
content: settingsView,
text: .settings,
imageName: "settings",
tag: .settings
)
}
.accentColor(.accent)
}
}
private func tab<Content: View>(
content: () -> Content,
text: String,
imageName: String,
tag: MainTab
) -> some View {
NavigationView(content: content)
.tabItem {
Text(text)
Image(imageName)
}
.tag(tag)
.navigationViewStyle(StackNavigationViewStyle())
.accessibility(label: .init(text))
}
struct TabNavView_Previews: PreviewProvider {
static var previews: some View {
TabNavView(
libraryView: { Text("LIBRARY") },
myTutorialsView: { Text("MY TUTORIALS") },
downloadsView: { Text("DOWNLOADS") },
settingsView: { Text("SETTINGS") }
).environmentObject(TabViewModel())
}
}
| 31.625 | 82 | 0.695652 |
69cbc4102f789459e9f140ef5b75ee59200f52a9 | 262 | //
// TextBarUpdateDelegate.swift
// kayako-messenger-SDK
//
// Created by Robin Malhotra on 08/03/17.
// Copyright ยฉ 2017 Robin Malhotra. All rights reserved.
//
public protocol TextBarUpdateDelegate: class {
func disableTextBar()
func enableTextBar()
}
| 20.153846 | 57 | 0.732824 |
7a28d1ad9a845d89d5827dbda63efc64f6005089 | 227 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import Foundation
protocol SearchTopicsViewOutput: class {
}
| 20.636364 | 91 | 0.753304 |
14f8b6f457108621b58cee725466092244825ddd | 4,854 | //
// MainDataSource.swift
// Uther
//
// Created by why on 7/30/15.
// Copyright (c) 2015 callmewhy. All rights reserved.
//
import UIKit
import SwiftDate
import SwiftHEXColors
import JSQMessagesViewController
class MainDataSource: NSObject {
fileprivate var messages:[Message] = []
func loadFromDatabase() -> Int {
let offset = messages.count
messages = DB.getReverseMessages(offset, limit: 3).reversed() + messages
return messages.count - offset
}
func addTextMessage(_ text:String, saved:([Message])->(), received:@escaping (EventType)->()) {
let message = TextMessage(text: text)
message.saveToDatabase()
messages.append(message)
saved(messages)
Uther.handleMessage(text, completion: { e in
switch e {
case let .emoji(p):
message.positive = p
message.saveToDatabase()
default:
break
}
received(e)
})
}
func removeMessageAtIndex(_ i: Int) -> Message? {
if i >= 0 && i < messages.count {
return messages.remove(at: i)
}
return nil
}
}
// MARK: - UICollectionViewDataSource
extension MainDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionView = collectionView as! JSQMessagesCollectionView
let dataSource = collectionView.dataSource!
let message = dataSource.collectionView(collectionView, messageDataForItemAt: indexPath)
// cell
let identifier: String = JSQMessagesCollectionViewCellOutgoing.cellReuseIdentifier()
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! JSQMessagesCollectionViewCell
cell.delegate = collectionView
cell.backgroundColor = UIColor.clear
// label
cell.cellTopLabel!.attributedText = dataSource.collectionView?(collectionView, attributedTextForCellTopLabelAt: indexPath)
cell.messageBubbleTopLabel!.attributedText = dataSource.collectionView?(collectionView, attributedTextForMessageBubbleTopLabelAt: indexPath)
cell.cellBottomLabel!.attributedText = dataSource.collectionView?(collectionView, attributedTextForCellBottomLabelAt: indexPath)
// text
cell.textView!.text = message?.text!()
cell.textView!.textColor = UIColor(hexString: "#F5F5F5")!
cell.textView!.isUserInteractionEnabled = false
// bubble image
if let bubbleDataSource = dataSource.collectionView(collectionView, messageBubbleImageDataForItemAt: indexPath) {
cell.messageBubbleImageView!.image = bubbleDataSource.messageBubbleImage()
cell.messageBubbleImageView!.highlightedImage = bubbleDataSource.messageBubbleHighlightedImage()
}
return cell
}
}
// MARK: - JSQMessagesCollectionViewDataSource
extension MainDataSource: JSQMessagesCollectionViewDataSource {
public func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
public func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let factory = JSQMessagesBubbleImageFactory()
return factory!.outgoingMessagesBubbleImage(with: UIColor(white: 1, alpha: 0.2))
}
public func senderDisplayName() -> String! {
return ""
}
public func senderId() -> String! {
return "ME"
}
public func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return messages[indexPath.row]
}
public func collectionView(_ collectionView: JSQMessagesCollectionView!, didDeleteMessageAt indexPath: IndexPath!) {
}
public func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAt indexPath: IndexPath!) -> NSAttributedString! {
let message = messages[indexPath.row]
let attributes = [ NSForegroundColorAttributeName: UIColor(hexString: "#F5F5F5")!.withAlphaComponent(0.5) ]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from: message.date)
let time = NSAttributedString(string: dateString, attributes: attributes)
return time
}
}
| 39.463415 | 169 | 0.692213 |
fb2ee5c99fefc0e386f5dfa5a013d9640085ac2d | 267 | //
// NibLoadingError.swift
// Tangram
//
// Created by Jordan Kay on 4/16/19.
// Copyright ยฉ 2019 CultivR. All rights reserved.
//
enum NibError {
case notFound
case contentsInvalid
case invalidVariantName
}
// MARK: -
extension NibError: Error {}
| 15.705882 | 50 | 0.674157 |
149105814e05eccd937e90be31889141ac1acb1f | 162 | //
// LiveNewsDetailInterector.swift
// TextureBase
//
// Created by midland on 2019/1/3.
// Copyright ยฉ 2019ๅนด ml. All rights reserved.
//
import Foundation
| 16.2 | 46 | 0.697531 |
72aa19098af60bfcc29b55c6c22be7b346013209 | 807 | //
// TVShowUseCase.swift
// Will
//
// Created by Edric D. on 10/24/19.
// Copyright ยฉ 2019 The Upside Down. All rights reserved.
//
import RxSwift
import RxCocoa
final class TVShowUseCase {
private let network: TVShowNetwork
init(network: TVShowNetwork) {
self.network = network
}
func topRated() -> Observable<[TVShow]> {
return network.topRated()
}
func popular() -> Observable<[TVShow]> {
return network.popular()
}
func detail(id: Int) -> Observable<TVShowDetail> {
return network.detail(id: id)
}
func credit(id: Int) -> Observable<Credit> {
return network.credit(id: id)
}
func videos(id: Int) -> Observable<[Video]> {
return network.videos(id: id)
}
}
| 19.682927 | 58 | 0.584882 |
de179fa0f1f224cd054a619d24345ee785119fef | 245 | // 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 b {
deinit {
protocol A : A {
}
protocol A {
func g
typealias b : A.g
| 20.416667 | 87 | 0.730612 |
16860b8c05aed7e6042054ec57227286c5720b7a | 2,885 | //
// ConferenceButton.swift
// AuviousSDK
//
// Created by Jason Kritikos on 24/9/20.
//
import Foundation
enum ConferenceButtonType {
case micEnabled, micDisabled, camEnabled, camDisabled, camSwitch, hangup
}
class ConferenceButton: UIButton {
var type: ConferenceButtonType {
didSet {
setup()
}
}
private var gradientLayer = CAGradientLayer()
init(type: ConferenceButtonType) {
self.type = type
super.init(frame: .zero)
setup()
layer.insertSublayer(gradientLayer, at: 0)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
layer.cornerRadius = bounds.width / 2
clipsToBounds = true
layer.zPosition = 300
}
func setup() {
translatesAutoresizingMaskIntoConstraints = false
var image: String = ""
//Background gradient
switch type {
case .micEnabled:
image = "micEnabled"
gradientLayer.colors = [UIColor(red: 55/255, green: 60/255, blue: 96/255, alpha: 0.85).cgColor, UIColor(red: 27/255, green: 30/255, blue: 47/255, alpha: 0.85).cgColor]
gradientLayer.setAngle(150)
case .micDisabled:
image = "micDisabledDark"
gradientLayer.colors = [UIColor(red: 225/255, green: 224/255, blue: 230/255, alpha: 0.85).cgColor, UIColor.white.cgColor]
gradientLayer.setAngle(150)
case .camEnabled:
image = "camEnabled"
gradientLayer.colors = [UIColor(red: 55/255, green: 60/255, blue: 96/255, alpha: 0.85).cgColor, UIColor(red: 27/255, green: 30/255, blue: 47/255, alpha: 0.85).cgColor]
gradientLayer.setAngle(150)
case .camDisabled:
image = "camDisabledDark"
gradientLayer.colors = [UIColor(red: 225/255, green: 224/255, blue: 230/255, alpha: 0.85).cgColor, UIColor.white.cgColor]
gradientLayer.setAngle(150)
case .camSwitch:
image = "camSwitch"
gradientLayer.colors = [UIColor(red: 55/255, green: 60/255, blue: 96/255, alpha: 0.85).cgColor, UIColor(red: 27/255, green: 30/255, blue: 47/255, alpha: 0.85).cgColor]
gradientLayer.setAngle(150)
case .hangup:
image = "hangup"
gradientLayer.colors = [UIColor(red: 245/255, green: 39/255, blue: 107/255, alpha: 0.85).cgColor, UIColor(red: 227/255, green: 23/255, blue: 23/255, alpha: 0.85).cgColor]
gradientLayer.setAngle(150)
}
//Background image
setImage(UIImage(podAssetName: image), for: [])
contentMode = .center
imageView?.contentMode = .scaleAspectFit
}
}
| 33.546512 | 182 | 0.599307 |
bbcbea67f9fe29433fe1630c059a4b1bad54630a | 3,478 | //
// DishDetailViewController.swift
// NationalDish
//
// Created by Alex Paul on 3/9/19.
// Copyright ยฉ 2019 Alex Paul. All rights reserved.
//
import UIKit
class DishDetailViewController: UIViewController {
@IBOutlet weak var dishImageView: UIImageView!
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var countryNameLabel: UILabel!
@IBOutlet weak var dishDescriptionLabel: UILabel!
private let authservice = AppDelegate.authservice
public var dish: Dish!
public var displayName: String?
override func viewDidLoad() {
super.viewDidLoad()
upadateUI()
}
private func upadateUI() {
navigationItem.title = "\(dish.country) - \(dish.dishDescription)"
dishImageView.kf.setImage(with: URL(string: dish.imageURL), placeholder: #imageLiteral(resourceName: "placeholder-image.png"))
displayNameLabel.text = (displayName ?? "username")
countryNameLabel.text = dish.country
dishDescriptionLabel.text = dish.dishDescription
}
// setting up unwind segue
// step 1: create unwindFrom....function
// writing this function in view controller unwinding to
@IBAction func unwindFromEditDishView(segue: UIStoryboardSegue) {
let editVC = segue.source as! EditDishViewController
countryNameLabel.text = editVC.countryTextField.text
dishDescriptionLabel.text = editVC.dishDescriptionTextView.text
}
@IBAction func moreInfoButtonPressed(_ sender: UIBarButtonItem) {
guard let user = authservice.getCurrentUser() else {
print("no logged user")
return
}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let saveImageAction = UIAlertAction(title: "Save Image", style: .default) { [unowned self] (action) in
if let image = self.dishImageView.image {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
let editAction = UIAlertAction(title: "Edit", style: .default) { [unowned self] (action) in
self.showEditView()
}
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { [unowned self] (action) in
self.confirmDeletionActionSheet(handler: { (action) in
self.executeDelete()
})
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(saveImageAction)
if user.uid == dish.userId {
alertController.addAction(editAction)
alertController.addAction(deleteAction)
}
alertController.addAction(cancelAction)
present(alertController, animated: true)
}
private func executeDelete() {
DBService.deleteDish(dish: dish) { [weak self] (error) in
if let error = error {
self?.showAlert(title: "Error deleting dish", message: error.localizedDescription)
} else {
self?.showAlert(title: "Deleted successfully", message: nil, handler: { (action) in
self?.navigationController?.popViewController(animated: true)
})
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Show Edit Dish" {
guard let navController = segue.destination as? UINavigationController,
let editVC = navController.viewControllers.first as? EditDishViewController else {
fatalError("failed to segue to editVC")
}
editVC.dish = dish
}
}
private func showEditView() {
performSegue(withIdentifier: "Show Edit Dish", sender: nil)
}
}
| 35.131313 | 130 | 0.70184 |
76d06d4ca6145bfdb611e1484c163f29f69f65c8 | 465 | //
// BaseItemState.swift
// RxItemArchitecture
//
// Created by Alexander Korus on 15.01.21.
//
#if canImport(UIKit)
import Foundation
import RxCocoa
import RxSwift
public protocol BaseItemState: State {
var items: BehaviorRelay<[ItemGroup]> { get set }
}
public struct BaseState: BaseItemState {
public static var `default`: BaseState {
BaseState(items: BehaviorRelay<[ItemGroup]>(value: []))
}
public var items: BehaviorRelay<[ItemGroup]>
}
#endif
| 17.884615 | 57 | 0.731183 |
4b6f8005e4d33e09f13f50b44c63b66480896bf9 | 315 | //
// SwiftyBytesError.swift
// SwityBytes
//
// Created by Quentin Berry on 2/7/20.
// Copyright ยฉ 2020 Quentin Berry. All rights reserved.
//
import Foundation
public enum SwiftyBytesError: Error {
case EndofDataError
case StringConversionError
case ArraySizeError
case IncorrectValueType
}
| 18.529412 | 56 | 0.730159 |
3954f73c14dd81fa53355844e86caa46d0f8e250 | 2,069 | //
// AddListingView.swift
// NeighbourhoodGardener
//
// Created by Micah Beech on 2022-02-08.
//
import SwiftUI
// MARK: ViewState
extension AddListingView {
struct ViewState: DefaultIdentifiable {}
enum ViewEvent {
case addListing(String, String, String)
}
}
// MARK: View
struct AddListingView: View {
typealias ViewModel = AnyViewModel<ViewState, ViewEvent>
@ObservedInject private var viewModel: ViewModel
@State private var name = ""
@State private var description = ""
@State private var price = ""
let onAdd: () -> Void
var body: some View {
Form {
Section(header: Text("Product Name").secondaryStyle()) {
TextField("Name", text: $name)
.font(.avenirMedium(.medium))
.foregroundColor(.gardenPrimarylabel)
}
Section(header: Text("Description").secondaryStyle()) {
TextEditor(text: $description)
.font(.avenirMedium(.medium))
.foregroundColor(.gardenPrimarylabel)
}
Section(header: Text("Price").secondaryStyle()) {
TextField("$0.00", text: $price)
.keyboardType(.decimalPad)
.font(.avenirMedium(.medium))
.foregroundColor(.gardenPrimarylabel)
}
Button {
viewModel.trigger(.addListing(name, description, price))
onAdd()
} label: {
HStack {
Spacer()
Text("Create")
.primaryStyle()
Spacer()
}
}
}
}
}
// MARK: Previews
struct AddListingView_Previews: PreviewProvider {
static var previews: some View {
PreviewGroup {
AddListingView(onAdd: {})
.injectPreview(AddListingView.ViewModel.self)
}
}
}
extension AddListingView.ViewState: StatePreviewable {
static let preview = Self()
}
| 25.8625 | 72 | 0.536974 |
5642a3b5006f961e7692082a8e3c32e81fb2393d | 6,333 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -O -module-name devirt_default_case -emit-sil %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NORMAL %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -O -module-name devirt_default_case -emit-sil -enable-testing %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-TESTABLE %s
@_silgen_name("action")
func action(_ n:Int) -> ()
// public class
open class Base1 {
@inline(never) func inner() { action(1)}
func middle() { inner() }
// Check that call to Base1.middle cannot be devirtualized
//
// CHECK-LABEL: sil @_T019devirt_default_case5Base1C5outer{{[_0-9a-zA-Z]*}}F
// CHECK: class_method
// CHECK: }
public func outer() {
middle()
}
}
// public class
open class Derived1 : Base1 {
override func inner() { action(2) }
@inline(never) final override func middle() { inner() }
}
// private class
private class Base2 {
@inline(never) func inner() { action(3)}
func middle() { inner() }
func outer() { middle() }
}
// private class
private class Derived2 : Base2 {
override func inner() { action(4) }
@inline(never) final override func middle() { inner() }
}
// Check that call to Base2.middle can be devirtualized
//
// CHECK-LABEL: sil @_T019devirt_default_case9callOuterSiSiF
// CHECK: function_ref @_T019devirt_default_case5Base233_{{.*}}5inner
// CHECK: function_ref @_T019devirt_default_case8Derived233_{{.*}}6middle
// CHECK-NOT: class_method
// CHECK: return
public func callOuter(_ x: Int) -> Int {
var o:Base2
if x == 1 {
o = Base2()
} else {
o = Derived2()
}
o.outer()
return x
}
// internl class
class Base3 {
@inline(never) func inner() { action(5)}
@inline(never) func middle() { inner() }
// Check that call to Base3.middle can be devirtualized when not compiling
// for testing.
//
// CHECK-LABEL: sil{{( hidden)?}} [noinline] @_T019devirt_default_case5Base3C5outeryyF
// CHECK: function_ref @_T019devirt_default_case5Base3C6middleyyF
// CHECK: function_ref @_T019devirt_default_case8Derived333_{{.*}}6middle
// CHECK-NORMAL-NOT: class_method
// CHECK-TESTABLE: class_method %0 : $Base3, #Base3.middle!1
// CHECK: }
@inline(never) func outer() {
middle()
}
}
// private class
private class Derived3 : Base3 {
override func inner() { action(6) }
@inline(never) final override func middle() { inner() }
override func outer() {
}
}
class A2 { @inline(never) func f() -> Int { return 0 } }
class B2 : A2 {}
class C2 : A2 {}
class D2: B2 {}
class E2 :C2 {}
class A3 { @inline(never) func f() -> Int { return 0 } }
class B3 : A3 { @inline(never) override func f() -> Int { return 1 }}
class C3 : A3 {}
class D3: C3 {}
class E3 :C3 {}
// CHECK-TESTABLE: sil{{( hidden)?}} [thunk] [always_inline] @_T019devirt_default_case3fooSiAA2A3CF
public func testfoo1() -> Int {
return foo(E2())
}
public func testfoo3() -> Int {
return foo(E3())
}
class Base4 {
@inline(never)
func test() {
// Check that call to foo() can be devirtualized
//
// CHECK-LABEL: sil{{( hidden)?}} [noinline] @_T019devirt_default_case5Base4C4testyyF
// CHECK: function_ref @_T019devirt_default_case5Base4C3fooyyFTf4d_n
// CHECK: function_ref @_T019devirt_default_case8Derived4C3fooyyFTf4d_n
// CHECK-NORMAL-NOT: class_method
// CHECK-TESTABLE: class_method %0 : $Base4, #Base4.foo!1
// CHECK: }
foo()
}
@inline(never) func foo() { }
}
// A, C,D,E all use the same implementation.
// B has its own implementation.
@inline(never)
func foo(_ a: A3) -> Int {
// Check that call to A3.f() can be devirtualized.
//
// CHECK-NORMAL: sil{{( hidden)?}} [noinline] @_T019devirt_default_case3fooSiAA2A3CFTf4g_n
// CHECK-NORMAL: function_ref @_T019devirt_default_case2B3C1fSiyFTf4d_n
// CHECK-NORMAL: function_ref @_T019devirt_default_case2A3C1fSiyFTf4d_n
// CHECK-NORMAL-NOT: class_method
// CHECK: }
return a.f()
}
class Derived4 : Base4 {
@inline(never) override func foo() { }
}
open class Base5 {
@inline(never)
open func test() {
foo()
}
@inline(never) public final func foo() { }
}
class Derived5 : Base5 {
}
open class C6 {
func bar() -> Int { return 1 }
}
class D6 : C6 {
override func bar() -> Int { return 2 }
}
@inline(never)
func check_static_class_devirt(_ c: C6) -> Int {
// Check that C.bar() and D.bar() are devirtualized.
//
// CHECK-LABEL: sil{{( hidden)?}} [noinline] @_T019devirt_default_case019check_static_class_A0SiAA2C6CFTf4g_n
// CHECK: checked_cast_br [exact] %0 : $C6 to $C6
// CHECK: checked_cast_br [exact] %0 : $C6 to $D6
// CHECK: class_method
// CHECK: return
return c.bar()
}
public func test_check_static_class_devirt() -> Int {
return check_static_class_devirt(D6())
}
class A7 { @inline(never) func foo() -> Bool { return false } }
class B7 : A7 { @inline(never) override func foo() -> Bool { return true } }
public func test_check_call_on_downcasted_instance() -> Bool {
return check_call_on_downcasted_instance(B7())
}
@inline(never)
func callIt(_ b3: Base3, _ b4: Base4, _ b5: Base5) {
b3.outer()
b4.test()
b5.test()
}
public func externalEntryPoint() {
callIt(Base3(), Base4(), Base5())
}
open class M {
func foo() -> Int32 {
return 0
}
}
open class M1: M {
@inline(never)
override func foo() -> Int32 {
return 1
}
}
internal class M2: M1 {
@inline(never)
override func foo() -> Int32 {
return 2
}
}
internal class M3: M1 {
@inline(never)
override func foo() -> Int32 {
return 3
}
}
internal class M22: M2 {
@inline(never)
override func foo() -> Int32 {
return 22
}
}
internal class M222: M22 {
@inline(never)
override func foo() -> Int32 {
return 222
}
}
internal class M33: M3 {
@inline(never)
override func foo() -> Int32 {
return 33
}
}
// Check that speculative devirtualization tries to devirtualize the first N
// alternatives, if it has too many.
// The alternatives should be taken in a breadth-first order, starting with
// the static type of the instance.
@inline(never)
public func testSpeculativeDevirtualizationWithTooManyAlternatives(_ c:M1) -> Int32{
return c.foo()
}
@inline(never)
func foo(_ a: A2) -> Int {
return a.f()
}
@inline(never)
func check_call_on_downcasted_instance(_ a: A7) -> Bool {
if a is B7 {
return (a as! B7).foo()
}
return a.foo()
}
| 23.029091 | 191 | 0.675193 |
e539f8821f705e1802fe06130f1ba72fb270ff77 | 712 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// ServiceObjectiveCapabilityProtocol is the service objectives capability.
public protocol ServiceObjectiveCapabilityProtocol : Codable {
var name: String? { get set }
var status: CapabilityStatusEnum? { get set }
var performanceLevel: PerformanceLevelProtocol? { get set }
var id: String? { get set }
var supportedMaxSizes: [MaxSizeCapabilityProtocol?]? { get set }
var includedMaxSize: MaxSizeCapabilityProtocol? { get set }
}
| 47.466667 | 96 | 0.738764 |
e56cac08a0432f7e076ce8e3a6bbdcbc6e582ef2 | 4,245 | //
// BeautyPerformer.swift
// TRTCScenesDemo
//
// Created by xcoderliu on 3/19/20.
// Copyright ยฉ 2020 xcoderliu. All rights reserved.
//
import Foundation
@objc class BeautyPerformer: NSObject, TCBeautyPanelActionPerformer {
func setFilterConcentration(_ level: Float) {
// liveRoom.setFilterConcentration(concentration: level)
}
func setGreenScreenFile(_ file: URL?) {
// liveRoom.setGreenScreenFile(file: file)
}
@objc var liveRoom: TRTCLiveRoom
@objc init(liveRoom: TRTCLiveRoom) {
self.liveRoom = liveRoom
super.init()
}
func setFilter(_ filterImage: UIImage?) {
guard let filterImage = filterImage else {
TRTCCloud.sharedInstance()?.setFilter(nil)
return
}
liveRoom.getBeautyManager().setFilter(filterImage)
}
func setFilterStrength(_ level: Float) {
liveRoom.getBeautyManager().setFilterStrength(level)
}
func setGreenScreenFile(_ file: String?) {
guard let file = file else {
TRTCCloud.sharedInstance()?.setGreenScreenFile(nil)
return
}
liveRoom.getBeautyManager().setGreenScreenFile(file)
}
func setBeautyStyle(_ beautyStyle: Int) {
liveRoom.getBeautyManager().setBeautyStyle(TXBeautyStyle(rawValue: beautyStyle) ?? .nature)
}
func setBeautyLevel(_ level: Float) {
liveRoom.getBeautyManager().setBeautyLevel(level)
}
func setWhitenessLevel(_ level: Float) {
liveRoom.getBeautyManager().setWhitenessLevel(level)
}
func setRuddyLevel(_ level: Float) {
liveRoom.getBeautyManager().setRuddyLevel(level)
}
func setEyeScaleLevel(_ level: Float) {
liveRoom.getBeautyManager().setEyeScaleLevel(level)
}
func setFaceSlimLevel(_ level: Float) {
liveRoom.getBeautyManager().setFaceSlimLevel(level)
}
func setFaceVLevel(_ level: Float) {
liveRoom.getBeautyManager().setFaceVLevel(level)
}
func setChinLevel(_ level: Float) {
liveRoom.getBeautyManager().setChinLevel(level)
}
func setFaceShortLevel(_ level: Float) {
liveRoom.getBeautyManager().setFaceShortLevel(level)
}
func setNoseSlimLevel(_ level: Float) {
liveRoom.getBeautyManager().setNoseSlimLevel(level)
}
func setEyeLightenLevel(_ level: Float) {
liveRoom.getBeautyManager().setEyeLightenLevel(level)
}
func setToothWhitenLevel(_ level: Float) {
liveRoom.getBeautyManager().setToothWhitenLevel(level)
}
func setWrinkleRemoveLevel(_ level: Float) {
liveRoom.getBeautyManager().setWrinkleRemoveLevel(level)
}
func setPounchRemoveLevel(_ level: Float) {
liveRoom.getBeautyManager().setPounchRemoveLevel(level)
}
func setSmileLinesRemoveLevel(_ level: Float) {
liveRoom.getBeautyManager().setSmileLinesRemoveLevel(level)
}
func setForeheadLevel(_ level: Float) {
liveRoom.getBeautyManager().setForeheadLevel(level)
}
func setEyeDistanceLevel(_ level: Float) {
liveRoom.getBeautyManager().setEyeDistanceLevel(level)
}
func setEyeAngleLevel(_ level: Float) {
liveRoom.getBeautyManager().setEyeAngleLevel(level)
}
func setMouthShapeLevel(_ level: Float) {
liveRoom.getBeautyManager().setMouthShapeLevel(level)
}
func setNoseWingLevel(_ level: Float) {
liveRoom.getBeautyManager().setNoseWingLevel(level)
}
func setNosePositionLevel(_ level: Float) {
liveRoom.getBeautyManager().setNosePositionLevel(level)
}
func setLipsThicknessLevel(_ level: Float) {
liveRoom.getBeautyManager().setLipsThicknessLevel(level)
}
func setFaceBeautyLevel(_ level: Float) {
liveRoom.getBeautyManager().setFaceBeautyLevel(level)
}
func setMotionTmpl(_ tmplName: String?, inDir tmplDir: String?) {
liveRoom.getBeautyManager().setMotionTmpl(tmplName, inDir: tmplDir)
}
func setMotionMute(_ motionMute: Bool) {
liveRoom.getBeautyManager().setMotionMute(motionMute)
}
}
| 28.682432 | 99 | 0.661484 |
2851d5464af0723d6fbc2252bfeb2b8f14db5ec0 | 326 | //
// LeagueDetailsResponse.swift
// SportsDB
//
// Created by Isaac Karam on 7/4/20.
// Copyright ยฉ 2020 Isaac. All rights reserved.
//
import Foundation
struct LeagueDetailsResponse : Decodable {
var leagues : [LeagueDetails]?
enum CodingKeys: String, CodingKey {
case leagues = "leagues"
}
}
| 18.111111 | 48 | 0.662577 |
33b0794645bbcbcf81808ae88126e6b8efb65956 | 32,252 | //
// FunStatsViewController.swift
// Timesheets
//
// Created by Paul Kirvan on 2015-06-21.
//
//
import Foundation
import UIKit
import CoreData
import NotificationCenter
final class FunStatsViewController : UITableViewController
{
var numberOfGliderHogsToDisplay = 0
var numberOfTowHogsToDisplay = 0
var numberOfWinchHogsToDisplay = 0
var numberOfLongFlightsToDisplay = 0
var numberOfGlidingCentresInRegion = 0
var numberOfGlidingCentresFlyingThisWeekend = 0
var pilotsSortedByGliderFlights = [(Pilot, Int)]()
var pilotsSortedByTowFlights = [(Pilot, Int)]()
var pilotsSortedByWinchLaunches = [(Pilot, Int)]()
var glidingCentresActiveLastFiveDays = [GlidingCentreData]()
var glidingCentresActiveThisSeason = [GlidingCentreData]()
var listOfGliderFlightsByLength = [FlightRecord]()
override func viewDidLoad()
{
super.viewDidLoad()
// cleanDatabase()
// annonymize(); #warning("Turn this off!!!!")
// cleanUbiquitousKeyValueStore(); #warning("Turn this off!!!!")
// minuteStats(); #warning("Turn this off!!!!")
// let obsoleteName = "BGC"
// let currentName = "Brandon"
////
// let mainStoreGcRequest = GlidingCentre.fetchRequest() as! NSFetchRequest<GlidingCentre>
// mainStoreGcRequest.predicate = NSPredicate(format: "name == %@", obsoleteName)
// let mainStoreRequest = Pilot.request
// let startDate = Date() - 850*24*60*60
// let endDate = Date() - 365*24*60*60*2
//
// mainStoreRequest.predicate = NSPredicate(format: "timeIn < %@ OR timeIn > %@", startDate as CVarArg, endDate as CVarArg)
// mainStoreRequest.predicate = NSPredicate(format: "highestScoutQual > 0 OR highestGliderQual > 0", argumentArray: [])
//
// let matchingRecords = try! dataModel.managedObjectContext.fetch(mainStoreRequest)
//
// for record in matchingRecords
// {
// let request = AttendanceRecord.request
// request.predicate = NSPredicate(format: "pilot == %@", argumentArray: [record])
// let sortDescriptor = NSSortDescriptor(key: #keyPath(AttendanceRecord.timeIn), ascending: false)
// request.sortDescriptors = [sortDescriptor]
// let results = try! dataModel.managedObjectContext.fetch(request)
//
// if let mostRecentAttendanceRecord = results.first
// {
// record.glidingCentre = mostRecentAttendanceRecord.glidingCentre
// }
//
//// print("deleted \(gc.name)")
//// if record.picFlights.count == 0 && record.dualFlights.count == 0
//// {
//// dataModel.managedObjectContext.delete(record)
//// }
////
//// if record.name != currentName
//// {
//// dataModel.managedObjectContext.delete(record)
//// }
////
//// if record.flightRecords.count == 0
//// {
//// dataModel.managedObjectContext.delete(record)
//// }
////
//// dataModel.managedObjectContext.delete(record)
//
// }
// dataModel.saveContext()
//
// var matchingGCs = try! dataModel.managedObjectContext.fetch(mainStoreGcRequest)
//
// for gc in matchingGCs
// {
// print("name is \(gc.name)")
// }
//
// let obsolete = matchingGCs.first!
// print("Obsolete contains \(obsolete.pilots.count) pilots, \(obsolete.timesheets.count) timesheets, \(obsolete.glidingDayComments.count) comments, and \(obsolete.attendaceRecords.count) attendance records")
//
// mainStoreGcRequest.predicate = NSPredicate(format: "name == %@", currentName)
// matchingGCs = try! dataModel.managedObjectContext.fetch(mainStoreGcRequest)
// let current = matchingGCs.first!
// print("Current contains \(current.pilots.count) pilots, \(current.timesheets.count) timesheets, \(current.glidingDayComments.count) comments, and \(current.attendaceRecords.count) attendance records")
//
// obsolete.aircraft.removeAll()
// current.attendaceRecords = current.attendaceRecords.union(obsolete.attendaceRecords)
// obsolete.attendaceRecords.removeAll()
// current.pilots = current.pilots.union(obsolete.pilots)
// obsolete.pilots.removeAll()
// current.timesheets = current.timesheets.union(obsolete.timesheets)
// obsolete.timesheets.removeAll()
// current.glidingDayComments = current.glidingDayComments.union(obsolete.glidingDayComments)
// obsolete.glidingDayComments.removeAll()
// dataModel.managedObjectContext.delete(obsolete)
// print("Current contains \(current.pilots.count) pilots, \(current.timesheets.count) timesheets, \(current.glidingDayComments.count) comments, and \(current.attendaceRecords.count) attendance records")
// dataModel.saveContext()
let today = Date()
let twelveWeeksAgo = today + TIME_PERIOD_FOR_FUN_STATS
let request = FlightRecord.request
request.predicate = NSPredicate(format: "timeUp > %@ AND timesheet.glidingCentre == %@", argumentArray: [twelveWeeksAgo, dataModel.glidingCentre!])
let pilotSortDescriptor = NSSortDescriptor(key: #keyPath(FlightRecord.pilot.name), ascending: false)
request.sortDescriptors = [pilotSortDescriptor]
let recordsForCurrentGlidingCentreThisSeason = try! dataModel.managedObjectContext.fetch(request)
var gliderHogs = Dictionary<Pilot, Int>()
var towHogs = Dictionary<Pilot, Int>()
var winchHogs = Dictionary<Pilot, Int>()
for record in recordsForCurrentGlidingCentreThisSeason
{
guard let type = record.timesheet?.aircraft?.type, let pilot = record.pilot else {continue}
switch type
{
case .glider:
if let flightsFound = gliderHogs[pilot]
{
gliderHogs[pilot] = flightsFound + 1
}
else
{
gliderHogs[pilot] = 1
}
case .towplane:
if let flightsFound = towHogs[pilot]
{
towHogs[pilot] = flightsFound + 1
}
else
{
towHogs[pilot] = 1
}
case .winch:
if let flightsFound = winchHogs[pilot]
{
winchHogs[pilot] = flightsFound + 1
}
else
{
winchHogs[pilot] = 1
}
case .auto:
break
}
}
for (pilot, numberOfFlights) in gliderHogs
{
pilotsSortedByGliderFlights.append((pilot, numberOfFlights))
}
for (pilot, numberOfFlights) in towHogs
{
pilotsSortedByTowFlights.append((pilot, numberOfFlights))
}
for (pilot, numberOfFlights) in winchHogs
{
pilotsSortedByWinchLaunches.append((pilot, numberOfFlights))
}
pilotsSortedByGliderFlights.sort(by: {$0.1 > $1.1})
pilotsSortedByTowFlights.sort(by: {$0.1 > $1.1})
pilotsSortedByWinchLaunches.sort(by: {$0.1 > $1.1})
let flightRecordRequest = FlightRecord.request
flightRecordRequest.predicate = NSPredicate(format: "timeUp > %@ AND timesheet.glidingCentre == %@ AND timesheet.aircraft.gliderOrTowplane == 1 AND flightSequence != %@", argumentArray: [twelveWeeksAgo, dataModel.glidingCentre!, "Transit"])
let flightTimeSortDescriptor = NSSortDescriptor(key: #keyPath(FlightRecord.flightLengthInMinutes), ascending: false)
flightRecordRequest.sortDescriptors = [flightTimeSortDescriptor]
listOfGliderFlightsByLength = try! dataModel.managedObjectContext.fetch(flightRecordRequest)
numberOfGliderHogsToDisplay = pilotsSortedByGliderFlights.count >= 3 ? 4 : pilotsSortedByGliderFlights.count
numberOfTowHogsToDisplay = pilotsSortedByTowFlights.count >= 3 ? 4 : pilotsSortedByTowFlights.count
numberOfWinchHogsToDisplay = pilotsSortedByWinchLaunches.count >= 3 ? 4 : pilotsSortedByWinchLaunches.count
numberOfLongFlightsToDisplay = listOfGliderFlightsByLength.count > 3 ? 4 : listOfGliderFlightsByLength.count
updateInfo()
numberOfGlidingCentresFlyingThisWeekend = glidingCentresActiveLastFiveDays.count
numberOfGlidingCentresInRegion = glidingCentresActiveThisSeason.count
tableView.backgroundColor = presentingViewController?.traitCollection.horizontalSizeClass == .compact ? UIColor.groupTableViewBackground : UIColor.clear
}
func updateInfo()
{
glidingCentresActiveLastFiveDays.removeAll(keepingCapacity: true)
var keyValueStoreData = dataModel.keyValueStore.dictionaryRepresentation as [String: AnyObject]
for gcName in keyValueStoreData.keys
{
let gcDataDictionary = keyValueStoreData[gcName] as! [String: AnyObject]
let processedData = GlidingCentreData(name: gcName, gcData: gcDataDictionary)
// print("\(processedData)")
if processedData.flightsInLastFiveDays > 0
{
glidingCentresActiveLastFiveDays.append(processedData)
}
if processedData.flightsThisSeason > 0 && processedData.activeInLast100Days == true
{
glidingCentresActiveThisSeason.append(processedData)
}
}
glidingCentresActiveLastFiveDays.sort(by: >)
glidingCentresActiveThisSeason.sort(by: >)
preferredContentSize = CGSize(width: 0, height: self.tableView.contentSize.height)
let controller = NCWidgetController()
guard let bundleIdentifier = Bundle.main.bundleIdentifier else {return}
if glidingCentresActiveLastFiveDays.count > 0
{
controller.setHasContent(true, forWidgetWithBundleIdentifier: bundleIdentifier)
}
else
{
controller.setHasContent(false, forWidgetWithBundleIdentifier: bundleIdentifier)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
adjustBackgroundGivenTraitCollection(previousTraitCollection, controller: self)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = (indexPath as NSIndexPath).section < 4 ? tableView.dequeueReusableCell(withIdentifier: "RightDetailCell", for: indexPath) : tableView.dequeueReusableCell(withIdentifier: "StandardCell", for: indexPath)
switch (indexPath as NSIndexPath).section
{
case 0:
if ((indexPath as NSIndexPath).row == numberOfGliderHogsToDisplay - 1) && (numberOfGliderHogsToDisplay == 4)
{
cell.textLabel?.text = "Show All"
cell.detailTextLabel?.text = ""
if pilotsSortedByGliderFlights.count == 3
{
cell.textLabel?.text = "All Pilots Shown"
}
}
else
{
cell.textLabel?.text = pilotsSortedByGliderFlights[(indexPath as NSIndexPath).row].0.fullName
cell.detailTextLabel?.text = "\(pilotsSortedByGliderFlights[(indexPath as NSIndexPath).row].1) Flights"
}
case 1:
if ((indexPath as NSIndexPath).row == numberOfTowHogsToDisplay - 1) && (numberOfTowHogsToDisplay == 4)
{
cell.textLabel?.text = "Show All"
cell.detailTextLabel?.text = ""
if pilotsSortedByTowFlights.count == 3
{
cell.textLabel?.text = "All Pilots Shown"
}
}
else
{
cell.textLabel?.text = pilotsSortedByTowFlights[(indexPath as NSIndexPath).row].0.fullName
cell.detailTextLabel?.text = "\(pilotsSortedByTowFlights[(indexPath as NSIndexPath).row].1) Flights"
}
case 2:
if ((indexPath as NSIndexPath).row == numberOfWinchHogsToDisplay - 1) && (numberOfWinchHogsToDisplay == 4)
{
cell.textLabel?.text = "Show All"
cell.detailTextLabel?.text = ""
if pilotsSortedByWinchLaunches.count == 3
{
cell.textLabel?.text = "All Pilots Shown"
}
}
else
{
cell.textLabel?.text = pilotsSortedByWinchLaunches[(indexPath as NSIndexPath).row].0.fullName
cell.detailTextLabel?.text = "\(pilotsSortedByWinchLaunches[(indexPath as NSIndexPath).row].1) Launches"
}
case 3:
if ((indexPath as NSIndexPath).row == numberOfLongFlightsToDisplay - 1) && (numberOfLongFlightsToDisplay < listOfGliderFlightsByLength.count)
{
cell.textLabel?.text = "Show More"
cell.detailTextLabel?.text = ""
}
else
{
let longestFlight = listOfGliderFlightsByLength[(indexPath as NSIndexPath).row]
cell.textLabel?.text = longestFlight.pilot!.fullName + " (\(longestFlight.timeUp.militaryFormatShort))"
cell.detailTextLabel?.text = String(fromMinutes: Double(longestFlight.flightLengthInMinutes))
}
case 4:
let listOfGlidingCentresByFlights = glidingCentresActiveThisSeason.sorted {$0.flightsThisSeason > $1.flightsThisSeason}
cell.textLabel?.text = "\(listOfGlidingCentresByFlights[(indexPath as NSIndexPath).row].gcName)"
cell.detailTextLabel?.text = "\(listOfGlidingCentresByFlights[(indexPath as NSIndexPath).row].flightsThisSeason) Flights"
let GCImage = UIImage(named: listOfGlidingCentresByFlights[(indexPath as NSIndexPath).row].gcName)
cell.imageView?.image = GCImage
case 5:
let listOfGlidingCentresByMinutes = glidingCentresActiveThisSeason.sorted {$0.minutesThisSeason > $1.minutesThisSeason}
let nameOfGC = listOfGlidingCentresByMinutes[(indexPath as NSIndexPath).row].gcName
let numberOfMinutesFlownForGC = listOfGlidingCentresByMinutes[(indexPath as NSIndexPath).row].minutesThisSeason
let hourString = String(fromMinutes: Double(numberOfMinutesFlownForGC))
cell.textLabel?.text = nameOfGC
cell.detailTextLabel?.text = hourString + " Hours"
let GCImage = UIImage(named: nameOfGC)
cell.imageView?.image = GCImage
case 6:
let listOfGlidingCentresByFlightsToday = glidingCentresActiveLastFiveDays
let gcData = listOfGlidingCentresByFlightsToday[(indexPath as NSIndexPath).row]
let nameOfGC = gcData.gcName
let mostRecentLaunch = gcData.mostRecentFlight
var cellTitle = nameOfGC
if mostRecentLaunch.midnight > Date().midnight
{
cellTitle += " (Last Launch \(mostRecentLaunch.hoursAndMinutes))"
}
cell.textLabel?.text = cellTitle
let flightsToday = gcData.flightsToday
var cellDetailLabel = "\(flightsToday) Flight"
if flightsToday != 1
{
cellDetailLabel += "s"
}
let fiveDaysAgo = Date().midnight + -4*24*60*60
cellDetailLabel += " (\(gcData.flightsInLastFiveDays) since \(fiveDaysAgo.militaryFormatShort))"
cell.detailTextLabel?.text = cellDetailLabel
let GCImage = UIImage(named: nameOfGC)
cell.imageView?.image = GCImage
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let numberOfRows: Int
switch section
{
case 0:
numberOfRows = numberOfGliderHogsToDisplay
case 1:
numberOfRows = numberOfTowHogsToDisplay
case 2:
numberOfRows = numberOfWinchHogsToDisplay
case 3:
numberOfRows = numberOfLongFlightsToDisplay
case 4:
numberOfRows = numberOfGlidingCentresInRegion
case 5:
numberOfRows = numberOfGlidingCentresInRegion
case 6:
numberOfRows = numberOfGlidingCentresFlyingThisWeekend
default:
numberOfRows = 0
}
return numberOfRows
}
override func numberOfSections(in tableView: UITableView) -> Int
{
return 7
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
let title: String
switch section
{
case 0:
title = "Glider Hog"
case 1:
title = "Tow Hog"
case 2:
title = "Winch Hog"
case 3:
title = "Longest Glider Flight"
case 4:
title = "GCs by Glider Flights"
case 5:
title = "GCs by Glider Hours"
case 6:
title = "Today's Flying"
default:
title = ""
}
return title
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?
{
return section == 6 ? "Data may not be available for all gliding centres." : nil
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
switch ((indexPath as NSIndexPath).section)
{
case 0:
if ((indexPath as NSIndexPath).row == 3) && (numberOfGliderHogsToDisplay == 4) && (pilotsSortedByGliderFlights.count > 3)
{
numberOfGliderHogsToDisplay = pilotsSortedByGliderFlights.count
var rowsToAdd = [IndexPath]()
for i in 4 ..< pilotsSortedByGliderFlights.count
{
rowsToAdd.append(IndexPath(row: i, section: 0))
}
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .fade)
tableView.insertRows(at: rowsToAdd, with: .automatic)
tableView.endUpdates()
}
case 1:
if ((indexPath as NSIndexPath).row == 3) && (numberOfTowHogsToDisplay == 4) && (pilotsSortedByTowFlights.count > 3)
{
numberOfTowHogsToDisplay = pilotsSortedByTowFlights.count
var rowsToAdd = [IndexPath]()
for i in 4 ..< pilotsSortedByTowFlights.count
{
rowsToAdd.append(IndexPath(row: i, section: 1))
}
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: 3, section: 1)], with: .fade)
tableView.insertRows(at: rowsToAdd, with: .automatic)
tableView.endUpdates()
}
case 2:
if ((indexPath as NSIndexPath).row == 3) && (numberOfWinchHogsToDisplay == 4) && (pilotsSortedByWinchLaunches.count > 3)
{
numberOfWinchHogsToDisplay = pilotsSortedByWinchLaunches.count
var rowsToAdd = [IndexPath]()
for i in 4 ..< pilotsSortedByWinchLaunches.count
{
rowsToAdd.append(IndexPath(row: i, section: 2))
}
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: 3, section: 2)], with: .fade)
tableView.insertRows(at: rowsToAdd, with: .automatic)
tableView.endUpdates()
}
case 3:
if ((indexPath as NSIndexPath).row == numberOfLongFlightsToDisplay - 1) && (listOfGliderFlightsByLength.count > numberOfLongFlightsToDisplay)
{
let formerNumberOfLongFlightsShown = numberOfLongFlightsToDisplay - 1
let newNumberOfLongFlightsShown = formerNumberOfLongFlightsShown + 5
if newNumberOfLongFlightsShown >= listOfGliderFlightsByLength.count
{
numberOfLongFlightsToDisplay = listOfGliderFlightsByLength.count
}
else
{
numberOfLongFlightsToDisplay = newNumberOfLongFlightsShown + 1
}
var rowsToAdd = [IndexPath]()
for i in (indexPath as NSIndexPath).row + 1 ..< numberOfLongFlightsToDisplay
{
rowsToAdd.append(IndexPath(row: i, section: 3))
}
tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .fade)
tableView.insertRows(at: rowsToAdd, with: .automatic)
tableView.endUpdates()
}
default:
break
}
}
func cleanUbiquitousKeyValueStore()
{
let keys = dataModel.keyValueStore.dictionaryRepresentation.keys
for key in keys
{
dataModel.keyValueStore.removeObject(forKey: key)
}
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.ca.cadets.Timesheets")!
let fullPath = containerURL.path.stringByAppendingPathComponent("KVSdata")
(dataModel.keyValueStore.dictionaryRepresentation as NSDictionary).write(toFile: fullPath, atomically: true)
}
func cleanDatabase()
{
var request = Pilot.fetchRequest()
request.predicate = NSPredicate(format: "name == %@ AND fullName == %@", "", "")
var deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
var deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) pilots")
request = GlidingDayComment.fetchRequest()
request.predicate = NSPredicate(format: "glidingCentre == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) comments")
request = FlightRecord.fetchRequest()
request.predicate = NSPredicate(format: "timesheet == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) flight records")
request = AircraftTimesheet.fetchRequest()
request.predicate = NSPredicate(format: "aircraft == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) timesheets")
request = AircraftTimesheet.fetchRequest()
request.predicate = NSPredicate(format: "glidingCentre == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) timesheets")
request = MaintenanceEvent.fetchRequest()
request.predicate = NSPredicate(format: "aircraft == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) maintenance records")
request = AttendanceRecord.fetchRequest()
request.predicate = NSPredicate(format: "pilot == nil")
deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
deleteRequest.resultType = .resultTypeCount
deleteResults = try! dataModel.managedObjectContext.execute(deleteRequest) as! NSBatchDeleteResult
print("Deleting \(deleteResults.result as! Int) attendance records")
// let newRequest = AttendanceRecord.request
// newRequest.predicate = NSPredicate(format: "pilot.typeOfParticipant == %@", argumentArray: ["cadet"])
// let result = try! dataModel.managedObjectContext.fetch(newRequest)
// for record in result
// {
// record.timeIn = record.recordID
// dataModel.saveContext()
// }
dataModel.managedObjectContext.refreshAllObjects()
}
func annonymize()
{
var myfile = Bundle.main.path(forResource: "RandomNames", ofType: "csv")
var rawList = try! String(contentsOfFile: myfile!, encoding: String.Encoding.ascii)
let separators = CharacterSet.newlines
let firstNames = rawList.components(separatedBy: separators)
myfile = Bundle.main.path(forResource: "RandomSurnames", ofType: "csv")
rawList = try! String(contentsOfFile: myfile!, encoding: String.Encoding.ascii)
let lastNames = rawList.components(separatedBy: separators)
let request = Pilot.request
let pilotsFound = try! dataModel.managedObjectContext.fetch(request)
let numberOfSurnames = lastNames.count
let numberOfNames = firstNames.count
let squadronOffset = Int.random(in: 0...100)
for pilot in pilotsFound
{
let indexOfNewSurname = Int.random(in: 0..<numberOfSurnames)
let indexOfNewName = Int.random(in: 0..<numberOfNames)
pilot.name = lastNames[indexOfNewSurname]
pilot.firstName = firstNames[indexOfNewName]
pilot.fullName = "\(pilot.name), \(pilot.firstName)"
let randonSeconds = Int.random(in: 0..<(24*60*60*180))
let dateOffset = Double(randonSeconds - 24*60*60*90)
var licenseNumber = Int.random(in: 0...999999)
while licenseNumber < 100000
{
licenseNumber = Int.random(in: 0...999999)
}
pilot.birthday = pilot.birthday + dateOffset
pilot.email = ""
pilot.squadron = pilot.squadron + Int16(squadronOffset)
pilot.aniversaryOfGliderAPC = pilot.aniversaryOfGliderAPC + dateOffset
pilot.aniversaryOfTowAPC = pilot.aniversaryOfTowAPC + dateOffset
pilot.fiExpiry = pilot.fiExpiry + dateOffset
pilot.medical = pilot.medical + dateOffset
pilot.medicalThumbnailImage = nil
pilot.photoThumbnailImage = nil
pilot.gliderThumbnailImage = nil
pilot.powerThumbnailImage = nil
pilot.gliderLicense = "\(licenseNumber)"
pilot.powerLicense = "\(licenseNumber)"
}
let pilotPhotoRequest = Photo.request
let pilotPhotos = try! dataModel.managedObjectContext.fetch(pilotPhotoRequest) as [NSManagedObject]
let gliderPhotoRequest = GliderLicenseImage.request
let gliderPhotos = try! dataModel.managedObjectContext.fetch(gliderPhotoRequest) as [NSManagedObject]
let powerPhotoRequest = PowerLicenseImage.request
let powerPhotos = try! dataModel.managedObjectContext.fetch(powerPhotoRequest) as [NSManagedObject]
let medicalPhotoRequest = MedicalImage.request
let medicalPhotos = try! dataModel.managedObjectContext.fetch(medicalPhotoRequest) as [NSManagedObject]
var itemsToDelete = [NSManagedObject]()
itemsToDelete += pilotPhotos
itemsToDelete += gliderPhotos
itemsToDelete += powerPhotos
itemsToDelete += medicalPhotos
for object in itemsToDelete
{
dataModel.managedObjectContext.delete(object)
}
dataModel.saveContext()
}
func minuteStats()
{
let hours = 5...21
let minutes = 0...59
var minutesAndFlights = [Int: Int]()
var minutesAndFlightsCompressed = [Int: Int]()
var decimalStartMinutes = [Int]()
for minute in stride(from: 0, to: 60, by: 12)
{
decimalStartMinutes.append(minute)
}
for hour in hours
{
for minute in minutes
{
let time = hour*100 + minute
minutesAndFlights[time] = 0
}
for minute in decimalStartMinutes
{
let time = hour*100 + minute
minutesAndFlightsCompressed[time] = 0
}
}
var components = gregorian.dateComponents([.year], from: Date())
components.year = 2013
components.month = 7
components.day = 16
components.hour = 1
components.minute = 1
let startTime = gregorian.date(from: components) ?? Date()
components.month = 8
components.day = 13
let endTime = gregorian.date(from: components) ?? Date()
let request = FlightRecord.request
request.predicate = NSPredicate(format: "timeUp > %@ AND timeDown < %@ AND timesheet.glidingCentre == %@ AND timesheet.aircraft.gliderOrTowplane = 1", argumentArray: [startTime, endTime, dataModel.glidingCentre!])
let records = try! dataModel.managedObjectContext.fetch(request)
for record in records
{
guard let upTime = Int(record.timeUp.hoursAndMinutes) else {continue}
if let priorLaunchesSameMinute = minutesAndFlights[upTime]
{
minutesAndFlights[upTime] = priorLaunchesSameMinute + 1
}
}
let compressedKeys = minutesAndFlightsCompressed.keys.sorted(by: <)
for key in compressedKeys
{
let affectedMinutes = [key, key + 1, key + 2, key + 3, key + 4, key + 5, key + 6, key + 7, key + 8, key + 9, key + 10, key + 11]
var sum = 0
for minute in affectedMinutes
{
if let value = minutesAndFlights[minute]
{
sum += value
}
}
minutesAndFlightsCompressed[key] = sum
print("\(key) \(sum)")
}
}
}
| 40.928934 | 248 | 0.592273 |
4b246ae0ea4af3adea96f621875a33ac442d9984 | 1,028 | //
// APIKit+Extensions.swift
// SampleGithub
//
// Created by Kosuke Matsuda on 2019/12/01.
// Copyright ยฉ 2019 Kosuke Matsuda. All rights reserved.
//
import Foundation
import APIKit
import RxSwift
extension Session {
class func response<T: Request>(request: T, callbackQueue: CallbackQueue? = .main) -> Single<T.Response> {
return Single.create { (observer) -> Disposable in
let task = self.send(request, callbackQueue: callbackQueue) { (result) in
switch result {
case .success(let response):
observer(.success(response))
case .failure(let error):
observer(.error(error))
}
}
return Disposables.create {
task?.cancel()
}
}
}
func response<T: Request>(request: T, callbackQueue: CallbackQueue? = .main) -> Single<T.Response> {
return type(of: self).response(request: request, callbackQueue: callbackQueue)
}
}
| 30.235294 | 110 | 0.58463 |
db6521c61fbe5f0604ecea52dc51d8970fbda511 | 3,550 | //
// Event SequenceNumber.swift
// MIDIKitSMF โข https://github.com/orchetect/MIDIKitSMF
//
import Foundation
import MIDIKit
@_implementationOnly import OTCore
@_implementationOnly import SwiftRadix
// MARK: - SequenceNumber
extension MIDI.File.Event {
/// Sequence Number event.
///
/// - For MIDI file type 0/1, this should only be on the first track. This is used to identify each track. If omitted, the sequences are numbered sequentially in the order the tracks appear.
///
/// - For MIDI file type 2, each track can contain a sequence number event.
public struct SequenceNumber: Equatable, Hashable {
/// Sequence number (0...32767)
public var sequence: UInt16 = 0 {
didSet {
if oldValue != sequence { sequence_Validate() }
}
}
private mutating func sequence_Validate() {
sequence = sequence.clamped(to: 0x0 ... 0x7FFF)
}
// MARK: - Init
public init(sequence: UInt16) {
self.sequence = sequence
}
}
}
extension MIDI.File.Event.SequenceNumber: MIDIFileEventPayload {
public static let smfEventType: MIDI.File.Event.EventType = .sequenceNumber
public init(midi1SMFRawBytes rawBytes: [MIDI.Byte]) throws {
guard rawBytes.count == Self.midi1SMFFixedRawBytesLength else {
throw MIDI.File.DecodeError.malformed(
"Invalid number of bytes. Expected \(Self.midi1SMFFixedRawBytesLength) but got \(rawBytes.count)"
)
}
// 3-byte preamble
guard rawBytes.starts(with: MIDI.File.kEventHeaders[.sequenceNumber]!) else {
throw MIDI.File.DecodeError.malformed(
"Event does not start with expected bytes."
)
}
guard let readSequenceNumber = rawBytes[3 ... 4].data.toUInt16(from: .bigEndian) else {
throw MIDI.File.DecodeError.malformed(
"Could not read sequence number as integer."
)
}
guard readSequenceNumber.isContained(in: 0x0 ... 0x7FFF) else {
throw MIDI.File.DecodeError.malformed(
"Sequence number is out of bounds: \(readSequenceNumber)"
)
}
sequence = readSequenceNumber
}
public var midi1SMFRawBytes: [MIDI.Byte] {
// FF 00 02 ssss
// ssss is UIn16 big-endian sequence number
MIDI.File.kEventHeaders[.sequenceNumber]! + sequence.toData(.bigEndian)
}
static let midi1SMFFixedRawBytesLength = 5
public static func initFrom(midi1SMFRawBytesStream rawBuffer: Data) throws -> InitFromMIDI1SMFRawBytesStreamResult {
let requiredData = rawBuffer.prefix(midi1SMFFixedRawBytesLength).bytes
guard requiredData.count == midi1SMFFixedRawBytesLength else {
throw MIDI.File.DecodeError.malformed(
"Unexpected byte length."
)
}
let newInstance = try Self(midi1SMFRawBytes: requiredData)
return (newEvent: newInstance,
bufferLength: midi1SMFFixedRawBytesLength)
}
public var smfDescription: String {
"seqNum:\(sequence)"
}
public var smfDebugDescription: String {
"SequenceNumber(\(sequence))"
}
}
| 29.338843 | 194 | 0.587042 |
332d010c0f69e2abee06b0ebf1049624fe99e13c | 908 | // Copyright 2005-2021 Michel Fortin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
fileprivate var queueCount = 0
public extension DispatchQueue {
static func uniqueUserInitiatedQueue() -> DispatchQueue {
queueCount += 1
return DispatchQueue(label: "com.michelf.sim-daltonism" + String(queueCount), qos: .userInitiated)
}
}
| 34.923077 | 106 | 0.715859 |
71984001d6a0c835825b5f596bb6f3b9d38132bf | 4,412 | /*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import GooglePlacePicker
/// A view controller which displays a UI for opening the Place Picker. Once a place is selected
/// it navigates to the place details screen for the selected location.
class PickAPlaceViewController: UIViewController {
@IBOutlet private weak var pickAPlaceButton: UIButton!
@IBOutlet weak var buildNumberLabel: UILabel!
@IBOutlet var containerView: UIView!
var mapViewController: BackgroundMapViewController?
init() {
super.init(nibName: String(describing: type(of: self)), bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// This is the size we would prefer to be.
self.preferredContentSize = CGSize(width: 330, height: 600)
// Configure our view.
view.backgroundColor = Colors.blue1
containerView.backgroundColor = Colors.blue1
view.clipsToBounds = true
// Set the build number.
buildNumberLabel.text = "Places SDK Build: \(GMSPlacesClient.sdkVersion())"
// Setup the constraint between the container and the layout guides to be consistant with
// LaunchScreen.storyboard. Because this view controller uses XIB rather than storyboard files
// this cannot be done in interface builder.
NSLayoutConstraint(item: containerView,
attribute: .top,
relatedBy: .equal,
toItem: topLayoutGuide,
attribute: .bottom,
multiplier: 1,
constant: 0)
.isActive = true
NSLayoutConstraint(item: bottomLayoutGuide,
attribute: .top,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1,
constant: 0)
.isActive = true
}
@IBAction func buttonTapped() {
// Create a place picker. Attempt to display it as a popover if we are on a device which
// supports popovers.
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
placePicker.modalPresentationStyle = .popover
placePicker.popoverPresentationController?.sourceView = pickAPlaceButton
placePicker.popoverPresentationController?.sourceRect = pickAPlaceButton.bounds
// Display the place picker. This will call the delegate methods defined below when the user
// has made a selection.
self.present(placePicker, animated: true, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension PickAPlaceViewController : GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
// Create the next view controller we are going to display and present it.
let nextScreen = PlaceDetailViewController(place: place)
self.splitPaneViewController?.push(viewController: nextScreen, animated: false)
self.mapViewController?.coordinate = place.coordinate
// Dismiss the place picker.
viewController.dismiss(animated: true, completion: nil)
}
func placePicker(_ viewController: GMSPlacePickerViewController, didFailWithError error: Error) {
// In your own app you should handle this better, but for the demo we are just going to log
// a message.
NSLog("An error occurred while picking a place: \(error)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
NSLog("The place picker was canceled by the user")
// Dismiss the place picker.
viewController.dismiss(animated: true, completion: nil)
}
}
| 38.701754 | 99 | 0.701949 |
69d4ca060f6c372850515d9940bf2b7ecd63e059 | 32,480 | import ElasticSwiftCore
import Foundation
import Logging
import NIOHTTP1
#if canImport(ElasticSwiftNetworking) && !os(Linux)
import ElasticSwiftNetworking
#endif
/// Represents elasticsearch host address
public typealias Host = URL
/// Elasticsearch Client
public class ElasticClient {
private static let logger = Logger(label: "org.pksprojects.ElasticSwfit.ElasticClient")
/// http reqeusts executer of the client
let transport: Transport
/// The settings of the client
private let _settings: Settings
/// The client for making requests against elasticsearch cluseterAPIs.
private var clusterClient: ClusterClient?
/// The client for making requests against elasticsearch indicesAPIs.
private var indicesClient: IndicesClient?
/// Initializes new client for `Elasticsearch`
/// - Parameter settings: The settings of the client.
public init(settings: Settings) {
transport = Transport(forHosts: settings.hosts, httpSettings: settings.httpSettings)
_settings = settings
indicesClient = IndicesClient(withClient: self)
clusterClient = ClusterClient(withClient: self)
}
/// The credentials used by the client.
private var credentials: ClientCredential? {
return _settings.credentials
}
/// The serializer of the client.
private var serializer: Serializer {
return _settings.serializer
}
}
public extension ElasticClient {
/// Asynchronously retrieves a document by id using the Get API.
///
/// [Get API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html)
/// - Parameters:
/// - getRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func get<T: Codable>(_ getRequest: GetRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<GetResponse<T>, Error>) -> Void) -> Void {
return execute(request: getRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously index a document using the Index API.
///
/// [Index API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html)
/// - Parameters:
/// - indexRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func index<T: Codable>(_ indexRequest: IndexRequest<T>, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<IndexResponse, Error>) -> Void) -> Void {
return execute(request: indexRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously deletes a document by id using the Delete API.
///
/// [Delete API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html)
/// - Parameters:
/// - deleteRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func delete(_ deleteRequest: DeleteRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<DeleteResponse, Error>) -> Void) {
return execute(request: deleteRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously updates a document using the Update API.
///
/// [Update API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html)
/// - Parameters:
/// - updateRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func update(_ updateRequest: UpdateRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<UpdateResponse, Error>) -> Void) {
return execute(request: updateRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a search using the Search API.
///
/// [Search API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html)
/// - Parameters:
/// - serachRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func search<T: Codable>(_ serachRequest: SearchRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<SearchResponse<T>, Error>) -> Void) -> Void {
return execute(request: serachRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a search using the Search Scroll API.
///
/// [Search Scroll API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html)
/// - Parameters:
/// - serachRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func scroll<T: Codable>(_ scrollRequest: SearchScrollRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<SearchResponse<T>, Error>) -> Void) -> Void {
return execute(request: scrollRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously clears one or more scroll ids using the Clear Scroll API.
///
/// [Clear Scroll API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html#_clear_scroll_api)
/// - Parameters:
/// - serachRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func clearScroll(_ clearScrollRequest: ClearScrollRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<ClearScrollResponse, Error>) -> Void) {
return execute(request: clearScrollRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a delete by query request.
///
/// [Delete By Query API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html)
/// - Parameters:
/// - deleteByQueryRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func deleteByQuery(_ deleteByQueryRequest: DeleteByQueryRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<DeleteByQueryResponse, Error>) -> Void) {
return execute(request: deleteByQueryRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes an update by query request.
///
/// [Update By Query API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html)
/// - Parameters:
/// - updateByQueryRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func updateByQuery(_ updateByQueryRequest: UpdateByQueryRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<UpdateByQueryResponse, Error>) -> Void) {
return execute(request: updateByQueryRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously retrieves multiple documents by id using the Multi Get API.
///
/// [Multi Get API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html)
/// - Parameters:
/// - multiGetRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func mget(_ multiGetRequest: MultiGetRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<MultiGetResponse, Error>) -> Void) {
return execute(request: multiGetRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a reindex request.
///
/// [Reindex API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html)
/// - Parameters:
/// - reIndexRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func reIndex(_ reIndexRequest: ReIndexRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<ReIndexResponse, Error>) -> Void) {
return execute(request: reIndexRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously calls the Term Vectors API
///
/// [Term Vectors API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-termvectors.html)
/// - Parameters:
/// - termVectorsRequest: the request
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func termVectors(_ termVectorsRequest: TermVectorsRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<TermVectorsResponse, Error>) -> Void) {
return execute(request: termVectorsRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously calls the Multi Term Vectors API
///
/// [Multi Term Vectors API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html)
/// - Parameters:
/// - mtermVectorsRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func mtermVectors(_ mtermVectorsRequest: MultiTermVectorsRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<MultiTermVectorsResponse, Error>) -> Void) {
return execute(request: mtermVectorsRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a bulk request using the Bulk API.
///
/// [Bulk API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html)
/// - Parameters:
/// - bulkRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func bulk(_ bulkRequest: BulkRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<BulkResponse, Error>) -> Void) {
return execute(request: bulkRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a count request using the Count API.
///
/// [Count API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html)
/// - Parameters:
/// - countRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func count(_ countRequest: CountRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<CountResponse, Error>) -> Void) {
return execute(request: countRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a request using the Explain API.
///
/// [Explain API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html)
/// - Parameters:
/// - explainRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func explain(_ explainRequest: ExplainRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<ExplainResponse, Error>) -> Void) {
return execute(request: explainRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a request using the Field Capabilities API.
///
/// [Field Capabilities API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html)
/// - Parameters:
/// - fieldCapabilitiesRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func fieldCaps(_ fieldCapabilitiesRequest: FieldCapabilitiesRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<FieldCapabilitiesResponse, Error>) -> Void) {
return execute(request: fieldCapabilitiesRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a request using the Ranking Evaluation API.
///
/// [Ranking Evaluation API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-rank-eval.html)
/// - Parameters:
/// - rankEvalRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func rankEval(_ rankEvalRequest: RankEvalRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<RankEvalResponse, Error>) -> Void) {
return execute(request: rankEvalRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously get stored script by id.
///
/// [How to use scripts on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html)
/// - Parameters:
/// - getStoredScriptRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func getScript(_ getStoredScriptRequest: GetStoredScriptRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<GetStoredScriptResponse, Error>) -> Void) {
return execute(request: getStoredScriptRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously delete stored script by id.
///
/// [How to use scripts on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html)
/// - Parameters:
/// - deleteStoredScriptRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func deleteScript(_ deleteStoredScriptRequest: DeleteStoredScriptRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<AcknowledgedResponse, Error>) -> Void) {
return execute(request: deleteStoredScriptRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously puts an stored script using the Scripting API.
///
/// [Scripting API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html)
/// - Parameters:
/// - putStoredScriptRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func putScript(_ putStoredScriptRequest: PutStoredScriptRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<AcknowledgedResponse, Error>) -> Void) {
return execute(request: putStoredScriptRequest, options: options, completionHandler: completionHandler)
}
/// Asynchronously executes a request using the Search Template API.
///
/// [Search Template API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html)
/// - Parameters:
/// - searchTemplateRequest: the request.
/// - options: the request options (e.g. headers), defaults to `RequestOptions.default` if nothing to be customized.
/// - completionHandler: callback to be invoked upon request completion.
func searchTemplate<T: Codable>(_ searchTemplateRequest: SearchTemplateRequest, with options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<SearchResponse<T>, Error>) -> Void) {
return execute(request: searchTemplateRequest, options: options, completionHandler: completionHandler)
}
}
/// Extention declaring various flavors of elasticsearch client
public extension ElasticClient {
/// Provides an `IndicesClient` which can be used to access Indices API.
///
/// [Indices API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html)
var indices: IndicesClient {
return indicesClient!
}
/// Provides an `ClusterClient` which can be used to access Cluster API.
///
/// [Cluster API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html)
var cluster: ClusterClient {
return clusterClient!
}
}
// MARK: - Settings
/// Elasticsearch ElasticClient Settings
public class Settings {
/// elasticsearch nodes
public let hosts: [Host]
/// elasticsearch credentials
public let credentials: ClientCredential?
/// serializer to use for request/response serialization
public let serializer: Serializer
/// settings for the underlying adaptor
public let httpSettings: HTTPSettings
/// Initializes settings for the `ElasticClient` with `HTTPAdaptorConfiguration`.
/// - Parameters:
/// - hosts: Array for elasticsearch hosts.
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - adaptorConfig: configuration for the underlying managed http adaptor
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public init(forHosts hosts: [Host], withCredentials credentials: ClientCredential? = nil, adaptorConfig: HTTPAdaptorConfiguration, serializer: Serializer = DefaultSerializer()) {
self.hosts = hosts
self.credentials = credentials
httpSettings = .managed(adaptorConfig: adaptorConfig)
self.serializer = serializer
}
/// Initializes settings for the `ElasticClient` with `HTTPClientAdaptor`.
/// - Parameters:
/// - hosts: Array for elasticsearch hosts.
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - clientAdaptor: adaptor to use for making http reqeusts
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public init(forHosts hosts: [Host], withCredentials credentials: ClientCredential? = nil, adaptor clientAdaptor: HTTPClientAdaptor, serializer: Serializer = DefaultSerializer()) {
self.hosts = hosts
self.credentials = credentials
httpSettings = .independent(adaptor: clientAdaptor)
self.serializer = serializer
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - host: elasticsearch host
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - adaptorConfig: configuration for the underlying managed http adaptor
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHost host: Host, withCredentials credentials: ClientCredential? = nil, adaptorConfig: HTTPAdaptorConfiguration, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: [host], withCredentials: credentials, adaptorConfig: adaptorConfig, serializer: serializer)
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - host: elasticsearch host
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - clientAdaptor: adaptor to use for making http reqeusts
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHost host: Host, withCredentials credentials: ClientCredential? = nil, adaptor clientAdaptor: HTTPClientAdaptor, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: [host], withCredentials: credentials, adaptor: clientAdaptor, serializer: serializer)
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - host: elasticsearch host address as string. Ex- `"http://localhost:9200"`
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - adaptorConfig: configuration for the underlying managed http adaptor
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHost host: String, withCredentials credentials: ClientCredential? = nil, adaptorConfig: HTTPAdaptorConfiguration, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: [URL(string: host)!], withCredentials: credentials, adaptorConfig: adaptorConfig, serializer: serializer)
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - host: elasticsearch host address as string. Ex- `"http://localhost:9200"`
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - clientAdaptor: adaptor to use for making http reqeusts
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHost host: String, withCredentials credentials: ClientCredential? = nil, adaptor clientAdaptor: HTTPClientAdaptor, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: [URL(string: host)!], withCredentials: credentials, adaptor: clientAdaptor, serializer: serializer)
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - hosts: array for elasticsearch host addresses as string. Ex- `["http://localhost:9200"]`
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - adaptorConfig: adaptor to use for making http reqeusts
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHosts hosts: [String], withCredentials credentials: ClientCredential? = nil, adaptorConfig: HTTPAdaptorConfiguration, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: hosts.map { URL(string: $0)! }, withCredentials: credentials, adaptorConfig: adaptorConfig, serializer: serializer)
}
/// Initializes settings for the `ElasticClient`
/// - Parameters:
/// - hosts: array for elasticsearch host addresses as string. Ex- `["http://localhost:9200"]`
/// - credentials: elasticsearch credentials, defaults to `nil` i.e. no credentials required.
/// - clientAdaptor: adaptor to use for making http reqeusts
/// - serializer: serializer for reqeust/response serialization, defaults to `DefaultSerializer`
public convenience init(forHosts hosts: [String], withCredentials credentials: ClientCredential? = nil, adaptor clientAdaptor: HTTPClientAdaptor, serializer: Serializer = DefaultSerializer()) {
self.init(forHosts: hosts.map { URL(string: $0)! }, withCredentials: credentials, adaptor: clientAdaptor, serializer: serializer)
}
#if canImport(ElasticSwiftNetworking) && !os(Linux)
/// default settings for ElasticClient with host
/// - Parameter host: elasticsearch host address as string. Ex- `"http://localhost:9200"`
public static func `default`(_ host: String) -> Settings {
return urlSession(host)
}
/// default settings for ElasticClient with host and `URLSessionAdaptorConfiguration`
/// - Parameter host: elasticsearch host address as string. Ex- `"http://localhost:9200"`
public static func urlSession(_ host: String) -> Settings {
return Settings(forHost: host, adaptorConfig: URLSessionAdaptorConfiguration.default)
}
#endif
}
/// Extension implementing low level request execution api
public extension ElasticClient {
/// Function to execute a `Reques`t and get raw HTTP response in callback.
/// - Parameters:
/// - request: elasticsearch request to execute
/// - options: reqeust options, defaults to `RequestOptions.default`
/// - completionHandler: function to be called with result when execution completes.
final func execute<T: Request>(request: T, options: RequestOptions = .default, completionHandler: @escaping (_ result: Result<HTTPResponse, Error>) -> Void) -> Void {
let httpRequestResult = createHTTPRequest(for: request, with: options)
switch httpRequestResult {
case let .failure(error):
let wrappedError = RequestConverterError(message: "Unable to create HTTPRequest from \(request)", error: error, request: request)
return completionHandler(.failure(wrappedError))
case let .success(httpRequest):
transport.performRequest(request: httpRequest, callback: completionHandler)
}
}
// final func execute<T: Request>(request: T, options: RequestOptions = .`default`, converter: ResponseConverter<T.ResponseType> = ResponseConverters.defaultConverter, completionHandler: @escaping (_ result: Result<T.ResponseType, Error>) -> Void) -> Void {
//
// self.execute(request: request, options: options, converter: converter, completionHandler: completionHandler)
// }
/// Function to execute a `Request`.
/// - Parameters:
/// - request: elasticsearch request to execute
/// - options: reqeust options, defaults to `RequestOptions.default`
/// - converter: the converter responsible for converting raw HTTP response to the desired type.
/// - completionHandler: function to be called with result when execution completes.
final func execute<T: Request, R: Codable>(request: T, options: RequestOptions = .default, converter: ResponseConverter<R> = ResponseConverters.defaultConverter, completionHandler: @escaping (_ result: Result<R, Error>) -> Void) -> Void {
let httpRequestResult = createHTTPRequest(for: request, with: options)
switch httpRequestResult {
case let .failure(error):
let wrappedError = RequestConverterError(message: "Unable to create HTTPRequest from \(request)", error: error, request: request)
return completionHandler(.failure(wrappedError))
case let .success(httpRequest):
transport.performRequest(request: httpRequest, callback: converter(serializer, completionHandler))
}
}
/// Function to execute a raw http reqeust and get raw http response in callback.
/// - Note: This method is useful to execute a request and/or feature(s) for existing request(s) that is not yet supported by creating an `HTTPRequest`. However it might be a good to contrubute and/or make a feature request.
/// - Parameters:
/// - request: elasticsearch request as a http request
/// - completionHandler: function to be called with result when execution completes.
final func execute(request: HTTPRequest, completionHandler: @escaping (_ result: Result<HTTPResponse, Error>) -> Void) {
return transport.performRequest(request: request, callback: completionHandler)
}
/// Function responsible to convert a `Request` to a `HTTPRequest`
/// - Parameters:
/// - request: elasticsearch reqeust
/// - options: request options for http reqeust.
private func createHTTPRequest<T: Request>(for request: T, with options: RequestOptions) -> Result<HTTPRequest, Error> {
var headers = HTTPHeaders()
headers.add(contentsOf: defaultHeaders())
headers.add(contentsOf: authHeader())
if request.headers.contains(name: "Content-Type") || options.headers.contains(name: "Content-Type") {
headers.remove(name: "Content-Type")
}
headers.add(contentsOf: request.headers)
headers.add(contentsOf: options.headers)
var params = [URLQueryItem]()
params.append(contentsOf: request.queryParams)
params.append(contentsOf: options.queryParams)
let bodyResult = request.makeBody(serializer)
switch bodyResult {
case let .success(data):
return .success(HTTPRequest(path: request.endPoint, method: request.method, queryParams: params, headers: headers, body: data))
case let .failure(error):
switch error {
case .noBodyForRequest:
return .success(HTTPRequest(path: request.endPoint, method: request.method, queryParams: params, headers: headers, body: nil))
default:
return .failure(error)
}
}
}
/// Generates default http headers for the request.
private func defaultHeaders() -> HTTPHeaders {
var headers = HTTPHeaders()
headers.add(name: "Accept", value: "application/json")
headers.add(name: "Content-Type", value: "application/json; charset=utf-8")
return headers
}
/// Generates Authorization headers based on client credentials
private func authHeader() -> HTTPHeaders {
var headers = HTTPHeaders()
if let credentials = self.credentials {
headers.add(name: "Authorization", value: credentials.token)
}
return headers
}
}
// MARK: - BasicClientCredential
/// Implementation of `ClientCredential` to support `Basic HTTP Auth`
public class BasicClientCredential: ClientCredential {
/// The username of the credentials
let username: String
/// The password of the credentials
let password: String
/// Initializes new basic client credentials
/// - Parameters:
/// - username: username of the user to be authenticated
/// - password: password of the user to be authenticated
public init(username: String, password: String) {
self.username = username
self.password = password
}
/// `Basic HTTP Auth` header string
public var token: String {
let token = "\(username):\(password)".data(using: .utf8)?.base64EncodedString()
return "Basic \(token!)"
}
}
| 59.270073 | 260 | 0.71133 |
181cf4b45e78728a343b13231896f14c5b50b2b1 | 2,185 | //
// Goal.swift
// antiSoccerGame2
//
// Created by Cameron Smith on 7/12/18.
// Copyright ยฉ 2018 com.cameronSmith. All rights reserved.
//
import Foundation
import SpriteKit
class Goal : SKSpriteNode {
//the name to reference it on the scene
static let nodeName = "goal"
//the goal image texture
static let texture: SKTexture = SKTexture(imageNamed: "goalOld")
//node dimensions
static let goalHeight: CGFloat = 55
static let goalWidth: CGFloat = 140
static let insideGoalMargin: CGFloat = 0
//margin from player to goal with y axis
static let goalPlayerDiff: CGFloat = 150
//the position of the goal
static var goalPosition: CGPoint = CGPoint(x: 0, y: 0) //will be reset
/* goal constructor
* @param scene: the scene to get dimensions from and add the goal to
* */
init (scene: GameScene) {
/* set up goal properties and add it to scene */
super.init(texture: Goal.texture,
color: UIColor.blue,
size: CGSize(width: Goal.goalWidth,
height: Goal.goalHeight))
Goal.goalPosition = CGPoint (x: 0,
y: scene.size.height/2 - CGFloat(SoccerPlayer.defenseToGoalMargin) + Goal.goalPlayerDiff - 20)
position = Goal.goalPosition
name = Goal.nodeName
setUpPhysics()
}
/* method to create the goal, just a wrapper of the constructor for convention
* @param scene: the scene to add the goal to
* */
static func createAndDisplayGoal (scene: GameScene) {
scene.addChild(Goal(scene: scene))
}
/* method to create physics of player */
private func setUpPhysics () {
/* set up physics properties */
physicsBody = SKPhysicsBody(rectangleOf:
CGSize(width: Goal.goalWidth - Goal.insideGoalMargin,
height: Goal.goalHeight))
physicsBody?.affectedByGravity = false
physicsBody?.categoryBitMask = 1
physicsBody?.collisionBitMask = 0
}
/* required decoder constructor, ignore */
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 33.615385 | 106 | 0.632037 |
e8d2971371ce781989bde35e04086aaa72639bdf | 4,003 |
//
// BridgeCap.swift
//
// Generated on 20/09/18
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import RxSwift
import PromiseKit
// MARK: Constants
extension Constants {
public static var bridgeNamespace: String = "bridge"
public static var bridgeName: String = "Bridge"
}
// MARK: Attributes
fileprivate struct Attributes {
static let bridgePairedDevices: String = "bridge:pairedDevices"
static let bridgeUnpairedDevices: String = "bridge:unpairedDevices"
static let bridgePairingState: String = "bridge:pairingState"
static let bridgeNumDevicesSupported: String = "bridge:numDevicesSupported"
}
public protocol ArcusBridgeCapability: class, RxArcusService {
/** Map from bridge-owned device identifier to the protocol address of paired children devices */
func getBridgePairedDevices(_ model: DeviceModel) -> [String: String]?
/** Set of bridge-owned device identifiers that have been seen but not paired. */
func getBridgeUnpairedDevices(_ model: DeviceModel) -> [String]?
/** The current pairing state of the bridge device. PAIRING indicates that any new devices seen will be paired, UNPAIRING that devices are being removed and IDLE means neither */
func getBridgePairingState(_ model: DeviceModel) -> BridgePairingState?
/** Total number of devices this bridge can support. */
func getBridgeNumDevicesSupported(_ model: DeviceModel) -> Int?
/** Puts bridge into pairing mode for timeout seconds. Any devices seen while not in pairing mode will be immediately paired as well as any new devices discovered within the timeout period */
func requestBridgeStartPairing(_ model: DeviceModel, timeout: Int)
throws -> Observable<ArcusSessionEvent>/** Removes the bridge from pairing mode. */
func requestBridgeStopPairing(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent>
}
extension ArcusBridgeCapability {
public func getBridgePairedDevices(_ model: DeviceModel) -> [String: String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.bridgePairedDevices] as? [String: String]
}
public func getBridgeUnpairedDevices(_ model: DeviceModel) -> [String]? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.bridgeUnpairedDevices] as? [String]
}
public func getBridgePairingState(_ model: DeviceModel) -> BridgePairingState? {
let attributes: [String: AnyObject] = model.get()
guard let attribute = attributes[Attributes.bridgePairingState] as? String,
let enumAttr: BridgePairingState = BridgePairingState(rawValue: attribute) else { return nil }
return enumAttr
}
public func getBridgeNumDevicesSupported(_ model: DeviceModel) -> Int? {
let attributes: [String: AnyObject] = model.get()
return attributes[Attributes.bridgeNumDevicesSupported] as? Int
}
public func requestBridgeStartPairing(_ model: DeviceModel, timeout: Int)
throws -> Observable<ArcusSessionEvent> {
let request: BridgeStartPairingRequest = BridgeStartPairingRequest()
request.source = model.address
request.setTimeout(timeout)
return try sendRequest(request)
}
public func requestBridgeStopPairing(_ model: DeviceModel) throws -> Observable<ArcusSessionEvent> {
let request: BridgeStopPairingRequest = BridgeStopPairingRequest()
request.source = model.address
return try sendRequest(request)
}
}
| 38.864078 | 194 | 0.749938 |
712a9b8163a7eea414ecbf7de5dfc50e4816d6fa | 5,121 | /*
* PubMatic Inc. ("PubMatic") CONFIDENTIAL
* Unpublished Copyright (c) 2006-2021 PubMatic, All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property of PubMatic. The intellectual and technical concepts contained
* herein are proprietary to PubMatic and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material is strictly forbidden unless prior written permission is obtained
* from PubMatic. Access to the source code contained herein is hereby forbidden to anyone except current PubMatic employees, managers or contractors who have executed
* Confidentiality and Non-disclosure agreements explicitly covering such access or to such other persons whom are directly authorized by PubMatic to access the source code and are subject to confidentiality and nondisclosure obligations with respect to the source code.
*
* The copyright notice above does not evidence any actual or intended publication or disclosure of this source code, which includes
* information that is confidential and/or proprietary, and is a trade secret, of PubMatic. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION, PUBLIC PERFORMANCE,
* OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF PUBMATIC IS STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE
* LAWS AND INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS
* TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.
*/
import UIKit
import OpenWrapSDK
class IBVideoViewController: UIViewController,POBBannerViewDelegate {
let owAdUnit = "OpenWrapBannerAdUnit"
let pubId = "156276"
let profileId: NSNumber = 1757
var bannerView: POBBannerView?
override func viewDidLoad() {
super.viewDidLoad()
// Create a banner view
// For test IDs refer - https://community.pubmatic.com/x/IAI5AQ#TestandDebugYourIntegration-TestProfile/Placement
self.bannerView = POBBannerView(publisherId: pubId, profileId: profileId, adUnitId: owAdUnit, adSizes: [POBAdSizeMake(300, 250)])
// Set the delegate
self.bannerView?.delegate = self
// Add the banner view to your view hierarchy
addBannerToView(banner: self.bannerView!, adSize: CGSize(width: 300, height: 250))
// Load Ad
self.bannerView?.loadAd()
}
func addBannerToView(banner : POBBannerView?, adSize : CGSize) -> Void {
bannerView?.translatesAutoresizingMaskIntoConstraints = false
if let bannerView = bannerView {
view.addSubview(bannerView)
}
bannerView?.heightAnchor.constraint(equalToConstant: adSize.height).isActive = true
bannerView?.widthAnchor.constraint(equalToConstant: adSize.width).isActive = true
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
bannerView?.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true;
bannerView?.centerXAnchor.constraint(equalTo: guide.centerXAnchor).isActive = true
} else {
let margins = self.view.layoutMarginsGuide
bannerView?.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true;
bannerView?.centerXAnchor.constraint(equalTo: margins.centerXAnchor).isActive = true
}
}
// MARK: - Banner view delegate methods
//Provides a view controller to use for presenting model views
func bannerViewPresentationController() -> UIViewController {
return self
}
// Notifies the delegate that an ad has been successfully loaded and rendered.
func bannerViewDidReceiveAd(_ bannerView: POBBannerView) {
print("Banner : Ad received with size \(String(describing: bannerView.creativeSize())) ")
}
// Notifies the delegate of an error encountered while loading or rendering an ad.
func bannerView(_ bannerView: POBBannerView,
didFailToReceiveAdWithError error: Error) {
print("Banner : Ad failed with error : \(error.localizedDescription )")
}
// Notifies the delegate whenever current app goes in the background due to user click
func bannerViewWillLeaveApplication(_ bannerView: POBBannerView) {
print("Banner : Will leave app")
}
// Notifies the delegate that the banner ad view will launch a modal on top of the current view controller, as a result of user interaction.
func bannerViewWillPresentModal(_ bannerView: POBBannerView) {
print("Banner : Will present modal")
}
// Notifies the delegate that the banner ad view has dismissed the modal on top of the current view controller.
func bannerViewDidDismissModal(_ bannerView: POBBannerView) {
print("Banner : Dismissed modal")
}
deinit {
bannerView = nil
}
}
| 51.727273 | 269 | 0.72564 |
2f30b6a176934b492158435ffd87b584b6d00f3c | 2,791 | //
// SelectionViewMOdel.swift
// MealToday
//
// Created by Geonhyeong LIm on 2021/05/26.
//
import SwiftUI
import Combine
extension SelectionView2 {
final class ViewModel: ObservableObject {
@Published var query: String = ""
@Published var foodType: FoodType = FoodType.dessertOrMeal
@Injected private var selectionUseCase: SelectionUseCase
@Injected private var appState: AppState
private var selectedA: Int = 0
private var valueOfA: Int = 0
private var selectedB: Int = 0
private var valueOfB: Int = 0
init() {
getNextQuery()
}
func selectionA(with selection: Int) {
if selectedA == 0 {
self.selectedA = selectedA + 1
self.valueOfA = selection
if self.selectedA == 1 && self.selectedB == 1 {
if valueOfB == 1 && valueOfA == 1 {
selectionUseCase.addChoice(for: foodType, isChosen: true)
} else {
selectionUseCase.addChoice(for: foodType, isChosen: false)
}
resetSelectedValue()
getNextQuery()
}
}
}
func selectionB(with selection: Int) {
if selectedB == 0 {
self.selectedB = selectedB + 1
self.valueOfB = selection
if self.selectedA == 1 && self.selectedB == 1 {
if valueOfB == 1 && valueOfA == 1 {
selectionUseCase.addChoice(for: foodType, isChosen: true)
} else {
selectionUseCase.addChoice(for: foodType, isChosen: false)
}
resetSelectedValue()
getNextQuery()
}
}
}
func onYes() {
selectionUseCase.addChoice(for: foodType, isChosen: true)
getNextQuery()
}
func onNo() {
selectionUseCase.addChoice(for: foodType, isChosen: false)
getNextQuery()
}
func resetSelectedValue() {
self.selectedA = 0
self.selectedB = 0
self.valueOfA = 0
self.valueOfB = 0
}
// MARK: - Private
private var cancelBag = Set<AnyCancellable>()
private func getNextQuery() {
selectionUseCase.getNextQuery().sink { [weak self] type in
if let type = type {
self?.foodType = type
self?.query = type.rawValue
} else {
self?.appState.viewRouting = .resultView
}
}.store(in: &cancelBag)
}
}
}
| 30.010753 | 82 | 0.493372 |
717e7456881211b5a00ae8e63b4fd5f2895ec94d | 2,736 | //
// BirdsTableViewController.swift
// HappyBird
//
// Created by Utshaho Gupta on 12/27/20.
//
import Foundation
import UIKit
import Alamofire
class BirdCell: UITableViewCell {
@IBOutlet var birdName: UILabel!
@IBOutlet var birdPhoto: UIImageView!
var name: String!
var url: String?
var request: Alamofire.Request?
override func prepareForReuse() {
super.prepareForReuse()
request?.cancel()
request = nil
birdName.text = nil
birdPhoto.image = UIImage(named: "PlaceholderImage")
url = nil
name = nil
}
}
class BirdsTableViewController: UITableViewController {
var family: Family!
var selectedBird: Bird? = nil
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
self.title = self.family.groupName
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return family.birds?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> BirdCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BirdCell", for: indexPath) as! BirdCell
guard let birds = family.birds else { return cell }
let bird = birds[indexPath.row]
cell.birdName.text = bird.comName
cell.name = bird.comName
PhotoDataService.shared.getPhotoURL(birds: [bird], size: "q") { url in
guard let url = url, cell.name == bird.comName else { return }
cell.url = url
cell.request = DataService.shared.request(url) { data, request in
cell.request = nil
guard let data = data, cell.name == bird.comName else { return }
DispatchQueue.main.async {
cell.birdPhoto.image = UIImage(data: data)?.cropMargins()
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectItemAt indexPath: IndexPath) {
selectedBird = BirdDataService.shared.birds[indexPath.row]
print(selectedBird?.comName as Any)
return
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewDetail" {
if let destVC = segue.destination as? BirdDetailViewController {
if let indexPath = self.tableView.indexPathForSelectedRow {
selectedBird = family.birds![indexPath.row]
destVC.bird = selectedBird
}
}
}
}
}
| 32.188235 | 105 | 0.613304 |
f990a9ce8ce0525638d7b60b30860dedf4540459 | 4,477 | //
// CalendarView.swift
// PeriodTracker
//
// Created by Rene B. Dena on 7/9/21.
//
import SwiftUI
/// Shows the calendar with the date selections
struct CalendarView: View {
@Binding var month: Date
@Binding var currentSelectedDate: Date?
/// Selected dates and the colors
let selectedDates: [Date]
let selectedDatesColors: [Date: Color]
/// Header and Footer views for the calendar
let headerView: AnyView
let footerView: AnyView
// MARK: - Main rendering function
var body: some View {
VStack(spacing: 15) {
headerView
CalendarMainView
footerView
}
}
// MARK: - Create the days of the week header view
private var WeekdaysHeaderView: some View {
HStack {
ForEach(Calendar.current.shortWeekdaySymbols, id: \.self, content: { day in
ZStack {
Rectangle().hidden()
Text(day.uppercased()).bold()
}.lineLimit(1).minimumScaleFactor(0.5)
})
}.frame(height: 50)
}
// MARK: - Calendar view
private var CalendarMainView: some View {
VStack(spacing: 0) {
WeekdaysHeaderView
Divider()
ForEach(weeks, id: \.self) { week in
WeekView(week: week)
}.frame(height: 50)
}.padding([.leading, .trailing], 20).padding([.top, .bottom], 10).background(
RoundedRectangle(cornerRadius: 30).foregroundColor(.white)
.shadow(color: Color.black.opacity(0.1), radius: 10)
).padding([.leading, .trailing], 20)
}
// MARK: - Create the week view
private func WeekView(week: Date) -> some View {
HStack(spacing: 0) {
ForEach(days(week: week), id: \.self) { date in
HStack {
/// Date of the week button
Button(action: {
UIImpactFeedbackGenerator().impactOccurred()
currentSelectedDate = date
}, label: {
WeekdayTextView(date: date, week: week)
}).foregroundColor(selectedDates.contains(date) ? .white : .black)
}
}
}
}
/// Week day text
private func WeekdayTextView(date: Date, week: Date) -> some View {
ZStack {
/// Background view for each day
Rectangle().foregroundColor(.clear).background(
ZStack {
/// Current selected date to be marked accordingly
if currentSelectedDate == date && date < Date() {
Circle().foregroundColor(Color(#colorLiteral(red: 0.9329922199, green: 0.9263274074, blue: 0.9380961061, alpha: 1))).overlay(
Circle().strokeBorder(Color(#colorLiteral(red: 0.8559404016, green: 0.8606798053, blue: 0.872363925, alpha: 1)), lineWidth: 1)
)
} else {
/// Marked selected day
if selectedDates.contains(date) {
Circle().foregroundColor(selectedDatesColors[date])
}
}
}.padding(8)
)
if Calendar.current.isDate(week, equalTo: date, toGranularity: .month) && date < Date() {
Text(date.day)
.font(.system(size: Calendar.current.isDateInToday(date) ? 22 : 20, weight: Calendar.current.isDateInToday(date) ? .bold : .regular))
} else {
Text(date.day).opacity(selectedDates.contains(date) ? 1 : 0.2)
}
}
}
/// Get all the weeks for the current selected month
private var weeks: [Date] {
guard let monthInterval = Calendar.current.dateInterval(of: .month, for: month)
else { return [] }
return Calendar.current.generateDates(inside: monthInterval, matching: DateComponents(hour: 0, minute: 0, second: 0, weekday: Calendar.current.firstWeekday))
}
/// Get all the days for a given week day
private func days(week: Date) -> [Date] {
guard let weekInterval = Calendar.current.dateInterval(of: .weekOfYear, for: week)
else { return [] }
return Calendar.current.generateDates(inside: weekInterval, matching: DateComponents(hour: 0, minute: 0, second: 0))
}
}
| 37.940678 | 165 | 0.545455 |
7930e43389ea2a482931f5206afc89fc3af6e26c | 422 | //
// DispatchQueue+Helpers.swift
// Swiftlier
//
// Created by Andrew J Wagner on 2/2/17.
// Copyright ยฉ 2017 Drewag. All rights reserved.
//
#if os(iOS)
import Foundation
extension DispatchQueue {
public func asyncAfter(seconds: Double, execute work: @escaping @convention(block) () -> ()) {
let time = DispatchTime.now() + seconds
self.asyncAfter(deadline: time, execute: work)
}
}
#endif
| 22.210526 | 98 | 0.665877 |
fc61a1b1b5b956354d4d83a996cab20d392f050c | 361 | //
// BeatBoxModel.swift
// BeatBox
//
// Created by Shailendra Barewar on 31/12/20.
// Copyright ยฉ 2020 Khoa Vo. All rights reserved.
//
import Foundation
class BeatBoxModel : NSObject {
var date: String?
var genre: String?
var name: String?
var videoData: String?
var musicGenreSoundId: String?
var musicGenreId: String?
}
| 17.190476 | 50 | 0.66482 |
188f611619a44f8526b0e8d588857df0b55f07c9 | 1,029 | //
// TextCellViewModel.swift
// Sbirka
//
// Created by ะะณะพัั on 02/01/2018.
// Copyright ยฉ 2018 Xuli. All rights reserved.
//
import Foundation
import UIKit
public class TextCellViewModel: BaseAutolayoutCellViewModel {
var text: NSAttributedString!
var aligment: NSTextAlignment!
var top: CGFloat = 0
var bottom: CGFloat = 0
var left: CGFloat = 0
var right: CGFloat = 0
var height: CGFloat?
public init(text: NSAttributedString, id: String = UUID().uuidString, aligment: NSTextAlignment = .left, background: UIColor = UIColor.clear, top: CGFloat = 0, bottom: CGFloat = 0, left: CGFloat = 16, right: CGFloat = 16, height: CGFloat? = nil) {
super.init(id: id)
self.text = text
self.aligment = aligment
self.background = background
self.top = top
self.bottom = bottom
self.left = left
self.right = right
self.height = height
}
override var cellHeight: CGFloat? {
return height
}
}
| 27.078947 | 251 | 0.633625 |
bbe5a911eab5c66fd83e7aaf116c2250661f0f3e | 2,072 | extension Document: ExpressibleByArrayLiteral {
/// Gets all top level values in this Document
public var values: [Primitive] {
ensureFullyCached()
return cache.cachedDimensions.compactMap(self.readPrimitive)
}
public subscript(index: Int) -> Primitive {
get {
repeat {
if cache.count > index {
return self[valueFor: cache[index].dimensions]
}
_ = self.scanValue(startingAt: cache.lastScannedPosition, mode: .single)
} while !self.fullyCached
fatalError("Index \(index) out of range")
}
set {
repeat {
if cache.count > index {
self.write(newValue, forDimensions: cache[index].dimensions, key: "\(index)")
}
_ = self.scanValue(startingAt: cache.lastScannedPosition, mode: .single)
} while !self.fullyCached
// TODO: Investigate other options than fatalError()
fatalError("Index \(index) out of range")
}
}
/// Appends a `Value` to this `Document` where this `Document` acts like an `Array`
///
/// TODO: Analyze what should happen with `Dictionary`-like documents and this function
///
/// - parameter value: The `Value` to append
public mutating func append(_ value: Primitive) {
let key = String(self.count)
self.write(value, forKey: key)
}
public init(arrayLiteral elements: PrimitiveConvertible...) {
self.init(array: elements.compactMap { $0.makePrimitive() } )
}
/// Converts an array of Primitives to a BSON ArrayDocument
public init(array: [Primitive]) {
self.init(isArray: true)
for element in array {
self.append(element)
}
}
}
extension Array where Element == Primitive {
public init(valuesOf document: Document) {
self = document.values
}
}
| 31.876923 | 97 | 0.557915 |
7221750788f0dcd4e5968bf5275b9cebad5834be | 5,630 | //
// SequenceConverterTests.swift
// SequenceConverterTests
//
// Created by Andrey Volobuev on 30/05/2017.
// Copyright ยฉ 2017 Andrey Volobuev. All rights reserved.
//
import XCTest
@testable import SequenceConverter
class SequenceConverterTests: XCTestCase {
// Comma space tests
func testFormatterBothItemsNotNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", "2")
let expected = ", 1, 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when all items are not nil")
}
func testFormatterFirstItemIsNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat(nil, "2")
let expected = ", 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when first item is nil")
}
func testFormatterSecodItemIsNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", nil)
let expected = ", 1"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when second item is nil")
}
func testFormatterBothItemsAreNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat(nil, nil)
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when both item are nil")
}
func testFormatterTreeItems() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", "2", "3")
let expected = ", 1, 2, 3"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
// Space tests
func testSpaceFormatterBothItemsNotNil() {
let formatted = SequenceConverter.middleSpaceFormat("1", "2")
let expected = "1 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when all items are not nil")
}
func testSpacFormatterFirstItemIsNil() {
let formatted = SequenceConverter.middleSpaceFormat(nil, "2")
let expected = "2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when first item is nil")
}
func testSpacFormatterSecodItemIsNil() {
let formatted = SequenceConverter.middleSpaceFormat("1", nil)
let expected = "1"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when second item is nil")
}
func testSpacFormatterBothItemsAreNil() {
let formatted = SequenceConverter.middleSpaceFormat(nil, nil)
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when both item are nil")
}
func testSpacFormatterTreeItems() {
let formatted = SequenceConverter.middleSpaceFormat("1", "2", "3")
let expected = "1 2 3"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
// Separator tests
func testThreeSeparartor() {
let arr: [CustomStringConvertible?] = ["1", "2", "3"]
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|2|3->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
func testOneSeparartor() {
let formatted = ["1"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when one item")
}
func testTwoSeparartor() {
let formatted = ["1", "2"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|2->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when two items")
}
func testEmptySeparartor() {
let arr: [CustomStringConvertible?] = [String]()
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when empty")
}
func testNilSeparartor() {
let arr: [CustomStringConvertible?] = [nil]
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when nil")
}
func testMultipleEmptySeparartor() {
let formatted = ["1", "", "", "", "4", "5"].toStringWithSeparators(before: "<-", between: "|", after: "->")
let expected = "<-1|4|5->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are empty")
}
func testMultipleNilSeparartor() {
let formatted = ["1", nil, nil, nil, "4", "5"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|4|5->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are nil")
}
func testMultipleEmptyAndNilSeparartor() {
let formatted = [nil, "1", "", nil, "", "4", nil, ""].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|4->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are empty and nil")
}
}
| 42.977099 | 125 | 0.62913 |
7a5dd97bc8778c6cf213b526e2999225bbba37c3 | 205 | //
// Copyright ยฉ 2020 Bunny Wong
// Created on 2019/12/19.
//
import UIKit
import PlaygroundSupport
import BookCore
PlaygroundPage.current.liveView = instantiateLiveView(identifier: .howImagesComposed)
| 18.636364 | 85 | 0.790244 |
e8acea0419ea4f77e4761cdc826a87ebb91f149f | 4,177 | //
// ContentView.swift
// Shared
//
// Created on 19/7/2020.
//
import SwiftUI
import GoogleSignIn
struct ContentView: View {
@ObservedObject var info : AppDelegate
var body: some View {
VStack{
Group{
Spacer()
Text("Learn")
.font(.largeTitle)
.fontWeight(.bold)
Text("Startway.io")
// Email ID Display
Text(info.email)
.padding(.top,25)
}
Group{
Text(" ")
Spacer()
Divider()
Text(" ")
}
HStack{
Image(systemName: "lock.rectangle.stack")
Text("Login Credential")
.font(.callout)
.fontWeight(.regular)
}
Text(" ")
// Apple Login Button
Button(action: {
GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.first?.rootViewController
GIDSignIn.sharedInstance()?.signIn()
}) {
Text(" ๏ฃฟ Sign in with Apple ")
.foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical, 10)
.padding(.horizontal, 45)
.background(Color.black)
.clipShape(Capsule())
}
Text(" ")
// Google Login Button
Button(action: {
GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.first?.rootViewController
GIDSignIn.sharedInstance()?.signIn()
}) {
Text(" Sign in with Google ")
.foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical, 10)
.padding(.horizontal, 45)
.background(Color.blue)
.clipShape(Capsule())
}
Text(" ")
}
}
}
struct ContentView_Previews: PreviewProvider {
@ObservedObject var info : AppDelegate
static var previews: some View {
VStack{
Group{
Spacer()
Text("Learn")
.font(.largeTitle)
.fontWeight(.bold)
Text("Startway.io")
}
Group{
Text(" ")
Spacer()
Divider()
Text(" ")
}
HStack{
Image(systemName: "lock.rectangle.stack")
Text("Login Credential")
.font(.callout)
.fontWeight(.regular)
}
Text(" ")
// Apple Login Button
Button(action: {
GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.first?.rootViewController
GIDSignIn.sharedInstance()?.signIn()
}) {
Text(" ๏ฃฟ Sign in with Apple ")
.foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical, 10)
.padding(.horizontal, 45)
.background(Color.black)
.clipShape(Capsule())
}
Text(" ")
// Google Login Button
Button(action: {
GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.first?.rootViewController
GIDSignIn.sharedInstance()?.signIn()
}) {
Text(" Sign in with Google ")
.foregroundColor(.white)
.fontWeight(.bold)
.padding(.vertical, 10)
.padding(.horizontal, 45)
.background(Color.blue)
.clipShape(Capsule())
}
}
}
}
| 32.889764 | 129 | 0.42327 |
d525480c7b9f8e649e3050b881cfb34b534be263 | 1,868 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import GoogleMaps
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("YOUR_API_KEY")
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 41.511111 | 177 | 0.772484 |
2f79a6ab60ba77821e8cebc0267c6b8e90b4855f | 985 |
import Foundation
public struct ProDraftPreviewLocation : Codable {
public let location_state : String?
public let parent : String?
public let area : String?
public let postal_code : String?
public let lat : String?
public let lng : String?
enum CodingKeys: String, CodingKey {
case location_state = "location_state"
case parent = "parent"
case area = "area"
case postal_code = "postal_code"
case lat = "lat"
case lng = "lng"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
location_state = try values.decodeIfPresent(String.self, forKey: .location_state)
parent = try values.decodeIfPresent(String.self, forKey: .parent)
area = try values.decodeIfPresent(String.self, forKey: .area)
postal_code = try values.decodeIfPresent(String.self, forKey: .postal_code)
lat = try values.decodeIfPresent(String.self, forKey: .lat)
lng = try values.decodeIfPresent(String.self, forKey: .lng)
}
}
| 29.848485 | 83 | 0.740102 |
f836c6997a5eecc5f87d64afa690d2ef50ede5bd | 304 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[[Void{
{ func a
class a: b { func g<C) {
{
Void{
let f = [[[Void{
case c,
{
return m((v: B? {
struct B? {
{
class
case c,
return m(((
| 16 | 87 | 0.667763 |
f9de28a47706b20456cad50a22640af97ac6dad7 | 291 | //
// UITableViewCell+Identifier.swift
// iOSSampler
//
// Created by Yuki Okudera on 2020/01/09.
// Copyright ยฉ 2020 YukiOkudera. All rights reserved.
//
import UIKit
extension UITableViewCell {
static var identifier: String {
return String(describing: self)
}
}
| 17.117647 | 54 | 0.676976 |
1a8a82b29fa1844008bb8e182ae875d47bd45450 | 1,246 | //
// HomeViewModelImpl.swift
// XCoordinator_Example
//
// Created by Paul Kraft on 20.11.18.
// Copyright ยฉ 2018 QuickBird Studios. All rights reserved.
//
import Action
import RxSwift
import XCoordinator
class HomeViewModelImpl: HomeViewModel, HomeViewModelInput, HomeViewModelOutput {
// MARK: - Inputs
private(set) lazy var logoutTrigger: InputSubject<Void> = logoutAction.inputs
private(set) lazy var usersTrigger: InputSubject<Void> = usersAction.inputs
private(set) lazy var aboutTrigger: InputSubject<Void> = aboutAction.inputs
// MARK: - Actions
private lazy var logoutAction = CocoaAction { [unowned self] in
self.router.rx.trigger(.logout)
}
private lazy var usersAction = CocoaAction { [unowned self] in
self.router.rx.trigger(.users)
}
private lazy var aboutAction = CocoaAction { [unowned self] in
self.router.rx.trigger(.about)
}
// MARK: - Private
private let router: AnyRouter<UserListRoute>
// MARK: - Init
init(router: AnyRouter<UserListRoute>) {
self.router = router
}
// MARK: - Methods
func registerPeek(for sourceView: Container) {
router.trigger(.registerUsersPeek(from: sourceView))
}
}
| 24.92 | 81 | 0.687801 |
2f0ef17c1ba4630fceaea22dace9a0623381238a | 2,705 | //
// StubDataGridViewDataSource.swift
//
// Created by Vladimir Lyukov on 03/08/15.
//
import UIKit
import GlyuckDataGrid
class StubDataGridViewDataSource: NSObject, DataGridViewDataSource {
var numberOfColumns = 7
var numberOfRows = 20
func numberOfColumnsInDataGridView(_ dataGridView: DataGridView) -> Int {
return numberOfColumns
}
func numberOfRowsInDataGridView(_ dataGridView: DataGridView) -> Int {
return numberOfRows
}
func dataGridView(_ dataGridView: DataGridView, titleForHeaderForColumn column: Int) -> String {
return "Title for column \(column)"
}
func dataGridView(_ dataGridView: DataGridView, titleForHeaderForRow row: Int) -> String {
return "Title for row \(row)"
}
func dataGridView(_ dataGridView: DataGridView, textForCellAtIndexPath indexPath: IndexPath) -> String {
return "Text for cell \(indexPath.dataGridColumn)x\(indexPath.dataGridRow)"
}
}
class StubDataGridViewDataSourceCustomCell: StubDataGridViewDataSource {
var cellForItemBlock: ((dataGridView: DataGridView, indexPath: IndexPath)) -> UICollectionViewCell = { (dataGridView, indexPath) in
let cell = dataGridView.dequeueReusableCellWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultCell, forIndexPath: indexPath)
cell.tag = indexPath.dataGridColumn * 100 + indexPath.dataGridRow
return cell
}
var viewForColumnHeaderBlock: ((dataGridView: DataGridView, column: Int)) -> DataGridViewColumnHeaderCell = { (dataGridView, column) in
let view = dataGridView.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultColumnHeader, forColumn: column)
view.tag = column
return view
}
var viewForRowHeaderBlock: ((dataGridView: DataGridView, row: Int)) -> DataGridViewRowHeaderCell = { (dataGridView, row) in
let view = dataGridView.dequeueReusableHeaderViewWithReuseIdentifier(DataGridView.ReuseIdentifiers.defaultRowHeader, forRow: row)
view.tag = row
return view
}
func dataGridView(_ dataGridView: DataGridView, viewForHeaderForColumn column: Int) -> DataGridViewColumnHeaderCell {
return viewForColumnHeaderBlock((dataGridView: dataGridView, column: column))
}
func dataGridView(_ dataGridView: DataGridView, viewForHeaderForRow row: Int) -> DataGridViewRowHeaderCell {
return viewForRowHeaderBlock((dataGridView: dataGridView, row: row))
}
func dataGridView(_ dataGridView: DataGridView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
return cellForItemBlock((dataGridView: dataGridView, indexPath: indexPath))
}
}
| 39.779412 | 146 | 0.743808 |
211fe73b5b814ef214ae29b881b098775e648aaf | 1,175 | //
// StringExtensions.swift
// Bish
//
// Created by Martin Kim Dung-Pham on 31.05.17.
// Copyright ยฉ 2017 elbedev.com. All rights reserved.
//
import UIKit
enum FontSize: CGFloat {
case big = 60
case small = 32
}
enum FontName: String {
case bold = "Menlo-Bold"
case regular = "Menlo"
}
extension String {
func attributedBigText() -> NSAttributedString {
return NSAttributedString(string: self, attributes: bigTextAttributes())
}
func attributedSmallText() -> NSAttributedString {
return NSAttributedString(string: self, attributes: smallTextAttributes())
}
private func bigTextAttributes() -> [NSAttributedStringKey: Any] {
return [NSAttributedStringKey.font: UIFont.init(name: FontName.bold.rawValue, size: FontSize.big.rawValue)!,
NSAttributedStringKey.foregroundColor: UIColor.white]
}
private func smallTextAttributes() -> [NSAttributedStringKey: Any] {
return [NSAttributedStringKey.font: UIFont.init(name: FontName.regular.rawValue, size: FontSize.small.rawValue)!,
NSAttributedStringKey.foregroundColor: UIColor.white]
}
}
| 28.658537 | 121 | 0.682553 |
e69e08d53aca75ba160f060730e89827d3316d5b | 9,000 | //
// Copyright 2020 Wultra s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
extension DocumentationDatabase {
/// Transform all `codetabs` or `tabs` metadata objects in all documents.
/// - Returns: true if everyghing was OK.
func updateCodeTabs() -> Bool {
Console.info("Building code tabs...")
var result = true
allDocuments().forEach { document in
// Process all <!-- begin codetabs ... --> metadata objects
document.allMetadata(withName: "codetabs", multiline: true).forEach { metadata in
let partialResult = self.updateCodeTabs(document: document, metadata: metadata)
result = result && partialResult
}
// Find all <!-- tab name --> metadata objects and create map with inline identifiers.
let allTabMarkers: [EntityId:MarkdownMetadata] = document.allMetadata(withName: "tab", multiline: false).reduce(into: [:]) { $0[$1.beginInlineCommentId] = $1 }
// Process all <!-- begin tabs --> metadata objects
document.allMetadata(withName: "tabs", multiline: true).forEach { metadata in
let partialResult = self.updateTabs(document: document, metadata: metadata, tabMarkers: allTabMarkers)
result = result && partialResult
}
}
return result
}
/// Transform `<!-- begin codetabs -->` metadata into `{% codetabs %}`.
/// - Parameters:
/// - document: Current document
/// - metadata: Metadata object contains codetabs.
/// - Returns: true in case of success.
private func updateCodeTabs(document: MarkdownDocument, metadata: MarkdownMetadata) -> Bool {
let tabNames = metadata.parameters ?? []
if tabNames.isEmpty {
Console.warning(document, metadata.beginLine, "'\(metadata.name)' marker has no tab names specified.")
}
// Acquire all lines
guard let oldLines = document.getLinesForMetadata(metadata: metadata, includeMarkers: false, removeLines: false) else {
Console.error(document, metadata.beginLine, "updateCodeTabs: Failed to acquire lines for '\(metadata.name)' metadata marker.")
return false
}
var codeBlocks = [[MarkdownLine]]()
var currentBlock = [MarkdownLine]()
var isInCodeBlock = false
for line in oldLines {
let isCodeBlockAtEnd = line.parserStateAtEnd.isCodeBlock
currentBlock.append(line)
if isInCodeBlock != isCodeBlockAtEnd {
// State has changed for this line
if !isCodeBlockAtEnd {
codeBlocks.append(currentBlock)
currentBlock.removeAll()
}
isInCodeBlock = isCodeBlockAtEnd
}
}
if !currentBlock.isEmpty {
codeBlocks.append(currentBlock)
}
return applyCodeTabs(document: document, metadata: metadata, tabNames: tabNames, tabContent: codeBlocks)
}
/// Transform `<!-- begin tabs -->` metadata into `{% codetabs %}`.
/// - Parameters:
/// - document: Document
/// - metadata: Metadata object
/// - tabMarkers: Dictionary with mapping from entity identifier to `<!-- tab -->` metadata object
/// - Returns: true in case of success.
private func updateTabs(document: MarkdownDocument, metadata: MarkdownMetadata, tabMarkers: [EntityId:MarkdownMetadata]) -> Bool {
// Acquire all lines
guard let oldLines = document.getLinesForMetadata(metadata: metadata, includeMarkers: false, removeLines: false) else {
Console.error(document, metadata.beginLine, "updateTabs: Failed to acquire lines for '\(metadata.name)' metadata marker.")
return false
}
var tabNames = [String]()
var tabBlocks = [[MarkdownLine]]()
var currentBlock = [MarkdownLine]()
for line in oldLines {
let copyLine: Bool
if let tabMetadata = findTabInLine(line: line, tabMarkers: tabMarkers) {
// It's also "tab" metadata marker
if let tabName = tabMetadata.parameters?.first {
tabNames.append(tabName)
} else {
Console.warning(document, tabMetadata.beginLine, "'\(tabMetadata.name)' marker must contain tab name. Using placeholder name.")
tabNames.append("Tab_\(tabNames.count + 1)")
}
if !currentBlock.isEmpty {
tabBlocks.append(currentBlock)
currentBlock.removeAll()
}
copyLine = false
} else {
// Unknown inline comment, just copy this line
copyLine = true
}
if copyLine {
if !tabNames.isEmpty {
currentBlock.append(line)
} else {
Console.warning(document, line.identifier, "'\(metadata.name)' marker contains lines without tab name specified. Use '<!-- tab NAME -->' before this content.")
}
}
}
if !currentBlock.isEmpty {
tabBlocks.append(currentBlock)
}
return applyCodeTabs(document: document, metadata: metadata, tabNames: tabNames, tabContent: tabBlocks)
}
/// Find metadata object matching one of inline comments available in the line.
/// - Parameters:
/// - line: Line containing inline comments.
/// - tabMarkers: All tab metadata objects.
/// - Returns: Metadata object or nil if no such object has been matched.
private func findTabInLine(line: MarkdownLine, tabMarkers: [EntityId:MarkdownMetadata]) -> MarkdownMetadata? {
for comment in line.allEntities(withType: .inlineComment) {
if let metadata = tabMarkers[comment.identifier] {
return metadata
}
}
return nil
}
/// Apply `codetabs` or `tabs` changes to the document.
/// - Parameters:
/// - document: Current document
/// - metadata: Metadata object containing `codetabs` or `tabs`
/// - names: Tab names
/// - tabContent: Content of tabs.
/// - Returns: true in case of success.
private func applyCodeTabs(document: MarkdownDocument, metadata: MarkdownMetadata, tabNames names: [String], tabContent: [[MarkdownLine]]) -> Bool {
var tabNames = names
if tabContent.count != tabNames.count {
if tabContent.count > tabNames.count {
Console.warning(document, metadata.beginLine, "'\(metadata.name)' meta tag contains more code blocks than tab names. Using placeholder names.")
tabNames.append(contentsOf: (tabNames.count...tabContent.count).map { "Tab_\($0)" })
} else {
Console.warning(document, metadata.beginLine, "'\(metadata.name)' meta tag contains less code blocks than tab names. Ignoring remaining tab names.")
}
}
// Prepare markers
let codeTabsMarkers = document.prepareLinesForAdd(lines: ["{% codetabs %}", "{% endcodetabs %}"])
let partialTabsMarkers = document.prepareLinesForAdd(lines: tabNames.flatMap { tabName -> [String] in
return [ "{% codetab \(tabName) %}", "{% endcodetab %}" ]
})
var newLines = [MarkdownLine]()
// Leading marker
newLines.append(codeTabsMarkers[0])
for (index, codeBlock) in tabContent.enumerated() {
newLines.append(partialTabsMarkers[index * 2]) // {% codetab XX %}
newLines.append(contentsOf: codeBlock) // code block lines
newLines.append(partialTabsMarkers[index * 2 + 1]) // {% codetab XX %}
}
// Trailing marker
newLines.append(codeTabsMarkers[1])
// Make modifications in document
guard let startLine = document.lineNumber(forLineIdentifier: metadata.beginLine) else {
Console.error(document, metadata.beginLine, "applyCodeTabs: Failed to acquire start line number.")
return false
}
document.removeLinesForMetadata(metadata: metadata, includeMarkers: true)
document.add(lines: newLines, at: startLine)
return true
}
}
| 44.334975 | 179 | 0.603444 |
79375872b7ba6b17af47ad09d33a410955114879 | 1,407 | //
// AppDelegate.swift
// LetcodeOffer
//
// Created by Cocos on 2020/3/9.
// Copyright ยฉ 2020 Cocos. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.026316 | 179 | 0.746979 |
71001631c001f20f76fb6939909b328cd67e3c27 | 488 | //
// InProgressView.swift
// SampleApp
//
// Created by Shinya Kumagai on 2020/10/29.
//
import SwiftUI
// MARK: - InProgressView
struct InProgressView: View {
var body: some View {
ProgressView("Loading...")
.progressViewStyle(CircularProgressViewStyle(tint: .gray))
.foregroundColor(.black)
.padding()
}
}
struct InProgressView_Previews: PreviewProvider {
static var previews: some View {
InProgressView()
}
}
| 18.769231 | 70 | 0.633197 |
69f667b9a38b5b3e57343f9573e4b748ff294ce1 | 1,053 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Redux",
platforms: [
.iOS(.v13), .macOS(.v10_15),
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Redux",
targets: ["Redux"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Redux",
dependencies: []),
.testTarget(
name: "ReduxTests",
dependencies: ["Redux"]),
]
)
| 32.90625 | 117 | 0.59924 |
1d39966f4df8dd3f2ae4d5fa7cce96e3c80c0cae | 589 | //
// CZImageView.swift
// GZWeibo05
//
// Created by zhangping on 15/11/9.
// Copyright ยฉ 2015ๅนด zhangping. All rights reserved.
//
import UIKit
class CZImageView: UIImageView {
// ่ฆ็็ถ็ฑป็ๅฑๆง
override var transform: CGAffineTransform {
didSet {
// ๅฝ่ฎพ็ฝฎ็็ผฉๆพๆฏไพๅฐไบๆๅฎ็ๆๅฐ็ผฉๆพๆฏไพๆถ.้ๆฐ่ฎพ็ฝฎ
if transform.a < CZPhotoBrowserCellMinimumZoomScale {
// print("่ฎพ็ฝฎ transform.a:\(transform.a)")
transform = CGAffineTransformMakeScale(CZPhotoBrowserCellMinimumZoomScale, CZPhotoBrowserCellMinimumZoomScale)
}
}
}
}
| 23.56 | 126 | 0.641766 |
ac58624ac2ab5465a94bd882a17ea93c57fbfa54 | 16,508 | //
// Script.swift
//
// Copyright ยฉ 2018 Kishikawa Katsumi
// Copyright ยฉ 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class Script {
// An array of Data objects (pushing data) or UInt8 objects (containing opcodes)
private var chunks: [ScriptChunk]
// Cached serialized representations for -data and -string methods.
private var dataCache: Data?
private var stringCache: String?
public var data: Data {
// When we calculate data from scratch, it's important to respect actual offsets in the chunks as they may have been copied or shifted in subScript* methods.
if let cache = dataCache {
return cache
}
dataCache = chunks.reduce(Data()) { $0 + $1.chunkData }
return dataCache!
}
public var string: String {
if let cache = stringCache {
return cache
}
stringCache = chunks.map { $0.string }.joined(separator: " ")
return stringCache!
}
public var hex: String {
return data.hex
}
public func toP2SH() -> Script {
return try! Script()
.append(.OP_HASH160)
.appendData(Crypto.sha256ripemd160(data))
.append(.OP_EQUAL)
}
public func standardP2SHAddress(network: Network) -> Address {
let scriptHash: Data = Crypto.sha256ripemd160(data)
return Cashaddr(data: scriptHash, type: .scriptHash, network: network)
}
// Multisignature script attribute.
// If multisig script is not detected, this is nil
public typealias MultisigVariables = (nSigRequired: UInt, publickeys: [PublicKey])
public var multisigRequirements: MultisigVariables?
public init() {
self.chunks = [ScriptChunk]()
}
public init(chunks: [ScriptChunk]) {
self.chunks = chunks
}
public convenience init?(data: Data) {
// It's important to keep around original data to correctly identify the size of the script for BTC_MAX_SCRIPT_SIZE check
// and to correctly calculate hash for the signature because in BitcoinQT scripts are not re-serialized/canonicalized.
do {
let chunks = try Script.parseData(data)
self.init(chunks: chunks)
} catch let error {
print(error)
return nil
}
}
public convenience init?(hex: String) {
guard let scriptData = Data(hex: hex) else {
return nil
}
self.init(data: scriptData)
}
public convenience init?(address: Address) {
self.init()
switch address.type {
case .pubkeyHash:
// OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG
do {
try self.append(.OP_DUP)
.append(.OP_HASH160)
.appendData(address.data)
.append(.OP_EQUALVERIFY)
.append(.OP_CHECKSIG)
} catch {
return nil
}
case .scriptHash:
// OP_HASH160 <hash> OP_EQUAL
do {
try self.append(.OP_HASH160)
.appendData(address.data)
.append(.OP_EQUAL)
} catch {
return nil
}
default:
return nil
}
}
// OP_<M> <pubkey1> ... <pubkeyN> OP_<N> OP_CHECKMULTISIG
public convenience init?(publicKeys: [PublicKey], signaturesRequired: UInt) {
// First make sure the arguments make sense.
// We need at least one signature
guard signaturesRequired > 0 else {
return nil
}
// And we cannot have more signatures than available pubkeys.
guard publicKeys.count >= signaturesRequired else {
return nil
}
// Both M and N should map to OP_<1..16>
let mOpcode: OpCode = OpCodeFactory.opcode(for: Int(signaturesRequired))
let nOpcode: OpCode = OpCodeFactory.opcode(for: publicKeys.count)
guard mOpcode != .OP_INVALIDOPCODE else {
return nil
}
guard nOpcode != .OP_INVALIDOPCODE else {
return nil
}
do {
self.init()
try append(mOpcode)
for pubkey in publicKeys {
try appendData(pubkey.raw)
}
try append(nOpcode)
try append(.OP_CHECKMULTISIG)
multisigRequirements = (signaturesRequired, publicKeys)
} catch {
return nil
}
}
private static func parseData(_ data: Data) throws -> [ScriptChunk] {
guard !data.isEmpty else {
return [ScriptChunk]()
}
var chunks = [ScriptChunk]()
var i: Int = 0
let count: Int = data.count
while i < count {
// Exit if failed to parse
let chunk = try ScriptChunkHelper.parseChunk(from: data, offset: i)
chunks.append(chunk)
i += chunk.range.count
}
return chunks
}
public var isStandard: Bool {
return isPayToPublicKeyHashScript
|| isPayToScriptHashScript
|| isPublicKeyScript
|| isStandardMultisignatureScript
}
public var isPublicKeyScript: Bool {
guard chunks.count == 2 else {
return false
}
guard let pushdata = pushedData(at: 0) else {
return false
}
return pushdata.count > 1 && opcode(at: 1) == OpCode.OP_CHECKSIG
}
public var isPayToPublicKeyHashScript: Bool {
guard chunks.count == 5 else {
return false
}
guard let dataChunk = chunk(at: 2) as? DataChunk else {
return false
}
return opcode(at: 0) == OpCode.OP_DUP
&& opcode(at: 1) == OpCode.OP_HASH160
&& dataChunk.range.count == 21
&& opcode(at: 3) == OpCode.OP_EQUALVERIFY
&& opcode(at: 4) == OpCode.OP_CHECKSIG
}
public var isPayToScriptHashScript: Bool {
guard chunks.count == 3 else {
return false
}
return opcode(at: 0) == OpCode.OP_HASH160
&& pushedData(at: 1)?.count == 20 // this is enough to match the exact byte template, any other encoding will be larger.
&& opcode(at: 2) == OpCode.OP_EQUAL
}
// Returns true if the script ends with P2SH check.
// Not used in CoreBitcoin. Similar code is used in bitcoin-ruby. I don't know if we'll ever need it.
public var endsWithPayToScriptHash: Bool {
guard chunks.count >= 3 else {
return false
}
return opcode(at: -3) == OpCode.OP_HASH160
&& pushedData(at: -2)?.count == 20
&& opcode(at: -1) == OpCode.OP_EQUAL
}
public var isStandardMultisignatureScript: Bool {
guard isMultisignatureScript else {
return false
}
guard let multisigPublicKeys = multisigRequirements?.publickeys else {
return false
}
return multisigPublicKeys.count <= 3
}
public var isMultisignatureScript: Bool {
guard let requirements = multisigRequirements else {
return false
}
if requirements.nSigRequired == 0 {
detectMultisigScript()
}
return requirements.nSigRequired > 0
}
// If typical multisig tx is detected, sets requirements:
private func detectMultisigScript() {
// multisig script must have at least 4 ops ("OP_1 <pubkey> OP_1 OP_CHECKMULTISIG")
guard chunks.count >= 4 else {
return
}
// The last op is multisig check.
guard opcode(at: -1) == OpCode.OP_CHECKMULTISIG else {
return
}
let mOpcode: OpCode = opcode(at: 0)
let nOpcode: OpCode = opcode(at: -2)
let m: Int = OpCodeFactory.smallInteger(from: mOpcode)
let n: Int = OpCodeFactory.smallInteger(from: nOpcode)
guard m > 0 && m != Int.max else {
return
}
guard n > 0 && n != Int.max && n >= m else {
return
}
// We must have correct number of pubkeys in the script. 3 extra ops: OP_<M>, OP_<N> and OP_CHECKMULTISIG
guard chunks.count == 3 + n else {
return
}
var pubkeys: [PublicKey] = []
for i in 0...n {
guard let data = pushedData(at: i) else {
return
}
let pubkey = PublicKey(bytes: data, network: .mainnet)
pubkeys.append(pubkey)
}
// Now we extracted all pubkeys and verified the numbers.
multisigRequirements = (UInt(m), pubkeys)
}
// Include both PUSHDATA ops and OP_0..OP_16 literals.
public var isDataOnly: Bool {
return !chunks.contains { $0.opcodeValue > OpCode.OP_16 }
}
public var scriptChunks: [ScriptChunk] {
return chunks
}
public func standardAddress(network: Network) -> Address? {
if isPayToPublicKeyHashScript {
guard let dataChunk = chunk(at: 2) as? DataChunk else {
return nil
}
return Cashaddr(data: dataChunk.pushedData, type: .pubkeyHash, network: network)
} else if isPayToScriptHashScript {
guard let dataChunk = chunk(at: 1) as? DataChunk else {
return nil
}
return Cashaddr(data: dataChunk.pushedData, type: .scriptHash, network: network)
}
return nil
}
// MARK: - Modification
public func invalidateSerialization() {
dataCache = nil
stringCache = nil
multisigRequirements = nil
}
private func update(with updatedData: Data) throws {
let updatedChunks = try Script.parseData(updatedData)
chunks = updatedChunks
invalidateSerialization()
}
@discardableResult
public func append(_ opcode: OpCode) throws -> Script {
let invalidOpCodes: [OpCode] = [.OP_PUSHDATA1,
.OP_PUSHDATA2,
.OP_PUSHDATA4,
.OP_INVALIDOPCODE]
guard !invalidOpCodes.contains(where: { $0 == opcode }) else {
throw ScriptError.error("\(opcode.name) cannot be executed alone.")
}
var updatedData: Data = data
updatedData += opcode
try update(with: updatedData)
return self
}
@discardableResult
public func appendData(_ newData: Data) throws -> Script {
guard !newData.isEmpty else {
throw ScriptError.error("Data is empty.")
}
guard let addedScriptData = ScriptChunkHelper.scriptData(for: newData, preferredLengthEncoding: -1) else {
throw ScriptError.error("Parse data to pushdata failed.")
}
var updatedData: Data = data
updatedData += addedScriptData
try update(with: updatedData)
return self
}
@discardableResult
public func appendScript(_ otherScript: Script) throws -> Script {
guard !otherScript.data.isEmpty else {
throw ScriptError.error("Script is empty.")
}
var updatedData: Data = self.data
updatedData += otherScript.data
try update(with: updatedData)
return self
}
@discardableResult
public func deleteOccurrences(of data: Data) throws -> Script {
guard !data.isEmpty else {
return self
}
let updatedData = chunks.filter { ($0 as? DataChunk)?.pushedData != data }.reduce(Data()) { $0 + $1.chunkData }
try update(with: updatedData)
return self
}
@discardableResult
public func deleteOccurrences(of opcode: OpCode) throws -> Script {
let updatedData = chunks.filter { $0.opCode != opcode }.reduce(Data()) { $0 + $1.chunkData }
try update(with: updatedData)
return self
}
public func subScript(from index: Int) throws -> Script {
let subScript: Script = Script()
for chunk in chunks[Range(index..<chunks.count)] {
try subScript.appendData(chunk.chunkData)
}
return subScript
}
public func subScript(to index: Int) throws -> Script {
let subScript: Script = Script()
for chunk in chunks[Range(0..<index)] {
try subScript.appendData(chunk.chunkData)
}
return subScript
}
// MARK: - Utility methods
// Raise exception if index is out of bounds
public func chunk(at index: Int) -> ScriptChunk {
return chunks[index < 0 ? chunks.count + index : index]
}
// Returns an opcode in a chunk.
// If the chunk is data, not an opcode, returns OP_INVALIDOPCODE
// Raises exception if index is out of bounds.
public func opcode(at index: Int) -> OpCode {
let chunk = self.chunk(at: index)
// If the chunk is not actually an opcode, return invalid opcode.
guard chunk is OpcodeChunk else {
return .OP_INVALIDOPCODE
}
return chunk.opCode
}
// Returns Data in a chunk.
// If chunk is actually an opcode, returns nil.
// Raises exception if index is out of bounds.
public func pushedData(at index: Int) -> Data? {
let chunk = self.chunk(at: index)
return (chunk as? DataChunk)?.pushedData
}
public func execute(with context: ScriptExecutionContext) throws {
for chunk in chunks {
if let opChunk = chunk as? OpcodeChunk {
try opChunk.opCode.execute(context)
} else if let dataChunk = chunk as? DataChunk {
if context.shouldExecute {
try context.pushToStack(dataChunk.pushedData)
}
} else {
throw ScriptMachineError.error("Unknown chunk")
}
}
guard context.conditionStack.isEmpty else {
throw ScriptMachineError.error("Condition branches not balanced.")
}
}
}
extension Script {
// Standard Transaction to Bitcoin address (pay-to-pubkey-hash)
// scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
public static func buildPublicKeyHashOut(pubKeyHash: Data) -> Data {
let tmp: Data = Data() + OpCode.OP_DUP + OpCode.OP_HASH160 + UInt8(pubKeyHash.count) + pubKeyHash + OpCode.OP_EQUALVERIFY
return tmp + OpCode.OP_CHECKSIG
}
public static func buildPublicKeyUnlockingScript(signature: Data, pubkey: PublicKey, hashType: SighashType) -> Data {
var data: Data = Data([UInt8(signature.count + 1)]) + signature + UInt8(hashType)
data += VarInt(pubkey.raw.count).serialized()
data += pubkey.raw
return data
}
public static func isPublicKeyHashOut(_ script: Data) -> Bool {
return script.count == 25 &&
script[0] == OpCode.OP_DUP && script[1] == OpCode.OP_HASH160 && script[2] == 20 &&
script[23] == OpCode.OP_EQUALVERIFY && script[24] == OpCode.OP_CHECKSIG
}
public static func getPublicKeyHash(from script: Data) -> Data {
return script[3..<23]
}
}
extension Script: CustomStringConvertible {
public var description: String {
return string
}
}
enum ScriptError: Error {
case error(String)
}
| 33.484787 | 165 | 0.595348 |
6ae2fd01a3c9fd10f6c0cee9f7b178b2d17cf408 | 1,903 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct ContainerServiceLinuxProfileData : ContainerServiceLinuxProfileProtocol {
public var adminUsername: String
public var ssh: ContainerServiceSshConfigurationProtocol
enum CodingKeys: String, CodingKey {case adminUsername = "adminUsername"
case ssh = "ssh"
}
public init(adminUsername: String, ssh: ContainerServiceSshConfigurationProtocol) {
self.adminUsername = adminUsername
self.ssh = ssh
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.adminUsername = try container.decode(String.self, forKey: .adminUsername)
self.ssh = try container.decode(ContainerServiceSshConfigurationData.self, forKey: .ssh)
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.adminUsername, forKey: .adminUsername)
try container.encode(self.ssh as! ContainerServiceSshConfigurationData, forKey: .ssh)
}
}
extension DataFactory {
public static func createContainerServiceLinuxProfileProtocol(adminUsername: String, ssh: ContainerServiceSshConfigurationProtocol) -> ContainerServiceLinuxProfileProtocol {
return ContainerServiceLinuxProfileData(adminUsername: adminUsername, ssh: ssh)
}
}
| 43.25 | 176 | 0.749343 |
e94d9b92a6d8b40930b91c445d645e196c217a01 | 3,841 | // Sources/protoc-gen-swift/StringUtils.swift - String processing utilities
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
func splitPath(pathname: String) -> (dir:String, base:String, suffix:String) {
var dir = ""
var base = ""
var suffix = ""
for c in pathname {
if c == "/" {
dir += base + suffix + String(c)
base = ""
suffix = ""
} else if c == "." {
base += suffix
suffix = String(c)
} else {
suffix += String(c)
}
}
let validSuffix = suffix.isEmpty || suffix.first == "."
if !validSuffix {
base += suffix
suffix = ""
}
return (dir: dir, base: base, suffix: suffix)
}
func partition(string: String, atFirstOccurrenceOf substring: String) -> (String, String) {
guard let index = string.range(of: substring)?.lowerBound else {
return (string, "")
}
return (String(string[..<index]),
String(string[string.index(after: index)...]))
}
func parseParameter(string: String?) -> [(key:String, value:String)] {
guard let string = string, !string.isEmpty else {
return []
}
let parts = string.components(separatedBy: ",")
let asPairs = parts.map { partition(string: $0, atFirstOccurrenceOf: "=") }
let result = asPairs.map { (key:trimWhitespace($0), value:trimWhitespace($1)) }
return result
}
func trimWhitespace(_ s: String) -> String {
return s.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// The protoc parser emits byte literals using an escaped C convention.
/// Fortunately, it uses only a limited subset of the C escapse:
/// \n\r\t\\\'\" and three-digit octal escapes but nothing else.
func escapedToDataLiteral(_ s: String) -> String {
if s.isEmpty {
return "\(SwiftProtobufInfo.name).Internal.emptyData"
}
var out = "Data(["
var separator = ""
var escape = false
var octal = 0
var octalAccumulator = 0
for c in s.utf8 {
if octal > 0 {
precondition(c >= 48 && c < 56)
octalAccumulator <<= 3
octalAccumulator |= (Int(c) - 48)
octal -= 1
if octal == 0 {
out += separator
out += "\(octalAccumulator)"
separator = ", "
}
} else if escape {
switch c {
case 110:
out += separator
out += "10"
separator = ", "
case 114:
out += separator
out += "13"
separator = ", "
case 116:
out += separator
out += "9"
separator = ", "
case 48..<56:
octal = 2 // 2 more digits
octalAccumulator = Int(c) - 48
default:
out += separator
out += "\(c)"
separator = ", "
}
escape = false
} else if c == 92 { // backslash
escape = true
} else {
out += separator
out += "\(c)"
separator = ", "
}
}
out += "])"
return out
}
/// Generate a Swift string literal suitable for including in
/// source code
private let hexdigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
func stringToEscapedStringLiteral(_ s: String) -> String {
if s.isEmpty {
return "String()"
}
var out = "\""
for c in s.unicodeScalars {
switch c.value {
case 0:
out += "\\0"
case 1..<32:
let n = Int(c.value)
let hex1 = hexdigits[(n >> 4) & 15]
let hex2 = hexdigits[n & 15]
out += "\\u{" + hex1 + hex2 + "}"
case 34:
out += "\\\""
case 92:
out += "\\\\"
default:
out.append(String(c))
}
}
return out + "\""
}
| 26.308219 | 104 | 0.554803 |
b947bebb1aa6a93fae8450a32a5b8022c9dca1e1 | 2,096 | //
// AvroFileContainerTests.swift
// BlueSteelTests
//
// Created by Stefan Paychรจre.
// Copyright ยฉ 2019 Myotest. All rights reserved.
//
import XCTest
import BlueSteel
class AvroFileContainerTests: XCTestCase {
var schema : Schema!
override func setUp() {
schema = Schema.avroRecordSchema("myRecord", [Schema.avroFieldSchema("myInt", Box(Schema.avroLongSchema)), Schema.avroFieldSchema("myString", Box(Schema.avroStringSchema))])
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testFileContainer() {
let writer = AvroFileWriter(schema: schema)
let count = 1000
writer.blockSize = 1000
for i in 1...count {
let value = AvroValue.avroRecordValue([
"myInt": AvroValue.avroLongValue(Int64(i)),
"myString": AvroValue.avroStringValue(String(i))
])
do {
try writer.append(value: value)
} catch {
XCTFail()
break
}
}
XCTAssertTrue(writer.tryToClose())
let writtenData = writer.outputData
XCTAssertNotNil(writtenData)
if let readData = writtenData {
var readCount = 0
let reader = AvroFileReader(schema: schema, data: readData)
do {
while let value = try reader.read() {
readCount += 1
switch value {
case let .avroRecordValue(dictionary):
XCTAssertEqual(dictionary["myInt"]?.long, Int64(readCount))
XCTAssertEqual(dictionary["myString"]?.string, String(readCount))
default:
XCTFail("Expected record value")
}
}
} catch let error {
XCTFail("Unexpected exception thrown while reading: \(error)")
}
XCTAssertEqual(readCount, count)
}
}
}
| 29.942857 | 181 | 0.524332 |
16a2504b6fc6f9124648a3e9634a517ac60b4a80 | 2,097 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import BeagleUI
import SnapshotTesting
final class BeagleContextTests: XCTestCase {
func test_screenController_shouldBeBeagleScreenViewController() {
// Given
let component = SimpleComponent()
let sut: BeagleContext = BeagleScreenViewController(viewModel: .init(
screenType: .declarative(component.content.toScreen()),
dependencies: BeagleScreenDependencies()
))
// Then
XCTAssertTrue(sut.screenController is BeagleScreenViewController)
}
}
// MARK: - Testing Helpers
class UINavigationControllerSpy: BeagleScreenViewController {
private(set) var presentViewControllerCalled = false
private(set) var dismissViewControllerCalled = false
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
presentViewControllerCalled = true
super.present(viewControllerToPresent, animated: flag, completion: completion)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismissViewControllerCalled = true
super.dismiss(animated: flag, completion: completion)
}
}
class OnStateUpdatableViewSpy: UIView, OnStateUpdatable {
private(set) var didCallOnUpdateState = false
func onUpdateState(component: ServerDrivenComponent) -> Bool {
didCallOnUpdateState = true
return true
}
}
| 34.95 | 126 | 0.718646 |
2f6950bfdd16a6defc3c84a27220e367caf345b5 | 3,052 | // Playground - noun: a place where people can play
import UIKit
/*
ๆฅๅฃ้็ฆปๅๅ Interface Segregation Principle (ISP)
ๅฎไน๏ผๅฎขๆท็ซฏไธๅบ่ฏฅไพ่ตๅฎไธ้่ฆ็ๆฅๅฃ๏ผไธไธช็ฑปๅฏนๅฆไธไธช็ฑป็ไพ่ตๅบ่ฏฅๅปบ็ซๅจๆๅฐ็ๆฅๅฃไธใ
้ฎ้ข็ฑๆฅ๏ผ็ฑปA้่ฟๆฅๅฃIไพ่ต็ฑปB๏ผ็ฑปC้่ฟๆฅๅฃIไพ่ต็ฑปD๏ผๅฆๆๆฅๅฃIๅฏนไบ็ฑปAๅ็ฑปBๆฅ่ฏดไธๆฏๆๅฐๆฅๅฃ๏ผๅ็ฑปBๅ็ฑปDๅฟ
้กปๅปๅฎ็ฐไปไปฌไธ้่ฆ็ๆนๆณใ
่งฃๅณๆนๆก๏ผๅฐ่่ฟ็ๆฅๅฃIๆๅไธบ็ฌ็ซ็ๅ ไธชๆฅๅฃ๏ผ็ฑปAๅ็ฑปCๅๅซไธไปไปฌ้่ฆ็ๆฅๅฃๅปบ็ซไพ่ตๅ
ณ็ณปใไนๅฐฑๆฏ้็จๆฅๅฃ้็ฆปๅๅใ
้็จๆฅๅฃ้็ฆปๅๅๅฏนๆฅๅฃ่ฟ่ก็บฆๆๆถ๏ผ่ฆๆณจๆไปฅไธๅ ็น๏ผ
1.ๆฅๅฃๅฐฝ้ๅฐ๏ผไฝๆฏ่ฆๆ้ๅบฆใๅฏนๆฅๅฃ่ฟ่ก็ปๅๅฏไปฅๆ้ซ็จๅบ่ฎพ่ฎก็ตๆดปๆงๆฏไธๆฃ็ไบๅฎ๏ผไฝๆฏๅฆๆ่ฟๅฐ๏ผๅไผ้ ๆๆฅๅฃๆฐ้่ฟๅค๏ผไฝฟ่ฎพ่ฎกๅคๆๅใๆไปฅไธๅฎ่ฆ้ๅบฆใ
2.ไธบไพ่ตๆฅๅฃ็็ฑปๅฎๅถๆๅก๏ผๅชๆด้ฒ็ป่ฐ็จ็็ฑปๅฎ้่ฆ็ๆนๆณ๏ผๅฎไธ้่ฆ็ๆนๆณๅ้่่ตทๆฅใๅชๆไธๆณจๅฐไธบไธไธชๆจกๅๆไพๅฎๅถๆๅก๏ผๆ่ฝๅปบ็ซๆๅฐ็ไพ่ตๅ
ณ็ณปใ
3.ๆ้ซๅ
่๏ผๅๅฐๅฏนๅคไบคไบใไฝฟๆฅๅฃ็จๆๅฐ็ๆนๆณๅปๅฎๆๆๅค็ไบๆ
ใ
*/
protocol I{
func method1()
func method2()
func method3()
func method4()
func method5()
}
class AA {
func depend1(i:I){
i.method1()
}
func depend2(i:I){
i.method2()
}
func depend3(i:I){
i.method3()
}
}
class BB :I {
func method1() {
println("implement method1")
}
func method2() {
println("implement method2")
}
func method3() {
println("implement method3")
}
//ไธ้ขไธคไธชๆฅๅฃBBๅนถไธๆฏๅฟ
้กป็,ไฝๅจprotocolไธญ่ขซๆด้ฒๅบๆฅ(็ปๆ่ขซ็ ดๅ)
func method4() {
}
func method5() {
}
}
class CC {
func depend1(i:I){
i.method1()
}
func depend2(i:I){
i.method4()
}
func depend3(i:I){
i.method5()
}
}
class DD :I {
func method1() {
println("implement method1")
}
func method4() {
println("implement method4")
}
func method5() {
println("implement method5")
}
//ไธ้ขไธคไธชๆฅๅฃBBๅนถไธๆฏๅฟ
้กป็,ไฝๅจprotocolไธญ่ขซๆด้ฒๅบๆฅ
func method2() {
}
func method3() {
}
}
class Client0 {
init(){
var aa = AA()
aa.depend1(BB())
aa.depend2(BB())
aa.depend3(BB())
var cc = CC()
cc.depend1(DD())
cc.depend2(DD())
cc.depend3(DD())
}
}
var client0 = Client0()
//่่ๅฐๆฅๅฃๆๅ
protocol I1 {
func method1()
}
protocol I2 {
func mehtod2()
func method3()
}
protocol I3{
func method4()
func method5()
}
class A {
func depend1(i:I1){
i.method1()
}
func depend2(i:I2){
i.mehtod2()
}
func depend3(i:I2){
i.method3()
}
}
class B : I1,I2 {
func method1() {
println("implement method1")
}
func mehtod2() {
println("implement method2")
}
func method3() {
println("implement method3")
}
}
class C {
func depend1(i:I1){
i.method1()
}
func depend4(i:I3){
i.method4()
}
func depend5(i:I3){
i.method5()
}
}
class D:I1,I3 {
func method1() {
println("implement method1")
}
func method4() {
println("implement method4")
}
func method5() {
println("implement method5")
}
}
class Client {
init(){
var aa = A()
aa.depend1(B())
aa.depend2(B())
aa.depend3(B())
var cc = C()
cc.depend1(D())
cc.depend4(D())
cc.depend5(D())
}
}
var client = Client()
//ๆฅๅฃ้็ฆป,ๆด้ฒๅฐฝๅฏ่ฝๅฐ็ไฟกๆฏ,ไฝๆฏๅพๆณจๆ็ฒๅบฆ็้ฎ้ข
| 17.242938 | 77 | 0.542595 |
215bc8f6658df521d24465e873799fcd68136656 | 991 | //
// AssessmentModelWrapperTests.swift
// AssessmentModelWrapperTests
//
// Created by Shannon Young on 3/19/20.
// Copyright ยฉ 2020 Sage Bionetworks. All rights reserved.
//
import XCTest
@testable import AssessmentModelWrapper
import AssessmentModel
class AssessmentModelWrapperTests: 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.
}
}
}
| 27.527778 | 111 | 0.682139 |
750303b705cae6b96d5069161f79a77600921a49 | 2,684 | // RUN: %target-swift-frontend -disable-generic-metadata-prespecialization -emit-ir %s -swift-version 4 | %FileCheck %s
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Hashable where T: Hashable {}
extension Struct: Codable where T: Codable {}
enum Enum<T> {
case a(T), b(T)
}
extension Enum: Equatable where T: Equatable {}
extension Enum: Hashable where T: Hashable {}
final class Final<T> {
var x: T
init(x: T) { self.x = x }
}
extension Final: Encodable where T: Encodable {}
extension Final: Decodable where T: Decodable {}
class Nonfinal<T> {
var x: T
init(x: T) { self.x = x }
}
extension Nonfinal: Encodable where T: Encodable {}
func doEquality<T: Equatable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s23synthesized_conformance8equalityyyF"()
public func equality() {
// CHECK: [[Struct_Equatable:%.*]] = call i8** @"$s23synthesized_conformance6StructVySiGACyxGSQAASQRzlWl"()
// CHECK-NEXT: call swiftcc void @"$s23synthesized_conformance10doEqualityyyxSQRzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Struct_Equatable]])
doEquality(Struct(x: 1))
// CHECK: [[Enum_Equatable:%.*]] = call i8** @"$s23synthesized_conformance4EnumOySiGACyxGSQAASQRzlWl"()
// CHECK-NEXT: call swiftcc void @"$s23synthesized_conformance10doEqualityyyxSQRzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Enum_Equatable]])
doEquality(Enum.a(1))
}
func doEncodable<T: Encodable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s23synthesized_conformance9encodableyyF"()
public func encodable() {
// CHECK: [[Struct_Encodable:%.*]] = call i8** @"$s23synthesized_conformance6StructVySiGACyxGSEAASeRzSERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s23synthesized_conformance11doEncodableyyxSERzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Struct_Encodable]])
doEncodable(Struct(x: 1))
// CHECK: [[Final_Encodable:%.*]] = call i8** @"$s23synthesized_conformance5FinalCySiGACyxGSEAASERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s23synthesized_conformance11doEncodableyyxSERzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Final_Encodable]])
doEncodable(Final(x: 1))
// CHECK: [[Nonfinal_Encodable:%.*]] = call i8** @"$s23synthesized_conformance8NonfinalCySiGACyxGSEAASERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s23synthesized_conformance11doEncodableyyxSERzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Nonfinal_Encodable]])
doEncodable(Nonfinal(x: 1))
}
| 47.928571 | 182 | 0.697839 |
01cb45962aa83b65aae4f8f06573eb183459ddbb | 4,276 | //
// UserProfileViewController.swift
// Pwitter
//
// Created by Peter Le on 2/26/17.
// Copyright ยฉ 2017 CodePath. All rights reserved.
//
import UIKit
class UserProfileViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource{
var tweets: [Tweet]!
var user: User?
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var headerPicture: UIImageView!
@IBOutlet weak var bio: UILabel!
@IBOutlet weak var tweetcountLabel: UILabel!
@IBOutlet weak var followingcountLabel: UILabel!
@IBOutlet weak var followerscountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Set up tableView
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
//Set up profile picture
profilePicture.layer.cornerRadius = 3
profilePicture.clipsToBounds = true
//Set up UI
self.profilePicture.layer.borderColor = UIColor.white.cgColor
self.profilePicture.layer.borderWidth = 3
if let profilePictureUrl = user?.profileUrl
{
self.profilePicture.setImageWith(profilePictureUrl as URL)
}
if let headerImageUrl = user?.headerImageUrl
{
self.headerPicture.setImageWith(headerImageUrl as URL)
}
self.handleLabel.text = "@\(user!.screenname!)"
self.nameLabel.text = user!.name! as? String
self.bio.text = user?.bio! as? String
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
self.tweetcountLabel.text = numberFormatter.string(from: NSNumber(value: user!.tweetsCount!))
self.followerscountLabel.text = numberFormatter.string(from: NSNumber(value: user!.followersCount!))
self.followingcountLabel.text = numberFormatter.string(from: NSNumber(value: user!.followingCount!))
//Get user tweets
TwitterClient.sharedInstance?.userTimeline(myUser: user!.screenname as! String, success: { (tweets: [Tweet]) in
self.tweets = tweets
self.tableView.reloadData()
}, failure: { (error: NSError) in
print(error.localizedDescription)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func back(_ sender: Any) {
_ = navigationController?.popViewController(animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tweets != nil {
return tweets.count
}
else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTweetTableViewCell", for: indexPath) as! TweetTableViewCell
cell.tweet = tweets[indexPath.row]
cell.selectionStyle = .none
cell.accessoryType = .none
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "UserProfileReply")
{
if let button = sender as? UIButton {
if let superview = button.superview {
if let cell = superview.superview as? TweetTableViewCell {
let indexPath = tableView.indexPath(for: cell)
let tweet = tweets[indexPath!.item]
//print(tweet)
let navdestinationViewController = segue.destination as! UINavigationController
let destinationViewController = navdestinationViewController.viewControllers.first as! ComposeTweetViewController
destinationViewController.tweet = tweet
}
}
}
}
}
}
| 36.237288 | 137 | 0.632133 |
165ef1d458c4c71686af897b5fbed76dfc7192ba | 898 | /*
* Copyright (c) 2011-2020, Zingaya, Inc. All rights reserved.
*/
import UIKit
final class DefaultIncomingCallView:
UIView,
NibLoadable
{
@IBOutlet private weak var displayNameLabel: UILabel!
var displayName: String? {
get { displayNameLabel.text }
set { displayNameLabel.text = newValue }
}
var declineHandler: (() -> Void)?
var acceptHandler: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
sharedInit()
}
private func sharedInit() {
setupFromNib()
}
@IBAction private func declineTouchUp(_ sender: PressableButton) {
declineHandler?()
}
@IBAction private func acceptTouchUp(_ sender: PressableButton) {
acceptHandler?()
}
}
| 21.380952 | 70 | 0.601336 |
d771ef3eccc5a840975826c9b37987942b8c553d | 3,555 | /*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class ArtistDetailViewController: UIViewController {
var selectedArtist: Artist!
let moreInfoText = "Select For More Info >"
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = selectedArtist.name
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: .none, queue: OperationQueue.main) { [weak self] _ in
self?.tableView.reloadData()
}
}
}
extension ArtistDetailViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selectedArtist.works.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WorkTableViewCell
let work = selectedArtist.works[indexPath.row]
cell.workTitleLabel.text = work.title
cell.workImageView.image = work.image
cell.workTitleLabel.backgroundColor = UIColor(white: 204/255, alpha: 1)
cell.workTitleLabel.textAlignment = .center
cell.moreInfoTextView.textColor = UIColor(white: 114 / 255, alpha: 1)
cell.selectionStyle = .none
cell.moreInfoTextView.text = work.isExpanded ? work.info : moreInfoText
cell.moreInfoTextView.textAlignment = work.isExpanded ? .left : .center
cell.workTitleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
cell.moreInfoTextView.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote)
return cell
}
}
extension ArtistDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? WorkTableViewCell else {
return
}
var work = selectedArtist.works[indexPath.row]
work.isExpanded = !work.isExpanded
selectedArtist.works[indexPath.row] = work
cell.moreInfoTextView.text = work.isExpanded ? work.info : moreInfoText
cell.moreInfoTextView.textAlignment = work.isExpanded ? .left : .center
tableView.beginUpdates()
tableView.endUpdates()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
| 37.03125 | 146 | 0.742053 |
5620ab826a2bbbe3c2bfff901f824af8b5025fda | 1,083 | guard CommandLine.argc == 3 else {
exit(1)
}
let inFile = CommandLine.arguments[1] as NSString
let outFile = CommandLine.arguments[2] as NSString
let data = try? NSData(contentsOfFile: inFile as String, options: .mappedIfSafe)
guard let data = data else {
exit(1)
}
let outBufferLength = data.length + MemoryLayout<Int>.stride + 500 * 1024
let outBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: outBufferLength)
let outLength = compression_encode_buffer(
outBuffer.advanced(by: MemoryLayout<Int>.stride), outBufferLength - MemoryLayout<Int>.stride,
data.bytes.assumingMemoryBound(to: UInt8.self), data.length, nil, COMPRESSION_LZFSE)
guard outLength > 0 else {
NSLog("Error occurred: either during compression, or because resulting file is much larger than original file")
exit(1)
}
var inLength = data.length
memcpy(outBuffer, &inLength, MemoryLayout<Int>.stride)
let outData = NSData(bytesNoCopy: outBuffer, length: outLength + MemoryLayout<Int>.stride, freeWhenDone: true)
try! outData.write(toFile: outFile as String, options: .atomic)
exit(0)
| 40.111111 | 115 | 0.76362 |
e8919318ff221e6687aafba69af0a81f2fa914b9 | 4,493 | //
// RidesScopeUtilTests.swift
// UberRides
//
// Copyright ยฉ 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import UberRides
class RidesScopeExtensionsTests: XCTestCase {
func testRidesScopeToString_withValidScopes()
{
let scopes : [RidesScope] = Array(arrayLiteral: RidesScope.profile, RidesScope.places)
let expectedString = "\(RidesScope.profile.rawValue) \(RidesScope.places.rawValue)"
let scopeString = scopes.toRidesScopeString()
XCTAssertEqual(expectedString, scopeString)
}
func testRidesScopeToString_withNoScopes()
{
let scopes : [RidesScope] = [RidesScope]()
let expectedString = ""
let scopeString = scopes.toRidesScopeString()
XCTAssertEqual(expectedString, scopeString)
}
func testRidesScopeToString_withValidScopesUsingSet()
{
let scopes : Set<RidesScope> = Set<RidesScope>(arrayLiteral: RidesScope.profile, RidesScope.places)
let scopeString = scopes.toRidesScopeString()
var testSet : Set<RidesScope> = Set<RidesScope>()
for scopeString in scopeString.components(separatedBy: " ") {
guard let scope = RidesScopeFactory.ridesScopeForString(scopeString) else {
continue
}
testSet.insert(scope)
}
XCTAssertEqual(scopes, testSet)
}
func testRidesScopeToString_withNoScopes_usingSet()
{
let scopes : Set<RidesScope> = Set<RidesScope>()
let expectedString = ""
let scopeString = scopes.toRidesScopeString()
XCTAssertEqual(expectedString, scopeString)
}
func testStringToRidesScope_withValidScopes()
{
let expectedScopes : [RidesScope] = Array(arrayLiteral: RidesScope.profile, RidesScope.places)
let scopeString = "\(RidesScope.profile.rawValue) \(RidesScope.places.rawValue)"
let scopes = scopeString.toRidesScopesArray()
XCTAssertEqual(scopes, expectedScopes)
}
func testStringToRidesScope_withInvalidScopes()
{
let expectedScopes : [RidesScope] = [RidesScope]()
let scopeString = "not actual values"
let scopes = scopeString.toRidesScopesArray()
XCTAssertEqual(scopes, expectedScopes)
}
func testStringToRidesScope_withNoScopes()
{
let expectedScopes : [RidesScope] = [RidesScope]()
let scopeString = ""
let scopes = scopeString.toRidesScopesArray()
XCTAssertEqual(scopes, expectedScopes)
}
func testStringToRidesScope_withInvalidAndValidScopes()
{
let expectedScopes : [RidesScope] = Array(arrayLiteral: RidesScope.places)
let scopeString = "not actual values \(RidesScope.places.rawValue)"
let scopes = scopeString.toRidesScopesArray()
XCTAssertEqual(scopes, expectedScopes)
}
func testStringToRidesScope_caseInsensitive()
{
let expectedScopes : [RidesScope] = Array(arrayLiteral: RidesScope.places, RidesScope.history)
let scopeString = "plAcEs HISTORY"
let scopes = scopeString.toRidesScopesArray()
XCTAssertEqual(scopes, expectedScopes)
}
}
| 34.037879 | 107 | 0.66726 |
227da08b20e34eb5815ebdf9d572d4c9708b50e0 | 440 | //
// VideoshopResponseSerializer.swift
// EurosportPlayer
//
// Created by Alexander Edge on 14/05/2016.
import Foundation
class VideoshopResponseSerializer<T>: ResponseSerializer<T> {
override func serializeResponse(_ data: Data?, response: URLResponse?, error: Error?) throws -> T {
return try JSONResponseSerializer<JSONObject>().serializeResponse(data, response: response, error: error).extract("PlayerObj")
}
}
| 27.5 | 134 | 0.738636 |
f73044cffdd54844344e3ef2f03fbb78ebcd1029 | 522 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
protocol Associated {
associatedtype Assoc
}
struct Abstracted<T: Associated, U: Associated> {
let closure: (T.Assoc) -> U.Assoc
}
struct S1 {}
struct S2 {}
// CHECK-LABEL: sil hidden @_TF21same_type_abstraction28callClosureWithConcreteTypes
// CHECK: function_ref @_TTR
func callClosureWithConcreteTypes<
T: Associated, U: Associated
where
T.Assoc == S1, U.Assoc == S2
>(x x: Abstracted<T, U>, arg: S1) -> S2 {
return x.closure(arg)
}
| 22.695652 | 84 | 0.699234 |
8774b4c9b98e2b1b830746496a9f6ea5256b3c0c | 1,352 | //
// AppDelegate.swift
// TipCalculator
//
// Created by Mason Hughes on 1/25/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.540541 | 179 | 0.746302 |
0101d10907c145904d3f6053ad58adc33f87fd19 | 370 |
import Foundation
public class BlinkingLabel: UILabel {
public func startBlinking() {
UIView.animate(withDuration: 0.25, delay:0.0, options:UIViewAnimationOptions.repeat, animations: {
self.alpha = 0
}, completion: nil)
}
public func stopBlinking() {
alpha = 1
layer.removeAllAnimations()
}
}
| 20.555556 | 106 | 0.608108 |
1861865362acfa63f336b3fb138ff8ee5714fe05 | 651 | //
// Pin.swift
// Virtual Tourist
//
// Created by Adland Lee on 5/12/16.
// Copyright ยฉ 2016 Adland Lee. All rights reserved.
//
import Foundation
import CoreData
class Pin: NSManagedObject {
struct Keys {
static let Latitude = "latitude"
static let Longitude = "longitude"
static let Photos = "photos"
}
convenience init(lat: Double, lon: Double, context: NSManagedObjectContext) {
let entity = NSEntityDescription.entity(forEntityName: "Pin", in: context)!
self.init(entity: entity, insertInto: context)
latitude = lat
longitude = lon
}
}
| 21 | 83 | 0.619048 |
f7038bf400177050056e0978d128d45fc5a07dc4 | 7,189 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _asciiDigit<CodeUnit : UnsignedInteger, Result : BinaryInteger>(
codeUnit u_: CodeUnit, radix: Result
) -> Result? {
let digit = _ascii16("0")..._ascii16("9")
let lower = _ascii16("a")..._ascii16("z")
let upper = _ascii16("A")..._ascii16("Z")
let u = UInt16(truncatingIfNeeded: u_)
let d: UInt16
if _fastPath(digit ~= u) { d = u &- digit.lowerBound }
else if _fastPath(upper ~= u) { d = u &- upper.lowerBound &+ 10 }
else if _fastPath(lower ~= u) { d = u &- lower.lowerBound &+ 10 }
else { return nil }
guard _fastPath(d < radix) else { return nil }
return Result(truncatingIfNeeded: d)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _parseUnsignedASCII<
Rest : IteratorProtocol, Result: FixedWidthInteger
>(
first: Rest.Element, rest: inout Rest, radix: Result, positive: Bool
) -> Result?
where Rest.Element : UnsignedInteger {
let r0 = _asciiDigit(codeUnit: first, radix: radix)
guard _fastPath(r0 != nil), var result = r0 else { return nil }
if !positive {
let (result0, overflow0)
= (0 as Result).subtractingReportingOverflow(result)
guard _fastPath(!overflow0) else { return nil }
result = result0
}
while let u = rest.next() {
let d0 = _asciiDigit(codeUnit: u, radix: radix)
guard _fastPath(d0 != nil), let d = d0 else { return nil }
let (result1, overflow1) = result.multipliedReportingOverflow(by: radix)
let (result2, overflow2) = positive
? result1.addingReportingOverflow(d)
: result1.subtractingReportingOverflow(d)
guard _fastPath(!overflow1 && !overflow2)
else { return nil }
result = result2
}
return result
}
//
// TODO (TODO: JIRA): This needs to be completely rewritten. It's about 20KB of
// always-inline code, most of which are MOV instructions.
//
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _parseASCII<
CodeUnits : IteratorProtocol, Result: FixedWidthInteger
>(
codeUnits: inout CodeUnits, radix: Result
) -> Result?
where CodeUnits.Element : UnsignedInteger {
let c0_ = codeUnits.next()
guard _fastPath(c0_ != nil), let c0 = c0_ else { return nil }
if _fastPath(c0 != _ascii16("+") && c0 != _ascii16("-")) {
return _parseUnsignedASCII(
first: c0, rest: &codeUnits, radix: radix, positive: true)
}
let c1_ = codeUnits.next()
guard _fastPath(c1_ != nil), let c1 = c1_ else { return nil }
if _fastPath(c0 == _ascii16("-")) {
return _parseUnsignedASCII(
first: c1, rest: &codeUnits, radix: radix, positive: false)
}
else {
return _parseUnsignedASCII(
first: c1, rest: &codeUnits, radix: radix, positive: true)
}
}
extension FixedWidthInteger {
// _parseASCII function thunk that prevents inlining used as an implementation
// detail for FixedWidthInteger.init(_: radix:) on the slow path to save code
// size.
@inlinable // FIXME(sil-serialize-all)
@_semantics("optimize.sil.specialize.generic.partial.never")
@inline(never)
internal static func _parseASCIISlowPath<
CodeUnits : IteratorProtocol, Result: FixedWidthInteger
>(
codeUnits: inout CodeUnits, radix: Result
) -> Result?
where CodeUnits.Element : UnsignedInteger {
return _parseASCII(codeUnits: &codeUnits, radix: radix)
}
/// Creates a new integer value from the given string and radix.
///
/// The string passed as `text` may begin with a plus or minus sign character
/// (`+` or `-`), followed by one or more numeric digits (`0-9`) or letters
/// (`a-z` or `A-Z`). Parsing of the string is case insensitive.
///
/// let x = Int("123")
/// // x == 123
///
/// let y = Int("-123", radix: 8)
/// // y == -83
/// let y = Int("+123", radix: 8)
/// // y == +83
///
/// let z = Int("07b", radix: 16)
/// // z == 123
///
/// If `text` is in an invalid format or contains characters that are out of
/// bounds for the given `radix`, or if the value it denotes in the given
/// `radix` is not representable, the result is `nil`. For example, the
/// following conversions result in `nil`:
///
/// Int(" 100") // Includes whitespace
/// Int("21-50") // Invalid format
/// Int("ff6600") // Characters out of bounds
/// Int("zzzzzzzzzzzzz", radix: 36) // Out of range
///
/// - Parameters:
/// - text: The ASCII representation of a number in the radix passed as
/// `radix`.
/// - radix: The radix, or base, to use for converting `text` to an integer
/// value. `radix` must be in the range `2...36`. The default is 10.
@inlinable // FIXME(sil-serialize-all)
@_semantics("optimize.sil.specialize.generic.partial.never")
public init?<S : StringProtocol>(_ text: S, radix: Int = 10) {
_precondition(2...36 ~= radix, "Radix not in range 2...36")
let r = Self(radix)
let range = text._encodedOffsetRange
let guts = text._wholeString._guts
let result: Self?
result = _visitGuts(guts,
range: (range, false), args: r,
ascii: { view, radix in
var i = view.makeIterator()
return _parseASCII(codeUnits: &i, radix: radix) },
utf16: { view, radix in
var i = view.makeIterator()
return Self._parseASCIISlowPath(codeUnits: &i, radix: radix) },
opaque: { view, radix in
var i = view.makeIterator()
return Self._parseASCIISlowPath(codeUnits: &i, radix: radix) }
)
guard _fastPath(result != nil) else { return nil }
self = result._unsafelyUnwrappedUnchecked
}
/// Creates a new integer value from the given string.
///
/// The string passed as `description` may begin with a plus or minus sign
/// character (`+` or `-`), followed by one or more numeric digits (`0-9`).
///
/// let x = Int("123")
/// // x == 123
///
/// If `description` is in an invalid format, or if the value it denotes in
/// base 10 is not representable, the result is `nil`. For example, the
/// following conversions result in `nil`:
///
/// Int(" 100") // Includes whitespace
/// Int("21-50") // Invalid format
/// Int("ff6600") // Characters out of bounds
/// Int("10000000000000000000000000") // Out of range
///
/// - Parameter description: The ASCII representation of a number.
@inlinable // FIXME(sil-serialize-all)
@_semantics("optimize.sil.specialize.generic.partial.never")
@inline(__always)
public init?(_ description: String) {
self.init(description, radix: 10)
}
}
| 37.442708 | 80 | 0.625122 |
d7508e1f313a18dd4101b8e86d41e53a43afac96 | 1,199 | //
// DivisionRef.swift
// TrefleSwiftSDK
//
// Created by James Barrow on 2020-04-26.
// Copyright ยฉ 2020 Pig on a Hill Productions. All rights reserved.
//
import Foundation
public struct DivisionClassRef: Codable, CustomStringConvertible {
// MARK: - Properties
public let identifier: Int
public let name: String
public let slug: String
public let division: Division?
public let links: Links
public var description: String {
"DivisionClassRef(identifier: \(identifier), name: \(name), slug: \(slug))"
}
// MARK: - Init
public init(identifier: Int, name: String, slug: String, division: Division? = nil) {
self.identifier = identifier
self.name = name
self.slug = slug
self.division = division
self.links = Links(current: "\(DivisionClassesManager.apiURL)/\(identifier)")
}
internal static var blank: Self {
Self(identifier: -1, name: "", slug: "")
}
// MARK: - Coding
private enum CodingKeys: String, CodingKey {
case identifier = "id"
case name
case slug
case division
case links
}
}
| 23.98 | 89 | 0.605505 |
61d87012763a9793b9337bfe32b4ff26c28ebbf2 | 5,026 | import Foundation
import HeliumLogger
import LoggerAPI
let AWS_REGION_KEY = "AWS_REGION"
let AWS_KEYID_KEY = "AWS_KEYID"
let AWS_KEYSECRET = "AWS_KEYSECRET"
let PUPIL_PORT = "PUPIL_PORT"
let PUPIL_ROOT = "PUPIL_ROOT"
let PUPIL_BUCKET = "PUPIL_BUCKET"
let PUPIL_THUMBNAIL_INTERVAL = "PUPIL_THUMBNAIL_INTERVAL"
let PUPIL_API_HOST = "PUPIL_API_HOST"
internal var ENVIRONMENT = ProcessInfo.processInfo.environment
let ENV_KEYS = [AWS_REGION_KEY,
AWS_KEYID_KEY,
AWS_KEYSECRET,
PUPIL_PORT,
PUPIL_ROOT,
PUPIL_BUCKET,
PUPIL_THUMBNAIL_INTERVAL]
public enum ConfigError: Error {
case fileNotFound
case keyNotFound(key: String)
case badKeyValue(key: String)
}
func configureLogger() {
let logger = HeliumLogger()
logger.colored = true
Log.logger = logger
setbuf(stdout, nil)
}
public struct Config {
internal static var values: ConfigValues?
public static var port: Int32 {
if let p = values?.port { return p }
return 42000
}
public static var root: URL {
if let r = values?.root { return r }
return URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
}
public static var thumbnailInterval: Int {
if let t = values?.thumbnailInterval { return t }
return 30
}
public static var bucket: String {
if let b = values?.bucket { return b }
return ""
}
public static var region: String {
if let r = values?.region { return r }
return ""
}
public static var key: String {
if let k = values?.keyID { return k }
return ""
}
public static var secret: String {
if let s = values?.keySecret { return s }
return ""
}
public static var apiHost: String {
if let h = values?.host { return h }
return ""
}
public static func load(from file: URL) throws {
configureLogger()
self.values = try ConfigValues.load(from: file)
}
public static func loadFromEnvironment() throws {
configureLogger()
self.values = try ConfigValues.from(environment: ENVIRONMENT)
}
}
public struct ConfigValues: Decodable {
let port: Int32
let root: URL
let bucket: String
let region: String
let keyID: String
let keySecret: String
let thumbnailInterval: Int
let host: String
enum CodingKeys: String, CodingKey {
case port = "port"
case root = "root"
case bucket = "bucket"
case region = "region"
case keyID = "key_id"
case keySecret = "key_secret"
case thumbnailInterval = "thumbnail_interval"
case host = "host"
}
internal static func load(from file: URL) throws -> ConfigValues {
if FileManager.default.fileExists(atPath: file.path) {
let configData = try Data(contentsOf: file)
let config = try JSONDecoder().decode(ConfigValues.self, from: configData)
return config
} else {
throw ConfigError.fileNotFound
}
}
internal static func from(environment: [String: String]) throws -> ConfigValues {
var port: Int32 = 42000
if let p = environment[PUPIL_PORT] {
if let intp = Int32(p) { port = intp }
}
var root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
if let r = environment[PUPIL_ROOT] { root = URL(fileURLWithPath: r) }
guard let bucket =
environment[PUPIL_BUCKET] else { throw ConfigError.keyNotFound(key: PUPIL_BUCKET) }
guard let region =
environment[AWS_REGION_KEY] else { throw ConfigError.keyNotFound(key: AWS_REGION_KEY) }
guard let key =
environment[AWS_KEYID_KEY] else { throw ConfigError.keyNotFound(key: AWS_KEYID_KEY) }
guard let secret =
environment[AWS_KEYSECRET] else { throw ConfigError.keyNotFound(key: AWS_KEYSECRET)}
guard let host =
environment[PUPIL_API_HOST] else { throw ConfigError.keyNotFound(key: PUPIL_API_HOST) }
var tInterval = 30
if let thumb = environment[PUPIL_THUMBNAIL_INTERVAL] {
if let t = Int(thumb) { tInterval = t }
}
let config = ConfigValues(port: port,
root: root,
bucket: bucket,
region: region,
keyID: key,
keySecret: secret,
thumbnailInterval: tInterval,
host: host)
return config
}
}
| 30.646341 | 99 | 0.56546 |
691c6ea8112a7b1f3239c9a28bd69c92fb0f3faa | 13,512 | /// Prefix for internal Turf sqlite3 tables
internal let TurfTablePrefix = "__turf"
private let TurfMetadataTableName = "\(TurfTablePrefix)_metadata"
private let TurfRuntimeTableName = "\(TurfTablePrefix)_runtime"
private let TurfExtensionsTableName = "\(TurfTablePrefix)_extensions"
let SQLITE_FIRST_BIND_COLUMN = Int32(1)
let SQLITE_FIRST_COLUMN = Int32(0)
let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
/**
Wrapper around sqlite3
*/
internal final class SQLiteAdapter {
typealias SQLStatement = OpaquePointer
// MARK: Internal properties
/// Connection state
private(set) var isClosed: Bool
/// sqlite3 pointer from `sqlite3_open`
let db: OpaquePointer
// MARK: Private properties
private var beginDeferredTransactionStmt: SQLStatement!
private var commitTransactionStmt: SQLStatement!
private var rollbackTransactionStmt: SQLStatement!
private var getSnapshotStmt: SQLStatement!
private var setSnapshotStmt: SQLStatement!
private var getExtensionDetailsStmt: SQLStatement!
private var setExtensionDetailsStmt: SQLStatement!
// MARK: Object lifecycle
/**
Open a sqlite3 connection
- throws: SQLiteError.FailedToOpenDatabase if sqlite3_open_v2 fails
- parameter sqliteDatabaseUrl: Path to a sqlite database (will be created if it does not exist)
*/
init(sqliteDatabaseUrl: URL) throws {
var internalDb: OpaquePointer? = nil
let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_PRIVATECACHE
self.isClosed = true
let success = sqlite3_open_v2(sqliteDatabaseUrl.absoluteString, &internalDb, flags, nil).isOK
self.db = internalDb!
if success {
sqlite3_busy_timeout(self.db, 0/*ms*/)
if sqlite3_exec(db, "PRAGMA journal_mode = WAL;", nil, nil, nil).isNotOK {
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
try createMetadataTable()
try createRuntimeOperationsTable()
try createExtensionsTable()
try prepareStatements()
self.isClosed = false
} else {
self.beginDeferredTransactionStmt = nil
self.commitTransactionStmt = nil
self.rollbackTransactionStmt = nil
self.getSnapshotStmt = nil
self.setSnapshotStmt = nil
throw SQLiteError.failedToOpenDatabase
}
}
deinit {
precondition(isClosed, "sqlite connection must be closed before deinitializing")
}
// MARK: Internal methods
/**
Close the sqlite3 connection
*/
func close() {
guard !isClosed else { return }
finalizePreparedStatements()
sqlite3_close_v2(db)
self.isClosed = true
}
/**
SQL: BEGIN DEFERRED TRANSACTION;
*/
func beginDeferredTransaction() throws {
sqlite3_reset(beginDeferredTransactionStmt)
if sqlite3_step(beginDeferredTransactionStmt).isNotDone {
Logger.log(error: "Could not begin transaction - SQLite error")
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
sqlite3_reset(beginDeferredTransactionStmt)
}
/**
SQL: COMMIT TRANSACTION;
*/
func commitTransaction() throws {
sqlite3_reset(self.commitTransactionStmt)
if sqlite3_step(commitTransactionStmt).isNotDone {
Logger.log(error: "Could not commit transaction - SQLite error")
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
sqlite3_reset(beginDeferredTransactionStmt)
}
/**
SQL: ROLLBACK TRANSACTION;
*/
func rollbackTransaction() throws {
sqlite3_reset(beginDeferredTransactionStmt)
if sqlite3_step(rollbackTransactionStmt).isNotDone {
Logger.log(error: "Could not rollback transaction - SQLite error")
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
}
/**
Fetch current transaction's snapshot number from the runtime table
- warning: Error handling yet to come
*/
func databaseSnapshotOnCurrentSqliteTransaction() -> UInt64 {
defer { sqlite3_reset(getSnapshotStmt) }
guard sqlite3_step(getSnapshotStmt).hasRow else { return 0 }
return UInt64(sqlite3_column_int64(getSnapshotStmt, SQLITE_FIRST_COLUMN))
}
/**
Set snapshot number in the runtime table
*/
func setSnapshot(_ snapshot: UInt64) throws {
sqlite3_bind_int64(setSnapshotStmt, SQLITE_FIRST_BIND_COLUMN, Int64(snapshot))
if sqlite3_step(setSnapshotStmt).isNotDone {
Logger.log(error: "Could not set snapshot - SQLite error")
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
sqlite3_reset(setSnapshotStmt)
}
/**
Each installed extension gets a row in a turf metadata table for extensions tracking versions and extension data.
- returns: Extension's version, turf version in case the extension is potentially refactored and a blob of data that could be associated with the extension's installation.
*/
func getDetailsForExtensionWithName(_ name: String) -> ExistingExtensionInstallation? {
defer { sqlite3_reset(getExtensionDetailsStmt) }
let nameIndex = SQLITE_FIRST_BIND_COLUMN
sqlite3_bind_text(getExtensionDetailsStmt, nameIndex, name, -1, SQLITE_TRANSIENT)
guard sqlite3_step(getExtensionDetailsStmt).hasRow else { return nil }
let versionIndex = SQLITE_FIRST_COLUMN
let dataIndex = SQLITE_FIRST_COLUMN + 1
let turfVersionIndex = SQLITE_FIRST_COLUMN + 2
let version = UInt64(sqlite3_column_int64(getExtensionDetailsStmt, versionIndex))
let data: Data
if let bytes = sqlite3_column_blob(getExtensionDetailsStmt, dataIndex){
let bytesLength = Int(sqlite3_column_bytes(getExtensionDetailsStmt, dataIndex))
data = Data(bytes: bytes, count: bytesLength)
} else {
data = Data()
}
let turfVersion = UInt64(sqlite3_column_int64(getExtensionDetailsStmt, turfVersionIndex))
return ExistingExtensionInstallation(version: version, turfVersion: turfVersion, data: data)
}
func setDetailsForExtension(name: String, version: UInt64, turfVersion: UInt64, data: Data) {
defer { sqlite3_reset(setExtensionDetailsStmt) }
let nameIndex = SQLITE_FIRST_BIND_COLUMN
let versionIndex = SQLITE_FIRST_BIND_COLUMN + 1
let dataIndex = SQLITE_FIRST_BIND_COLUMN + 2
let turfVersionIndex = SQLITE_FIRST_BIND_COLUMN + 3
sqlite3_bind_text(setExtensionDetailsStmt, nameIndex, name, -1, SQLITE_TRANSIENT)
sqlite3_bind_int64(setExtensionDetailsStmt, versionIndex, Int64(version))
sqlite3_bind_blob(setExtensionDetailsStmt, dataIndex, (data as NSData).bytes, Int32(data.count), nil)
sqlite3_bind_int64(setExtensionDetailsStmt, turfVersionIndex, Int64(turfVersion))
if sqlite3_step(setExtensionDetailsStmt).isNotDone {
print("ERROR: Could not set extension details")
print(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
}
// MARK: Private methods
private func prepareStatements() throws {
var beginDeferredTransactionStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "BEGIN TRANSACTION;", -1, &beginDeferredTransactionStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.beginDeferredTransactionStmt = beginDeferredTransactionStmt
var commitTransactionStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "COMMIT TRANSACTION;", -1, &commitTransactionStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.commitTransactionStmt = commitTransactionStmt
var rollbackTransactionStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "ROLLBACK TRANSACTION;", -1, &rollbackTransactionStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.rollbackTransactionStmt = rollbackTransactionStmt
var getSnapshotStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "SELECT snapshot FROM `\(TurfRuntimeTableName)` WHERE key=1;", -1, &getSnapshotStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.getSnapshotStmt = getSnapshotStmt
var setSnapshotStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO `\(TurfRuntimeTableName)` (key, snapshot) VALUES (1, ?);", -1, &setSnapshotStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.setSnapshotStmt = setSnapshotStmt
var getExtensionDetailsStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "SELECT version, data, turfVersion FROM `\(TurfExtensionsTableName)` WHERE name=?;", -1, &getExtensionDetailsStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.getExtensionDetailsStmt = getExtensionDetailsStmt
var setExtensionDetailsStmt: OpaquePointer? = nil
if sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO `\(TurfExtensionsTableName)` (name, version, data, turfVersion) VALUES (?, ?, ?, 0);", -1, &setExtensionDetailsStmt, nil).isNotOK {
throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(db), String(cString: sqlite3_errmsg(db)))
}
self.setExtensionDetailsStmt = setExtensionDetailsStmt
}
private func finalizePreparedStatements() {
if let stmt = beginDeferredTransactionStmt {
sqlite3_finalize(stmt)
}
if let stmt = commitTransactionStmt {
sqlite3_finalize(stmt)
}
if let stmt = rollbackTransactionStmt {
sqlite3_finalize(stmt)
}
if let stmt = getSnapshotStmt {
sqlite3_finalize(stmt)
}
if let stmt = setSnapshotStmt {
sqlite3_finalize(stmt)
}
if let stmt = getExtensionDetailsStmt {
sqlite3_finalize(stmt)
}
if let stmt = setExtensionDetailsStmt {
sqlite3_finalize(stmt)
}
}
private func createMetadataTable() throws {
if sqlite3_exec(db,
"CREATE TABLE IF NOT EXISTS `\(TurfMetadataTableName)` (schemaVersion INTEGER NOT NULL DEFAULT '(1)' );", nil, nil, nil).isNotOK {
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
}
private func createExtensionsTable() throws {
let sql = "CREATE TABLE IF NOT EXISTS `\(TurfExtensionsTableName)` (" +
"name TEXT NOT NULL UNIQUE," +
"version INTEGER NOT NULL DEFAULT '(0)'," +
"data BLOB," +
"turfVersion INTEGER NOT NULL DEFAULT '(0)'," +
"PRIMARY KEY(name)" +
");"
if sqlite3_exec(db,
sql, nil, nil, nil).isNotOK {
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
}
private func createRuntimeOperationsTable() throws {
if sqlite3_exec(db,
"CREATE TABLE IF NOT EXISTS `\(TurfRuntimeTableName)`" +
"(key INTEGER NOT NULL UNIQUE," +
"snapshot INTEGER NOT NULL DEFAULT '(0)'" +
");", nil, nil, nil).isNotOK {
throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db)))
}
}
}
internal extension Int32 {
/// Compare self to SQLITE_OK
var isOK: Bool {
return self == SQLITE_OK
}
/// Compare self to SQLITE_OK
var isNotOK: Bool {
return self != SQLITE_OK
}
/// Compare self to SQLITE_DONE
var isDone: Bool {
return self == SQLITE_DONE
}
/// Compare self to SQLITE_DONE
var isNotDone: Bool {
return self != SQLITE_DONE
}
/// Compare self to SQLITE_ROW
var hasRow: Bool {
return self == SQLITE_ROW
}
}
///http://ericasadun.com/2014/07/04/swift-my-love-for-postfix-printing/
postfix operator ***
postfix func *** <T>(object : T) -> T {
if let i = object as? Int32 {
switch i {
case SQLITE_ERROR: print("SQLITE_ERROR")
case SQLITE_OK: print("SQLITE_OK")
case SQLITE_DONE: print("SQLITE_DONE")
case SQLITE_ROW: print("SQLITE_ROW")
case SQLITE_MISUSE: print("SQLITE_MISUSE")
case SQLITE_BUSY: print("SQLITE_BUSY")
case SQLITE_LOCKED: print("SQLITE_LOCKED")
default: print("#AnotherOne \(i)")
}
} else {
print(object)
}
return object
}
| 39.393586 | 190 | 0.670219 |
22ce004385a7c09258ba817fb39f8c2ae3734d9f | 3,450 | //
// MultiplyDataSourcePageObjectsControllerDemo.swift
// EZBasicKit_Example
//
// Created by ezbuy on 2019/7/16.
// Copyright ยฉ 2019 CocoaPods. All rights reserved.
//
import UIKit
import EZBasicKit
class MultiplyDataSourceViewController: UIViewController {
fileprivate let fatchController = BatchFetchController()
fileprivate let controller = EmojiListMultiplyDataSourceController()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
fatchController.fetchDelegate = self
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadData()
}
func loadData() {
let _ = controller.reload(completion: { (_) in
self.tableView.reloadData()
}) { (error) in
print(error)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.fatchController.batchFetchIfNeeded(for: scrollView)
}
}
extension MultiplyDataSourceViewController: BatchFetchControllerDelegate {
func shouldBatchFetch(for scrollView: UIScrollView) -> Bool {
return controller.hasMore
}
func scrollView(_ scrollView: UIScrollView, willBeginBatchFetchWith context: BatchFetchContext) {
let processing = controller.loadMore(completion: { (inserted) -> Void in
//asyncAfter method is to imitate http requst, when you have real http request, delete this method
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.tableView.reloadData()
context.completeBatchFetching()
}
}, failure: { (error) -> Void in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
context.completeBatchFetching()
}
})
if processing {
context.beginBatchFetching()
}
}
}
extension MultiplyDataSourceViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return controller.objects.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MultiplyDataSourceDemoCell", for: indexPath)
let emoji = controller.objects.object(at: indexPath.row)
cell.textLabel?.text = emoji?.code
return cell
}
}
class EmojiListMultiplyDataSourceController: MultiplyDataSourcePageObjectsController<Emoji> {
override func loadObjects(atOffset offset: Int, limit: Int, completion: @escaping (([Emoji]) -> Void), failure: @escaping (Error) -> Void) -> Bool {
//request sever to load data
var emojis: [Emoji] = []
debugPrint("EmojiListMultiplyDataSourceController: offset=\(offset) limit=\(limit)")
for i in (offset)..<(offset + limit) {
if let emojiCode = list().object(at: i) {
let emoji = Emoji(code: emojiCode)
debugPrint(emoji.code)
emojis.append(emoji)
}
}
completion(emojis)
return true
}
}
| 31.651376 | 152 | 0.632754 |
6a681c5354d9dd6f7236d66b8ac00e9ea6ba4c88 | 3,045 | //
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MaterialComponents
private let kBoxBorderWidth: CGFloat = 2.0
private let kLightBoxBorderAlpha: CGFloat = 0.5
private let kBoxCornerRadius: CGFloat = 12.0
private let kChipBackgroundAlpha: CGFloat = 0.6
private let kChipCornerRadius: CGFloat = 8.0
private let kChipFadeInDuration: CGFloat = 0.075
private let kChipScaleDuration: CGFloat = 0.15
private let kChipScaleFromRatio: CGFloat = 0.8
private let kChipScaleToRatio: CGFloat = 1.0
private let kChipBottomPadding: CGFloat = 36.0
private let kBoxBackgroundAlpha: CGFloat = 0.40
class CameraOverlayView: UIView {
private var boxLayer: CAShapeLayer!
private var boxMaskLayer: CAShapeLayer!
private var messageChip = MDCChipView()
override init(frame: CGRect) {
super.init(frame: frame)
boxMaskLayer = CAShapeLayer()
layer.addSublayer(boxMaskLayer)
boxLayer = CAShapeLayer()
boxLayer.cornerRadius = kBoxCornerRadius
layer.addSublayer(boxLayer)
messageChip.setBackgroundColor(
UIColor.black.withAlphaComponent(kChipBackgroundAlpha), for: .normal)
messageChip.clipsToBounds = true
messageChip.titleLabel.textColor = UIColor.white
messageChip.layer.cornerRadius = kChipCornerRadius
addSubview(messageChip)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showBox(in rect: CGRect) {
let maskPath = UIBezierPath(rect: self.bounds)
let boxPath = UIBezierPath(roundedRect: rect, cornerRadius: kBoxCornerRadius).reversing()
maskPath.append(boxPath)
boxMaskLayer.frame = self.frame
boxMaskLayer.path = maskPath.cgPath
boxMaskLayer.strokeStart = 0.0
boxMaskLayer.strokeEnd = 1.0
self.layer.backgroundColor = UIColor.black.withAlphaComponent(kBoxBackgroundAlpha).cgColor
self.layer.mask = boxMaskLayer
boxLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: kBoxCornerRadius).cgPath
boxLayer.lineWidth = kBoxBorderWidth
boxLayer.strokeStart = 0.0
boxLayer.strokeEnd = 1.0
boxLayer.strokeColor = UIColor.white.cgColor
boxLayer.fillColor = nil
}
func showMessage(_ message: String?, in center: CGPoint) {
if messageChip.titleLabel.text?.isEqual(message) ?? false {
return
}
messageChip.titleLabel.text = message
messageChip.sizeToFit()
self.messageChip.center = center
}
func clear() {
boxLayer?.isHidden = true
boxLayer?.removeFromSuperlayer()
}
}
| 32.741935 | 94 | 0.745156 |
f8cc242a29080c2c3993e3a0e48f0cd021885268 | 5,906 | /* file: preferred_ordering.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -TYPE DEFINITION in EXPRESS
/*
TYPE preferred_ordering = ENUMERATION OF
( extremity_order,
detected_order );
END_TYPE; -- preferred_ordering (line:4867 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
/** ENUMERATION type
- EXPRESS:
```express
TYPE preferred_ordering = ENUMERATION OF
( extremity_order,
detected_order );
END_TYPE; -- preferred_ordering (line:4867 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public enum nPREFERRED_ORDERING : SDAI.ENUMERATION, SDAIValue,
AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nPREFERRED_ORDERING__type {
/// ENUMERATION case in ``nPREFERRED_ORDERING``
case EXTREMITY_ORDER
/// ENUMERATION case in ``nPREFERRED_ORDERING``
case DETECTED_ORDER
// SDAIGenericType
public var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
return members
}
public var entityReference: SDAI.EntityReference? {nil}
public var stringValue: SDAI.STRING? {nil}
public var binaryValue: SDAI.BINARY? {nil}
public var logicalValue: SDAI.LOGICAL? {nil}
public var booleanValue: SDAI.BOOLEAN? {nil}
public var numberValue: SDAI.NUMBER? {nil}
public var realValue: SDAI.REAL? {nil}
public var integerValue: SDAI.INTEGER? {nil}
public var genericEnumValue: SDAI.GenericEnumValue? { SDAI.GenericEnumValue(self) }
public func arrayOptionalValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY_OPTIONAL<ELEM>? {nil}
public func arrayValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY<ELEM>? {nil}
public func listValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.LIST<ELEM>? {nil}
public func bagValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.BAG<ELEM>? {nil}
public func setValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.SET<ELEM>? {nil}
public func enumValue<ENUM:SDAIEnumerationType>(enumType:ENUM.Type) -> ENUM? { return self as? ENUM }
// SDAIUnderlyingType
public typealias FundamentalType = Self
public static var typeName: String =
"AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.PREFERRED_ORDERING"
public var asFundamentalType: FundamentalType { return self }
public init(fundamental: FundamentalType) {
self = fundamental
}
public init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let enumval = generic?.enumValue(enumType: Self.self) else { return nil }
self = enumval
}
// InitializableByP21Parameter
public static var bareTypeName: String = "PREFERRED_ORDERING"
public init?(p21untypedParam: P21Decode.ExchangeStructure.UntypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) {
switch p21untypedParam {
case .enumeration(let enumcase):
switch enumcase {
case "EXTREMITY_ORDER": self = .EXTREMITY_ORDER
case "DETECTED_ORDER": self = .DETECTED_ORDER
default:
exchangeStructure.error = "unexpected p21parameter enum case(\(enumcase)) while resolving \(Self.bareTypeName) value"
return nil
}
case .rhsOccurenceName(let rhsname):
switch rhsname {
case .constantValueName(let name):
guard let generic = exchangeStructure.resolve(constantValueName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) value"); return nil }
guard let enumValue = generic.enumValue(enumType:Self.self) else { exchangeStructure.error = "constant value(\(name): \(generic)) is not compatible with \(Self.bareTypeName)"; return nil }
self = enumValue
case .valueInstanceName(let name):
guard let param = exchangeStructure.resolve(valueInstanceName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) value from \(rhsname)"); return nil }
self.init(p21param: param, from: exchangeStructure)
default:
exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) value"
return nil
}
case .noValue:
return nil
default:
exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) value"
return nil
}
}
public init(p21omittedParamfrom exchangeStructure: P21Decode.ExchangeStructure) {
self = .EXTREMITY_ORDER
}
//WHERE RULE VALIDATION (ENUMERATION TYPE)
public static func validateWhereRules(instance:Self?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] {
return [:]
}
}
//MARK: -enum case symbol promotions
/// promoted ENUMERATION case in ``nPREFERRED_ORDERING``
public static let EXTREMITY_ORDER = nPREFERRED_ORDERING.EXTREMITY_ORDER
/// promoted ENUMERATION case in ``nPREFERRED_ORDERING``
public static let DETECTED_ORDER = nPREFERRED_ORDERING.DETECTED_ORDER
}
//MARK: - ENUMERATION TYPE HIERARCHY
public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nPREFERRED_ORDERING__type:
SDAIEnumerationType {}
public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nPREFERRED_ORDERING__subtype:
AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nPREFERRED_ORDERING__type, SDAIDefinedType
where Supertype: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nPREFERRED_ORDERING__type
{}
| 40.731034 | 198 | 0.734338 |
712277de1f16bac822f625e6d8cd0246ffe13a00 | 726 | //
// Command{T}.swift
// GithubEvents
//
// Created by Joรฃo Palma on 23/09/2020.
//
struct WpCommand<T> {
private let actionWithParam: CompletionHandlerWithParam<T>
private let canExecuteAction: CanExecuteCompletionHandler
init(_ actionWithParam: @escaping CompletionHandlerWithParam<T>, canExecute: @escaping CanExecuteCompletionHandler = { true }) {
self.actionWithParam = actionWithParam
self.canExecuteAction = canExecute
}
func execute(_ value: T) {
actionWithParam(value)
}
func executeIf(_ value: T) {
if canExecuteAction() {
actionWithParam(value)
}
}
func canExecute() -> Bool {
return canExecuteAction()
}
}
| 23.419355 | 132 | 0.658402 |
6a336451a593d00b2b949c7f406e555b486dc27b | 499 | import Foundation
import FluentProvider
extension ProblemCase: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("input")
builder.string("output")
builder.bool("visible")
builder.parent(Problem.self, optional: false)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| 23.761905 | 57 | 0.597194 |
4bd618a60e03d18932c2909fd92adbc83d790806 | 6,131 | //
// TweetCell.swift
// Twitter
//
// Created by jasmine_lee on 11/2/16.
// Copyright ยฉ 2016 jasmine_lee. All rights reserved.
//
import UIKit
import AFNetworking
@objc protocol TweetCellDelegate {
@objc optional func tweetCellChanged(_ cell: UITableViewCell, tweet: Tweet, action: String)
}
enum TweetActionIdentifier : String {
case Retweet = "retweet"
case UndoRetweet = "undoRetweet"
case Favorite = "favorite"
case UndoFavorite = "undoFavorite"
}
class TweetCell: UITableViewCell {
weak var delegate: TweetCellDelegate?
@IBOutlet weak var profileTitleLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var tweetMessageLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteButton: UIButton!
var isFavorited : Bool!
var isRetweeted : Bool!
var tweetId : Int!
var tweet: Tweet! {
didSet {
profileTitleLabel.text = tweet.profileName
usernameLabel.text = "@\(tweet.username!) ยท"
timestampLabel.text = "\(tweet.timestampString!)"
tweetMessageLabel.text = tweet.text
favoriteCountLabel.text = "\(tweet.favoritesCount)"
retweetCountLabel.text = "\(tweet.retweetCount)"
isFavorited = tweet.favorited
isRetweeted = tweet.retweeted
tweetId = tweet.id
toggleRetweetButton(turnOn: isRetweeted, isRefresh: false)
toggleFavoriteButton(turnOn: isFavorited, isRefresh: false)
if let url = tweet.profileUrl {
print(url.absoluteString)
profileImageView.setImageWith(url)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setUp()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private func setUp(){
profileImageView.layer.cornerRadius = 3
profileImageView.clipsToBounds = true
let replyImage = UIImage(named: "reply")?.withRenderingMode(.alwaysTemplate)
replyButton.setImage(replyImage, for: .normal)
replyButton.tintColor = UIColor.lightGray
}
@IBAction func retweetAction(_ sender: UIButton) {
if isRetweeted == true
{
if tweet.retweetedStatus == nil {
// original tweet
TwitterClient.sharedInstance?.undoRetweet(id: tweetId!, success: { (updatedTweet: Tweet) in
self.delegate?.tweetCellChanged!(self, tweet: updatedTweet, action: TweetActionIdentifier.UndoRetweet.rawValue)
self.toggleRetweetButton(turnOn: false, isRefresh: true)
}, failure: { (error: Error) in
print(error.localizedDescription)
})
} else {
let originalIdString = tweet.retweetedStatus!["id_str"] as! String
let originalId = Int(originalIdString)
TwitterClient.sharedInstance?.undoRetweet(id: originalId!, success: { (updatedTweet: Tweet) in
self.delegate?.tweetCellChanged!(self, tweet: updatedTweet, action: TweetActionIdentifier.UndoRetweet.rawValue)
self.toggleRetweetButton(turnOn: false, isRefresh: true)
}, failure: { (error: Error) in
print(error.localizedDescription)
})
}
} else {
TwitterClient.sharedInstance?.retweet(id: tweetId!, success: { (updatedTweet: Tweet) in
self.delegate?.tweetCellChanged!(self, tweet: updatedTweet, action: TweetActionIdentifier.Retweet.rawValue)
self.toggleRetweetButton(turnOn: true, isRefresh: true)
}, failure: { (error: Error) in
print(error.localizedDescription)
})
}
}
@IBAction func favoriteAction(_ sender: UIButton) {
if isFavorited == true
{
TwitterClient.sharedInstance?.undoFavorite(id: tweetId!, success: { (updatedTweet: Tweet) in
self.delegate?.tweetCellChanged!(self, tweet: updatedTweet, action: TweetActionIdentifier.UndoFavorite.rawValue)
self.toggleFavoriteButton(turnOn: false, isRefresh: true)
}, failure: { (error: Error) in
print(error.localizedDescription)
})
} else {
TwitterClient.sharedInstance?.favorite(id: tweetId!, success: { (updatedTweet: Tweet) in
self.delegate?.tweetCellChanged!(self, tweet: updatedTweet, action: TweetActionIdentifier.Favorite.rawValue)
self.toggleFavoriteButton(turnOn: true, isRefresh: true)
}, failure: { (error: Error) in
print(error.localizedDescription)
})
}
}
private func toggleRetweetButton (turnOn: Bool, isRefresh: Bool){
let retweetImage = UIImage(named: "retweet")?.withRenderingMode(.alwaysTemplate)
retweetButton.setImage(retweetImage, for: .normal)
if turnOn {
retweetButton.tintColor = UIColor.green
isRetweeted = true
} else {
retweetButton.tintColor = UIColor.lightGray
isRetweeted = false
}
}
private func toggleFavoriteButton (turnOn: Bool, isRefresh: Bool){
let favoriteImage = UIImage(named: "favorite")?.withRenderingMode(.alwaysTemplate)
favoriteButton.setImage(favoriteImage, for: .normal)
if turnOn {
favoriteButton.tintColor = UIColor.red
isFavorited = true
} else {
favoriteButton.tintColor = UIColor.lightGray
isFavorited = false
}
}
}
| 35.235632 | 131 | 0.624042 |
09a17ed43f3ceeb340690bc276dcdee71a570d01 | 4,683 | //: [Previous](@previous)
import Foundation
let jsonString = """
{
"taskName": "Solor",
"taskNumber": 100105,
"startDate": "05-30-2019",
"isAssigned": false,
"task_mission": "this is to do something",
"taskCondition": {
"load": 5000,
"temperature": 50,
"pressure": 1200
},
"assigner": {
"csr_name": "Wang Gang"
},
"parts":[{"number": "WD062781", "name": "fep"},{"number": "WF065212", "name": "ltp"}],
"workers": {
"site": [
{"worker": { "id": "W60001", "name": "Li"}},
{"worker": { "id": "W60023", "name": "Wan"}}
]
},
"sales":[
{"workers":{"id": "S80010","name": "Cang"}}
]
}
"""
var jsonData = jsonString.data(using: .utf8)!
var task = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves)
if let taskdic = task as? Dictionary<String, Any> {
taskdic["taskName"]
}
struct ZZHPart {
let partNumber: String
let partName: String
}
extension ZZHPart: Decodable {
enum CodingKeys: String, CodingKey {
case partNumber = "number"
case partName = "name"
}
}
struct ZZHWorker {
let workerID: String
let workerName: String
}
extension ZZHWorker: Decodable {
enum CodingKeys: String, CodingKey {
case workerID = "id"
case workerName = "name"
}
enum WorkerKey: String, CodingKey { case worker }
init(from decoder: Decoder) throws {
let rootKeys = try decoder.container(keyedBy: WorkerKey.self)
let workerContainer = try rootKeys.nestedContainer(keyedBy: CodingKeys.self, forKey: .worker)
workerID = try workerContainer.decode(String.self, forKey: .workerID )
workerName = try workerContainer.decode(String.self, forKey: .workerName)
}
}
struct ZZHCondition {
let load: Int
let temperature: Int
let pressure: Int
}
extension ZZHCondition: Decodable {
}
struct ZZHTask {
let taskName: String
let taskNumber: Int
let startDate: Date
let isAssigned: Bool
let taskMission: String
let taskCondition: ZZHCondition
let assigner: String
let parts: [ZZHPart]
let workers: [ZZHWorker]
let sales:[ZZHWorker]
}
extension ZZHTask: Decodable {
enum CodingKeys: String, CodingKey {
case taskName
case taskNumber
case startDate
case isAssigned
case taskMission = "task_mission"
case taskCondition
case assigner
case variance
case parts
case workers
case sales
enum AssignerKey: String, CodingKey {
case csrName = "csr_name"
}
enum WorkersKey: String, CodingKey {
case site
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
taskName = try container.decode(String.self, forKey: .taskName)
taskNumber = try container.decode(Int.self, forKey: .taskNumber)
startDate = try container.decode(Date.self, forKey: .startDate)
isAssigned = try container.decode(Bool.self, forKey: .isAssigned)
taskMission = try container.decode(String.self, forKey: .taskMission)
taskCondition = try container.decode(ZZHCondition.self, forKey: .taskCondition)
let assignContainer = try container.nestedContainer(keyedBy: CodingKeys.AssignerKey.self, forKey: .assigner)
assigner = try assignContainer.decode(String.self, forKey: .csrName)
parts = try container.decode([ZZHPart].self, forKey: .parts)
let workerContainer = try container.nestedContainer(keyedBy: CodingKeys.WorkersKey.self, forKey: .workers)
var siteContainer = try workerContainer.nestedUnkeyedContainer(forKey: .site)
var workerTmp:[ZZHWorker] = []
while !siteContainer.isAtEnd {
let work = try siteContainer.decode(ZZHWorker.self)
workerTmp += [work]
}
workers = workerTmp
var saleContainer = try container.nestedUnkeyedContainer(forKey: .sales)
var saleTmp: [ZZHWorker] = []
while !saleContainer.isAtEnd {
let work = try saleContainer.decode(ZZHWorker.self)
saleTmp += [work]
}
sales = saleTmp
}
}
extension DateFormatter {
static let customerFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
return formatter
}()
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.customerFormat)
do {
task = try decoder.decode(ZZHTask.self, from: jsonData)
print("task : \(task)")
} catch {
print("error: \(error)")
}
//: [Next](@next)
| 27.226744 | 116 | 0.636985 |
9b0ab1e7887f1a744eab139eb8609731c7a1bbdf | 526 | //
// ViewController.swift
// SRNoNetRetryTool
//
// Created by [email protected] on 08/18/2017.
// Copyright (c) 2017 [email protected]. 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.04 | 80 | 0.676806 |
ffb7428413523fc5a730c9fa81ff2d64adbe2d22 | 279 | import Foundation
import Tasker
class DummyTask: Task {
typealias SuccessValue = Void
func execute(completion: @escaping CompletionCallback) {
completion(.success(()))
}
}
// It's mutable because it's passed to inout funcitons.
var kDummyTask = DummyTask()
| 21.461538 | 60 | 0.713262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.