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
|
---|---|---|---|---|---|
50e6ccd20496fbd1660db54c426f516ed7db30eb | 6,316 | /*
* 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
enum RingIndex : Int {
case inner = 0
case middle = 1
case outer = 2
}
public let RingCompletedNotification = "RingCompletedNotification"
public let AllRingsCompletedNotification = "AllRingsCompletedNotification"
@IBDesignable
public class ThreeRingView : UIView {
fileprivate let rings : [RingIndex : RingLayer] = [.inner : RingLayer(), .middle : RingLayer(), .outer : RingLayer()]
fileprivate let ringColors = [UIColor.hrPinkColor, UIColor.hrGreenColor, UIColor.hrBlueColor]
public override init(frame: CGRect) {
super.init(frame: frame)
sharedInitialization()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInitialization()
}
public override func layoutSubviews() {
super.layoutSubviews()
drawLayers()
}
fileprivate func sharedInitialization() {
backgroundColor = UIColor.black
for (_, ring) in rings {
layer.addSublayer(ring)
ring.backgroundColor = UIColor.clear.cgColor
ring.ringBackgroundColor = ringBackgroundColor.cgColor
ring.ringWidth = ringWidth
}
// Set the default values
for (index, ring) in rings {
setColorForRing(index, color: ringColors[index.rawValue])
ring.value = 0.0
}
}
fileprivate func drawLayers() {
let size = min(bounds.width, bounds.height)
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
for (index, ring) in rings {
// Sort sizes
let curSize = size - CGFloat(index.rawValue) * ( ringWidth + ringPadding ) * 2.0
ring.bounds = CGRect(x: 0, y: 0, width: curSize, height: curSize)
ring.position = center
}
}
//: API Properties
@IBInspectable
public var ringWidth : CGFloat = 20.0 {
didSet {
drawLayers()
for (_, ring) in rings {
ring.ringWidth = ringWidth
}
}
}
@IBInspectable
public var ringPadding : CGFloat = 1.0 {
didSet {
drawLayers()
}
}
@IBInspectable
public var ringBackgroundColor : UIColor = UIColor.darkGray {
didSet {
for (_, ring) in rings {
ring.ringBackgroundColor = ringBackgroundColor.cgColor
}
}
}
var animationDuration : TimeInterval = 1.5
}
//: Values
extension ThreeRingView {
@IBInspectable
public var innerRingValue : CGFloat {
get {
return rings[.inner]?.value ?? 0
}
set(newValue) {
maybePostNotification(innerRingValue, new: newValue, current: .inner)
setValueOnRing(.inner, value: newValue, animated: false)
}
}
@IBInspectable
public var middleRingValue : CGFloat {
get {
return rings[.middle]?.value ?? 0
}
set(newValue) {
maybePostNotification(middleRingValue, new: newValue, current: .middle)
setValueOnRing(.middle, value: newValue, animated: false)
}
}
@IBInspectable
public var outerRingValue : CGFloat {
get {
return rings[.outer]?.value ?? 0
}
set(newValue) {
maybePostNotification(outerRingValue, new: newValue, current: .outer)
setValueOnRing(.outer, value: newValue, animated: false)
}
}
func setValueOnRing(_ ringIndex: RingIndex, value: CGFloat, animated: Bool = false) {
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
rings[ringIndex]?.setValue(value, animated: animated)
CATransaction.commit()
}
fileprivate func maybePostNotification(_ old: CGFloat, new: CGFloat, current: RingIndex) {
if old < 1 && new >= 1 { //threshold crossed
let allDone: Bool
switch(current) {
case .inner:
allDone = outerRingValue >= 1 && middleRingValue >= 1
case .middle:
allDone = innerRingValue >= 1 && outerRingValue >= 1
case .outer:
allDone = innerRingValue >= 1 && middleRingValue >= 1
}
if allDone {
postAllRingsCompletedNotification()
} else {
postRingCompletedNotification()
}
}
}
fileprivate func postAllRingsCompletedNotification() {
NotificationCenter.default.post(name: Notification.Name(rawValue: AllRingsCompletedNotification), object: self)
}
fileprivate func postRingCompletedNotification() {
NotificationCenter.default.post(name: Notification.Name(rawValue: RingCompletedNotification), object: self)
}
}
//: Colors
extension ThreeRingView {
@IBInspectable
public var innerRingColor : UIColor {
get {
return colorForRing(.inner)
}
set(newColor) {
setColorForRing(.inner, color: newColor)
}
}
@IBInspectable
public var middleRingColor : UIColor {
get {
return UIColor.clear
}
set(newColor) {
setColorForRing(.middle, color: newColor)
}
}
@IBInspectable
public var outerRingColor : UIColor {
get {
return UIColor.clear
}
set(newColor) {
setColorForRing(.outer, color: newColor)
}
}
fileprivate func colorForRing(_ index: RingIndex) -> UIColor {
return UIColor(cgColor: rings[index]!.ringColors.0)
}
fileprivate func setColorForRing(_ index: RingIndex, color: UIColor) {
rings[index]?.ringColors = (color.cgColor, color.darkerColor.cgColor)
}
}
| 29.240741 | 119 | 0.678594 |
69aa599984ba89ef0055d59f91f88b299c3bf845 | 4,372 | //
// ViewController.swift
// WXPhotoBrowser
//
// Created by June Young on 3/28/18.
// Copyright © 2018 young. All rights reserved.
//
import UIKit
import SnapKit
struct WXViewControllerConstants {
static let kCommonContentPaddingSpace: CGFloat = 15.0
static let kCollectionViewerContentWidth: CGFloat = UIScreen.main.bounds.width - kCommonContentPaddingSpace*2
static let kCollectionViewItemHeightWidth: CGFloat = floor((WXViewControllerConstants.kCollectionViewerContentWidth)/3.0)
}
class WXViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var collectionView : UICollectionView?
var dataList : Array<String>?
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigationBarStyle()
setUpFakeData()
setUpCollectionViewAndLayout()
}
func setUpNavigationBarStyle() {
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic
}
self.navigationItem.title = "First Page"
}
func setUpFakeData() {
self.view.backgroundColor = .blue
dataList = ["1", "2", "3", "4"]
}
func setUpCollectionViewAndLayout() {
let collectionLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
collectionLayout.minimumLineSpacing = WXViewControllerConstants.kCommonContentPaddingSpace
collectionLayout.minimumInteritemSpacing = WXViewControllerConstants.kCommonContentPaddingSpace
collectionView = UICollectionView.init(frame:.zero, collectionViewLayout: collectionLayout)
collectionView?.layer.borderColor = UIColor.red.cgColor
collectionView?.layer.borderWidth = CGFloat.leastNormalMagnitude
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = .white
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.register(WXMainCollectionViewCell.self, forCellWithReuseIdentifier: WXMainCollectionViewCellConstants.kMainCollectionViewCellIdentifier)
self.view.addSubview(collectionView!)
collectionView?.snp.makeConstraints({ (make) -> Void in
make.edges.equalTo(self.view)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - UICollectionViewDataSource
func existDataSource() -> Bool {
if let list = dataList {
return list.count > 0
}
return false
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if existDataSource() {
return dataList!.count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: WXMainCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: WXMainCollectionViewCellConstants.kMainCollectionViewCellIdentifier, for: indexPath) as! WXMainCollectionViewCell
cell.imageNameString = dataList?[indexPath.row]
cell.cellIndex = indexPath.row
cell.updateImageViewer()
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if existDataSource() {
return CGSize.init(width: WXViewControllerConstants.kCollectionViewItemHeightWidth, height: WXViewControllerConstants.kCollectionViewItemHeightWidth)
}
return CGSize.zero
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return existDataSource()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let vc = WXPhotoBrowserViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 38.690265 | 214 | 0.712031 |
1a484a8fab1a59dbbdfabb3167df88b357744514 | 7,442 | //
// HRMController.swift
// MyHeartMonitor
//
// Created by Mosdafa on 25/04/2017.
// Copyright © 2017 Mostafa Berg. All rights reserved.
//
import UIKit
import CoreBluetooth
//MARK - Services
let battery_service_uuid = "180F"
let hrm_service_uuid = "180D"
//MARK - Characteristis
let battery_level_characteristic_uuid = "2A19"
let hrm_location_characteristic_uuid = "2A38"
let hrm_reading_characteristic_uuid = "2A37"
enum heartSensorLocation: UInt8 {
case other = 0x00
case chest = 0x01
case wrist = 0x02
case finger = 0x03
case hand = 0x04
case earLobe = 0x05
case foot = 0x06
}
class HRMController: NSObject, CBPeripheralDelegate {
//MARK: - Properties
var delegate: HRMControllerDelegate?
var targetPeripheral: CBPeripheral
var batteryLevelCharacteristic: CBCharacteristic!
var heartMonitorLocationCharacteristic: CBCharacteristic!
var heartMonitorReadingCharacteristic: CBCharacteristic!
//MARK: - Implementation
required init(withPeripheral aPeripheral: CBPeripheral) {
targetPeripheral = aPeripheral
super.init()
targetPeripheral.delegate = self
let batteryServiceIdentifier = CBUUID(string: battery_service_uuid)
let hrmServiceIdentifier = CBUUID(string: hrm_service_uuid)
targetPeripheral.discoverServices([batteryServiceIdentifier,
hrmServiceIdentifier])
}
func beginHRMNotifications() {
guard heartMonitorReadingCharacteristic != nil else{
print("HRM reading characteristic not present")
return
}
setNotificationState(aState: true, forCharacteristic: heartMonitorReadingCharacteristic)
}
func stopHRMNotifications() {
guard heartMonitorReadingCharacteristic != nil else{
print("HRM reading characteristic not present")
return
}
setNotificationState(aState: false, forCharacteristic: heartMonitorReadingCharacteristic)
}
func beginBatteryNotificaitons() {
guard batteryLevelCharacteristic != nil else{
print("Battery level characteristic not present")
return
}
setNotificationState(aState: true, forCharacteristic: batteryLevelCharacteristic)
}
func stopBatteryNotifications() {
guard batteryLevelCharacteristic != nil else{
print("Battery level characteristic not present")
return
}
setNotificationState(aState: false, forCharacteristic: batteryLevelCharacteristic)
}
private func setNotificationState(aState: Bool, forCharacteristic aCharacteristic: CBCharacteristic) {
targetPeripheral.setNotifyValue(aState, for: aCharacteristic)
}
func readSensorLocation() {
guard heartMonitorLocationCharacteristic != nil else {
print("Sensor location characteristic not present")
return
}
targetPeripheral.readValue(for: heartMonitorLocationCharacteristic)
}
//MARK: - CBperipheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard peripheral.services != nil && peripheral.services!.count > 0 else {
print("peripheral has no services")
return
}
for aService in peripheral.services! {
if aService.uuid.uuidString == battery_service_uuid {
let batteryLevelCharcateristicUUID = CBUUID(string: battery_level_characteristic_uuid)
peripheral.discoverCharacteristics([batteryLevelCharcateristicUUID], for: aService)
}
if aService.uuid.uuidString == hrm_service_uuid {
let hrmSensorLocationUUID = CBUUID(string: hrm_location_characteristic_uuid)
let hrmSensorReadingUUID = CBUUID(string: hrm_reading_characteristic_uuid)
peripheral.discoverCharacteristics([hrmSensorLocationUUID,
hrmSensorReadingUUID], for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("an error has occured: \(error!)")
return
}
for aService in peripheral.services! {
if aService.uuid.uuidString == battery_service_uuid {
if let discoveredCharcateristics = aService.characteristics {
for aCharacteristic in discoveredCharcateristics {
if aCharacteristic.uuid.uuidString == battery_level_characteristic_uuid {
print("Battery level chtx found")
batteryLevelCharacteristic = aCharacteristic
}
}
}
}
if aService.uuid.uuidString == hrm_service_uuid {
if let discoveredCharcateristics = aService.characteristics {
for aCharacteristic in discoveredCharcateristics {
if aCharacteristic.uuid.uuidString == hrm_reading_characteristic_uuid {
print("HRM reading chtx found")
heartMonitorReadingCharacteristic = aCharacteristic
}
if aCharacteristic.uuid.uuidString == hrm_location_characteristic_uuid {
print("HRM location chtx found")
heartMonitorLocationCharacteristic = aCharacteristic
}
}
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid.uuidString == battery_level_characteristic_uuid {
//handle battery level change
let data = characteristic.value!
let bytes = [UInt8](data)
delegate?.didReceiveBatteryLevel(percentage: bytes[0])
}
if characteristic.uuid.uuidString == hrm_reading_characteristic_uuid {
//handle hrm readings
let data = characteristic.value!
let bytes = [UInt8](data)
//Check if value is UInt8 or UInt16 (as per spec)
if bytes[0] & 0x01 == 0 {
//UInt8 value
delegate?.didReceiveReading(bpm: UInt16(bytes[1]))
} else {
//UInt16 value
//Convert Endianess from Little to Big
let convertedBytes = UInt16(bytes[2] * 0xFF) + UInt16(bytes[1])
delegate?.didReceiveReading(bpm: convertedBytes)
}
}
if characteristic.uuid.uuidString == hrm_location_characteristic_uuid {
//handle location reading
let data = characteristic.value!
let bytes = [UInt8](data)
if let location = heartSensorLocation(rawValue: bytes[0]) {
delegate?.didUpdateSensorLocation(location: location)
} else {
delegate?.didUpdateSensorLocation(location: .other)
}
}
}
}
| 39.796791 | 116 | 0.608842 |
f7ddf521d5dc73e25e166b2c31ba86b68f84ae70 | 6,983 | //
// GongLueViewController.swift
// Gift
//
// Created by qianfeng on 16/10/26.
// Copyright © 2016年 Jiangpeng. All rights reserved.
//
import UIKit
import Alamofire
import Kingfisher
//总攻略
class GongLueViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
var dataArray:[ClassifyModel] = []
var collectionView:UICollectionView!
//var scrollView:UIScrollView!
var id:NSNumber = 0
var jumpClosure:(NSNumber->Void)!
//lazy var webNumber:NSNumber = 0
var vc:GongLueHeadView!
override func viewDidLoad() {
super.viewDidLoad()
configUI()
loadData()
view.backgroundColor = UIColor.whiteColor()
vc = GongLueHeadView.init(frame: CGRect(x: 0, y: -250, width: screenWidth, height: 250))
collectionView.addSubview(vc)
vc.jumpClosure = { (a) in
let vc1 = GongLueHeadSubView()
self.navigationController?.pushViewController(vc1, animated: true)
vc1.number = a
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func configUI() {
automaticallyAdjustsScrollViewInsets = false
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumInteritemSpacing = 10
flowLayout.minimumLineSpacing = 10
flowLayout.scrollDirection = .Vertical
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight-104-49), collectionViewLayout: flowLayout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsVerticalScrollIndicator = false
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.contentInset = UIEdgeInsets(top: 250, left: 0, bottom: 0, right: 0)
collectionView.userInteractionEnabled = true
self.collectionView?.registerNib(UINib(nibName: "GongLueCell", bundle: nil), forCellWithReuseIdentifier: "GongLueCellId")
self.collectionView.registerClass(ClassifyHeadView.classForCoder(), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader,withReuseIdentifier: "header")
view.addSubview(collectionView)
}
//整个攻略的CollectionView的数据解析
func loadData() {
Alamofire.request(.GET, classifyAllUrl).responseJSON { [unowned self] (response) in
if response.result.error == nil {
let array = (response.result.value)!["data"]!!["channel_groups"] as! [AnyObject]
for items in array {
let model = ClassifyModel()
model.name = items["name"] as! String
let array1 = items["channels"] as! [[String:AnyObject]]
for item in array1 {
let model1 = ClassifyImageModel()
model1.setValuesForKeysWithDictionary(item)
model.imageModels.append(model1)
}
self.dataArray.append(model)
}
self.collectionView!.reloadData()
}
}
}
// MARK: - Navigation
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return dataArray.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(170, 70)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSizeMake(screenWidth, 40)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(10, 10, 10, 10)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GongLueCellId", forIndexPath: indexPath) as! GongLueCell
let model = dataArray[indexPath.section].imageModels[indexPath.row]
cell.GongLueImageView.kf_setImageWithURL(NSURL(string: model.cover_image_url))
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let kind = UICollectionElementKindSectionHeader
let model = dataArray[indexPath.section]
let header=collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as! ClassifyHeadView
header.backgroundColor=UIColor.colorWith(R: 212, G: 212, B: 212, A: 0.8)
header.leftLabel.text = model.name
if (dataArray[indexPath.section].imageModels).count > 6 {
header.rightLabel.text = "查看全部 >"
if indexPath.section == 0 {
let g1 = UITapGestureRecognizer(target: self, action: #selector(tapAction1))
header.rightLabel.addGestureRecognizer(g1)
}else if indexPath.section == 2 {
let g2 = UITapGestureRecognizer(target: self, action: #selector(tapAction2))
header.rightLabel.addGestureRecognizer(g2)
}
}
return header
}
}
extension GongLueViewController {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let vc = GongLueSubView()
vc.hidesBottomBarWhenPushed = true
let id = dataArray[indexPath.section].imageModels[indexPath.row].id ?? ""
let str = "http://api.liwushuo.com/v2/channels/\(id!)/items_v2?limit=20&offset=%ld"
vc.url = str
navigationController?.pushViewController(vc, animated: true)
}
func tapAction1() {
let vc = GongLueSortSubView()
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
// print("1")
// let url1 = NSURL(string:"TestKitChen_1607://")
// UIApplication.sharedApplication().openURL(url1!)
}
func tapAction2() {
let vc = GongLueTargetSubView()
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
}
| 34.915 | 171 | 0.648862 |
722d2ddc26b89ce5d35f7cc3a5c87f746123f747 | 528 | /*
"Swiftly Salesforce: the Swift-est way to build iOS apps that connect to Salesforce"
For more information and license see: https://www.github.com/mike4aday/SwiftlySalesforce
Copyright (c) 2021. All rights reserved.
*/
import Foundation
public extension JSONDecoder {
static var salesforce = JSONDecoder(dateDecodingStrategy: .formatted(.salesforce(.long)))
convenience init(dateDecodingStrategy: DateDecodingStrategy) {
self.init()
self.dateDecodingStrategy = dateDecodingStrategy
}
}
| 29.333333 | 93 | 0.748106 |
2f5ca1af4fcd47a6566593bd7132fd9b42c5691e | 3,129 | import UIKit
final class TodayViewController: UIViewController {
private let newsView: UITableView = UITableView.initView(style: .plain) { view in
view.register(TodayCardUITableViewCell.self, forCellReuseIdentifier: "cell")
}
private let items: [String] = ["Hello", "My", "Name", "Is", "Mark"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.view.addSubview(self.newsView)
self.newsView.dataSource = self
self.newsView.delegate = self
self.newsView.rowHeight = 400
self.newsView.separatorStyle = .none
self.newsView.allowsSelection = false
self.newsView.pin(to: self.view)
}
}
extension TodayViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TodayCardUITableViewCell
= tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
as! TodayCardUITableViewCell
let cardContentVC = CustomViewController()
cardContentVC.view.backgroundColor = UIColor(named: "CardBackgroundColor")
// cell.card.shouldPresent(cardContentVC, from: self, fullscreen: true)
// cell.card.delegate = self
return cell
}
}
class CustomViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override var prefersStatusBarHidden: Bool {
true
}
}
//extension TodayViewController: CardDelegate {
// func cardDidTapInside(card: Card) {
// self.setTabBarHidden(true, animated: true, duration: 0.1)
// }
//
// func cardIsHidingDetail(card: Card) {
// self.setTabBarHidden(false, animated: true, duration: 0.3)
// }
//}
extension UIViewController {
func setTabBarHidden(_ hidden: Bool, animated: Bool = true, duration: TimeInterval = 0.5) {
if self.tabBarController?.tabBar.isHidden != hidden{
if animated {
//Show the tabbar before the animation in case it has to appear
if (self.tabBarController?.tabBar.isHidden)!{
self.tabBarController?.tabBar.isHidden = hidden
}
if let frame = self.tabBarController?.tabBar.frame {
let factor: CGFloat = hidden ? 1 : -1
let y = frame.origin.y + (frame.size.height * factor)
UIView.animate(withDuration: duration, animations: {
self.tabBarController?.tabBar.frame = CGRect(x: frame.origin.x, y: y, width: frame.width, height: frame.height)
}) { (bool) in
//hide the tabbar after the animation in case ti has to be hidden
if (!(self.tabBarController?.tabBar.isHidden)!){
self.tabBarController?.tabBar.isHidden = hidden
}
}
}
}
}
}
}
| 33.645161 | 131 | 0.620326 |
cc59f00afd902e43446af0633e027692f533190b | 4,035 | //
// CALayer+Extension.swift
// ExtensionKit
//
// Created by Moch Xiao on 2/22/17.
// Copyright © 2017 Moch. All rights reserved.
//
import Foundation
import QuartzCore
import UIKit
// MARK: - Frame & Struct
public extension CALayer {
public var origin: CGPoint {
get { return frame.origin }
set { frame = CGRect(x: newValue.x, y: newValue.y, width: width, height: height) }
}
public var size: CGSize {
get { return frame.size }
set { frame = CGRect(x: minX, y: minY, width: newValue.width, height: newValue.height) }
}
public var minX: CGFloat {
get { return frame.origin.x }
set { frame = CGRect(x: newValue, y: minY, width: width, height: height) }
}
public var left: CGFloat {
get { return frame.origin.x }
set { frame = CGRect(x: newValue, y: minY, width: width, height: height) }
}
public var midX: CGFloat {
get { return frame.midX }
set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) }
}
public var centerX: CGFloat {
get { return frame.midX }
set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) }
}
public var maxX: CGFloat {
get { return minX + width }
set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) }
}
public var right: CGFloat {
get { return minX + width }
set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) }
}
public var minY: CGFloat {
get { return frame.origin.y }
set { frame = CGRect(x: minX, y: newValue, width: width, height: height) }
}
public var top: CGFloat {
get { return frame.origin.y }
set { frame = CGRect(x: minX, y: newValue, width: width, height: height) }
}
public var midY: CGFloat {
get { return frame.midY }
set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) }
}
public var centerY: CGFloat {
get { return frame.midY }
set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) }
}
public var maxY: CGFloat {
get { return minY + height }
set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) }
}
public var bottom: CGFloat {
get { return minY + height }
set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) }
}
public var width: CGFloat {
get { return bounds.width }
set { frame = CGRect(x: minX, y: minY, width: newValue, height: height) }
}
public var height: CGFloat {
get { return bounds.height }
set { frame = CGRect(x: minX, y: minY, width: width, height: newValue) }
}
public var center: CGPoint {
set { frame = CGRect(x: newValue.x - frame.size.width * 0.5, y: newValue.y - frame.size.height * 0.5, width: width, height: height) }
get { return CGPoint(x: origin.x + size.width * 0.5, y: origin.y + size.height * 0.5) }
}
}
public extension CALayer {
public var snapshotImage: UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func setShadow(color: UIColor, offset: CGSize, radius: CGFloat) {
shadowColor = color.cgColor
shadowOffset = offset
shadowRadius = radius
shadowOpacity = 1
shouldRasterize = true
rasterizationScale = UIScreen.main.scale
}
public func removeAllSublayers() {
sublayers?.forEach { (sender) in
sender.removeFromSuperlayer()
}
}
}
| 31.27907 | 141 | 0.587113 |
dd019cfdb239efc91de3465323f8634586b902b2 | 1,262 | //
// +UIScrollView.swift
// WPAppKit
//
// Created by 王鹏 on 2020/7/16.
//
import UIKit
public extension UIScrollView {
/// SwifterSwift: Takes a snapshot of an entire ScrollView
///
/// AnySubclassOfUIScroolView().snapshot
/// UITableView().snapshot
///
/// - Returns: Snapshot as UIimage for rendered ScrollView
var snapshot: UIImage? {
// Original Source: https://gist.github.com/thestoics/1204051
UIGraphicsBeginImageContextWithOptions(contentSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
let previousFrame = frame
frame = CGRect(origin: frame.origin, size: contentSize)
layer.render(in: context)
frame = previousFrame
return UIGraphicsGetImageFromCurrentImageContext()
}
/// 滚动到底部
func scrollToBottom(animated: Bool? = true) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated ?? true)
}
/// 滚动到顶部
func scrollToTop(animated: Bool? = true) {
setContentOffset(CGPoint.zero, animated: animated ?? true)
}
}
| 29.348837 | 84 | 0.641046 |
ffc3c8a78ae316375c427803a23193691b567940 | 314 | //
// ConsoleIO.swift
// SDMTS_DataWrangler
//
// Created by Will An on 8/9/17.
// Copyright © 2017 Will An. All rights reserved.
//
import Foundation
class IO {
let dictionaryPath: String
init(dictionaryPath: NSString) {
self.dictionaryPath = dictionaryPath as String
}
}
| 15.7 | 54 | 0.640127 |
1e8975ae9b9d08c96aab6cac5db3fdd73d6de330 | 1,982 | import Foundation
import UIKit
class JSONPlaceholderNetworking {
public func getImages(_ imageCount: Int, completion: @escaping ([Image]) -> ()) {
getRequest("https://jsonplaceholder.typicode.com/photos?_limit=10") { data in
let images = try! JSONDecoder().decode([Image].self, from: data)
completion(images)
}
}
private func getRequest(_ url: String, completion: @escaping (Data) -> ()) {
let urlRequest = URLRequest(url: URL(string: url)!)
let session = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: urlRequest) { (data, response, error) in
guard let data = data, let _ = response, error == nil else {
fatalError()
}
completion(data)
}
session.resume()
}
}
struct Image: Codable {
let albumId: Int
let title: String
let url: String
let thumbnailUrl: String
}
// THANK YOU STACK OVERFLOW
extension UIImageView {
func download(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) { // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
guard let url = URL(string: link) else { return }
download(from: url, contentMode: mode)
}
}
| 37.396226 | 160 | 0.607972 |
2ffdda3303faf8e13a8ca502bcc7bb05b597ff90 | 223 | //
// Created by Dmitriy Stupivtsev on 03/05/2019.
//
import Foundation
import Promises
// sourcery: AutoMockable
protocol TimeZoneService {
func getTimeZones(from coordinates: [Coordinate]) -> Promise<[TimeZone]>
}
| 18.583333 | 76 | 0.73991 |
50f57111fdcf08cbe381a6d627023e8161ccfd0f | 7,109 | import Foundation
import XCTest
@testable import Tea
final class TeaTests: XCTestCase {
func testTeaCoreComposeUrl() {
let request: TeaRequest = TeaRequest()
var url = TeaCore.composeUrl(request)
XCTAssertEqual("http://", url)
request.headers["host"] = "fake.domain.com"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com", url)
request.port = 8080
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080", url)
request.pathname = "/index.html"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html", url)
request.query["foo"] = ""
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html", url)
request.query["foo"] = "bar"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html?foo=bar", url)
request.pathname = "/index.html?a=b"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html?a=b&foo=bar", url)
request.pathname = "/index.html?a=b&"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html?a=b&foo=bar", url)
request.query["fake"] = nil
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html?a=b&foo=bar", url)
request.query["fake"] = "val"
url = TeaCore.composeUrl(request)
XCTAssertEqual("http://fake.domain.com:8080/index.html?a=b&fake=val&foo=bar", url)
}
func testTeaModelToMap() {
let model = ListDriveRequestModel()
model.limit = 100
model.marker = "fake-marker"
model.owner = "fake-owner"
let dict: [String: Any] = model.toMap()
let limit: Int = dict["limit"] as! Int
let marker: String = dict["marker"] as! String
let owner: String = dict["owner"] as! String
XCTAssertEqual(100, limit)
XCTAssertEqual("fake-marker", marker)
XCTAssertEqual("fake-owner", owner)
}
func testTeaModelValidate() {
let model = ListDriveRequestModel()
var thrownError: Error?
XCTAssertThrowsError(try model.validate()) {
thrownError = $0
}
XCTAssertTrue(
thrownError is TeaException,
"Unexpected error type: \(type(of: thrownError))"
)
model.owner = "notEmpty"
XCTAssertTrue(try model.validate())
}
func testTeaModelToModel() {
var dict: [String: Any] = [String: Any]()
dict["limit"] = 1
dict["marker"] = "marker"
dict["owner"] = "owner"
let model = TeaModel.toModel(dict, ListDriveRequestModel()) as! ListDriveRequestModel
XCTAssertEqual(1, model.limit)
XCTAssertEqual("marker", model.marker)
XCTAssertEqual("owner", model.owner)
}
func testTeaCoreSleep() {
let sleep: Int = 10
let start: Double = Date().timeIntervalSince1970
TeaCore.sleep(sleep)
let end: Double = Date().timeIntervalSince1970
XCTAssertTrue(Int((end - start)) >= sleep)
}
func testTeaCoreDoAction() {
var res: TeaResponse?
let expectation = XCTestExpectation(description: "Test async request")
let request: requestCompletion = { done in
let request_ = TeaRequest()
request_.protocol_ = "http"
request_.method = "POST"
request_.pathname = "/v2/drive/list"
request_.headers = [
"user-agent": "Tea Test for TeaCore.doAction",
"host": "sz16.api.alicloudccp.com",
"content-type": "application/json; charset=utf-8"
]
let utils: TestsUtils = TestsUtils()
request_.headers["date"] = utils._getRFC2616Date()
request_.headers["accept"] = "application/json"
request_.headers["x-acs-signature-method"] = "HMAC-SHA1"
request_.headers["x-acs-signature-version"] = "1.0"
request_.headers["authorization"] = "acs AccessKeyId:TestSignature"
let model = ListDriveRequestModel()
model.owner = "owner"
request_.body = utils._toJSONString([model])
var runtime = [String: Any]()
runtime["connectTimeout"] = 0
runtime["readTimeout"] = 0
res = TeaCore.doAction(request_, runtime)
done(res)
}
let done: doneCompletion = { response in
// do something when get response
res = response as? TeaResponse
XCTAssertNotNil(res)
XCTAssertNil(res?.error)
XCTAssertEqual("403", res?.statusCode ?? "0")
XCTAssertEqual("{\"code\":\"InvalidParameter.Accesskeyid\",\"message\":\"The input parameter AccessKeyId is not valid. DoesNotExist\"}", String(bytes: res!.data, encoding: .utf8))
expectation.fulfill()
}
TeaClient.async(request: request, done: done)
wait(for: [expectation], timeout: 100.0)
}
func testTeaCoreAllowRetry() {
var result: Bool = TeaCore.allowRetry(nil, 3, 0)
XCTAssertFalse(result)
var dict: [String: Int] = [String: Int]()
dict["maxAttempts"] = 5
result = TeaCore.allowRetry(dict, 0, 0)
XCTAssertTrue(result)
}
func testTeaCoreGetBackoffTime() {
var dict: [String: String] = [String: String]()
dict["policy"] = "no"
XCTAssertEqual(0, TeaCore.getBackoffTime(dict, 3))
dict["policy"] = "yes"
dict["period"] = ""
XCTAssertEqual(0, TeaCore.getBackoffTime(dict, 3))
dict["period"] = "-1"
XCTAssertEqual(3, TeaCore.getBackoffTime(dict, 3))
dict["period"] = "1"
XCTAssertEqual(1, TeaCore.getBackoffTime(dict, 3))
}
func testTeaCoreIsRetryable() {
XCTAssertTrue(TeaCore.isRetryable(TeaException.ValidateError("foo")))
}
func testTeaConverterMerge() {
var dict1: [String: String] = [String: String]()
var dict2: [String: String] = [String: String]()
dict1["foo"] = "bar"
dict2["bar"] = "foo"
let dict: [String: String] = TeaConverter.merge(dict1, dict2) as! [String: String]
XCTAssertEqual(dict["foo"], "bar")
XCTAssertEqual(dict["bar"], "foo")
}
static var allTests = [
("testTeaCoreComposeUrl", testTeaCoreComposeUrl),
("testTeaModelToMap", testTeaModelToMap),
("testTeaModelValidate", testTeaModelValidate),
("testTeaModelToModel", testTeaModelToModel),
("testTeaCoreSleep", testTeaCoreSleep),
("testTeaCoreDoAction", testTeaCoreDoAction),
("testTeaCoreAllowRetry", testTeaCoreAllowRetry),
("testTeaCoreGetBackoffTime", testTeaCoreGetBackoffTime),
("testTeaCoreIsRetryable", testTeaCoreIsRetryable),
("testTeaConverterMerge", testTeaConverterMerge),
]
}
| 35.723618 | 191 | 0.602335 |
3366e7f3bcf8ffd96fa7952d562accf2b9f258c0 | 268 | //
// TodoListSection.swift
// TodoRx
//
// Created by Matt Fenwick on 7/19/17.
// Copyright © 2017 mf. All rights reserved.
//
import Foundation
struct TodoListSection: AutoEquatable {
let sectionType: TodoListSectionType
let rows: [TodoListRowModel]
}
| 17.866667 | 45 | 0.712687 |
fc9b5ebe728bcd50d6e38d179361637d6abc53f3 | 1,529 | //
// Created by Zap on 01.08.2018.
//
import Foundation
import XCTest
@testable import Swiftygram
final class ToolsTests: XCTestCase {
func test_Environmental_variable_is_loaded_from_environment() {
prepareEnvVar(key: "RANDOM_VARIABLE", value: "abc")
XCTAssertEqual(readFromEnvironment("RANDOM_VARIABLE"), "abc")
}
func test_Environmental_variable_is_loaded_from_file() {
prepareFile(key: "test", value: "File content")
XCTAssertEqual(readFromEnvironment("test"), "File content")
}
func test_Environmental_variable_tries_to_load_value_from_environment_first_and_then_from_file() {
prepareEnvVar(key: "direct_order", value: "ab1")
prepareFile(key: "direct_order", value: "ab2")
XCTAssertEqual(readFromEnvironment("direct_order"), "ab1")
prepareFile(key: "revert_order", value: "ab3")
prepareEnvVar(key: "revert_order", value: "ab4")
XCTAssertEqual(readFromEnvironment("revert_order"), "ab4")
}
}
private func prepareEnvVar(key: String, value: String) {
setenv(key, value, 1)
}
private func prepareFile(key: String, value: String) {
guard let testFileURL = URL(string: "file://\(FileManager.default.currentDirectoryPath)/\(key)") else {
XCTFail("Failed to convert path to URL")
return
}
do {
try value.write(to: testFileURL, atomically: true, encoding: .utf8)
} catch {
XCTFail("Test setup error - couldn't write content to file: \(error)")
}
}
| 27.303571 | 107 | 0.679529 |
c1e87d91a127f8ba93cf7cda46263b2784f18614 | 5,250 | //
// TwitterClient.swift
// TwitterDemo
//
// Created by sophie on 7/20/16.
// Copyright © 2016 CorazonCreations. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class TwitterClient: BDBOAuth1SessionManager {
static let sharedInstance = TwitterClient(baseURL: NSURL(string: "https://api.twitter.com")!, consumerKey: "07gLjl13xAm49nSybYUrOps75", consumerSecret: "CGU1xWYj0zYEt5vvdF3mOK36WmXzj0OTMOMO5p7t9MzBWATvJF")
var loginSuccess: (() -> ())?
var loginFailure: ((NSError) -> ())?
func login(success: () -> (), failure: (NSError) -> ()) {
loginSuccess = success
loginFailure = failure
TwitterClient.sharedInstance.deauthorize()
TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "twitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in
print("I got a token")
let url = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")!
//this line is to open an url
UIApplication.sharedApplication().openURL(url)
}) { (error: NSError!) -> Void in
print("error: \(error.localizedDescription)")
self.loginFailure?(error)
}
}
func handleOpenUrl(url: NSURL) {
let requestToken = BDBOAuth1Credential(queryString: url.query)
fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential!) -> Void in
self.currentAccount({ (user: User) -> () in
User.currentUser = user
self.loginSuccess?()
}, failure: { (error: NSError) -> () in
self.loginFailure?(error)
})
self.loginSuccess?()
}) { (error: NSError!) -> Void in
print("error: \(error.localizedDescription)")
self.loginFailure?(error)
}
}
func homeTimeLine(success: ([Tweet]) -> (), failure: (NSError) -> ()) {
GET("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let dictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries)
success(tweets)
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
func currentAccount(success: (User) -> (), failure: (NSError) -> ()) {
GET("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let userDictionary = response as! NSDictionary
let user = User(dictionary: userDictionary)
success(user)
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
func postTweet(params: NSDictionary, success: (Tweet) -> (), failure: (NSError) -> ()) {
// let params: [String: AnyObject] = ["status": status, "in_reply_to_status_id": statusId]
POST("1.1/statuses/update.json", parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) in
if let tweetData = response as? NSDictionary {
let tweet = Tweet(dictionary: tweetData)
success(tweet)
}
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure(error)
}
}
func createFavorite(statusId: String, success: (Tweet) -> (), failure: (NSError) -> ()) {
// let params: [String: AnyObject] = ["id" : statusId]
let params = ["id" : statusId]
POST("1.1/favorites/create.json", parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) in
if let tweetData = response as? NSDictionary {
let tweet = Tweet(dictionary: tweetData)
success(tweet)
}
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure(error)
}
}
func retweet(retweetId: String, success: (Tweet) -> (), failure: (NSError) -> ()) {
let url = "1.1/statuses/retweet/\(retweetId).json"
POST(url, parameters: nil, progress: nil, success: { (task: NSURLSessionDataTask,response: AnyObject?) in
if let tweetData = response as? NSDictionary {
let tweet = Tweet(dictionary: tweetData)
success(tweet)
}
}) { (task: NSURLSessionDataTask?, error: NSError) in
failure(error)
}
}
func logout() {
User.currentUser = nil
deauthorize()
NSNotificationCenter.defaultCenter().postNotificationName(User.userDidLogoutNotification, object: nil)
}
}
| 37.769784 | 223 | 0.571619 |
e5e1a387c94a0d1231fcee57ee61af59645bfee2 | 1,054 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
@testable import Amplify
@testable import AmplifyTestCommon
@testable import AWSAPICategoryPlugin
class AWSGraphQLOperationTests: XCTestCase {
// TODO: Complete the implementation below
// override func setUp() {
// }
//
// override func tearDown() {
// }
//
// func testGraphQLOperationSuccess() {
// XCTFail("Not yet implemented.")
// }
//
// func testGraphQLOperationValidationError() {
// XCTFail("Not yet implemented.")
// }
//
// func testGraphQLOperationEndpointConfigurationError() {
// XCTFail("Not yet implemented.")
// }
//
// func testGraphQLOperationJSONSerializationError() {
// XCTFail("Not yet implemented.")
// }
//
// func testGraphQLOperationInterceptorError() {
// XCTFail("Not yet implemented.")
// }
}
| 24.511628 | 65 | 0.59203 |
2350d30aceb0996c40f44cc39d298b9907f905b9 | 5,836 | import CasePaths
import Dispatch
/// Determines how the string description of an action should be printed when using the `.debug()`
/// higher-order reducer.
public enum ActionFormat {
/// Prints the action in a single line by only specifying the labels of the associated values:
///
/// Action.screenA(.row(index:, action: .textChanged(query:)))
case labelsOnly
/// Prints the action in a multiline, pretty-printed format, including all the labels of
/// any associated values, as well as the data held in the associated values:
///
/// Action.screenA(
/// ScreenA.row(
/// index: 1,
/// action: RowAction.textChanged(
/// query: "Hi"
/// )
/// )
/// )
case prettyPrint
}
@available(iOS 13, *)
extension Reducer {
/// Prints debug messages describing all received actions and state mutations.
///
/// Printing is only done in debug (`#if DEBUG`) builds.
///
/// - Parameters:
/// - prefix: A string with which to prefix all debug messages.
/// - toDebugEnvironment: A function that transforms an environment into a debug environment by
/// describing a print function and a queue to print from. Defaults to a function that ignores
/// the environment and returns a default `DebugEnvironment` that uses Swift's `print`
/// function and a background queue.
/// - Returns: A reducer that prints debug messages for all received actions.
public func debug(
_ prefix: String = "",
actionFormat: ActionFormat = .prettyPrint,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
self.debug(
prefix,
state: { $0 },
action: .self,
actionFormat: actionFormat,
environment: toDebugEnvironment
)
}
/// Prints debug messages describing all received actions.
///
/// Printing is only done in debug (`#if DEBUG`) builds.
///
/// - Parameters:
/// - prefix: A string with which to prefix all debug messages.
/// - toDebugEnvironment: A function that transforms an environment into a debug environment by
/// describing a print function and a queue to print from. Defaults to a function that ignores
/// the environment and returns a default `DebugEnvironment` that uses Swift's `print`
/// function and a background queue.
/// - Returns: A reducer that prints debug messages for all received actions.
public func debugActions(
_ prefix: String = "",
actionFormat: ActionFormat = .prettyPrint,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
self.debug(
prefix,
state: { _ in () },
action: .self,
actionFormat: actionFormat,
environment: toDebugEnvironment
)
}
/// Prints debug messages describing all received local actions and local state mutations.
///
/// Printing is only done in debug (`#if DEBUG`) builds.
///
/// - Parameters:
/// - prefix: A string with which to prefix all debug messages.
/// - toLocalState: A function that filters state to be printed.
/// - toLocalAction: A case path that filters actions that are printed.
/// - toDebugEnvironment: A function that transforms an environment into a debug environment by
/// describing a print function and a queue to print from. Defaults to a function that ignores
/// the environment and returns a default `DebugEnvironment` that uses Swift's `print`
/// function and a background queue.
/// - Returns: A reducer that prints debug messages for all received actions.
public func debug<LocalState, LocalAction>(
_ prefix: String = "",
state toLocalState: @escaping (State) -> LocalState,
action toLocalAction: CasePath<Action, LocalAction>,
actionFormat: ActionFormat = .prettyPrint,
environment toDebugEnvironment: @escaping (Environment) -> DebugEnvironment = { _ in
DebugEnvironment()
}
) -> Reducer {
#if DEBUG
return .init { state, action, environment in
let previousState = toLocalState(state)
let effects = self.run(&state, action, environment)
guard let localAction = toLocalAction.extract(from: action) else { return effects }
let nextState = toLocalState(state)
let debugEnvironment = toDebugEnvironment(environment)
return .merge(
.fireAndForget {
debugEnvironment.queue.async {
let actionOutput =
actionFormat == .prettyPrint
? debugOutput(localAction).indent(by: 2)
: debugCaseOutput(localAction).indent(by: 2)
let stateOutput =
LocalState.self == Void.self
? ""
: debugDiff(previousState, nextState).map { "\($0)\n" } ?? " (No state changes)\n"
debugEnvironment.printer(
"""
\(prefix.isEmpty ? "" : "\(prefix): ")received action:
\(actionOutput)
\(stateOutput)
"""
)
}
},
effects
)
}
#else
return self
#endif
}
}
/// An environment for debug-printing reducers.
public struct DebugEnvironment {
public var printer: (String) -> Void
public var queue: DispatchQueue
public init(
printer: @escaping (String) -> Void = { print($0) },
queue: DispatchQueue
) {
self.printer = printer
self.queue = queue
}
public init(
printer: @escaping (String) -> Void = { print($0) }
) {
self.init(printer: printer, queue: _queue)
}
}
private let _queue = DispatchQueue(
label: "co.pointfree.ComposableArchitecture.DebugEnvironment",
qos: .background
)
| 35.803681 | 100 | 0.636223 |
f7b255d488708628651f757b6e94ea8a468fc7c7 | 662 | //
// ObservableService.swift
// JivoMobile
//
// Created by Stan Potemkin on 15/05/2017.
// Copyright © 2017 JivoSite. All rights reserved.
//
import Foundation
public final class BroadcastUniqueTool<VT: Equatable>: BroadcastTool<VT> {
private(set) public var cachedValue: VT?
public func broadcast(_ value: VT, tag: BroadcastToolTag? = nil, force: Bool) {
guard value != cachedValue || force else { return }
cachedValue = value
super.broadcast(value, tag: tag)
}
public override func broadcast(_ value: VT, tag: BroadcastToolTag? = nil) {
broadcast(value, tag: tag, force: false)
}
}
| 27.583333 | 83 | 0.652568 |
231f4b1d53daddaffe0ee6d95d3d9da9ef6cfd42 | 1,022 | // Copyright © 2017-2018 Trust.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
import SwiftProtobuf
public typealias SigningInput = Message
public final class AnySigner {
public static func sign<SigningOutput: Message>(input: SigningInput, coin: CoinType) -> SigningOutput {
do {
let outputData = nativeSign(data: try input.serializedData(), coin: coin)
return try SigningOutput(serializedData: outputData)
} catch let error {
fatalError(error.localizedDescription)
}
}
public static func nativeSign(data: Data, coin: CoinType) -> Data {
let inputData = TWDataCreateWithNSData(data)
defer {
TWDataDelete(inputData)
}
return TWDataNSData(TWAnySignerSign(inputData, TWCoinType(rawValue: coin.rawValue)))
}
}
| 34.066667 | 107 | 0.691781 |
9b406cc3da802a8fa81c160138d5d7d01fee12f6 | 2,974 | /*
* 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 UIKit
import Beagle
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let deepLinkHandler = DeeplinkScreenManager.shared
deepLinkHandler[.LAZY_COMPONENTS_ENDPOINT] = LazyComponentScreen.self
deepLinkHandler[.PAGE_VIEW_ENDPOINT] = PageViewScreen.self
deepLinkHandler[.TAB_VIEW_ENDPOINT] = TabViewScreen.self
deepLinkHandler[.FORM_ENDPOINT] = FormScreen.self
deepLinkHandler[.CUSTOM_COMPONENT_ENDPOINT] = CustomComponentScreen.self
deepLinkHandler[.DEEPLINK_ENDPOINT] = ScreenDeepLink.self
deepLinkHandler[.LIST_VIEW_ENDPOINT] = ListViewScreen.self
deepLinkHandler[.WEB_VIEW_ENDPOINT] = WebViewScreen.self
deepLinkHandler[.COMPONENT_INTERACTION_ENDPOINT] = ComponentInteractionText.self
let validator = ValidatorProviding()
validator[FormScreen.textValidatorName] = FormScreen.textValidator
let dependencies = BeagleDependencies()
dependencies.theme = AppTheme.theme
dependencies.urlBuilder = UrlBuilder(baseUrl: URL(string: .BASE_URL))
dependencies.navigation.defaultAnimation = .init(pushTransition: .init(type: .fade, subtype: .fromRight, duration: 0.1), modalPresentationStyle: .formSheet)
dependencies.deepLinkHandler = deepLinkHandler
dependencies.validatorProvider = validator
dependencies.analytics = AnalyticsMock()
dependencies.isLoggingEnabled = true
Beagle.dependencies = dependencies
registerCustomComponents()
let rootViewController = MainScreen().screenController()
window?.rootViewController = rootViewController
return true
}
private func registerCustomComponents() {
Beagle.registerCustomComponent("DSCollection", componentType: DSCollection.self)
Beagle.registerCustomComponent("SampleTextField", componentType: DemoTextField.self)
Beagle.registerCustomComponent("MyComponent", componentType: MyComponent.self)
Beagle.registerCustomAction("CustomConsoleLogAction", actionType: CustomConsoleLogAction.self)
}
}
| 44.38806 | 164 | 0.735709 |
4873492b0eb941fcabe27aa113a27109bf51441f | 2,547 | //
// ModelItems.swift
// StanwoodDebugger_Example
//
// Created by Tal Zion on 28/12/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
class ModelItems {
static let getImgesNetworkingItems: [NetworkExample] = [
NetworkExample(method: .get, url: "https://httpbin.org/image/jpeg"),
NetworkExample(method: .get, url: "https://httpbin.org/image/png"),
]
static let getNetworkingItems: [NetworkExample] = [
NetworkExample(method: .get, url: "https://httpbin.org/status/400"),
NetworkExample(method: .get, url: "https://httpbin.org/status/404"),
NetworkExample(method: .get, url: "https://httpbin.org/headers"),
NetworkExample(method: .get, url: "https://httpbin.org/status/410"),
NetworkExample(method: .get, url: "https://httpbin.org/status/202"),
NetworkExample(method: .get, url: "https://httpbin.org/status/500"),
NetworkExample(method: .get, url: "https://httpbin.org/status/300"),
NetworkExample(method: .get, url: "https://httpbin.org/status/100")
]
static let responseFormatItems: [NetworkExample] = [
NetworkExample(method: .get, url: "https://httpbin.org/json"),
NetworkExample(method: .get, url: "https://httpbin.org/html"),
NetworkExample(method: .get, url: "https://httpbin.org/xml"),
NetworkExample(method: .get, url: "https://httpbin.org/robots.txt"),
NetworkExample(method: .get, url: "https://httpbin.org/deny")
]
static let postNetworkingItems: [NetworkExample] = [
NetworkExample(method: .post, url: "https://httpbin.org/post")
]
static let analyticsContentItems: [AnalyticExample] = [
AnalyticExample(eventName: "content_type", screenName: nil, itemId: "09873rf", category: "articles", contentType: "website"),
AnalyticExample(eventName: "content_type", screenName: nil, itemId: "asdf987", category: "foood", contentType: nil),
AnalyticExample(eventName: "content_type", screenName: nil, itemId: "cnaiodnc", category: nil, contentType: "product"),
AnalyticExample(eventName: "content_type", screenName: nil, itemId: nil, category: nil, contentType: nil)
]
static let analyticsScreenItems: [AnalyticExample] = [
AnalyticExample(eventName: "", screenName: "home_view", itemId: nil, category: nil, contentType: nil)
]
static let crashesContentItems: [CrashExample] = [
CrashExample(type: .crash),
CrashExample(type: .signal)
]
}
| 44.684211 | 133 | 0.662348 |
288a029f2e8d1a64f15af813b2b5b3b315b5e6fa | 1,216 | import Darwin
import Foundation
import Logging
public final class SynchronousWaiter: Waiter {
public init() {}
public func waitWhile(
pollPeriod: TimeInterval = 0.3,
timeout: Timeout = .infinity,
condition: WaitCondition
) throws {
Logger.debug("Waiting for \(timeout.description), checking every \(pollPeriod) sec for up to \(timeout.value) sec")
let startTime = Date().timeIntervalSince1970
defer {
Logger.debug("Finished waiting for \(timeout.description), took \(Date().timeIntervalSince1970 - startTime) sec")
}
while try condition() {
let currentTime = Date().timeIntervalSince1970
if currentTime - startTime > timeout.value {
throw TimeoutError.waitTimeout(timeout)
}
if !RunLoop.current.run(mode: RunLoop.Mode.default, before: Date().addingTimeInterval(pollPeriod)) {
let passedPollPeriod = Date().timeIntervalSince1970 - currentTime
if passedPollPeriod < pollPeriod {
Thread.sleep(forTimeInterval: pollPeriod - passedPollPeriod)
}
}
}
}
}
| 35.764706 | 125 | 0.60773 |
0a4932a7813d57b77522b5bb4d512463c8f150eb | 930 | //
// OrderPizzaSDKTests.swift
// OrderPizzaSDKTests
//
// Created by Sunil Chauhan on 04/10/18.
// Copyright © 2018 Sunil Chauhan. All rights reserved.
//
import XCTest
@testable import OrderPizzaSDK
class OrderPizzaSDKTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.571429 | 111 | 0.663441 |
f754b3a44285f4bd97f37c6aca32d73ed3a569ae | 10,607 | /* file: texture_style_tessellation_specification.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: -ENTITY DEFINITION in EXPRESS
/*
ENTITY texture_style_tessellation_specification
ABSTRACT SUPERTYPE
SUBTYPE OF ( texture_style_specification );
END_ENTITY; -- texture_style_tessellation_specification (line:32263 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
//MARK: - ALL DEFINED ATTRIBUTES
/*
SUPER- ENTITY(1) founded_item
ATTR: users, TYPE: SET [0 : ?] OF founded_item_select -- DERIVED
:= using_items( SELF, [] )
SUPER- ENTITY(2) texture_style_specification
(no local attributes)
ENTITY(SELF) texture_style_tessellation_specification
(no local attributes)
SUB- ENTITY(4) single_texture_style_tessellation_specification
ATTR: texture_image, TYPE: label -- EXPLICIT
ATTR: texture_coordinates, TYPE: LIST [1 : ?] OF LIST [2 : 2] OF non_negative_real -- EXPLICIT
ATTR: texture_format, TYPE: texture_file_type -- EXPLICIT
ATTR: repeating_pattern, TYPE: BOOLEAN -- EXPLICIT
*/
//MARK: - Partial Entity
public final class _texture_style_tessellation_specification : SDAI.PartialEntity {
public override class var entityReferenceType: SDAI.EntityReference.Type {
eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.self
}
//ATTRIBUTES
// (no local attributes)
public override var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
//SELECT data types (indirectly) referencing the current type as a member of the select list
members.insert(SDAI.STRING(sPRESENTATION_STYLE_SELECT.typeName)) // -> Self
return members
}
//VALUE COMPARISON SUPPORT
public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) {
super.hashAsValue(into: &hasher, visited: &complexEntities)
}
public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool {
guard let rhs = rhs as? Self else { return false }
if !super.isValueEqual(to: rhs, visited: &comppairs) { return false }
return true
}
public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? {
guard let rhs = rhs as? Self else { return false }
var result: Bool? = true
if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) {
if !comp { return false }
}
else { result = nil }
return result
}
//EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR
public init() {
super.init(asAbstructSuperclass:())
}
//p21 PARTIAL ENTITY CONSTRUCTOR
public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) {
let numParams = 0
guard parameters.count == numParams
else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil }
self.init( )
}
}
//MARK: - Entity Reference
/** ENTITY reference
- EXPRESS:
```express
ENTITY texture_style_tessellation_specification
ABSTRACT SUPERTYPE
SUBTYPE OF ( texture_style_specification );
END_ENTITY; -- texture_style_tessellation_specification (line:32263 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public final class eTEXTURE_STYLE_TESSELLATION_SPECIFICATION : SDAI.EntityReference {
//MARK: PARTIAL ENTITY
public override class var partialEntityType: SDAI.PartialEntity.Type {
_texture_style_tessellation_specification.self
}
public let partialEntity: _texture_style_tessellation_specification
//MARK: SUPERTYPES
public let super_eFOUNDED_ITEM: eFOUNDED_ITEM // [1]
public let super_eTEXTURE_STYLE_SPECIFICATION: eTEXTURE_STYLE_SPECIFICATION // [2]
public var super_eTEXTURE_STYLE_TESSELLATION_SPECIFICATION: eTEXTURE_STYLE_TESSELLATION_SPECIFICATION { return self } // [3]
//MARK: SUBTYPES
public var sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION: eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION? { // [4]
return self.complexEntity.entityReference(eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION.self)
}
//MARK: ATTRIBUTES
/// __EXPLICIT__ attribute
/// - origin: SUB( ``eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION`` )
public var TEXTURE_COORDINATES: (SDAI.LIST<SDAI.LIST<tNON_NEGATIVE_REAL>/*[2:2]*/ >/*[1:nil]*/ )? {
get {
return sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.partialEntity._texture_coordinates
}
set(newValue) {
guard let partial = sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.super_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION
.partialEntity else { return }
partial._texture_coordinates = SDAI.UNWRAP(newValue)
}
}
/// __DERIVE__ attribute
/// - origin: SUPER( ``eFOUNDED_ITEM`` )
public var USERS: (SDAI.SET<sFOUNDED_ITEM_SELECT>/*[0:nil]*/ )? {
get {
if let cached = cachedValue(derivedAttributeName:"USERS") {
return cached.value as! (SDAI.SET<sFOUNDED_ITEM_SELECT>/*[0:nil]*/ )?
}
let origin = super_eFOUNDED_ITEM
let value = SDAI.SET<sFOUNDED_ITEM_SELECT>(origin.partialEntity._users__getter(SELF: origin))
updateCache(derivedAttributeName:"USERS", value:value)
return value
}
}
/// __EXPLICIT__ attribute
/// - origin: SUB( ``eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION`` )
public var TEXTURE_FORMAT: nTEXTURE_FILE_TYPE? {
get {
return sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.partialEntity._texture_format
}
set(newValue) {
guard let partial = sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.super_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION
.partialEntity else { return }
partial._texture_format = SDAI.UNWRAP(newValue)
}
}
/// __EXPLICIT__ attribute
/// - origin: SUB( ``eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION`` )
public var REPEATING_PATTERN: SDAI.BOOLEAN? {
get {
return sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.partialEntity._repeating_pattern
}
set(newValue) {
guard let partial = sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.super_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION
.partialEntity else { return }
partial._repeating_pattern = SDAI.UNWRAP(newValue)
}
}
/// __EXPLICIT__ attribute
/// - origin: SUB( ``eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION`` )
public var TEXTURE_IMAGE: tLABEL? {
get {
return sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.partialEntity._texture_image
}
set(newValue) {
guard let partial = sub_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION?.super_eSINGLE_TEXTURE_STYLE_TESSELLATION_SPECIFICATION
.partialEntity else { return }
partial._texture_image = SDAI.UNWRAP(newValue)
}
}
//MARK: INITIALIZERS
public convenience init?(_ entityRef: SDAI.EntityReference?) {
let complex = entityRef?.complexEntity
self.init(complex: complex)
}
public required init?(complex complexEntity: SDAI.ComplexEntity?) {
guard let partial = complexEntity?.partialEntityInstance(_texture_style_tessellation_specification.self) else { return nil }
self.partialEntity = partial
guard let super1 = complexEntity?.entityReference(eFOUNDED_ITEM.self) else { return nil }
self.super_eFOUNDED_ITEM = super1
guard let super2 = complexEntity?.entityReference(eTEXTURE_STYLE_SPECIFICATION.self) else { return nil }
self.super_eTEXTURE_STYLE_SPECIFICATION = super2
super.init(complex: complexEntity)
}
public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let entityRef = generic?.entityReference else { return nil }
self.init(complex: entityRef.complexEntity)
}
public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) }
public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) }
//MARK: DICTIONARY DEFINITION
public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition }
private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition()
private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition {
let entityDef = SDAIDictionarySchema.EntityDefinition(name: "TEXTURE_STYLE_TESSELLATION_SPECIFICATION", type: self, explicitAttributeCount: 0)
//MARK: SUPERTYPE REGISTRATIONS
entityDef.add(supertype: eFOUNDED_ITEM.self)
entityDef.add(supertype: eTEXTURE_STYLE_SPECIFICATION.self)
entityDef.add(supertype: eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.self)
//MARK: ATTRIBUTE REGISTRATIONS
entityDef.addAttribute(name: "TEXTURE_COORDINATES", keyPath: \eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.TEXTURE_COORDINATES,
kind: .explicit, source: .subEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "USERS", keyPath: \eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.USERS,
kind: .derived, source: .superEntity, mayYieldEntityReference: true)
entityDef.addAttribute(name: "TEXTURE_FORMAT", keyPath: \eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.TEXTURE_FORMAT,
kind: .explicit, source: .subEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "REPEATING_PATTERN", keyPath: \eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.REPEATING_PATTERN,
kind: .explicit, source: .subEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "TEXTURE_IMAGE", keyPath: \eTEXTURE_STYLE_TESSELLATION_SPECIFICATION.TEXTURE_IMAGE,
kind: .explicit, source: .subEntity, mayYieldEntityReference: false)
return entityDef
}
}
}
| 40.17803 | 185 | 0.734703 |
e0e0a8d845197d9e81919293e0ca112733452fbe | 1,189 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** Age information about a face. */
public struct FaceAge: Decodable {
/// Estimated minimum age.
public var min: Int?
/// Estimated maximum age.
public var max: Int?
/// Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the property.
public var score: Double?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case min = "min"
case max = "max"
case score = "score"
}
}
| 30.487179 | 133 | 0.699748 |
8f268365c6f234ecd581405533db2cc445e9d858 | 5,867 | //
// SocialNetwork.swift
// Shall-we-eat
//
// Created by Halyna on 30/12/2020.
//
import SwiftUI
import AVKit
struct SocialNetworkView: View {
@State private var changeView: Bool = false
@State private var videos = Post.DataVideo
// @State private var login = Author.AllAcount
var body: some View {
NavigationView {
ZStack() {
PlayerScrollView(DataVideo: $videos)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 25){
Button (action:{
self.changeView = true
}) {
}
NavigationLink(
destination: SocialNetwork1(),
isActive: self.$changeView,
label: {
Image("onion")
.resizable()
.frame(width: 60, height: 60)
.clipShape(Circle())
})
Button(action:{
}) {
Image(systemName: "suit.heart")
.font(.largeTitle)
.foregroundColor(.white)
}
Button(action:{
}) {
Image(systemName: "message")
.font(.title)
.foregroundColor(.white)
}
Button(action:{
}) {
Image(systemName: "arrowshape.turn.up.right")
.font(.largeTitle)
.foregroundColor(.white)
}
Button(action:{
}) {
Image(systemName: "newspaper")
.font(.largeTitle)
.foregroundColor(.white)
}
}.padding(.bottom, 50)
.padding(.trailing)
.position(x: 360.0, y: 150.0)
}.navigationBarHidden(true)
}
}
}
struct PlayerView: View {
@Binding var DataVideo: [Post]
var body: some View {
VStack (spacing: 0){
ForEach(self.DataVideo){i in
Player(videoURL: i.video)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)//full screensize
.offset(y: -5)
}
}
.onAppear{
}
}
}
struct Player: UIViewControllerRepresentable {
let videoURL: URL
let player: AVPlayer
init(videoURL: URL) {
self.videoURL = videoURL
self.player = AVPlayer(url: videoURL)
}
func makeUIViewController(context: Context) -> AVPlayerViewController{
let view = AVPlayerViewController()
view.player = player
view.showsPlaybackControls = false
view.videoGravity = .resizeAspectFill
return view
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
}
struct PlayerScrollView: UIViewRepresentable {
func makeCoordinator() -> Coordinator {
return PlayerScrollView.Coordinator(parent1: self)
}
@Binding var DataVideo: [Post]
func makeUIView(context: Context) -> UIScrollView {
let view = UIScrollView()
let childView = UIHostingController(rootView: PlayerView(DataVideo: self.$DataVideo))
childView.view.frame = CGRect(x: 0, y: 0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * CGFloat((DataVideo.count)))//full screen
view.contentSize = CGSize(width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * CGFloat((DataVideo.count)))
view.addSubview(childView.view)
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.contentInsetAdjustmentBehavior = .never
view.isPagingEnabled = true
view.delegate = context.coordinator
return view
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
uiView.contentSize = CGSize(width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * CGFloat((DataVideo.count)))
for i in 0..<uiView.subviews.count{
uiView.subviews[i].frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * CGFloat((DataVideo.count)))
}
}
class Coordinator : NSObject,UIScrollViewDelegate{
var parent: PlayerScrollView
var index = 0
init(parent1: PlayerScrollView){
parent = parent1
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currnerindex = Int(scrollView.contentOffset.y / UIScreen.main.bounds.height)
/*
if index != currnerindex{
index = currnerindex
for i in 0..<parent.DataVideo.count{
parent.DataVideo[i].player.seek(to: .zero)//pause for all video
parent.DataVideo[i].player.pause()
}
parent.DataVideo[index].player.play() //play next video
}
*/
}
}
}
struct SocialNetwork_Previews: PreviewProvider {
static var previews: some View {
SocialNetworkView()
}
}
| 32.236264 | 162 | 0.49412 |
f96bc083ec7eaec7b39517b505d63d7823f15b58 | 27,347 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
class MXThreadingServiceTests: XCTestCase {
private var testData: MatrixSDKTestsData!
override func setUp() {
testData = MatrixSDKTestsData()
}
override func tearDown() {
testData = nil
}
/// Test: Expect the threading service is initialized after creating a session
/// - Create a Bob session
/// - Expect threading service is initialized
func testInitialization() {
testData.doMXSessionTest(withBob: self) { bobSession, expectation in
guard let bobSession = bobSession,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
XCTAssertNotNil(bobSession.threadingService, "Threading service must be created")
expectation.fulfill()
}
}
/// Test: Expect a thread is created after sending an event to a thread
/// - Create a Bob session
/// - Create an initial room
/// - Send a text message A to be used as thread root event
/// - Send a threaded event B referencing the root event A
/// - Expect a thread created with identifier A
/// - Expect thread's last message is B
/// - Expect thread has the root event
/// - Expect thread's number of replies is 1
func testStartingThread() {
let store = MXMemoryStore()
testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
guard let bobSession = bobSession,
let initialRoom = initialRoom,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
let threadingService = bobSession.threadingService
var localEcho: MXEvent?
initialRoom.sendTextMessage("Root message", localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message", threadId: threadId, localEcho: &localEcho) { response2 in
switch response2 {
case .success(let eventId):
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
guard let thread = threadingService.thread(withId: threadId) else {
XCTFail("Thread must be created")
expectation.fulfill()
return
}
XCTAssertEqual(thread.id, threadId, "Thread must have the correct id")
XCTAssertEqual(thread.roomId, initialRoom.roomId, "Thread must have the correct room id")
XCTAssertEqual(thread.lastMessage?.eventId, eventId, "Thread last message must have the correct event id")
XCTAssertNotNil(thread.rootMessage, "Thread must have the root event")
XCTAssertEqual(thread.numberOfReplies, 1, "Thread must have only 1 reply")
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
}
/// Test: Expect a thread is updated after sending multiple events to the thread
/// - Create a Bob session
/// - Create an initial room
/// - Send a text message A to be used as thread root event
/// - Send a threaded event B referencing the root event A
/// - Expect a thread created with identifier A
/// - Send threaded events [C, D] referencing the root event A
/// - Wait for a sync, for events to be processed by the threading service
/// - Expect thread's last message is D
/// - Expect thread has the root event
/// - Expect thread's number of replies is 3 (replies should be B, C, D)
func testUpdatingThread() {
let store = MXMemoryStore()
testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
guard let bobSession = bobSession,
let initialRoom = initialRoom,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
let threadingService = bobSession.threadingService
var localEcho: MXEvent?
initialRoom.sendTextMessage("Root message", localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message 1",
threadId: threadId,
localEcho: &localEcho) { response2 in
switch response2 {
case .success:
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
guard let thread = threadingService.thread(withId: threadId) else {
XCTFail("Thread must be created")
expectation.fulfill()
return
}
initialRoom.sendTextMessages(messages: ["Thread message 2", "Thread message 3"],
threadId: threadId) { response3 in
switch response3 {
case .success(let eventIds):
var syncObserver: NSObjectProtocol?
syncObserver = NotificationCenter.default.addObserver(forName: .mxSessionDidSync,
object: nil,
queue: .main) { notification in
if let syncObserver = syncObserver {
NotificationCenter.default.removeObserver(syncObserver)
}
XCTAssertEqual(thread.id, threadId, "Thread must have the correct id")
XCTAssertEqual(thread.roomId, initialRoom.roomId, "Thread must have the correct room id")
XCTAssertEqual(thread.lastMessage?.eventId, eventIds.last, "Thread last message must have the correct event id")
XCTAssertNotNil(thread.rootMessage, "Thread must have the root event")
XCTAssertEqual(thread.numberOfReplies, 3, "Thread must have 3 replies")
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
}
/// Test: Expect a reply to an event in a thread is also in the same thread
/// - Create a Bob session
/// - Create an initial room
/// - Send a text message A to be used as thread root event
/// - Send a threaded event B referencing the root event A
/// - Expect a thread created with identifier A
/// - Send a reply to event B
/// - Wait for a sync for the reply to be processed
/// - Expect the reply event is also in the thread A
func testReplyingInThread() {
let store = MXMemoryStore()
testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
guard let bobSession = bobSession,
let initialRoom = initialRoom,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
let threadingService = bobSession.threadingService
var localEcho: MXEvent?
initialRoom.sendTextMessage("Root message", localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message", threadId: threadId, localEcho: &localEcho) { response2 in
switch response2 {
case .success(let lastEventId):
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
guard let thread = threadingService.thread(withId: threadId),
let lastMessage = thread.lastMessage else {
XCTFail("Thread must be created with a last message")
expectation.fulfill()
return
}
initialRoom.sendReply(to: lastMessage, textMessage: "Reply message", formattedTextMessage: nil, stringLocalizer: nil, localEcho: &localEcho) { response3 in
switch response3 {
case .success(let replyEventId):
var syncObserver: NSObjectProtocol?
syncObserver = NotificationCenter.default.addObserver(forName: .mxSessionDidSync,
object: nil,
queue: .main) { notification in
if let syncObserver = syncObserver {
NotificationCenter.default.removeObserver(syncObserver)
}
guard let replyEvent = store.event(withEventId: replyEventId!, inRoom: thread.roomId) else {
XCTFail("Reply event must be found in the store")
expectation.fulfill()
return
}
XCTAssertEqual(replyEvent.threadId, threadId, "Reply must also be in the thread")
guard let relatesTo = replyEvent.content[kMXEventRelationRelatesToKey] as? [String: Any],
let inReplyTo = relatesTo["m.in_reply_to"] as? [String: String] else {
XCTFail("Reply event must have a reply-to dictionary in the content")
expectation.fulfill()
return
}
XCTAssertEqual(inReplyTo["event_id"], lastEventId, "Reply must point to the last message event")
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
}
/// Test: Expect a thread is listed in the thread list after sending an event to a thread
/// - Create a Bob session
/// - Create an initial room
/// - Send a text message A to be used as thread root event
/// - Send a threaded event B referencing the root event A
/// - Expect a thread created with identifier A
/// - Expect thread's last message is B
/// - Expect thread has the root event
/// - Expect thread's number of replies is 1
func testThreadListSingleItem() {
let store = MXMemoryStore()
testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
guard let bobSession = bobSession,
let initialRoom = initialRoom,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
let threadingService = bobSession.threadingService
var localEcho: MXEvent?
initialRoom.sendTextMessage("Root message",
threadId: nil,
localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message", threadId: threadId, localEcho: &localEcho) { response2 in
switch response2 {
case .success(let eventId):
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
guard let thread = threadingService.threads(inRoom: initialRoom.roomId).first else {
XCTFail("Thread must be created")
expectation.fulfill()
return
}
XCTAssertEqual(thread.id, threadId, "Thread must have the correctid")
XCTAssertEqual(thread.roomId, initialRoom.roomId, "Thread must have the correct room id")
XCTAssertEqual(thread.lastMessage?.eventId, eventId, "Thread last message must have the correct event id")
XCTAssertNotNil(thread.rootMessage, "Thread must have the root event")
XCTAssertEqual(thread.numberOfReplies, 1, "Thread must have only 1 reply")
XCTAssertTrue(thread.isParticipated, "Thread must be participated")
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
}
/// Test: Expect a thread list has a correct sorting
/// - Create a Bob session
/// - Create an initial room
/// - Send a text message A to be used as thread root event
/// - Send a threaded event B referencing the root event A
/// - Expect a thread created with identifier A
/// - Send a text message C to be used as thread root event
/// - Send a threaded event D referencing the root event C
/// - Expect a thread created with identifier C
/// - Fetch all threads in the room
/// - Expect thread C is first thread
/// - Expect thread A is the last thread
/// - Fetch participated threads in the room
/// - Expect thread C is first thread
/// - Expect thread A is the last thread
func testThreadListSortingAndFiltering() {
let store = MXMemoryStore()
testData.doMXSessionTest(withBobAndARoom: self, andStore: store) { bobSession, initialRoom, expectation in
guard let bobSession = bobSession,
let initialRoom = initialRoom,
let expectation = expectation else {
XCTFail("Failed to setup test conditions")
return
}
let threadingService = bobSession.threadingService
var localEcho: MXEvent?
initialRoom.sendTextMessage("Root message 1",
threadId: nil,
localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId1 = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message 1", threadId: threadId1, localEcho: &localEcho) { response2 in
switch response2 {
case .success:
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
initialRoom.sendTextMessage("Root message 2",
threadId: nil,
localEcho: &localEcho) { response in
switch response {
case .success(let eventId):
guard let threadId2 = eventId else {
XCTFail("Failed to setup test conditions")
expectation.fulfill()
return
}
initialRoom.sendTextMessage("Thread message 2", threadId: threadId2, localEcho: &localEcho) { response2 in
switch response2 {
case .success:
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: MXThreadingService.newThreadCreated,
object: nil,
queue: .main) { notification in
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
let threads = threadingService.threads(inRoom: initialRoom.roomId)
XCTAssertEqual(threads.count, 2, "Must have 2 threads")
XCTAssertEqual(threads.first?.id, threadId2, "Latest thread must be in the first position")
XCTAssertEqual(threads.last?.id, threadId1, "Older thread must be in the last position")
let participatedThreads = threadingService.participatedThreads(inRoom: initialRoom.roomId)
XCTAssertEqual(participatedThreads.count, 2, "Must have 2 participated threads")
XCTAssertEqual(participatedThreads.first?.id, threadId2, "Latest thread must be in the first position")
XCTAssertEqual(participatedThreads.last?.id, threadId1, "Older thread must be in the last position")
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
expectation.fulfill()
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
case .failure(let error):
XCTFail("Failed to setup test conditions: \(error)")
expectation.fulfill()
}
}
}
}
}
| 56.736515 | 187 | 0.438878 |
29c6ad119bfe882ba77571f2daaa22fc96453806 | 3,442 | import Foundation
extension FileManager {
/// The user's document directory.
var documentsDirectory: URL {
let url = self.urls(for: .documentDirectory, in: .userDomainMask).first
precondition(url != nil, "Could not find the user's directory.")
return url!
}
/// The user's `Documents/Inbox` directory.
var inboxDirectory: URL {
documentsDirectory.appendingPathComponent("Inbox", isDirectory: true)
}
/// Removes all items in the user's temporary and `Documents/Inbox` directory.
///
/// The system typically places files in the inbox directory when opening external files in the
/// app.
func clearTemporaryDirectories() throws {
try clear(contentsOf: temporaryDirectory)
try clear(contentsOf: inboxDirectory)
}
/// Deletes all items in the directory.
func clear(contentsOf directory: URL) throws {
do {
try contentsOfDirectory(at: directory, includingPropertiesForKeys: [])
.forEach(removeItem)
}
}
/// Moves or copies the source file to a temporary directory (controlled by the application).
///
/// If the file is copied, optionally deletes the source file (including when the copy operation
/// fails). Throws an error if any operation fails, including deletion of the source file.
func importFile(at source: URL, asCopy: Bool, deletingSource: Bool) throws -> URL {
let temporaryURL = try createUniqueTemporaryDirectory()
.appendingPathComponent(source.lastPathComponent)
let deleteIfNeeded = {
guard asCopy, deletingSource else { return }
try self.removeItem(at: source)
}
do {
if asCopy {
try copyItem(at: source, to: temporaryURL)
} else {
try moveItem(at: source, to: temporaryURL)
}
} catch {
try deleteIfNeeded()
throw error
}
try deleteIfNeeded()
return temporaryURL
}
}
// MARK: - Creating Temporary Directories
extension FileManager {
/// See `createUniqueDirectory(in:preferredName)`.
func createUniqueTemporaryDirectory() throws -> URL {
try createUniqueDirectory()
}
/// Creates a unique directory, in a temporary or other directory.
///
/// - Parameters:
/// - directory: The containing directory in which to create the unique directory. If nil,
/// uses the user's temporary directory.
/// - preferredName: The base name for the directory. If the name is not unique, appends
/// indexes starting with 1. Uses a UUID by default.
///
/// - Returns: The URL of the created directory.
func createUniqueDirectory(
in directory: URL? = nil,
preferredName: String = UUID().uuidString
) throws -> URL {
let directory = directory ?? temporaryDirectory
var i = 0
while true {
do {
let name = (i == 0) ? preferredName : "\(preferredName)-\(i)"
let subdirectory = directory.appendingPathComponent(name, isDirectory: true)
try createDirectory(at: subdirectory, withIntermediateDirectories: false)
return subdirectory
} catch CocoaError.fileWriteFileExists {
i += 1
}
}
}
}
| 33.745098 | 100 | 0.611563 |
28f385ffec8a6fea30c48b02e246ce70ceaaf0f4 | 2,946 | //
// ImageLoader.swift
// MyGithubUserSearch
//
// Created by Jinwoo Kim on 2020/03/03.
// Copyright © 2020 jinuman. All rights reserved.
//
import Nuke
import RxSwift
class ImageLoader: ReactiveCompatible {
typealias Completion = (Result<UIImage, Error>) -> Void
static let shared = ImageLoader()
private init() {}
// MARK: - Methods
func loadImage(with url: URL?, completion: @escaping Completion) {
guard let url = url else { return }
self.loadImage(url: url, completion: completion)
}
func loadImage(with urlString: String?, completion: @escaping Completion) {
guard let urlString = urlString else { return }
self.loadImage(with: urlString, completion: completion)
}
private func loadImage(url: URL, completion: @escaping Completion) {
ImagePipeline.shared.loadImage(with: url) { result in
switch result {
case let .success(response):
completion(.success(response.image))
case let .failure(error):
completion(.failure(error))
}
}
}
}
// MARK: - Extensions
extension Reactive where Base: ImageLoader {
func loadImage(urlString: String?) -> Observable<UIImage?> {
return Observable<UIImage?>.create { observer in
self.base.loadImage(with: urlString) { result in
switch result {
case let .success(image):
observer.onNext(image)
case let .failure(error):
observer.onError(error)
}
}
return Disposables.create()
}
}
}
extension UIImageView {
func setImage(
with urlString: String?,
placeholder: UIImage? = nil)
{
if let urlString = urlString {
ImageLoader.shared.loadImage(with: urlString) { result in
switch result {
case let .success(image):
self.image = image
case let .failure(error):
logger.debugPrint(error, level: .error)
self.image = placeholder
}
}
} else {
self.image = placeholder
}
}
func setImage(
with url: URL?,
placeholder: UIImage? = nil)
{
if let url = url {
ImageLoader.shared.loadImage(with: url) { result in
switch result {
case let .success(image):
self.image = image
case let .failure(error):
logger.debugPrint(error, level: .error)
self.image = placeholder
}
}
} else {
self.image = placeholder
}
}
}
| 26.070796 | 79 | 0.510183 |
916514fb1fc264c882451538646dab82642034fc | 16,491 | // Copyright 2021 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 AndroidAutoCoreBluetoothProtocols
import AndroidAutoCoreBluetoothProtocolsMocks
import CoreBluetooth
import XCTest
import AndroidAutoCompanionProtos
@testable import AndroidAutoMessageStream
private typealias VersionExchange = Com_Google_Companionprotos_VersionExchange
/// Unit tests for `BLEVersionResolverImpl`.
@available(iOS 10.0, *)
class BLEVersionResolverImplTest: XCTestCase {
private var bleVersionResolver: BLEVersionResolverImpl!
// The read and write characteristics. The actual UUIDs of these characteristics do not matter.
private let readCharacteristic = CharacteristicMock(uuid: CBUUID(string: "bad1"), value: nil)
private let writeCharacteristic = CharacteristicMock(uuid: CBUUID(string: "bad2"), value: nil)
private let peripheralMock = PeripheralMock(name: "mock", services: nil)
private let delegateMock = BLEVersionResolverDelegateMock()
override func setUp() {
super.setUp()
continueAfterFailure = false
readCharacteristic.value = nil
writeCharacteristic.value = nil
delegateMock.reset()
peripheralMock.reset()
bleVersionResolver = BLEVersionResolverImpl()
bleVersionResolver.delegate = delegateMock
}
// MARK: - Peripheral set up tests.
func testResolveVersion_correctlySetsNotifyOnReadCharacteristic() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
XCTAssertTrue(peripheralMock.notifyEnabled)
XCTAssertTrue(peripheralMock.notifyValueCalled)
XCTAssert(peripheralMock.characteristicToNotifyFor === readCharacteristic)
}
func testResolveVersion_correctlySetsPeripheralDelegate() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
XCTAssert(peripheralMock.delegate === bleVersionResolver)
}
// MARK: - Created proto validation test
func testVersionResolver_createsCorrectVersionProto() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// Assert proto has been written to the peripheral.
XCTAssertEqual(peripheralMock.writtenData.count, 1)
// Now assert the version information.
let versionProto = try! VersionExchange(
serializedData: peripheralMock.writtenData[0])
XCTAssertEqual(versionProto.maxSupportedMessagingVersion, 3)
XCTAssertEqual(versionProto.minSupportedMessagingVersion, 2)
XCTAssertEqual(versionProto.maxSupportedSecurityVersion, 4)
XCTAssertEqual(versionProto.minSupportedSecurityVersion, 1)
}
// MARK: - Valid version resolution tests.
func testResolveVersion_correctlyResolvesVersionWithSameMaxMin() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// A version exchange proto whose messaging and security versions have the same max and min.
let versionExchangeProto = makeVersionExchangeProto(messagingVersion: 2, securityVersion: 1)
notify(from: peripheralMock, withValue: versionExchangeProto)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(false))
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v1)
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesStreamVersionToTwo() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 3,
minSupportedMessagingVersion: 2,
maxSupportedSecurityVersion: 1,
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(true))
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v1)
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesSecurityVersionToTwo() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 2,
minSupportedMessagingVersion: 2,
maxSupportedSecurityVersion: 2,
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v2)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(false))
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesSecurityVersionToThree() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 2,
minSupportedMessagingVersion: 2,
maxSupportedSecurityVersion: 3,
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v3)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(false))
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesWithCapabilitiesExchange() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: true
)
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 2,
minSupportedMessagingVersion: 2,
maxSupportedSecurityVersion: 3, // Only version 3 exchanges capabilities.
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
// Any response from the peripheral for capabilities response will do as payload is ignored.
notify(from: peripheralMock, withValue: Data())
// Version + capabilities responses.
XCTAssertEqual(peripheralMock.writtenData.count, 2)
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v3)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(false))
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesSecurityVersionToFour() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: true
)
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 2,
minSupportedMessagingVersion: 2,
maxSupportedSecurityVersion: 4,
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v4)
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(false))
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
func testResolveVersion_correctlyResolvesIfMinimumVersionMatches() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
let maxVersion: Int32 = 10
let securityVersion: Int32 = 1
// A version exchange proto that has a range, but its minimum version is the correct one.
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: maxVersion,
minSupportedMessagingVersion: securityVersion,
maxSupportedSecurityVersion: maxVersion,
minSupportedSecurityVersion: securityVersion
)
notify(from: peripheralMock, withValue: versionExchangeProto)
// Should now take the highest available version
XCTAssertEqual(delegateMock.resolvedStreamVersion, .v2(true))
XCTAssertEqual(delegateMock.resolvedSecurityVersion, .v4)
XCTAssert(delegateMock.resolvedPeripheral === peripheralMock)
XCTAssertNil(delegateMock.encounteredError)
}
// MARK: - Invalid version resolution test.
func testResolveVersion_MessageStreamVersionNotSupported() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// A version exchange proto that does not support message stream version 1 or 2.
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 20,
minSupportedMessagingVersion: 10,
maxSupportedSecurityVersion: 4,
minSupportedSecurityVersion: 1
)
notify(from: peripheralMock, withValue: versionExchangeProto)
// Delegate should be notified of error.
XCTAssertEqual(delegateMock.encounteredError, .versionNotSupported)
XCTAssertNil(delegateMock.resolvedStreamVersion)
XCTAssertNil(delegateMock.resolvedSecurityVersion)
XCTAssertNil(delegateMock.resolvedPeripheral)
}
func testResolveVersion_SecurityVersionNotSupported() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// A version exchange proto that does not support security version between 1 and 4.
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: 2,
minSupportedMessagingVersion: 1,
maxSupportedSecurityVersion: 20,
minSupportedSecurityVersion: 10
)
notify(from: peripheralMock, withValue: versionExchangeProto)
// Delegate should be notified of error.
XCTAssertEqual(delegateMock.encounteredError, .versionNotSupported)
XCTAssertNil(delegateMock.resolvedStreamVersion)
XCTAssertNil(delegateMock.resolvedSecurityVersion)
XCTAssertNil(delegateMock.resolvedPeripheral)
}
func testResolveVersion_invalidIfNoSupportedVersionPresent() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// A version exchange proto that does not support version 1 or 2.
let maxVersion: Int32 = 20
let minVersion: Int32 = 10
let versionExchangeProto = makeVersionExchangeProto(
maxSupportedMessagingVersion: maxVersion,
minSupportedMessagingVersion: minVersion,
maxSupportedSecurityVersion: maxVersion,
minSupportedSecurityVersion: minVersion
)
notify(from: peripheralMock, withValue: versionExchangeProto)
// Delegate should be notified of error.
XCTAssertEqual(delegateMock.encounteredError, .versionNotSupported)
XCTAssertNil(delegateMock.resolvedStreamVersion)
XCTAssertNil(delegateMock.resolvedSecurityVersion)
XCTAssertNil(delegateMock.resolvedPeripheral)
}
// MARK: - Peripheral error tests.
func testUpdateError_correctlyNotifiesDelegate() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// Error when updating a value on a characteristic.
bleVersionResolver.peripheral(
peripheralMock,
didUpdateValueFor: readCharacteristic,
error: makeFakeError()
)
XCTAssertEqual(delegateMock.encounteredError, .failedToRead)
XCTAssertNil(delegateMock.resolvedStreamVersion)
XCTAssertNil(delegateMock.resolvedSecurityVersion)
XCTAssertNil(delegateMock.resolvedPeripheral)
}
func testEmptyResponse_correctlyNotifiesDelegate() {
bleVersionResolver.resolveVersion(
with: peripheralMock,
readCharacteristic: readCharacteristic,
writeCharacteristic: writeCharacteristic,
allowsCapabilitiesExchange: false
)
// Empty response for the read characteristic.
readCharacteristic.value = nil
bleVersionResolver.peripheral(
peripheralMock,
didUpdateValueFor: readCharacteristic,
error: nil
)
XCTAssertEqual(delegateMock.encounteredError, .emptyResponse)
XCTAssertNil(delegateMock.resolvedStreamVersion)
XCTAssertNil(delegateMock.resolvedSecurityVersion)
XCTAssertNil(delegateMock.resolvedPeripheral)
}
// MARK: - Convenience functions.
private func makeFakeError() -> Error {
return NSError(domain: "", code: 0, userInfo: nil)
}
private func notify(from peripheral: BLEPeripheral, withValue value: Data) {
readCharacteristic.value = value
bleVersionResolver.peripheral(peripheral, didUpdateValueFor: readCharacteristic, error: nil)
}
/// Makes a version exchange proto whose max and minimum versions are the same as the ones given.
private func makeVersionExchangeProto(messagingVersion: Int32, securityVersion: Int32) -> Data {
return makeVersionExchangeProto(
maxSupportedMessagingVersion: messagingVersion,
minSupportedMessagingVersion: messagingVersion,
maxSupportedSecurityVersion: securityVersion,
minSupportedSecurityVersion: securityVersion
)
}
private func makeVersionExchangeProto(
maxSupportedMessagingVersion: Int32,
minSupportedMessagingVersion: Int32,
maxSupportedSecurityVersion: Int32,
minSupportedSecurityVersion: Int32
) -> Data {
var versionExchange = VersionExchange()
versionExchange.maxSupportedMessagingVersion = maxSupportedMessagingVersion
versionExchange.minSupportedMessagingVersion = minSupportedMessagingVersion
versionExchange.maxSupportedSecurityVersion = maxSupportedSecurityVersion
versionExchange.minSupportedSecurityVersion = minSupportedSecurityVersion
return try! versionExchange.serializedData()
}
}
// MARK: - BLEVersionResolverDelegateMock
private class BLEVersionResolverDelegateMock: BLEVersionResolverDelegate {
var resolvedStreamVersion: MessageStreamVersion?
var resolvedSecurityVersion: MessageSecurityVersion?
var resolvedPeripheral: BLEPeripheral?
var encounteredError: BLEVersionResolverError?
func bleVersionResolver(
_ bleVersionResolver: BLEVersionResolver,
didResolveStreamVersionTo streamVersion: MessageStreamVersion,
securityVersionTo securityVersion: MessageSecurityVersion,
for peripheral: BLEPeripheral
) {
resolvedStreamVersion = streamVersion
resolvedSecurityVersion = securityVersion
resolvedPeripheral = peripheral
}
func bleVersionResolver(
_ bleVersionResolver: BLEVersionResolver,
didEncounterError error: BLEVersionResolverError,
for peripheral: BLEPeripheral
) {
encounteredError = error
}
func reset() {
resolvedStreamVersion = nil
resolvedSecurityVersion = nil
resolvedPeripheral = nil
encounteredError = nil
}
}
| 34.717895 | 99 | 0.775635 |
db5a8316aceebfd0c530ee4865a84c3db55b553d | 1,119 | //
// MercadoPagoCheckout+Screens+Plugins.swift
// MercadoPagoSDK
//
// Created by Eden Torres on 12/14/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import Foundation
extension MercadoPagoCheckout {
func showPaymentMethodPluginConfigScreen() {
guard let paymentMethodPlugin = self.viewModel.paymentOptionSelected as? PXPaymentMethodPlugin else {
return
}
guard let paymentMethodConfigPluginComponent = paymentMethodPlugin.paymentMethodConfigPlugin else {
return
}
viewModel.populateCheckoutStore()
paymentMethodConfigPluginComponent.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance, theme: ThemeManager.shared.getCurrentTheme())
// Create navigation handler.
paymentMethodConfigPluginComponent.navigationHandler?(navigationHandler: PXPluginNavigationHandler(withCheckout: self))
if let configPluginVC = paymentMethodConfigPluginComponent.configViewController() {
viewModel.pxNavigationHandler.pushViewController(targetVC: configPluginVC, animated: true)
}
}
}
| 34.96875 | 147 | 0.743521 |
9b53181f797bd15583ea32c62d65a058b70b1b72 | 3,120 | // The MIT License (MIT)
//
// Copyright (c) 2016 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(macOS)
import AppKit.NSImage
/// Alias for NSImage
public typealias Image = NSImage
#else
import UIKit.UIImage
/// Alias for UIImage
public typealias Image = UIImage
#endif
/// Loads an image into the given target.
///
/// For more info see `loadImage(with:into:)` method of `Manager`.
public func loadImage(with url: URL, into target: Target) {
Manager.shared.loadImage(with: url, into: target)
}
/// Loads an image into the given target.
///
/// For more info see `loadImage(with:into:)` method of `Manager`.
public func loadImage(with request: Request, into target: Target) {
Manager.shared.loadImage(with: request, into: target)
}
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Manager.Handler) {
Manager.shared.loadImage(with: url, into: target, handler: handler)
}
/// Loads an image and calls the given `handler`.
///
/// For more info see `loadImage(with:into:handler:)` method of `Manager`.
public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Manager.Handler) {
Manager.shared.loadImage(with: request, into: target, handler: handler)
}
/// Cancels an outstanding request associated with the target.
public func cancelRequest(for target: AnyObject) {
Manager.shared.cancelRequest(for: target)
}
public extension Manager {
/// Shared `Manager` instance.
///
/// Shared manager is created with `Loader.shared` and `Cache.shared`.
public static var shared = Manager(loader: Loader.shared, cache: Cache.shared)
}
public extension Loader {
/// Shared `Loading` object.
///
/// Shared loader is created with `DataLoader()`, `DataDecoder()` and
// `Cache.shared`. The resulting loader is wrapped in a `Deduplicator`.
public static var shared: Loading = Deduplicator(loader: Loader(loader: DataLoader(), decoder: DataDecoder(), cache: Cache.shared))
}
public extension Cache {
/// Shared `Cache` instance.
public static var shared = Cache()
}
internal final class Lock {
var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
init() {
pthread_mutex_init(mutex, nil)
}
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize()
mutex.deallocate(capacity: 1)
}
/// In critical places it's better to use lock() and unlock() manually
func sync<T>(_ closure: (Void) -> T) -> T {
pthread_mutex_lock(mutex)
defer { pthread_mutex_unlock(mutex) }
return closure()
}
func lock() { pthread_mutex_lock(mutex) }
func unlock() { pthread_mutex_unlock(mutex) }
}
| 31.836735 | 135 | 0.685897 |
7aa1467fac3243a5518c2d11dd24a067959d9c6d | 1,316 | //
// SwiftNSUserDefaultsTutorialUITests.swift
// SwiftNSUserDefaultsTutorialUITests
//
// Created by Ada Lovelace Code on 01/01/2018.
// Copyright © 2018 Ada Lovelace Code. All rights reserved.
//
import XCTest
class SwiftNSUserDefaultsTutorialUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 35.567568 | 182 | 0.679331 |
ef71f7fadf0a17cb9e552ac61d5390727ee8124a | 6,233 | /*
* Copyright (c) 2019-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 OktaOidc
class OktaOidcEndpointTests: XCTestCase {
func testGetURI_Introspection() {
let testEndpoint = "http://test.endpoint.com"
let testIssuer = "http://test.issuer.com"
let expectedEndpointBasedOnIssuer = testIssuer + "/oauth2/v1/" + "introspect"
XCTAssertNil(OktaOidcEndpoint.introspection.getURL(discoveredMetadata: nil, issuer: nil))
XCTAssertNil(OktaOidcEndpoint.introspection.getURL(discoveredMetadata: ["invalidKey": testEndpoint], issuer: nil))
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: ["introspection_endpoint": testEndpoint], issuer: nil)
)
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: ["introspection_endpoint": testEndpoint], issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: nil, issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: nil, issuer: testIssuer + "/")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.introspection.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2/")
)
}
func testGetURI_Revocation() {
let testEndpoint = "http://test.endpoint.com"
let testIssuer = "http://test.issuer.com"
let expectedEndpointBasedOnIssuer = testIssuer + "/oauth2/v1/" + "revoke"
XCTAssertNil(OktaOidcEndpoint.revocation.getURL(discoveredMetadata: nil, issuer: nil))
XCTAssertNil(OktaOidcEndpoint.revocation.getURL(discoveredMetadata: ["invalidKey": testEndpoint], issuer: nil))
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: ["revocation_endpoint": testEndpoint], issuer: nil)
)
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: ["revocation_endpoint": testEndpoint], issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: nil, issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: nil, issuer: testIssuer + "/")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.revocation.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2/")
)
}
func testGetURI_UserInfo() {
let testEndpoint = "http://test.endpoint.com"
let testIssuer = "http://test.issuer.com"
let expectedEndpointBasedOnIssuer = testIssuer + "/oauth2/v1/" + "userinfo"
XCTAssertNil(OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: nil, issuer: nil))
XCTAssertNil(OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: ["invalidKey": testEndpoint], issuer: nil))
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: ["userinfo_endpoint": testEndpoint], issuer: nil)
)
XCTAssertEqual(
URL(string: testEndpoint),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: ["userinfo_endpoint": testEndpoint], issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: nil, issuer: testIssuer)
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: nil, issuer: testIssuer + "/")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2")
)
XCTAssertEqual(
URL(string: (expectedEndpointBasedOnIssuer)),
OktaOidcEndpoint.userInfo.getURL(discoveredMetadata: nil, issuer: testIssuer + "/oauth2/")
)
}
func testNoEndpointError() {
XCTAssertEqual(
OktaOidcError.noIntrospectionEndpoint.localizedDescription,
OktaOidcEndpoint.introspection.noEndpointError.localizedDescription
)
XCTAssertEqual(
OktaOidcError.noRevocationEndpoint.localizedDescription,
OktaOidcEndpoint.revocation.noEndpointError.localizedDescription
)
XCTAssertEqual(
OktaOidcError.noUserInfoEndpoint.localizedDescription,
OktaOidcEndpoint.userInfo.noEndpointError.localizedDescription
)
}
}
| 42.986207 | 131 | 0.667897 |
e5cdd84e0e38a084cff7fee1ab315024cd86cb52 | 3,000 | import Quick
import Nimble
import Cuckoo
@testable import CuckooExample
final class MoviesListPresenterTests: QuickSpec {
override func spec() {
var sut: MoviesListPresenter!
var requestManagerMock: MockRequestManagerProtocol!
var viewControllerMock: MockMoviesListViewControllerProtocol!
beforeEach {
requestManagerMock = MockRequestManagerProtocol()
viewControllerMock = MockMoviesListViewControllerProtocol()
sut = MoviesListPresenter(requestManager: requestManagerMock)
sut.controller = viewControllerMock
stubViewController()
stubRequestManager(with: .success([Movie()]))
}
describe("#getInitialMovies") {
it("calls request on requestManager with expected endpoint") {
sut.getInitialMovies()
verify(requestManagerMock).request(equal(to: "/getMovies"),
completion: any())
}
var argumentCaptor: ArgumentCaptor<MoviesListViewState>!
beforeEach {
argumentCaptor = ArgumentCaptor<MoviesListViewState>()
}
context("on request success") {
beforeEach {
sut.getInitialMovies()
}
it("calls show on viewController 2 times (loading, success)") {
let expectedViewModel = MoviesListViewModel(posterURL: "",
title: "Parasite",
rating: 10.0)
verify(viewControllerMock, times(2)).set(state: argumentCaptor.capture())
expect(argumentCaptor.allValues.first).to(equal(.loading))
expect(argumentCaptor.allValues[1]).to(equal(.ready(expectedViewModel)))
}
}
context("on request failure") {
beforeEach {
stubRequestManager(with: .failure(NSError()))
sut.getInitialMovies()
}
it("calls show on viewController 2 times (loading, error)") {
verify(viewControllerMock, times(2)).set(state: argumentCaptor.capture())
expect(argumentCaptor.allValues.first).to(equal(.loading))
expect(argumentCaptor.allValues[1]).to(equal(.error))
}
}
}
func stubViewController() {
stub(viewControllerMock) { mock in
when(mock).set(state: any()).thenDoNothing()
}
}
func stubRequestManager(with mockedResult: Result<[Movie], Error>) {
stub(requestManagerMock) { mock in
when(mock).request(any(), completion: any()).then { _, completion in
completion(mockedResult)
}
}
}
}
}
| 34.090909 | 93 | 0.535333 |
269396bab0ee3a33aa44baa82e69f99cd2bdb3fe | 11,111 | import Foundation
import PathKit
public final class Declaration: Entity, CustomStringConvertible {
enum RetentionReason {
case xib
case unknown
case applicationMain
case publicAccessible
case objcAnnotated
case unknownTypeExtension
case unknownTypeConformance
case mainEntryPoint
case xctest
case rootEquatableInfixOperator
case paramFuncOverridden
case paramFuncForeginProtocol
case paramFuncLocalProtocol
}
enum Kind: String, RawRepresentable, CaseIterable {
case `associatedtype` = "source.lang.swift.decl.associatedtype"
case `class` = "source.lang.swift.decl.class"
case `enum` = "source.lang.swift.decl.enum"
case enumelement = "source.lang.swift.decl.enumelement"
case `extension` = "source.lang.swift.decl.extension"
case extensionClass = "source.lang.swift.decl.extension.class"
case extensionEnum = "source.lang.swift.decl.extension.enum"
case extensionProtocol = "source.lang.swift.decl.extension.protocol"
case extensionStruct = "source.lang.swift.decl.extension.struct"
case functionAccessorAddress = "source.lang.swift.decl.function.accessor.address"
case functionAccessorDidset = "source.lang.swift.decl.function.accessor.didset"
case functionAccessorGetter = "source.lang.swift.decl.function.accessor.getter"
case functionAccessorMutableaddress = "source.lang.swift.decl.function.accessor.mutableaddress"
case functionAccessorSetter = "source.lang.swift.decl.function.accessor.setter"
case functionAccessorWillset = "source.lang.swift.decl.function.accessor.willset"
case functionConstructor = "source.lang.swift.decl.function.constructor"
case functionDestructor = "source.lang.swift.decl.function.destructor"
case functionFree = "source.lang.swift.decl.function.free"
case functionMethodClass = "source.lang.swift.decl.function.method.class"
case functionMethodInstance = "source.lang.swift.decl.function.method.instance"
case functionMethodStatic = "source.lang.swift.decl.function.method.static"
case functionOperator = "source.lang.swift.decl.function.operator"
case functionOperatorInfix = "source.lang.swift.decl.function.operator.infix"
case functionOperatorPostfix = "source.lang.swift.decl.function.operator.postfix"
case functionOperatorPrefix = "source.lang.swift.decl.function.operator.prefix"
case functionSubscript = "source.lang.swift.decl.function.subscript"
case genericTypeParam = "source.lang.swift.decl.generic_type_param"
case module = "source.lang.swift.decl.module"
case precedenceGroup = "source.lang.swift.decl.precedencegroup"
case `protocol` = "source.lang.swift.decl.protocol"
case `struct` = "source.lang.swift.decl.struct"
case `typealias` = "source.lang.swift.decl.typealias"
case varClass = "source.lang.swift.decl.var.class"
case varGlobal = "source.lang.swift.decl.var.global"
case varInstance = "source.lang.swift.decl.var.instance"
case varLocal = "source.lang.swift.decl.var.local"
case varParameter = "source.lang.swift.decl.var.parameter"
case varStatic = "source.lang.swift.decl.var.static"
static var functionKinds: Set<Kind> {
return Set(Kind.allCases.filter { $0.isFunctionKind })
}
var isFunctionKind: Bool {
return rawValue.hasPrefix("source.lang.swift.decl.function")
}
static var variableKinds: Set<Kind> {
return Set(Kind.allCases.filter { $0.isVariableKind })
}
var isVariableKind: Bool {
return rawValue.hasPrefix("source.lang.swift.decl.var")
}
static var globalKinds: Set<Kind> = [
.class,
.protocol,
.enum,
.struct,
.typealias,
.functionFree,
.extensionClass,
.extensionStruct,
.extensionProtocol,
.varGlobal
]
static var extensionKinds: Set<Kind> {
return Set(Kind.allCases.filter { $0.isExtensionKind })
}
var isExtensionKind: Bool {
return rawValue.hasPrefix("source.lang.swift.decl.extension")
}
static var accessorKinds: Set<Kind> {
return Set(Kind.allCases.filter { $0.isAccessorKind })
}
var isAccessorKind: Bool {
return rawValue.hasPrefix("source.lang.swift.decl.function.accessor")
}
static var accessibleKinds: Set<Kind> {
return functionKinds.union(variableKinds).union(globalKinds)
}
var shortName: String {
let namespace = "source.lang.swift.decl"
let index = rawValue.index(after: namespace.endIndex)
return String(rawValue.suffix(from: index))
}
var displayName: String? {
switch self {
case .class:
return "class"
case .protocol:
return "protocol"
case .struct:
return "struct"
case .enum:
return "enum"
case .enumelement:
return "enum case"
case .typealias:
return "typealias"
case .associatedtype:
return "associatedtype"
case .functionConstructor:
return "initializer"
case .extension, .extensionEnum, .extensionClass, .extensionStruct, .extensionProtocol:
return "extension"
case .functionMethodClass, .functionMethodStatic, .functionMethodInstance, .functionFree, .functionOperator, .functionSubscript:
return "function"
case .varStatic, .varInstance, .varClass, .varGlobal, .varLocal:
return "property"
case .varParameter:
return "parameter"
default:
return nil
}
}
func isEqualToStructure(kind: Kind?) -> Bool {
guard let kind = kind else { return false }
guard self != kind else { return true }
if self == .functionConstructor && kind == .functionMethodInstance {
return true
}
if kind == .extension && isExtensionKind {
return true
}
return false
}
var referenceEquivalent: Reference.Kind? {
let value = rawValue.replacingOccurrences(of: ".decl.", with: ".ref.")
return Reference.Kind(rawValue: value)
}
}
public let location: SourceLocation
let kind: Kind
let usr: String
let name: String?
var parent: Entity?
var attributes: Set<String> = []
var declarations: Set<Declaration> = []
var unusedParameters: Set<Declaration> = []
var references: Set<Reference> = []
var related: Set<Reference> = []
var structureAccessibility: Accessibility = .internal
var analyzerHints: [Analyzer.Hint] = []
var attributeAccessibility: Accessibility {
if attributes.contains("public") {
return .public
} else if attributes.contains("open") {
return .open
} else if attributes.contains("private") {
return .private
} else if attributes.contains("fileprivate") {
return .fileprivate
}
return .internal
}
var accessibility: Accessibility {
let featureManager: FeatureManager = inject()
if featureManager.isEnabled(.determineAccessibilityFromStructure) {
return structureAccessibility
}
return attributeAccessibility
}
var ancestralDeclarations: Set<Declaration> {
var entity: Entity? = parent
var declarations: Set<Declaration> = []
while let thisEntity = entity {
if let declaration = thisEntity as? Declaration {
declarations.insert(declaration)
}
entity = thisEntity.parent
}
return declarations
}
var descendentDeclarations: Set<Declaration> {
return Set(declarations.flatMap { $0.descendentDeclarations }).union(declarations)
}
var immediateSuperclassReferences: Set<Reference> {
let superclassReferences = related.filter { [.class, .struct, .protocol].contains($0.kind) }
// SourceKit returns inherited typealiases as a Reference instead of a Related.
let typealiasReferences = references.filter { $0.kind == .typealias }
return superclassReferences.union(typealiasReferences)
}
var isComplexProperty: Bool {
return declarations.contains {
if [.functionAccessorWillset,
.functionAccessorDidset].contains($0.kind) {
return true
}
// All properties have a getter and setter, however they only have a name when
// explicitly implemented.
if $0.name != nil,
[.functionAccessorGetter,
.functionAccessorSetter].contains($0.kind) {
return true
}
return false
}
}
public var description: String {
return "Declaration(\(descriptionParts.joined(separator: ", ")))"
}
public var descriptionParts: [String] {
let formattedName = name != nil ? "'\(name!)'" : "nil"
let formattedAttributes = "[" + attributes.map { $0 }.sorted().joined(separator: ", ") + "]"
return [kind.shortName, formattedName, accessibility.shortName, formattedAttributes, "'\(usr)'", location.shortDescription]
}
init(kind: Kind, usr: String, location: SourceLocation, name: String?) {
self.kind = kind
self.usr = usr
self.location = location
self.name = name
}
func isDeclaredInExtension(kind: Declaration.Kind) -> Bool {
guard let parent = parent as? Declaration else { return false }
return parent.kind == kind
}
// MARK: - Analyzer Marking
private(set) var isRetained: Bool = false // retained regardless of presence of references
private(set) var retentionReason: RetentionReason = .unknown
func markRetained(reason: RetentionReason) {
isRetained = true
retentionReason = reason
}
}
extension Declaration: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(kind)
hasher.combine(usr)
hasher.combine(name)
hasher.combine(location)
}
}
extension Declaration: Equatable {
public static func == (lhs: Declaration, rhs: Declaration) -> Bool {
let usrIsEqual = lhs.usr == rhs.usr
let kindIsEqual = lhs.kind == rhs.kind
let nameIsEqual = lhs.name == rhs.name
let locationIsEqual = lhs.location == rhs.location
return kindIsEqual && usrIsEqual && nameIsEqual && locationIsEqual
}
}
| 36.429508 | 140 | 0.623436 |
7ae635cf76a93c603096c02884f6c9c95af0e999 | 5,530 | //
// FaceAnnotationSpec.swift
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
import Nimble
import Quick
import Picguard
final class FaceAnnotationSpec: QuickSpec {
override func spec() {
describe("FaceAnnotation") {
func initWithRawValuesShouldSucceed(
values values: (
rollAngle: Double,
panAngle: Double,
tiltAngle: Double,
detectionConfidence: Double,
landmarkingConfidence: Double
)
) {
it("should properly initialize the receiver") {
expect {
try FaceAnnotation(
boundingPolygon: BoundingPolygon(vertices: []),
skinBoundingPolygon: BoundingPolygon(vertices: []),
landmarks: [],
rollAngle: values.rollAngle,
panAngle: values.panAngle,
tiltAngle: values.tiltAngle,
detectionConfidence: values.detectionConfidence,
landmarkingConfidence: values.landmarkingConfidence,
joyLikelihood: .Unknown,
sorrowLikelihood: .Unknown,
angerLikelihood: .Unknown,
surpriseLikelihood: .Unknown,
underExposedLikelihood: .Unknown,
blurredLikelihood: .Unknown,
headwearLikelihood: .Unknown
)
}.toNot(throwError())
}
}
func initWithRawValuesShouldFail<E: ErrorType>(
values values: (
rollAngle: Double,
panAngle: Double,
tiltAngle: Double,
detectionConfidence: Double,
landmarkingConfidence: Double
),
error: E
) {
it("should throw error") {
expect {
try FaceAnnotation(
boundingPolygon: BoundingPolygon(vertices: []),
skinBoundingPolygon: BoundingPolygon(vertices: []),
landmarks: [],
rollAngle: values.rollAngle,
panAngle: values.panAngle,
tiltAngle: values.tiltAngle,
detectionConfidence: values.detectionConfidence,
landmarkingConfidence: values.landmarkingConfidence,
joyLikelihood: .Unknown,
sorrowLikelihood: .Unknown,
angerLikelihood: .Unknown,
surpriseLikelihood: .Unknown,
underExposedLikelihood: .Unknown,
blurredLikelihood: .Unknown,
headwearLikelihood: .Unknown
)
}.to(throwError(error))
}
}
describe("init with raw values") {
context("with all numeric values being valid") {
initWithRawValuesShouldSucceed(values: (
rollAngle: 30,
panAngle: -60,
tiltAngle: 120,
detectionConfidence: 0.5,
landmarkingConfidence: 0.5
))
}
context("with invalid roll angle") {
initWithRawValuesShouldFail(values: (
rollAngle: 200,
panAngle: 0,
tiltAngle: 0,
detectionConfidence: 0,
landmarkingConfidence: 0
), error: FaceAnnotation.Error.InvalidRollAngle)
}
context("with invalid pan angle") {
initWithRawValuesShouldFail(values: (
rollAngle: 0,
panAngle: -300,
tiltAngle: 0,
detectionConfidence: 0,
landmarkingConfidence: 0
), error: FaceAnnotation.Error.InvalidPanAngle)
}
context("with invalid tilt angle") {
initWithRawValuesShouldFail(values: (
rollAngle: 0,
panAngle: 0,
tiltAngle: 400,
detectionConfidence: 0,
landmarkingConfidence: 0
), error: FaceAnnotation.Error.InvalidTiltAngle)
}
context("with invalid detection confidence") {
initWithRawValuesShouldFail(values: (
rollAngle: 0,
panAngle: 0,
tiltAngle: 0,
detectionConfidence: 2,
landmarkingConfidence: 0
), error: FaceAnnotation.Error.InvalidDetectionConfidence)
}
context("with invalid landmarking confidence") {
initWithRawValuesShouldFail(values: (
rollAngle: 0,
panAngle: 0,
tiltAngle: 0,
detectionConfidence: 0,
landmarkingConfidence: -3
), error: FaceAnnotation.Error.InvalidLandmarkingConfidence)
}
}
describe("init with api representation") {
context("with valid dictionary") {
initWithAPIRepresentationShouldSucceed(value: [
"boundingPoly": ["vertices": [["x": 1, "y": 2]]],
"fdBoundingPoly": ["vertices": [["x": 3, "y": 4]]],
"landmarks": [["type": "UNKNOWN_LANDMARK", "position": ["x": 5, "y": 6, "z": 7]]],
"rollAngle": 30,
"panAngle": 60,
"tiltAngle": 120,
"detectionConfidence": 0.25,
"landmarkingConfidence": 0.75,
"joyLikelihood": "UNKNOWN",
"sorrowLikelihood": "UNKNOWN",
"angerLikelihood": "UNKNOWN",
"surpriseLikelihood": "UNKNOWN",
"underExposedLikelihood": "UNKNOWN",
"blurredLikelihood": "UNKNOWN",
"headwearLikelihood": "UNKNOWN"
], expected: try! FaceAnnotation(
boundingPolygon: BoundingPolygon(vertices: [Vertex(x: 1, y: 2)]),
skinBoundingPolygon: BoundingPolygon(vertices: [Vertex(x: 3, y: 4)]),
landmarks: [FaceLandmark(type: .Unknown, position: Position(x: 5, y: 6, z: 7))],
rollAngle: 30,
panAngle: 60,
tiltAngle: 120,
detectionConfidence: 0.25,
landmarkingConfidence: 0.75,
joyLikelihood: .Unknown,
sorrowLikelihood: .Unknown,
angerLikelihood: .Unknown,
surpriseLikelihood: .Unknown,
underExposedLikelihood: .Unknown,
blurredLikelihood: .Unknown,
headwearLikelihood: .Unknown
))
}
context("with invalid representation value type") {
initWithAPIRepresentationShouldFail(
value: "foobar",
type: FaceAnnotation.self,
error: APIRepresentationError.UnexpectedValueType
)
}
}
}
}
}
| 27.65 | 88 | 0.646112 |
f908fc72766b1d463c1bdf66471c3e8cda6e9279 | 256 | import XCTest
class Notes60UITests: XCTestCase {
override func setUp() {
super.setUp()
XCUIApplication().launch()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
}
}
| 19.692308 | 36 | 0.535156 |
4b24b516768bf6b562276a87503074ed6a236e3e | 7,172 | //
// main.swift
// WifiToggle
//
// Created by Kett, Oliver on 06.11.15.
// Copyright © 2015 Kett, Oliver. All rights reserved.
//
import Foundation
import SystemConfiguration
import CoreWLAN
func set_wifi_power(power: Bool) -> Bool {
// on Yosemite and later, we use CoreWLAN WifiClient
if #available(OSX 10.10, *) {
if let interfaces = CWWiFiClient.interfaceNames() {
for interface in interfaces {
if let interface = CWWiFiClient()?.interfaceWithName(interface) {
do {
try interface.setPower(power)
NSLog("set Wifi Power for \(interface.interfaceName!) to \(power)")
} catch {
NSLog("error: \(error)")
return false
}
}
}
}
} else {
// we use CWInterface for older OS X releases
if let interfaces = CWInterface.interfaceNames() {
for interface in interfaces {
// entitlement com.apple.wifi.set_power is required, so no sandboxing is allowed
do {
try CWInterface(name: interface).setPower(power)
NSLog("set Wifi Power for \(interface) to \(power)")
} catch {
NSLog("error: \(error)")
return false
}
}
}
}
return true
}
func NetworkInterfaceCopyMediaOptions(interface: SCNetworkInterfaceRef) -> (NSDictionary, NSDictionary, NSArray)? {
var ptrActive = Unmanaged<CFDictionary>?()
var ptrCurrent = Unmanaged<CFDictionary>?()
var ptrAvailable = Unmanaged<CFArray>?()
SCNetworkInterfaceCopyMediaOptions(interface, &ptrActive, &ptrCurrent, &ptrAvailable, false)
if let active = ptrActive?.takeRetainedValue(),
let current = ptrCurrent?.takeRetainedValue(),
let available = ptrAvailable?.takeRetainedValue() {
return (active as NSDictionary, current as NSDictionary, available as NSArray)
}
return nil
}
func check_media_status() {
var ethernet = false
var wifi = false
let interfaces = SCNetworkInterfaceCopyAll() as Array
for i in 0..<interfaces.count {
let interface = interfaces[i] as! SCNetworkInterface
if let interface_type = SCNetworkInterfaceGetInterfaceType(interface) {
if interface_type == "Ethernet" {
if let (_, current, _) = NetworkInterfaceCopyMediaOptions(interface) {
if let mediaType = current["MediaSubType"] as! String? {
if mediaType.rangeOfString("baseT") != nil {
// we have a ethernet link
ethernet = true
}
}
}
} else if interface_type == "IEEE80211" {
if NetworkInterfaceCopyMediaOptions(interface) == nil {
// wifi is disabled
wifi = false
} else {
wifi = true
}
}
}
}
if ethernet == true && wifi == true {
set_wifi_power(false)
}
if ethernet == false && wifi == false {
set_wifi_power(true)
}
// on ethernet == true && wifi == false we don't need to change anything
// on ethernet == false && wifi == true we don't need to change anything
}
func updateKeys(store: SCDynamicStore) -> Array<String> {
guard let interfaces = SCDynamicStoreCopyValue(store, "State:/Network/Interface") as! NSDictionary?,
let interface_array = interfaces["Interfaces"] as! NSArray? else {
NSLog("Error: could not find any network interfaces")
exit(2)
}
var keys = [
"State:/Network/Global/IPv6",
"State:/Network/Global/IPv4",
"State:/Network/Interface"
]
for interface in interface_array {
if interface as! String == "lo0" {
continue
}
if let _ = SCDynamicStoreCopyValue(store, "State:/Network/Interface/\(interface)/Link") {
keys.append("State:/Network/Interface/\(interface)/Link")
}
if let _ = SCDynamicStoreCopyValue(store, "State:/Network/Interface/\(interface)/AirPort") {
keys.append("State:/Network/Interface/\(interface)/AirPort")
}
}
return keys
}
func callback(store: SCDynamicStoreRef, changedKeys: CFArrayRef, info: UnsafeMutablePointer<Void>) {
Log(changedKeys)
for key in changedKeys as Array {
if key as! String == "State:/Network/Interface" {
Log("Network hardware changed, restart CFRunLoop")
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
check_media_status()
}
func start(pidfile: String) {
// get a callback on every network change: https://github.com/chetan51/sidestep/blob/master/NetworkNotifier.m
// https://developer.apple.com/library/mac/documentation/Networking/Reference/SCDynamicStore/#//apple_ref/c/tdef/SCDynamicStoreContext
let pid = String(NSProcessInfo().processIdentifier)
do {
try pid.writeToFile(pidfile, atomically: true, encoding: NSASCIIStringEncoding)
} catch {
NSLog("error writing pid to \(pidfile)")
}
let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier ?? "WifiToggle"
guard let store = SCDynamicStoreCreate(nil, bundleIdentifier, callback, nil) else {
NSLog("Error: cannot create SCDynamicStore!")
exit(1)
}
// CFRunLoop is stopped in the callback function and here restarted with the updated keys
while true {
SCDynamicStoreSetNotificationKeys(store, updateKeys(store), nil)
CFRunLoopAddSource(CFRunLoopGetCurrent(), SCDynamicStoreCreateRunLoopSource(nil, store, 0), kCFRunLoopDefaultMode)
CFRunLoopRun()
}
}
func stop(pidfile: String) {
do {
if let oldpid = try Int32(String(contentsOfFile: pidfile)) {
kill(oldpid, SIGKILL)
}
} catch {
Log("can't read pid file at \(pidfile)")
}
if NSFileManager.defaultManager().fileExistsAtPath(pidfile) {
do {
try NSFileManager.defaultManager().removeItemAtPath(pidfile)
} catch {
Log("error removing \(pidfile)")
}
}
}
if getuid() != 0 {
print("error: run me as root!")
exit(1)
}
let pidfile = "/var/run/WifiToggle.pid"
switch Process.arguments[1] {
case "--start":
stop(pidfile)
start(pidfile)
case "--stop":
stop(pidfile)
case "--version":
print("WifiToggle 1.0.0")
default:
// print usage
print("usage: WifiToggle COMMAND")
print("\nAvailable commands (there must be exactly one):")
print("\t--start")
print("\t\t starts this program in daemon mode. You should use launchd(8) to start automatically.")
print("\t--stop")
print("\t\tend daemon")
print("\nThis tools monitors all network interfaces connected and disables the Wifi interface if a wired connection is established.")
}
| 35.330049 | 141 | 0.594395 |
bb6129b65ee6eb3514a5705549c01c3f2e2e9a52 | 21,196 | //
// ActivityDefinition.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/ActivityDefinition) on 2019-05-21.
// 2019, SMART Health IT.
//
import Foundation
/**
The definition of a specific activity to be taken, independent of any particular patient or context.
This resource allows for the definition of some activity to be performed, independent of a particular patient,
practitioner, or other performance context.
*/
open class ActivityDefinition: DomainResource {
override open class var resourceType: String {
get { return "ActivityDefinition" }
}
/// When the activity definition was approved by publisher.
public var approvalDate: FHIRDate?
/// Who authored the content.
public var author: [ContactDetail]?
/// What part of body to perform on.
public var bodySite: [CodeableConcept]?
/// Detail type of activity.
public var code: CodeableConcept?
/// Contact details for the publisher.
public var contact: [ContactDetail]?
/// Use and/or publishing restrictions.
public var copyright: FHIRString?
/// Date last changed.
public var date: DateTime?
/// Natural language description of the activity definition.
public var description_fhir: FHIRString?
/// True if the activity should not be performed.
public var doNotPerform: FHIRBool?
/// Detailed dosage instructions.
public var dosage: [Dosage]?
/// Dynamic aspects of the definition.
public var dynamicValue: [ActivityDefinitionDynamicValue]?
/// Who edited the content.
public var editor: [ContactDetail]?
/// When the activity definition is expected to be used.
public var effectivePeriod: Period?
/// Who endorsed the content.
public var endorser: [ContactDetail]?
/// For testing purposes, not real usage.
public var experimental: FHIRBool?
/// Additional identifier for the activity definition.
public var identifier: [Identifier]?
/// Indicates the level of authority/intentionality associated with the activity and where the request should fit
/// into the workflow chain.
public var intent: RequestIntent?
/// Intended jurisdiction for activity definition (if applicable).
public var jurisdiction: [CodeableConcept]?
/// A description of the kind of resource the activity definition is representing. For example, a MedicationRequest,
/// a ServiceRequest, or a CommunicationRequest. Typically, but not always, this is a Request resource.
public var kind: RequestResourceType?
/// When the activity definition was last reviewed.
public var lastReviewDate: FHIRDate?
/// Logic used by the activity definition.
public var library: [FHIRCanonical]?
/// Where it should happen.
public var location: Reference?
/// Name for this activity definition (computer friendly).
public var name: FHIRString?
/// What observations are required to perform this action.
public var observationRequirement: [Reference]?
/// What observations must be produced by this action.
public var observationResultRequirement: [Reference]?
/// Who should participate in the action.
public var participant: [ActivityDefinitionParticipant]?
/// Indicates how quickly the activity should be addressed with respect to other requests.
public var priority: RequestPriority?
/// What's administered/supplied.
public var productCodeableConcept: CodeableConcept?
/// What's administered/supplied.
public var productReference: Reference?
/// What profile the resource needs to conform to.
public var profile: FHIRCanonical?
/// Name of the publisher (organization or individual).
public var publisher: FHIRString?
/// Why this activity definition is defined.
public var purpose: FHIRString?
/// How much is administered/consumed/supplied.
public var quantity: Quantity?
/// Additional documentation, citations, etc..
public var relatedArtifact: [RelatedArtifact]?
/// Who reviewed the content.
public var reviewer: [ContactDetail]?
/// What specimens are required to perform this action.
public var specimenRequirement: [Reference]?
/// The status of this activity definition. Enables tracking the life-cycle of the content.
public var status: PublicationStatus?
/// Type of individual the activity definition is intended for.
public var subjectCodeableConcept: CodeableConcept?
/// Type of individual the activity definition is intended for.
public var subjectReference: Reference?
/// Subordinate title of the activity definition.
public var subtitle: FHIRString?
/// When activity is to occur.
public var timingAge: Age?
/// When activity is to occur.
public var timingDateTime: DateTime?
/// When activity is to occur.
public var timingDuration: Duration?
/// When activity is to occur.
public var timingPeriod: Period?
/// When activity is to occur.
public var timingRange: Range?
/// When activity is to occur.
public var timingTiming: Timing?
/// Name for this activity definition (human friendly).
public var title: FHIRString?
/// E.g. Education, Treatment, Assessment, etc..
public var topic: [CodeableConcept]?
/// Transform to apply the template.
public var transform: FHIRCanonical?
/// Canonical identifier for this activity definition, represented as a URI (globally unique).
public var url: FHIRURL?
/// Describes the clinical usage of the activity definition.
public var usage: FHIRString?
/// The context that the content is intended to support.
public var useContext: [UsageContext]?
/// Business version of the activity definition.
public var version: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(status: PublicationStatus) {
self.init()
self.status = status
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
approvalDate = createInstance(type: FHIRDate.self, for: "approvalDate", in: json, context: &instCtx, owner: self) ?? approvalDate
author = createInstances(of: ContactDetail.self, for: "author", in: json, context: &instCtx, owner: self) ?? author
bodySite = createInstances(of: CodeableConcept.self, for: "bodySite", in: json, context: &instCtx, owner: self) ?? bodySite
code = createInstance(type: CodeableConcept.self, for: "code", in: json, context: &instCtx, owner: self) ?? code
contact = createInstances(of: ContactDetail.self, for: "contact", in: json, context: &instCtx, owner: self) ?? contact
copyright = createInstance(type: FHIRString.self, for: "copyright", in: json, context: &instCtx, owner: self) ?? copyright
date = createInstance(type: DateTime.self, for: "date", in: json, context: &instCtx, owner: self) ?? date
description_fhir = createInstance(type: FHIRString.self, for: "description", in: json, context: &instCtx, owner: self) ?? description_fhir
doNotPerform = createInstance(type: FHIRBool.self, for: "doNotPerform", in: json, context: &instCtx, owner: self) ?? doNotPerform
dosage = createInstances(of: Dosage.self, for: "dosage", in: json, context: &instCtx, owner: self) ?? dosage
dynamicValue = createInstances(of: ActivityDefinitionDynamicValue.self, for: "dynamicValue", in: json, context: &instCtx, owner: self) ?? dynamicValue
editor = createInstances(of: ContactDetail.self, for: "editor", in: json, context: &instCtx, owner: self) ?? editor
effectivePeriod = createInstance(type: Period.self, for: "effectivePeriod", in: json, context: &instCtx, owner: self) ?? effectivePeriod
endorser = createInstances(of: ContactDetail.self, for: "endorser", in: json, context: &instCtx, owner: self) ?? endorser
experimental = createInstance(type: FHIRBool.self, for: "experimental", in: json, context: &instCtx, owner: self) ?? experimental
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
intent = createEnum(type: RequestIntent.self, for: "intent", in: json, context: &instCtx) ?? intent
jurisdiction = createInstances(of: CodeableConcept.self, for: "jurisdiction", in: json, context: &instCtx, owner: self) ?? jurisdiction
kind = createEnum(type: RequestResourceType.self, for: "kind", in: json, context: &instCtx) ?? kind
lastReviewDate = createInstance(type: FHIRDate.self, for: "lastReviewDate", in: json, context: &instCtx, owner: self) ?? lastReviewDate
library = createInstances(of: FHIRCanonical.self, for: "library", in: json, context: &instCtx, owner: self) ?? library
location = createInstance(type: Reference.self, for: "location", in: json, context: &instCtx, owner: self) ?? location
name = createInstance(type: FHIRString.self, for: "name", in: json, context: &instCtx, owner: self) ?? name
observationRequirement = createInstances(of: Reference.self, for: "observationRequirement", in: json, context: &instCtx, owner: self) ?? observationRequirement
observationResultRequirement = createInstances(of: Reference.self, for: "observationResultRequirement", in: json, context: &instCtx, owner: self) ?? observationResultRequirement
participant = createInstances(of: ActivityDefinitionParticipant.self, for: "participant", in: json, context: &instCtx, owner: self) ?? participant
priority = createEnum(type: RequestPriority.self, for: "priority", in: json, context: &instCtx) ?? priority
productCodeableConcept = createInstance(type: CodeableConcept.self, for: "productCodeableConcept", in: json, context: &instCtx, owner: self) ?? productCodeableConcept
productReference = createInstance(type: Reference.self, for: "productReference", in: json, context: &instCtx, owner: self) ?? productReference
profile = createInstance(type: FHIRCanonical.self, for: "profile", in: json, context: &instCtx, owner: self) ?? profile
publisher = createInstance(type: FHIRString.self, for: "publisher", in: json, context: &instCtx, owner: self) ?? publisher
purpose = createInstance(type: FHIRString.self, for: "purpose", in: json, context: &instCtx, owner: self) ?? purpose
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
relatedArtifact = createInstances(of: RelatedArtifact.self, for: "relatedArtifact", in: json, context: &instCtx, owner: self) ?? relatedArtifact
reviewer = createInstances(of: ContactDetail.self, for: "reviewer", in: json, context: &instCtx, owner: self) ?? reviewer
specimenRequirement = createInstances(of: Reference.self, for: "specimenRequirement", in: json, context: &instCtx, owner: self) ?? specimenRequirement
status = createEnum(type: PublicationStatus.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
subjectCodeableConcept = createInstance(type: CodeableConcept.self, for: "subjectCodeableConcept", in: json, context: &instCtx, owner: self) ?? subjectCodeableConcept
subjectReference = createInstance(type: Reference.self, for: "subjectReference", in: json, context: &instCtx, owner: self) ?? subjectReference
subtitle = createInstance(type: FHIRString.self, for: "subtitle", in: json, context: &instCtx, owner: self) ?? subtitle
timingAge = createInstance(type: Age.self, for: "timingAge", in: json, context: &instCtx, owner: self) ?? timingAge
timingDateTime = createInstance(type: DateTime.self, for: "timingDateTime", in: json, context: &instCtx, owner: self) ?? timingDateTime
timingDuration = createInstance(type: Duration.self, for: "timingDuration", in: json, context: &instCtx, owner: self) ?? timingDuration
timingPeriod = createInstance(type: Period.self, for: "timingPeriod", in: json, context: &instCtx, owner: self) ?? timingPeriod
timingRange = createInstance(type: Range.self, for: "timingRange", in: json, context: &instCtx, owner: self) ?? timingRange
timingTiming = createInstance(type: Timing.self, for: "timingTiming", in: json, context: &instCtx, owner: self) ?? timingTiming
title = createInstance(type: FHIRString.self, for: "title", in: json, context: &instCtx, owner: self) ?? title
topic = createInstances(of: CodeableConcept.self, for: "topic", in: json, context: &instCtx, owner: self) ?? topic
transform = createInstance(type: FHIRCanonical.self, for: "transform", in: json, context: &instCtx, owner: self) ?? transform
url = createInstance(type: FHIRURL.self, for: "url", in: json, context: &instCtx, owner: self) ?? url
usage = createInstance(type: FHIRString.self, for: "usage", in: json, context: &instCtx, owner: self) ?? usage
useContext = createInstances(of: UsageContext.self, for: "useContext", in: json, context: &instCtx, owner: self) ?? useContext
version = createInstance(type: FHIRString.self, for: "version", in: json, context: &instCtx, owner: self) ?? version
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.approvalDate?.decorate(json: &json, withKey: "approvalDate", errors: &errors)
arrayDecorate(json: &json, withKey: "author", using: self.author, errors: &errors)
arrayDecorate(json: &json, withKey: "bodySite", using: self.bodySite, errors: &errors)
self.code?.decorate(json: &json, withKey: "code", errors: &errors)
arrayDecorate(json: &json, withKey: "contact", using: self.contact, errors: &errors)
self.copyright?.decorate(json: &json, withKey: "copyright", errors: &errors)
self.date?.decorate(json: &json, withKey: "date", errors: &errors)
self.description_fhir?.decorate(json: &json, withKey: "description", errors: &errors)
self.doNotPerform?.decorate(json: &json, withKey: "doNotPerform", errors: &errors)
arrayDecorate(json: &json, withKey: "dosage", using: self.dosage, errors: &errors)
arrayDecorate(json: &json, withKey: "dynamicValue", using: self.dynamicValue, errors: &errors)
arrayDecorate(json: &json, withKey: "editor", using: self.editor, errors: &errors)
self.effectivePeriod?.decorate(json: &json, withKey: "effectivePeriod", errors: &errors)
arrayDecorate(json: &json, withKey: "endorser", using: self.endorser, errors: &errors)
self.experimental?.decorate(json: &json, withKey: "experimental", errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
self.intent?.decorate(json: &json, withKey: "intent", errors: &errors)
arrayDecorate(json: &json, withKey: "jurisdiction", using: self.jurisdiction, errors: &errors)
self.kind?.decorate(json: &json, withKey: "kind", errors: &errors)
self.lastReviewDate?.decorate(json: &json, withKey: "lastReviewDate", errors: &errors)
arrayDecorate(json: &json, withKey: "library", using: self.library, errors: &errors)
self.location?.decorate(json: &json, withKey: "location", errors: &errors)
self.name?.decorate(json: &json, withKey: "name", errors: &errors)
arrayDecorate(json: &json, withKey: "observationRequirement", using: self.observationRequirement, errors: &errors)
arrayDecorate(json: &json, withKey: "observationResultRequirement", using: self.observationResultRequirement, errors: &errors)
arrayDecorate(json: &json, withKey: "participant", using: self.participant, errors: &errors)
self.priority?.decorate(json: &json, withKey: "priority", errors: &errors)
self.productCodeableConcept?.decorate(json: &json, withKey: "productCodeableConcept", errors: &errors)
self.productReference?.decorate(json: &json, withKey: "productReference", errors: &errors)
self.profile?.decorate(json: &json, withKey: "profile", errors: &errors)
self.publisher?.decorate(json: &json, withKey: "publisher", errors: &errors)
self.purpose?.decorate(json: &json, withKey: "purpose", errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
arrayDecorate(json: &json, withKey: "relatedArtifact", using: self.relatedArtifact, errors: &errors)
arrayDecorate(json: &json, withKey: "reviewer", using: self.reviewer, errors: &errors)
arrayDecorate(json: &json, withKey: "specimenRequirement", using: self.specimenRequirement, errors: &errors)
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
self.subjectCodeableConcept?.decorate(json: &json, withKey: "subjectCodeableConcept", errors: &errors)
self.subjectReference?.decorate(json: &json, withKey: "subjectReference", errors: &errors)
self.subtitle?.decorate(json: &json, withKey: "subtitle", errors: &errors)
self.timingAge?.decorate(json: &json, withKey: "timingAge", errors: &errors)
self.timingDateTime?.decorate(json: &json, withKey: "timingDateTime", errors: &errors)
self.timingDuration?.decorate(json: &json, withKey: "timingDuration", errors: &errors)
self.timingPeriod?.decorate(json: &json, withKey: "timingPeriod", errors: &errors)
self.timingRange?.decorate(json: &json, withKey: "timingRange", errors: &errors)
self.timingTiming?.decorate(json: &json, withKey: "timingTiming", errors: &errors)
self.title?.decorate(json: &json, withKey: "title", errors: &errors)
arrayDecorate(json: &json, withKey: "topic", using: self.topic, errors: &errors)
self.transform?.decorate(json: &json, withKey: "transform", errors: &errors)
self.url?.decorate(json: &json, withKey: "url", errors: &errors)
self.usage?.decorate(json: &json, withKey: "usage", errors: &errors)
arrayDecorate(json: &json, withKey: "useContext", using: self.useContext, errors: &errors)
self.version?.decorate(json: &json, withKey: "version", errors: &errors)
}
}
/**
Dynamic aspects of the definition.
Dynamic values that will be evaluated to produce values for elements of the resulting resource. For example, if the
dosage of a medication must be computed based on the patient's weight, a dynamic value would be used to specify an
expression that calculated the weight, and the path on the request resource that would contain the result.
*/
open class ActivityDefinitionDynamicValue: BackboneElement {
override open class var resourceType: String {
get { return "ActivityDefinitionDynamicValue" }
}
/// An expression that provides the dynamic value for the customization.
public var expression: Expression?
/// The path to the element to be set dynamically.
public var path: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(expression: Expression, path: FHIRString) {
self.init()
self.expression = expression
self.path = path
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
expression = createInstance(type: Expression.self, for: "expression", in: json, context: &instCtx, owner: self) ?? expression
if nil == expression && !instCtx.containsKey("expression") {
instCtx.addError(FHIRValidationError(missing: "expression"))
}
path = createInstance(type: FHIRString.self, for: "path", in: json, context: &instCtx, owner: self) ?? path
if nil == path && !instCtx.containsKey("path") {
instCtx.addError(FHIRValidationError(missing: "path"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.expression?.decorate(json: &json, withKey: "expression", errors: &errors)
if nil == self.expression {
errors.append(FHIRValidationError(missing: "expression"))
}
self.path?.decorate(json: &json, withKey: "path", errors: &errors)
if nil == self.path {
errors.append(FHIRValidationError(missing: "path"))
}
}
}
/**
Who should participate in the action.
Indicates who should participate in performing the action described.
*/
open class ActivityDefinitionParticipant: BackboneElement {
override open class var resourceType: String {
get { return "ActivityDefinitionParticipant" }
}
/// E.g. Nurse, Surgeon, Parent, etc..
public var role: CodeableConcept?
/// The type of participant in the action.
public var type: ActionParticipantType?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(type: ActionParticipantType) {
self.init()
self.type = type
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
role = createInstance(type: CodeableConcept.self, for: "role", in: json, context: &instCtx, owner: self) ?? role
type = createEnum(type: ActionParticipantType.self, for: "type", in: json, context: &instCtx) ?? type
if nil == type && !instCtx.containsKey("type") {
instCtx.addError(FHIRValidationError(missing: "type"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.role?.decorate(json: &json, withKey: "role", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
if nil == self.type {
errors.append(FHIRValidationError(missing: "type"))
}
}
}
| 50.951923 | 179 | 0.739055 |
626e79953f53162c22508c02d212bc921356e946 | 2,997 | //
// File.swift
// Mocky
//
// Created by Andrzej Michnia on 28.09.2018.
// Copyright © 2018 MakeAWishFoundation. All rights reserved.
//
import Foundation
// MARK: - Issue 240 - generating mocks when attributes depends on generic constraints and other attributes associated types
protocol StringConvertibleType { }
//sourcery: AutoMockable
//sourcery: associatedtype = "ValueType: StringConvertibleType"
protocol ProtocolWithAssociatedType2 {
associatedtype ValueType: StringConvertibleType
var property: String { get }
}
//sourcery: AutoMockable
protocol AnotherProtocol {
func doSomething<T: ProtocolWithAssociatedType2>(type: T) -> T.ValueType?
func doSomething2<T: ProtocolWithAssociatedType2>(type: T, withValue: T.ValueType?)
}
// MARK: - Edge case for generics
struct Mytest<Key, Value> {
let value: Value
let key: Key
}
//sourcery: AutoMockable
protocol EdgeCasesGenericsProtocol {
func sorted<Key, Value>(by key: Mytest<Key, Value>)
func getter<K,V: Sequence,T: Equatable>(swapped key: Mytest<K,V>) -> T
}
// MARK: - Failing because of untagged attribute
//sourcery: AutoMockable
protocol FailsWithUntagged {
init<T>(with t: T) where T:Equatable
func foo<T>(_: T, bar : String) where T: Sequence // wrong formatted
}
// MARK: - Issue when names are escaped with backtick
//sourcery: AutoMockable
protocol FailsWithKeywordArguments {
func foo(for: String)
func `throw`(while: String) -> Error
func `return`(do while: String) -> Bool
var `throw`: Error { get set }
subscript (_ return: Int) -> Bool { get set }
}
// MARK: - Should allow no stub
//sourcery: AutoMockable
protocol ShouldAllowNoStubDefined {
static var property: Int? { get }
var property: Int? { get }
subscript (_ x: Int) -> Int? { get }
func voidMethod(_ key: String) -> Void
func throwingVoidMethod(_ key: String) throws -> Void
func optionalMethod(_ key: String) -> Int?
func optionalThrowingMethod(_ key: String) -> Int?
static func voidMethod(_ key: String) -> Void
static func throwingVoidMethod(_ key: String) throws -> Void
static func optionalMethod(_ key: String) -> Int?
static func optionalThrowingMethod(_ key: String) -> Int?
}
// MARK: - Autoclosure issues
//sourcery: AutoMockable
protocol FailsWithAutoClosureOnSwift5 {
func connect(_ token: @autoclosure () -> String) -> Bool
}
// MARK: - Generics with Self
//sourcery: AutoMockable
protocol FailsWithReturnedTypeBeingGenericOfSelf: AnyObject {
func methodWillReturnSelfTypedArray() -> Array<Self>
func methodWillReturnSelfTypedArray2() -> [Self]
func methodWillReturnSelfTypedCustom() -> CustomGeneric<Self>
func test(value: Self) -> Bool
func insanetTest(value: CustomGeneric<[Self]>) -> Bool
}
struct CustomGeneric<T> {
let t: T
}
//sourcery: typealias = "A = WithConflictingName.A"
protocol WithConflictingName: AutoMockable {
typealias A = Int
func test(with attribute: A) -> Bool
}
| 28.273585 | 124 | 0.712379 |
e206fb7cbb5986f7ed9e15d84d739ef2a3a93cf3 | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( [ 1
protocol A {
func a
protocol a {
protocol A : A
{
func d
protocol A : d
}
{
}
typealias b : A
| 15.823529 | 87 | 0.710037 |
1c999972dfecb5cc4f7a6d2d9e18eb7178206830 | 568 | //
// ActivityIndicator.swift
// Al Quran (iOS)
//
// Created by Asim Khan on 25/09/2021.
//
import UIKit
import SwiftUI
struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool
func makeUIView(context: Context) -> UIActivityIndicatorView {
let v = UIActivityIndicatorView()
return v
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {
if isAnimating {
uiView.startAnimating()
} else {
uiView.stopAnimating()
}
}
}
| 20.285714 | 76 | 0.617958 |
29439c3dc99c5c31070a829443bcba5568dfffff | 4,109 | //
// PaidMessageSentTableViewCell.swift
// sphinx
//
// Created by Tomas Timinskas on 17/04/2020.
// Copyright © 2020 Sphinx. All rights reserved.
//
import UIKit
class PaidMessageSentTableViewCell: CommonPaidMessageTableViewCell, MessageRowProtocol {
@IBOutlet weak var seenSign: UILabel!
@IBOutlet weak var errorContainer: UIView!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var attachmentPriceView: AttachmentPriceView!
@IBOutlet weak var bubbleWidth: NSLayoutConstraint!
public static let kMinimumWidth:CGFloat = 200
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func configureMessageRow(messageRow: TransactionMessageRow, contact: UserContact?, chat: Chat?) {
super.configureMessageRow(messageRow: messageRow, contact: contact, chat: chat)
commonConfigurationForMessages()
configurePrice(messageRow: messageRow)
if messageRow.shouldShowRightLine {
addRightLine()
}
if messageRow.shouldShowLeftLine {
addLeftLine()
}
}
func configurePrice(messageRow: TransactionMessageRow) {
let price = messageRow.transactionMessage.getAttachmentPrice() ?? 0
let statusAttributes = messageRow.transactionMessage.getPurchaseStatusLabel(queryDB: false)
attachmentPriceView.configure(price: price, status: statusAttributes, forceShow: true)
}
override func showBubble(messageRow: TransactionMessageRow, error: Bool = false) {
let minimumWidth:CGFloat = PaidMessageSentTableViewCell.kMinimumWidth
let (label, bubbleSize) = bubbleView.showOutgoingMessageBubble(messageRow: messageRow, minimumWidth: minimumWidth)
setBubbleWidth(bubbleSize: bubbleSize)
configureReplyBubble(bubbleView: bubbleView, bubbleSize: bubbleSize, incoming: false)
addLinksOnLabel(label: label)
configureMessageStatus(bubbleSize: bubbleSize)
}
func setBubbleWidth(bubbleSize: CGSize) {
bubbleWidth.constant = bubbleSize.width
bubbleView.superview?.layoutIfNeeded()
bubbleView.layoutIfNeeded()
}
func configureMessageStatus(bubbleSize: CGSize) {
guard let messageRow = messageRow else {
return
}
let received = messageRow.transactionMessage.received()
let failed = messageRow.transactionMessage.failed()
let encrypted = messageRow.encrypted
errorMessageLabel.text = "message.failed".localized
seenSign.alpha = received ? 1.0 : 0.0
lockSign.text = (encrypted && !failed) ? "lock" : ""
errorContainer.alpha = failed ? 1.0 : 0.0
errorContainer.layoutIfNeeded()
let shouldShowMessage = bubbleSize.width + MessageBubbleView.kBubbleSentRightMargin - errorContainer.frame.width > 75
errorMessageLabel.alpha = shouldShowMessage ? 1.0 : 0.0
}
public static func getBubbleSize(messageRow: TransactionMessageRow) -> CGSize {
let minimumWidth:CGFloat = PaidMessageSentTableViewCell.kMinimumWidth
let bubbleMaxWidth = CommonBubbleView.getBubbleMaxWidth(message: messageRow.transactionMessage)
return CommonPaidMessageTableViewCell.getBubbleSize(messageRow: messageRow, minimumWidth: minimumWidth, maxWidth: bubbleMaxWidth)
}
public static func getRowHeight(messageRow: TransactionMessageRow) -> CGFloat {
let bubbleSize = getBubbleSize(messageRow: messageRow)
let replyTopPading = CommonChatTableViewCell.getReplyTopPadding(message: messageRow.transactionMessage)
let rowHeight = bubbleSize.height + CommonChatTableViewCell.kBubbleTopMargin + CommonChatTableViewCell.kBubbleBottomMargin + Constants.kPaidMessageTopPadding + replyTopPading
let linksHeight = CommonChatTableViewCell.getLinkPreviewHeight(messageRow: messageRow)
return rowHeight + linksHeight
}
}
| 41.09 | 182 | 0.716719 |
395cdb144953055f6819b137dd74eb1d01a9490b | 19,243 | import Foundation
import MapboxDirections
import Turf
#if canImport(CarPlay)
import CarPlay
#endif
/**
`RouteProgress` stores the user’s progress along a route.
*/
@objc(MBRouteProgress)
open class RouteProgress: NSObject {
private static let reroutingAccuracy: CLLocationAccuracy = 90
/**
Returns the current `Route`.
*/
@objc public let route: Route
/**
Index representing current `RouteLeg`.
*/
@objc public var legIndex: Int {
didSet {
assert(legIndex >= 0 && legIndex < route.legs.endIndex)
// TODO: Set stepIndex to 0 or last index based on whether leg index was incremented or decremented.
currentLegProgress = RouteLegProgress(leg: currentLeg)
}
}
/**
If waypoints are provided in the `Route`, this will contain which leg the user is on.
*/
@objc public var currentLeg: RouteLeg {
return route.legs[legIndex]
}
/**
Returns true if `currentLeg` is the last leg.
*/
public var isFinalLeg: Bool {
guard let lastLeg = route.legs.last else { return false }
return currentLeg == lastLeg
}
/**
Total distance traveled by user along all legs.
*/
@objc public var distanceTraveled: CLLocationDistance {
return route.legs.prefix(upTo: legIndex).map { $0.distance }.reduce(0, +) + currentLegProgress.distanceTraveled
}
/**
Total seconds remaining on all legs.
*/
@objc public var durationRemaining: TimeInterval {
return route.legs.suffix(from: legIndex + 1).map { $0.expectedTravelTime }.reduce(0, +) + currentLegProgress.durationRemaining
}
/**
Number between 0 and 1 representing how far along the `Route` the user has traveled.
*/
@objc public var fractionTraveled: Double {
return distanceTraveled / route.distance
}
/**
Total distance remaining in meters along route.
*/
@objc public var distanceRemaining: CLLocationDistance {
return route.distance - distanceTraveled
}
/**
Number of waypoints remaining on the current route.
*/
@objc public var remainingWaypoints: [Waypoint] {
return route.legs.suffix(from: legIndex).map { $0.destination }
}
/**
Returns the progress along the current `RouteLeg`.
*/
@objc public var currentLegProgress: RouteLegProgress
/**
Tuple containing a `CongestionLevel` and a corresponding `TimeInterval` representing the expected travel time for this segment.
*/
public typealias TimedCongestionLevel = (CongestionLevel, TimeInterval)
/**
If the route contains both `segmentCongestionLevels` and `expectedSegmentTravelTimes`, this property is set to a deeply nested array of `TimeCongestionLevels` per segment per step per leg.
*/
public var congestionTravelTimesSegmentsByStep: [[[TimedCongestionLevel]]] = []
/**
An dictionary containing a `TimeInterval` total per `CongestionLevel`. Only `CongestionLevel` founnd on that step will present. Broken up by leg and then step.
*/
public var congestionTimesPerStep: [[[CongestionLevel: TimeInterval]]] = [[[:]]]
/**
Intializes a new `RouteProgress`.
- parameter route: The route to follow.
- parameter legIndex: Zero-based index indicating the current leg the user is on.
*/
@objc public init(route: Route, legIndex: Int = 0, spokenInstructionIndex: Int = 0) {
self.route = route
self.legIndex = legIndex
self.currentLegProgress = RouteLegProgress(leg: route.legs[legIndex], stepIndex: 0, spokenInstructionIndex: spokenInstructionIndex)
super.init()
for (legIndex, leg) in route.legs.enumerated() {
var maneuverCoordinateIndex = 0
congestionTimesPerStep.append([])
/// An index into the route’s coordinates and congestionTravelTimesSegmentsByStep that corresponds to a step’s maneuver location.
var congestionTravelTimesSegmentsByLeg: [[TimedCongestionLevel]] = []
if let segmentCongestionLevels = leg.segmentCongestionLevels, let expectedSegmentTravelTimes = leg.expectedSegmentTravelTimes {
for step in leg.steps {
guard let coordinates = step.coordinates else { continue }
let stepCoordinateCount = step.maneuverType == .arrive ? Int(step.coordinateCount) : coordinates.dropLast().count
let nextManeuverCoordinateIndex = maneuverCoordinateIndex + stepCoordinateCount - 1
guard nextManeuverCoordinateIndex < segmentCongestionLevels.count else { continue }
guard nextManeuverCoordinateIndex < expectedSegmentTravelTimes.count else { continue }
let stepSegmentCongestionLevels = Array(segmentCongestionLevels[maneuverCoordinateIndex..<nextManeuverCoordinateIndex])
let stepSegmentTravelTimes = Array(expectedSegmentTravelTimes[maneuverCoordinateIndex..<nextManeuverCoordinateIndex])
maneuverCoordinateIndex = nextManeuverCoordinateIndex
let stepTimedCongestionLevels = Array(zip(stepSegmentCongestionLevels, stepSegmentTravelTimes))
congestionTravelTimesSegmentsByLeg.append(stepTimedCongestionLevels)
var stepCongestionValues: [CongestionLevel: TimeInterval] = [:]
for (segmentCongestion, segmentTime) in stepTimedCongestionLevels {
stepCongestionValues[segmentCongestion] = (stepCongestionValues[segmentCongestion] ?? 0) + segmentTime
}
congestionTimesPerStep[legIndex].append(stepCongestionValues)
}
}
congestionTravelTimesSegmentsByStep.append(congestionTravelTimesSegmentsByLeg)
}
}
public var averageCongestionLevelRemainingOnLeg: CongestionLevel? {
let coordinatesLeftOnStepCount = Int(floor((Double(currentLegProgress.currentStepProgress.step.coordinateCount)) * currentLegProgress.currentStepProgress.fractionTraveled))
guard coordinatesLeftOnStepCount >= 0 else { return .unknown }
guard legIndex < congestionTravelTimesSegmentsByStep.count,
currentLegProgress.stepIndex < congestionTravelTimesSegmentsByStep[legIndex].count else { return .unknown }
let congestionTimesForStep = congestionTravelTimesSegmentsByStep[legIndex][currentLegProgress.stepIndex]
guard coordinatesLeftOnStepCount <= congestionTimesForStep.count else { return .unknown }
let remainingCongestionTimesForStep = congestionTimesForStep.suffix(from: coordinatesLeftOnStepCount)
let remainingCongestionTimesForRoute = congestionTimesPerStep[legIndex].suffix(from: currentLegProgress.stepIndex + 1)
var remainingStepCongestionTotals: [CongestionLevel: TimeInterval] = [:]
for stepValues in remainingCongestionTimesForRoute {
for (key, value) in stepValues {
remainingStepCongestionTotals[key] = (remainingStepCongestionTotals[key] ?? 0) + value
}
}
for (segmentCongestion, segmentTime) in remainingCongestionTimesForStep {
remainingStepCongestionTotals[segmentCongestion] = (remainingStepCongestionTotals[segmentCongestion] ?? 0) + segmentTime
}
if durationRemaining < 60 {
return .unknown
} else {
if let max = remainingStepCongestionTotals.max(by: { a, b in a.value < b.value }) {
return max.key
} else {
return .unknown
}
}
}
func reroutingOptions(with current: CLLocation) -> RouteOptions {
let oldOptions = route.routeOptions
let user = Waypoint(coordinate: current.coordinate)
if (current.course >= 0) {
user.heading = current.course
user.headingAccuracy = RouteProgress.reroutingAccuracy
}
let newWaypoints = [user] + remainingWaypoints
let newOptions = oldOptions.copy() as! RouteOptions
newOptions.waypoints = newWaypoints
return newOptions
}
}
/**
`RouteLegProgress` stores the user’s progress along a route leg.
*/
@objc(MBRouteLegProgress)
open class RouteLegProgress: NSObject {
/**
Returns the current `RouteLeg`.
*/
@objc public let leg: RouteLeg
/**
Index representing the current step.
*/
@objc public var stepIndex: Int {
didSet {
assert(stepIndex >= 0 && stepIndex < leg.steps.endIndex)
currentStepProgress = RouteStepProgress(step: currentStep)
}
}
/**
The remaining steps for user to complete.
*/
@objc public var remainingSteps: [RouteStep] {
return Array(leg.steps.suffix(from: stepIndex + 1))
}
/**
Total distance traveled in meters along current leg.
*/
@objc public var distanceTraveled: CLLocationDistance {
return leg.steps.prefix(upTo: stepIndex).map { $0.distance }.reduce(0, +) + currentStepProgress.distanceTraveled
}
/**
Duration remaining in seconds on current leg.
*/
@objc public var durationRemaining: TimeInterval {
return remainingSteps.map { $0.expectedTravelTime }.reduce(0, +) + currentStepProgress.durationRemaining
}
/**
Distance remaining on the current leg.
*/
@objc public var distanceRemaining: CLLocationDistance {
return remainingSteps.map { $0.distance }.reduce(0, +) + currentStepProgress.distanceRemaining
}
/**
Number between 0 and 1 representing how far along the current leg the user has traveled.
*/
@objc public var fractionTraveled: Double {
return distanceTraveled / leg.distance
}
@objc public var userHasArrivedAtWaypoint = false
/**
Returns the `RouteStep` before a given step. Returns `nil` if there is no step prior.
*/
@objc public func stepBefore(_ step: RouteStep) -> RouteStep? {
guard let index = leg.steps.index(of: step) else {
return nil
}
if index > 0 {
return leg.steps[index-1]
}
return nil
}
/**
Returns the `RouteStep` after a given step. Returns `nil` if there is not a step after.
*/
@objc public func stepAfter(_ step: RouteStep) -> RouteStep? {
guard let index = leg.steps.index(of: step) else {
return nil
}
if index+1 < leg.steps.endIndex {
return leg.steps[index+1]
}
return nil
}
/**
Returns the `RouteStep` before the current step.
If there is no `priorStep`, nil is returned.
*/
@objc public var priorStep: RouteStep? {
guard stepIndex - 1 >= 0 else {
return nil
}
return leg.steps[stepIndex - 1]
}
/**
Returns the current `RouteStep` for the leg the user is on.
*/
@objc public var currentStep: RouteStep {
return leg.steps[stepIndex]
}
/**
Returns the upcoming `RouteStep`.
If there is no `upcomingStep`, nil is returned.
*/
@objc public var upComingStep: RouteStep? {
guard stepIndex + 1 < leg.steps.endIndex else {
return nil
}
return leg.steps[stepIndex + 1]
}
/**
Returns step 2 steps ahead.
If there is no `followOnStep`, nil is returned.
*/
@objc public var followOnStep: RouteStep? {
guard stepIndex + 2 < leg.steps.endIndex else {
return nil
}
return leg.steps[stepIndex + 2]
}
/**
Return bool whether step provided is the current `RouteStep` the user is on.
*/
@objc public func isCurrentStep(_ step: RouteStep) -> Bool {
return step == currentStep
}
/**
Returns the progress along the current `RouteStep`.
*/
@objc public var currentStepProgress: RouteStepProgress
/**
Intializes a new `RouteLegProgress`.
- parameter leg: Leg on a `Route`.
- parameter stepIndex: Current step the user is on.
*/
@objc public init(leg: RouteLeg, stepIndex: Int = 0, spokenInstructionIndex: Int = 0) {
self.leg = leg
self.stepIndex = stepIndex
currentStepProgress = RouteStepProgress(step: leg.steps[stepIndex], spokenInstructionIndex: spokenInstructionIndex)
}
/**
Returns an array of `CLLocationCoordinate2D` of the prior, current and upcoming step geometry.
*/
@objc public var nearbyCoordinates: [CLLocationCoordinate2D] {
let priorCoords = priorStep?.coordinates ?? []
let upcomingCoords = upComingStep?.coordinates ?? []
let currentCoords = currentStep.coordinates ?? []
let nearby = priorCoords + currentCoords + upcomingCoords
assert(!nearby.isEmpty, "Step must have coordinates")
return nearby
}
typealias StepIndexDistance = (index: Int, distance: CLLocationDistance)
func closestStep(to coordinate: CLLocationCoordinate2D) -> StepIndexDistance? {
var currentClosest: StepIndexDistance?
let remainingSteps = leg.steps.suffix(from: stepIndex)
for (currentStepIndex, step) in remainingSteps.enumerated() {
guard let coords = step.coordinates else { continue }
guard let closestCoordOnStep = Polyline(coords).closestCoordinate(to: coordinate) else { continue }
let foundIndex = currentStepIndex + stepIndex
// First time around, currentClosest will be `nil`.
guard let currentClosestDistance = currentClosest?.distance else {
currentClosest = (index: foundIndex, distance: closestCoordOnStep.distance)
continue
}
if closestCoordOnStep.distance < currentClosestDistance {
currentClosest = (index: foundIndex, distance: closestCoordOnStep.distance)
}
}
return currentClosest
}
}
/**
`RouteStepProgress` stores the user’s progress along a route step.
*/
@objc(MBRouteStepProgress)
open class RouteStepProgress: NSObject {
/**
Returns the current `RouteStep`.
*/
@objc public let step: RouteStep
/**
Returns distance user has traveled along current step.
*/
@objc public var distanceTraveled: CLLocationDistance = 0
/**
Returns distance from user to end of step.
*/
@objc public var userDistanceToManeuverLocation: CLLocationDistance = Double.infinity
/**
Total distance in meters remaining on current step.
*/
@objc public var distanceRemaining: CLLocationDistance {
return step.distance - distanceTraveled
}
/**
Number between 0 and 1 representing fraction of current step traveled.
*/
@objc public var fractionTraveled: Double {
guard step.distance > 0 else { return 1 }
return distanceTraveled / step.distance
}
/**
Number of seconds remaining on current step.
*/
@objc public var durationRemaining: TimeInterval {
return (1 - fractionTraveled) * step.expectedTravelTime
}
/**
Intializes a new `RouteStepProgress`.
- parameter step: Step on a `RouteLeg`.
*/
@objc public init(step: RouteStep, spokenInstructionIndex: Int = 0) {
self.step = step
self.intersectionIndex = 0
self.spokenInstructionIndex = spokenInstructionIndex
}
/**
All intersections on the current `RouteStep` and also the first intersection on the upcoming `RouteStep`.
The upcoming `RouteStep` first `Intersection` is added because it is omitted from the current step.
*/
@objc public var intersectionsIncludingUpcomingManeuverIntersection: [Intersection]?
/**
The next intersection the user will travel through.
The step must contain `intersectionsIncludingUpcomingManeuverIntersection` otherwise this property will be `nil`.
*/
@objc public var upcomingIntersection: Intersection? {
guard let intersections = intersectionsIncludingUpcomingManeuverIntersection, intersections.startIndex..<intersections.endIndex-1 ~= intersectionIndex else {
return nil
}
return intersections[intersections.index(after: intersectionIndex)]
}
/**
Index representing the current intersection.
*/
@objc public var intersectionIndex: Int = 0
/**
The current intersection the user will travel through.
The step must contain `intersectionsIncludingUpcomingManeuverIntersection` otherwise this property will be `nil`.
*/
@objc public var currentIntersection: Intersection? {
guard let intersections = intersectionsIncludingUpcomingManeuverIntersection, intersections.startIndex..<intersections.endIndex ~= intersectionIndex else {
return nil
}
return intersections[intersectionIndex]
}
/**
Returns an array of the calculated distances from the current intersection to the next intersection on the current step.
*/
@objc public var intersectionDistances: Array<CLLocationDistance>?
/**
The distance in meters the user is to the next intersection they will pass through.
*/
public var userDistanceToUpcomingIntersection: CLLocationDistance?
/**
Index into `step.instructionsDisplayedAlongStep` representing the current visual instruction for the step.
*/
@objc public var visualInstructionIndex: Int = 0
/**
An `Array` of remaining `VisualInstruction` for a step.
*/
@objc public var remainingVisualInstructions: [VisualInstructionBanner]? {
guard let visualInstructions = step.instructionsDisplayedAlongStep else { return nil }
return Array(visualInstructions.suffix(from: visualInstructionIndex))
}
/**
Index into `step.instructionsSpokenAlongStep` representing the current spoken instruction.
*/
@objc public var spokenInstructionIndex: Int = 0
/**
An `Array` of remaining `SpokenInstruction` for a step.
*/
@objc public var remainingSpokenInstructions: [SpokenInstruction]? {
guard let instructions = step.instructionsSpokenAlongStep else { return nil }
return Array(instructions.suffix(from: spokenInstructionIndex))
}
/**
Current spoken instruction for the user's progress along a step.
*/
@objc public var currentSpokenInstruction: SpokenInstruction? {
guard let instructionsSpokenAlongStep = step.instructionsSpokenAlongStep else { return nil }
guard spokenInstructionIndex < instructionsSpokenAlongStep.count else { return nil }
return instructionsSpokenAlongStep[spokenInstructionIndex]
}
/**
Current visual instruction for the user's progress along a step.
*/
@objc public var currentVisualInstruction: VisualInstructionBanner? {
guard let instructionsDisplayedAlongStep = step.instructionsDisplayedAlongStep else { return nil }
guard visualInstructionIndex < instructionsDisplayedAlongStep.count else { return nil }
return instructionsDisplayedAlongStep[visualInstructionIndex]
}
}
| 35.834264 | 193 | 0.669906 |
1822f90ec66ec709e9cf26e55583c3f1380430f5 | 3,787 | /**
Attempt to transform `Any` into a `Decodable` value.
This function takes `Any` (usually the output from
`NSJSONSerialization`) and attempts to transform it into a `Decodable` value.
This works based on the type you ask for.
For example, the following code attempts to decode to `Decoded<String>`,
because that's what we have explicitly stated is the return type:
```
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: nil)
let str: Decoded<String> = decode(object)
} catch {
// handle error
}
```
- parameter object: The `Any` instance to attempt to decode
- returns: A `Decoded<T>` value where `T` is `Decodable`
*/
public func decode<T: Decodable>(_ object: Any) -> Decoded<T> where T == T.DecodedType {
return T.decode(JSON(object))
}
/**
Attempt to transform `Any` into a `Decodable` value and return an `Optional`.
This function takes `Any` (usually the output from
`NSJSONSerialization`) and attempts to transform it into a `Decodable` value,
returning an `Optional`. This works based on the type you ask for.
For example, the following code attempts to decode to `Optional<String>`,
because that's what we have explicitly stated is the return type:
```
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: nil)
let str: String? = decode(object)
} catch {
// handle error
}
```
- parameter object: The `Any` instance to attempt to decode
- returns: An `Optional<T>` value where `T` is `Decodable`
*/
public func decode<T: Decodable>(_ object: Any) -> T? where T == T.DecodedType {
return decode(object).value
}
/**
Attempt to transform `Any` into a `Decodable` value using a specified
root key.
This function attempts to extract the embedded `JSON` object from the
dictionary at the specified key and transform it into a `Decodable` value.
This works based on the type you ask for.
For example, the following code attempts to decode to `Decoded<String>`,
because that's what we have explicitly stated is the return type:
```
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data, options: nil) as? [String: Any] ?? [:]
let str: Decoded<String> = decode(dict, rootKey: "value")
} catch {
// handle error
}
```
- parameter dict: The dictionary containing the `Any` instance to
attempt to decode
- parameter rootKey: The root key that contains the object to decode
- returns: A `Decoded<T>` value where `T` is `Decodable`
*/
public func decode<T: Decodable>(_ dict: [String: Any], rootKey: String) -> Decoded<T> where T == T.DecodedType {
return JSON(dict as Any)[rootKey]
}
/**
Attempt to transform `Any` into a `Decodable` value using a specified
root key and return an `Optional`.
This function attempts to extract the embedded `JSON` object from the
dictionary at the specified key and transform it into a `Decodable` value,
returning an `Optional`. This works based on the type you ask for.
For example, the following code attempts to decode to `Optional<String>`,
because that's what we have explicitly stated is the return type:
```
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data, options: nil) as? [String: Any] ?? [:]
let str: String? = decode(dict, rootKey: "value")
} catch {
// handle error
}
```
- parameter dict: The dictionary containing the `Any` instance to
attempt to decode
- parameter rootKey: The root key that contains the object to decode
- returns: A `Decoded<T>` value where `T` is `Decodable`
*/
public func decode<T: Decodable>(_ dict: [String: Any], rootKey: String) -> T? where T == T.DecodedType {
return decode(dict, rootKey: rootKey).value
}
| 33.219298 | 113 | 0.693161 |
e818b72b70b862d4cf6c5c3eb989e1bb1b6e25df | 2,295 | //
// TableViewDataSourceWithoutNib.swift
// AnotaAi
//
// Created by Vinicius Galhardo Machado on 23/01/22.
//
import Foundation
import UIKit
import Reusable
public class TableViewDataSourceWithoutNib: NSObject, UITableViewDataSource, UITableViewDelegate {
public weak var scrollDelegate: UIScrollViewDelegate?
public var tableView: UITableView? {
didSet {
tableView?.delegate = self
tableView?.dataSource = self
register()
}
}
public var sections: [TableSectionWithoutNibProtocol] = [] {
didSet {
tableView?.reloadData()
register()
}
}
private func register() {
for section in sections {
section.registerCell(tableView: tableView)
}
}
// MARK: - TableView
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].itemsCount
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = sections[indexPath.section]
let cell = tableView.dequeueReusableCell(for: indexPath, cellType: section.cellType)
section.bindCell(cell: cell, at: indexPath.row)
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
sections[indexPath.section].didSelectAt(row: indexPath.row)
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidScroll?(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollDelegate?.scrollViewDidEndDecelerating?(scrollView)
}
}
| 30.197368 | 110 | 0.66841 |
2273ac78065fc0643b2f61c6e97cd3093ebb64bf | 1,524 | /*
-----------------------------------------------------------------------------
This source file is part of MedKitAssignedNumbers.
Copyright 2018 Jon Griffeth
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 MedKitAssignedNumbers
/**
Placeholder
*/
class PatientInfoV1Generator {
typealias Value = PatientInfoV1
typealias Iterator = AnyIterator<Value>
private var count: Int = 0
init()
{
}
func iterator() -> Iterator
{
return Iterator { self.next() }
}
private func next() -> Value?
{
var value: Value!
count += 1;
if (count == 1) {
var name = NameV1()
let photo = ImageV1(named: "Doe, John")
name.first = "John"
name.last = "Doe"
value = PatientInfoV1(identifier: "ID1", name: name)
value.photo = photo
}
return value
}
}
// End of File
| 22.411765 | 78 | 0.573491 |
26919034a3a1ab1bb5c491190ace281f381c746d | 1,523 | //
// AppDelegate.swift
// Lumpen Radio
//
// Created by Anthony on 10/20/19.
// Copyright © 2019 Public Media Institute. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// For non-SwiftUI
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// SwiftUI - iOS 13+
// 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.
}
*/
}
| 35.418605 | 179 | 0.728168 |
09782b21bb056f3a02e0e11fe593bca15882e2d9 | 2,301 | //
// WOWLeaderboard.swift
// BattleNetAPI
//
// Created by Christopher Jennewein on 4/22/18.
// Copyright © 2018 Prismatic Games. All rights reserved.
//
import Foundation
public class WOWLeaderboard: Codable {
public let rows: [WOWLeaderboardEntry]
}
public enum WOWLeaderboardBracket: String {
case _2v2 = "2v2"
case _3v3 = "3v3"
case _5v5 = "5v5"
case rbg
}
public class WOWLeaderboardEntry: Codable {
public let ranking: Int
public let rating: Int
public let name: String
public let realmID: Int
public let realmName: String
public let realmSlug: String
public let raceID: Int
public let classID: Int
public let specID: Int
public let factionID: Int
public let genderID: Int
public let seasonWins: Int
public let seasonLosses: Int
public let weeklyWins: Int
public let weeklyLosses: Int
enum CodingKeys: String, CodingKey {
case ranking
case rating
case name
case realmID = "realmId"
case realmName
case realmSlug
case raceID = "raceId"
case classID = "classId"
case specID = "specId"
case factionID = "factionId"
case genderID = "genderId"
case seasonWins
case seasonLosses
case weeklyWins
case weeklyLosses
}
}
public class WOWPVP: Codable {
public let brackets: WOWBrackets
}
public class WOWBrackets: Codable {
public let arenaBracket2V2: WOWArenaBracket
public let arenaBracket2V2Skirmish: WOWArenaBracket
public let arenaBracket3V3: WOWArenaBracket
public let arenaBracketRbg: WOWArenaBracket
public let unknown: WOWArenaBracket
enum CodingKeys: String, CodingKey {
case arenaBracket3V3 = "ARENA_BRACKET_3v3"
case arenaBracketRbg = "ARENA_BRACKET_RBG"
case arenaBracket2V2Skirmish = "ARENA_BRACKET_2v2_SKIRMISH"
case arenaBracket2V2 = "ARENA_BRACKET_2v2"
case unknown = "UNKNOWN"
}
}
public class WOWArenaBracket: Codable {
public let slug: String
public let rating: Int
public let weeklyWon: Int
public let weeklyLost: Int
public let weeklyPlayed: Int
public let seasonWon: Int
public let seasonLost: Int
public let seasonPlayed: Int
}
| 23.01 | 67 | 0.677097 |
9b0229da9f0917e235d71f9ec0a4a7cd7020f5bb | 2,171 | //
// TokenView.swift
// GoCard
//
// Created by ナム Nam Nguyen on 3/16/17.
// Copyright © 2017 GoCard, Ltd. All rights reserved.
//
import UIKit
class TokenView: UIView {
@IBOutlet weak var backButton: UIButton?
@IBOutlet weak var backgroundView: UIView?
@IBOutlet weak var tokenView: UILabel?
@IBOutlet weak var copyButton: UIButton?
@IBOutlet weak var sendButton: UIButton?
@IBOutlet var otpMethods: [OTPAppSelectionControl]?
@IBOutlet weak var title:UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
title.characterSpacing(1.27, lineHeight: 16, withFont: UIFont.boldRoboto(size:14))
backgroundView?.round(6)
backButton?.round()
backButton?.characterSpacing(1.5, lineHeight: 16, withFont: UIFont.boldRoboto(size:14))
tokenView?.round()
copyButton?.round()
sendButton?.round()
otpMethods?.sort(by:{ return $0.tag < $1.tag })
otpMethods?.forEach {
$0.round(5)
$0.addTarget(self, action: #selector(didTouchMethod(_:)), for: UIControlEvents.touchUpInside)
}
}
@IBAction func didTouchMethod(_ sender: OTPAppSelectionControl) {
if !sender.isSelected { sender.isSelected.toggle() }
if sender.isSelected { otpMethods?.forEach { if $0 != sender { $0.isSelected = false } } }
}
@IBAction func didTouchCopy(_ sender: Any) {
UIPasteboard.general.string = tokenView?.text
}
@IBAction func didTouchSend(_ sender: Any) {
var hasMethodSelect = false
otpMethods?.forEach {
if $0.isSelected {
UIViewController.topViewController()?.showWaiting()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
UIViewController.topViewController()?.hideWaiting()
}
hasMethodSelect = true
}
}
if !hasMethodSelect {
print("Please select method first !")
}
}
@IBAction func didTouchBack(_ sender: Any) {
self.removeFromSuperview()
}
}
| 32.893939 | 105 | 0.613542 |
48564a15b47fafd044e6a3f0f84a4095a55b984c | 315 | //
// StaticGroup.swift
// KMART
//
// Created by Nindi Gill on 15/2/21.
//
import Foundation
struct StaticGroup: Codable {
var id: Int = -1
var name: String = ""
var devices: [Int] = []
var dictionary: [String: Any] {
[
"id": id,
"name": name
]
}
}
| 15 | 37 | 0.492063 |
ff84f6553dc6e173730627b8ab2587ee0908ffd6 | 4,206 | //
// PDFPaginationStyle_Spec.swift
// TPPDF_Tests
//
// Created by Philip Niedertscheider on 04/11/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import TPPDF
class PDFPaginationStyle_Spec: QuickSpec {
override func spec() {
describe("PDFPagiationStyle") {
context("default") {
let style = PDFPaginationStyle.default
it("can format a page number") {
expect(style.format(page: 2, total: 7)) == "2 - 7"
}
}
context("roman") {
let style = PDFPaginationStyle.roman(template: "%@ / %@")
it("can format a page number") {
expect(style.format(page: 2, total: 7)) == "II / VII"
}
}
context("customNumberFormat") {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
let style = PDFPaginationStyle.customNumberFormat(template: "%@ +++ %@", formatter: formatter)
it("can format a page number") {
let ds = Locale.current.decimalSeparator!
expect(style.format(page: 2, total: 7)) == "2\(ds)00 +++ 7\(ds)00"
}
}
context("customClosure") {
let style = PDFPaginationStyle.customClosure { (page, total) -> String in
return String(format: "%i - %i", page * page, 2 * total)
}
it("can format a page number") {
expect(style.format(page: 3, total: 7)) == "9 - 14"
}
}
context("equatable") {
it("can be equated when default") {
expect(PDFPaginationStyle.default == PDFPaginationStyle.default).to(beTrue())
}
it("can be equated when default") {
expect(PDFPaginationStyle.roman(template: "%@ - %@") == PDFPaginationStyle.roman(template: "%@ - %@")).to(beTrue())
expect(PDFPaginationStyle.roman(template: "%@ - %@") == PDFPaginationStyle.roman(template: "%@ / %@")).to(beFalse())
}
it("can be equated when default") {
let numberFormatter1 = NumberFormatter()
let numberFormatter2 = NumberFormatter()
let template1 = "%@ - %@"
let template2 = "%@ / %@"
expect(
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter1) ==
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter1)
).to(beTrue())
expect(
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter1) ==
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter2)
).to(beFalse())
expect(
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter1) ==
PDFPaginationStyle.customNumberFormat(template: template2, formatter: numberFormatter1)
).to(beFalse())
expect(
PDFPaginationStyle.customNumberFormat(template: template1, formatter: numberFormatter1) ==
PDFPaginationStyle.customNumberFormat(template: template2, formatter: numberFormatter2)
).to(beFalse())
}
it("can be equated when default") {
expect(PDFPaginationStyle.customClosure { (page, total) -> String in
return String(format: "%@ %@", page, total)
} == PDFPaginationStyle.customClosure { (page, total) -> String in
return String(format: "%@ %@", page, total)
}).to(beFalse())
}
}
}
}
}
| 38.944444 | 136 | 0.509272 |
e683b5c19a6e72de42301b08b45799cb2e0f7412 | 61,093 | //
// AppDelegate.swift
// Helium
//
// Created by Jaden Geller on 4/9/15.
// Copyright (c) 2015 Jaden Geller. All rights reserved.
// Copyright (c) 2017 Carlos D. Santiago. All rights reserved.
//
// We have user IBAction centrally here, share by panel and webView controllers
// The design is to centrally house the preferences and notify these interested
// parties via notification. In this way all menu state can be consistency for
// statusItem, main menu, and webView contextual menu.
//
import Cocoa
struct RequestUserStrings {
let currentURL: String?
let alertMessageText: String
let alertButton1stText: String
let alertButton1stInfo: String?
let alertButton2ndText: String
let alertButton2ndInfo: String?
let alertButton3rdText: String?
let alertButton3rdInfo: String?
}
fileprivate class SearchField : NSSearchField {
var title : String?
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
if let textEditor = currentEditor() {
textEditor.selectAll(self)
}
}
convenience init(withValue: String?, modalTitle: String?) {
self.init()
if let string = withValue {
self.stringValue = string
}
if let title = modalTitle {
self.title = title
}
else
{
self.title = (NSApp.delegate as! AppDelegate).title
}
if let cell : NSSearchFieldCell = self.cell as? NSSearchFieldCell {
cell.searchMenuTemplate = searchMenu()
cell.usesSingleLineMode = false
cell.wraps = true
cell.lineBreakMode = .byWordWrapping
cell.formatter = nil
cell.allowsEditingTextAttributes = false
}
(self.cell as! NSSearchFieldCell).searchMenuTemplate = searchMenu()
}
fileprivate func searchMenu() -> NSMenu {
let menu = NSMenu.init(title: "Search Menu")
var item : NSMenuItem
item = NSMenuItem.init(title: "Clear", action: nil, keyEquivalent: "")
item.tag = NSSearchFieldClearRecentsMenuItemTag
menu.addItem(item)
item = NSMenuItem.separator()
item.tag = NSSearchFieldRecentsTitleMenuItemTag
menu.addItem(item)
item = NSMenuItem.init(title: "Recent Searches", action: nil, keyEquivalent: "")
item.tag = NSSearchFieldRecentsTitleMenuItemTag
menu.addItem(item)
item = NSMenuItem.init(title: "Recent", action: nil, keyEquivalent: "")
item.tag = NSSearchFieldRecentsTitleMenuItemTag
menu.addItem(item)
item = NSMenuItem.init(title: "Recent Searches", action: nil, keyEquivalent: "")
item.tag = NSSearchFieldRecentsMenuItemTag
menu.addItem(item)
return menu
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let title = self.title {
self.window?.title = title
}
// MARK: this gets us focus even when modal
self.becomeFirstResponder()
}
}
fileprivate class URLField: NSTextField {
var title : String?
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
if let textEditor = currentEditor() {
textEditor.selectAll(self)
}
}
convenience init(withValue: String?, modalTitle: String?) {
self.init()
if let string = withValue {
self.stringValue = string
}
if let title = modalTitle {
self.title = title
}
else
{
let infoDictionary = (Bundle.main.infoDictionary)!
// Get the app name field
let appName = infoDictionary[kCFBundleExecutableKey as String] as? String ?? "Helium"
// Setup the version to one we constrict
self.title = String(format:"%@ %@", appName,
infoDictionary["CFBundleVersion"] as! CVarArg)
}
self.lineBreakMode = NSLineBreakMode.byTruncatingHead
self.usesSingleLineMode = true
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let title = self.title {
self.window?.title = title
}
// MARK: this gets us focus even when modal
self.becomeFirstResponder()
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
var os = ProcessInfo().operatingSystemVersion
@IBOutlet weak var magicURLMenu: NSMenuItem!
// MARK:- Global IBAction, but ship to keyWindow when able
@IBOutlet weak var appMenu: NSMenu!
var appStatusItem:NSStatusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
fileprivate var searchField : SearchField = SearchField.init(withValue: "Helium", modalTitle: "Search")
fileprivate var recentSearches = Array<String>()
var title : String {
get {
let infoDictionary = (Bundle.main.infoDictionary)!
// Get the app name field
let appName = infoDictionary[kCFBundleExecutableKey as String] as? String ?? "Helium"
// Setup the version to one we constrict
let title = String(format:"%@ %@", appName,
infoDictionary["CFBundleVersion"] as! CVarArg)
return title
}
}
internal func menuClicked(_ sender: AnyObject) {
if let menuItem = sender as? NSMenuItem {
Swift.print("Menu '\(menuItem.title)' clicked")
}
}
internal func syncAppMenuVisibility() {
if UserSettings.HideAppMenu.value {
NSStatusBar.system().removeStatusItem(appStatusItem)
}
else
{
appStatusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
appStatusItem.image = NSImage.init(named: "statusIcon")
let menu : NSMenu = appMenu.copy() as! NSMenu
// add quit to status menu only - already is in dock
let item = NSMenuItem(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "")
item.target = NSApp
menu.addItem(item)
appStatusItem.menu = menu
}
}
@IBAction func hideAppStatusItem(_ sender: NSMenuItem) {
UserSettings.HideAppMenu.value = (sender.state == NSOffState)
self.syncAppMenuVisibility()
}
@IBAction func homePagePress(_ sender: AnyObject) {
didRequestUserUrl(RequestUserStrings (
currentURL: UserSettings.homePageURL.value,
alertMessageText: "New home page",
alertButton1stText: "Set", alertButton1stInfo: nil,
alertButton2ndText: "Cancel", alertButton2ndInfo: nil,
alertButton3rdText: "Default", alertButton3rdInfo: UserSettings.homePageURL.default),
onWindow: NSApp.keyWindow as? HeliumPanel,
title: "Enter URL",
acceptHandler: { (newUrl: String) in
UserSettings.homePageURL.value = newUrl
}
)
}
// Complimented with createNewWindows to hold until really open
var openForBusiness = false
// By default we auto save any document changes
@IBAction func autoSaveDocsPress(_ sender: NSMenuItem) {
UserSettings.AutoSaveDocs.value = (sender.state == NSOffState)
// if turning on, then we save all documents manually
if autoSaveDocs {
for doc in NSDocumentController.shared().documents {
if let hwc = doc.windowControllers.first, hwc.isKind(of: HeliumPanelController.self) {
DispatchQueue.main.async {
(hwc as! HeliumPanelController).saveDocument(sender)
}
}
}
NSDocumentController.shared().saveAllDocuments(sender)
}
}
var autoSaveDocs : Bool {
get {
return UserSettings.AutoSaveDocs.value
}
}
@IBAction func createNewWindowPress(_ sender: NSMenuItem) {
UserSettings.createNewWindows.value = (sender.state == NSOnState ? false : true)
}
var fullScreen : NSRect? = nil
@IBAction func toggleFullScreen(_ sender: NSMenuItem) {
if let keyWindow = NSApp.keyWindow {
if let last_rect = fullScreen {
keyWindow.setFrame(last_rect, display: true, animate: true)
fullScreen = nil;
}
else
{
fullScreen = keyWindow.frame
keyWindow.setFrame(NSScreen.main()!.visibleFrame, display: true, animate: true)
}
}
}
@IBAction func magicURLRedirectPress(_ sender: NSMenuItem) {
UserSettings.disabledMagicURLs.value = (sender.state == NSOnState)
}
@IBAction func hideZoomIconPress(_ sender: NSMenuItem) {
UserSettings.HideZoomIcon.value = (sender.state == NSOffState)
// sync all document zoom icons now - yuck
for doc in NSDocumentController.shared().documents {
if let hwc = doc.windowControllers.first, hwc.isKind(of: HeliumPanelController.self) {
(hwc as! HeliumPanelController).zoomButton?.isHidden = hideZoomIcon
}
}
}
var hideZoomIcon : Bool {
get {
return UserSettings.HideZoomIcon.value
}
}
func doOpenFile(fileURL: URL, fromWindow: NSWindow? = nil) -> Bool {
let newWindows = UserSettings.createNewWindows.value
let dc = NSDocumentController.shared()
let fileType = fileURL.pathExtension
dc.noteNewRecentDocumentURL(fileURL)
if let thisWindow = fromWindow != nil ? fromWindow : NSApp.keyWindow {
guard (newWindows && openForBusiness) || (thisWindow.contentViewController?.isKind(of: PlaylistViewController.self))! else {
let hwc = fromWindow?.windowController
let doc = hwc?.document
// If it's a "h3w" type read it and load it into defaults
if let wvc = thisWindow.contentViewController as? WebViewController {
if fileType == "h3w" {
(doc as! Document).update(to: fileURL)
wvc.loadURL(url: (doc as! Document).fileURL!)
}
else
{
wvc.loadURL(url: fileURL)
}
return true
}
else
{
return false
}
}
}
// Open a new window
UserSettings.createNewWindows.value = false
var status = false
// This could be anything so add/if a doc and initialize
do {
let doc = try Document.init(contentsOf: fileURL)
if let hwc = (doc as NSDocument).windowControllers.first, let window = hwc.window {
window.offsetFromKeyWindow()
window.makeKey()
(hwc.contentViewController as! WebViewController).loadURL(url: fileURL)
status = true
}
} catch let error {
print("*** Error open file: \(error.localizedDescription)")
status = false
}
UserSettings.createNewWindows.value = newWindows
return status
}
@IBAction func newDocument(_ sender: Any) {
let dc = NSDocumentController.shared()
let doc = Document.init()
doc.makeWindowControllers()
dc.addDocument(doc)
let wc = doc.windowControllers.first
let window : NSPanel = wc!.window as! NSPanel as NSPanel
// Close down any observations before closure
window.delegate = wc as? NSWindowDelegate
doc.settings.rect.value = window.frame
// SHIFT key down creates new tabs as tag=1
if ((NSApp.currentEvent?.modifierFlags.contains(.shift))! || (sender as! NSMenuItem).tag == 1), let keyWindow = NSApp.keyWindow,
!(keyWindow.contentViewController?.isKind(of: AboutBoxController.self))! {
keyWindow.addTabbedWindow(window, ordered: .below)
}
else
{
window.makeKeyAndOrderFront(sender)
}
}
@IBAction func openDocument(_ sender: Any) {
self.openFilePress(sender as AnyObject)
}
@IBAction func openFilePress(_ sender: AnyObject) {
var openFilesInNewWindows : Bool = false
let open = NSOpenPanel()
open.allowsMultipleSelection = true
open.canChooseDirectories = false
open.resolvesAliases = true
open.canChooseFiles = true
// No window, so load panel modally
NSApp.activate(ignoringOtherApps: true)
if open.runModal() == NSModalResponseOK {
open.orderOut(sender)
let urls = open.urls
for url in urls {
if openFilesInNewWindows {
self.openURLInNewWindow(url)
}
else
{
_ = self.doOpenFile(fileURL: url)
}
// Multiple files implies new windows
openFilesInNewWindows = true
}
}
return
}
internal func openURLInNewWindow(_ newURL: URL) {
let newWindows = UserSettings.createNewWindows.value
UserSettings.createNewWindows.value = false
do {
let doc = try NSDocumentController.shared().openUntitledDocumentAndDisplay(true)
if let hpc = doc.windowControllers.first as? HeliumPanelController {
hpc.webViewController.loadURL(text: newURL.absoluteString)
}
} catch let error {
NSApp.presentError(error)
}
UserSettings.createNewWindows.value = newWindows
}
@IBAction func openURLInNewWindowPress(_ sender: NSMenuItem) {
if let newURL = sender.representedObject {
self.openURLInNewWindow(newURL as! URL)
}
}
@IBAction func openLocationPress(_ sender: AnyObject) {
// No window, so load alert modally
let rawString = NSPasteboard.general().string(forType: NSPasteboardTypeString)
let urlString = URL.init(string: rawString!)?.absoluteString ?? UserSettings.homePageURL.value
didRequestUserUrl(RequestUserStrings (
currentURL: urlString,
alertMessageText: "URL to load",
alertButton1stText: "Load", alertButton1stInfo: nil,
alertButton2ndText: "Cancel", alertButton2ndInfo: nil,
alertButton3rdText: "Home", alertButton3rdInfo: UserSettings.homePageURL.value),
onWindow: nil,
title: "Enter URL",
acceptHandler: { (newUrl: String) in
self.openURLInNewWindow(URL.init(string: newUrl)!)
})
}
@IBAction func openSearchPress(_ sender: AnyObject) {
let name = k.searchNames[ UserSettings.Search.value ]
let info = k.searchInfos[ UserSettings.Search.value ]
// We have a window, create as sheet and load playlists there
guard let item: NSMenuItem = sender as? NSMenuItem, let window: NSWindow = item.representedObject as? NSWindow else {
// No window, so load alert modally
didRequestSearch(RequestUserStrings (
currentURL: nil,
alertMessageText: "Search",
alertButton1stText: name, alertButton1stInfo: info,
alertButton2ndText: "Cancel", alertButton2ndInfo: nil,
alertButton3rdText: nil, alertButton3rdInfo: nil),
onWindow: nil,
title: "Web Search",
acceptHandler: { (newWindow,searchURL: URL) in
self.openURLInNewWindow(searchURL)
})
return
}
if let wvc : WebViewController = window.contentViewController as? WebViewController {
didRequestSearch(RequestUserStrings (
currentURL: nil,
alertMessageText: "Search",
alertButton1stText: name, alertButton1stInfo: info,
alertButton2ndText: "Cancel", alertButton2ndInfo: nil,
alertButton3rdText: "New Window", alertButton3rdInfo: "Results in new window"),
onWindow: window as? HeliumPanel,
title: "Web Search",
acceptHandler: { (newWindow: Bool, searchURL: URL) in
if newWindow {
self.openURLInNewWindow(searchURL)
}
else
{
wvc.loadURL(url: searchURL)
}
})
}
}
@IBAction func pickSearchPress(_ sender: NSMenuItem) {
// This needs to match validateMenuItem below
let group = sender.tag / 100
let index = (sender.tag - (group * 100)) % 3
let key = String(format: "search%d", group)
defaults.set(index as Any, forKey: key)
// Swift.print("\(key) -> \(index)")
}
var playlistWindows = [NSWindow]()
@IBAction func presentPlaylistSheet(_ sender: Any) {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
// If we have a window, present a sheet with playlists, otherwise ...
guard let item: NSMenuItem = sender as? NSMenuItem, let window: NSWindow = item.representedObject as? NSWindow else {
// No window, load panel and its playlist controller
let ppc = storyboard.instantiateController(withIdentifier: "PlaylistPanelController") as! PlaylistPanelController
if let window = ppc.window {
NSApp.addWindowsItem(window, title: window.title, filename: false)
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(sender)
playlistWindows.append(ppc.window!)
window.center()
}
return
}
if let wvc = window.windowController?.contentViewController {
// We're already here so exit
if wvc.isKind(of: PlaylistViewController.self) {
return
}
// If a web view controller, fetch and present playlist here
if let wvc: WebViewController = wvc as? WebViewController {
if wvc.presentedViewControllers?.count == 0 {
let pvc = storyboard.instantiateController(withIdentifier: "PlaylistViewController") as! PlaylistViewController
pvc.webViewController = wvc
wvc.presentViewControllerAsSheet(pvc)
}
return
}
Swift.print("who are we? \(String(describing: window.contentViewController))")
}
}
@IBAction func showReleaseInfo(_ sender: Any) {
// Temporarily disable new windows as we'll create one now
let newWindows = UserSettings.createNewWindows.value
let urlString = UserSettings.releaseNotesURL.value
UserSettings.createNewWindows.value = false
do
{
let next = try NSDocumentController.shared().openUntitledDocumentAndDisplay(true) as! Document
next.docType = k.docRelease
let hwc = next.windowControllers.first?.window?.windowController
let relnotes = NSString.string(fromAsset: "RELEASE")
(hwc?.contentViewController as! WebViewController).webView.loadHTMLString(relnotes, baseURL: nil)
hwc?.window?.center()
}
catch let error {
NSApp.presentError(error)
Swift.print("Yoink, unable to load url (\(urlString))")
}
UserSettings.createNewWindows.value = newWindows
return
}
var canRedo : Bool {
if let redo = NSApp.keyWindow?.undoManager {
return redo.canRedo
}
else
{
return false
}
}
@IBAction func redo(_ sender: Any) {
if let window = NSApp.keyWindow, let undo = window.undoManager, undo.canRedo {
Swift.print("redo:");
}
}
var canUndo : Bool {
if let undo = NSApp.keyWindow?.undoManager {
return undo.canUndo
}
else
{
return false
}
}
@IBAction func undo(_ sender: Any) {
if let window = NSApp.keyWindow, let undo = window.undoManager, undo.canUndo {
Swift.print("undo:");
}
}
@IBAction func userAgentPress(_ sender: AnyObject) {
didRequestUserAgent(RequestUserStrings (
currentURL: UserSettings.userAgent.value,
alertMessageText: "New user agent",
alertButton1stText: "Set", alertButton1stInfo: nil,
alertButton2ndText: "Cancel", alertButton2ndInfo: nil,
alertButton3rdText: "Default", alertButton3rdInfo: UserSettings.userAgent.default),
onWindow: NSApp.keyWindow as? HeliumPanel,
title: "User Agent",
acceptHandler: { (newUserAgent: String) in
UserSettings.userAgent.value = newUserAgent
let notif = Notification(name: Notification.Name(rawValue: "HeliumNewUserAgentString"),
object: newUserAgent);
NotificationCenter.default.post(notif)
}
)
}
func modalOKCancel(_ message: String, info: String?) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = message
if info != nil {
alert.informativeText = info!
}
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
let response = alert.runModal()
switch response {
case NSAlertFirstButtonReturn:
return true
default:
return false
}
}
func sheetOKCancel(_ message: String, info: String?,
acceptHandler: @escaping (NSModalResponse) -> Void) {
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = message
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
if info != nil {
alert.informativeText = info!
}
if let window = NSApp.keyWindow {
alert.beginSheetModal(for: window, completionHandler: { response in
acceptHandler(response)
})
}
else
{
acceptHandler(alert.runModal())
}
alert.buttons.first!.becomeFirstResponder()
}
func userAlertMessage(_ message: String, info: String?) {
let alert = NSAlert()
alert.messageText = message
alert.addButton(withTitle: "OK")
if info != nil {
alert.informativeText = info!
}
if let window = NSApp.mainWindow {
alert.beginSheetModal(for: window, completionHandler: { response in
return
})
}
else
{
alert.runModal()
return
}
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.title.hasPrefix("Redo") {
menuItem.isEnabled = self.canRedo
}
else
if menuItem.title.hasPrefix("Undo") {
menuItem.isEnabled = self.canUndo
}
else
{
switch menuItem.title {
case k.bingName, k.googleName, k.yahooName:
let group = menuItem.tag / 100
let index = (menuItem.tag - (group * 100)) % 3
menuItem.state = UserSettings.Search.value == index ? NSOnState : NSOffState
break
case "Preferences":
break
case "Auto save documents":
menuItem.state = UserSettings.AutoSaveDocs.value ? NSOnState : NSOffState
break;
case "Create New Windows":
menuItem.state = UserSettings.createNewWindows.value ? NSOnState : NSOffState
break
case "Hide Helium in menu bar":
menuItem.state = UserSettings.HideAppMenu.value ? NSOnState : NSOffState
break
case "Hide zoom icon":
menuItem.state = UserSettings.HideZoomIcon.value ? NSOnState : NSOffState
break
case "Home Page":
break
case "Magic URL Redirects":
menuItem.state = UserSettings.disabledMagicURLs.value ? NSOffState : NSOnState
break
case "User Agent":
break
case "Quit":
break
default:
break
}
}
return true;
}
// MARK:- Lifecyle
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
// Now we're open for business
self.openForBusiness = true
let dc = NSDocumentController.shared()
return dc.documents.count == 0
}
func resetDefaults() {
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
}
let toHMS = hmsTransformer()
let rectToString = rectTransformer()
var launchedAsLogInItem : Bool = false
func applicationWillFinishLaunching(_ notification: Notification) {
let flags : NSEvent.ModifierFlags = NSEvent.ModifierFlags(rawValue: NSEvent.modifierFlags().rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue)
let event = NSAppleEventDescriptor.currentProcess()
// Wipe out defaults when OPTION+SHIFT is held down at startup
if flags.contains([.shift,.option]) {
Swift.print("shift+option at start")
resetDefaults()
NSSound(named: "Purr")?.play()
}
// We were started as a login item startup save this
launchedAsLogInItem = event.eventID == kAEOpenApplication &&
event.paramDescriptor(forKeyword: keyAEPropData)?.enumCodeValue == keyAELaunchedAsLogInItem
// We need our own to reopen our "document" urls
_ = HeliumDocumentController.init()
NSAppleEventManager.shared().setEventHandler(
self,
andSelector: #selector(AppDelegate.handleURLEvent(_:withReply:)),
forEventClass: AEEventClass(kInternetEventClass),
andEventID: AEEventID(kAEGetURL)
)
// So they can interact everywhere with us without focus
appStatusItem.image = NSImage.init(named: "statusIcon")
appStatusItem.menu = appMenu
// Initialize our h:m:s transformer
ValueTransformer.setValueTransformer(toHMS, forName: NSValueTransformerName(rawValue: "hmsTransformer"))
// Initialize our rect [point,size] transformer
ValueTransformer.setValueTransformer(rectToString, forName: NSValueTransformerName(rawValue: "rectTransformer"))
// Maintain a history of titles
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.haveNewTitle(_:)),
name: NSNotification.Name(rawValue: "HeliumNewURL"),
object: nil)
// Load sandbox bookmark url when necessary
if self.isSandboxed() != self.loadBookmarks() {
Swift.print("Yoink, unable to load bookmarks")
}
}
var itemActions = Dictionary<String, Any>()
// Keep playlist names unique by Array entension checking name
dynamic var playlists = [PlayList]()
dynamic var histories = [PlayItem]()
var defaults = UserDefaults.standard
var disableDocumentReOpening = false
var hiddenWindows = Dictionary<String, Any>()
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
let reopenMessage = disableDocumentReOpening ? "do not reopen doc(s)" : "reopen doc(s)"
let hasVisibleDocs = flag ? "has doc(s)" : "no doc(s)"
Swift.print("applicationShouldHandleReopen: \(reopenMessage) docs:\(hasVisibleDocs)")
return !disableDocumentReOpening
}
// Local/global event monitor: CTRL+OPTION+COMMAND to toggle windows' alpha / audio values
// https://stackoverflow.com/questions/41927843/global-modifier-key-press-detection-in-swift/41929189#41929189
var localKeyDownMonitor : Any? = nil
var globalKeyDownMonitor : Any? = nil
var shiftKeyDown : Bool = false {
didSet {
let notif = Notification(name: Notification.Name(rawValue: "shiftKeyDown"),
object: NSNumber(booleanLiteral: shiftKeyDown));
NotificationCenter.default.post(notif)
}
}
var commandKeyDown : Bool = false {
didSet {
let notif = Notification(name: Notification.Name(rawValue: "commandKeyDown"),
object: NSNumber(booleanLiteral: commandKeyDown))
NotificationCenter.default.post(notif)
}
}
func keyDownMonitor(event: NSEvent) -> Bool {
switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
case [.control, .option, .command]:
print("control-option-command keys are pressed")
if self.hiddenWindows.count > 0 {
// Swift.print("show all windows")
for frame in self.hiddenWindows.keys {
let dict = self.hiddenWindows[frame] as! Dictionary<String,Any>
let alpha = dict["alpha"]
let win = dict["window"] as! NSWindow
// Swift.print("show \(frame) to \(String(describing: alpha))")
win.alphaValue = alpha as! CGFloat
if let path = dict["name"], let actions = itemActions[path as! String]
{
if let action = (actions as! Dictionary<String,Any>)["mute"] {
let item = (action as! Dictionary<String,Any>)["item"] as! NSMenuItem
Swift.print("action \(item)")
}
if let action = (actions as! Dictionary<String,Any>)["play"] {
let item = (action as! Dictionary<String,Any>)["item"] as! NSMenuItem
Swift.print("action \(item)")
}
}
}
self.hiddenWindows = Dictionary<String,Any>()
}
else
{
// Swift.print("hide all windows")
for win in NSApp.windows {
let frame = NSStringFromRect(win.frame)
let alpha = win.alphaValue
var dict = Dictionary <String,Any>()
dict["alpha"] = alpha
dict["window"] = win
if let wvc = win.contentView?.subviews.first as? MyWebView, let url = wvc.url {
dict["name"] = url.absoluteString
}
self.hiddenWindows[frame] = dict
// Swift.print("hide \(frame) to \(String(describing: alpha))")
win.alphaValue = 0.01
}
}
return true
case [.shift]:
self.shiftKeyDown = true
return true
case [.command]:
self.commandKeyDown = true
return true
default:
// Only clear when true
if shiftKeyDown { self.shiftKeyDown = false }
if commandKeyDown { self.commandKeyDown = false }
return false
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// OPTION at startup disables reopening documents
if let currentEvent = NSApp.currentEvent {
let flags = currentEvent.modifierFlags
disableDocumentReOpening = flags.contains(.option)
}
let flags : NSEvent.ModifierFlags = NSEvent.ModifierFlags(rawValue: NSEvent.modifierFlags().rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue)
disableDocumentReOpening = flags.contains(.option)
// Local/Global Monitor
_ /*accessEnabled*/ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
globalKeyDownMonitor = NSEvent.addGlobalMonitorForEvents(matching: NSEventMask.flagsChanged) { (event) -> Void in
_ = self.keyDownMonitor(event: event)
}
localKeyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.flagsChanged) { (event) -> NSEvent? in
return self.keyDownMonitor(event: event) ? nil : event
}
// Asynchronous code running on the low priority queue
DispatchQueue.global(qos: .utility).async {
// Restore history name change
if let historyName = self.defaults.value(forKey: UserSettings.HistoryName.keyPath) {
UserSettings.HistoryName.value = historyName as! String
}
if let items = self.defaults.array(forKey: UserSettings.HistoryList.keyPath) {
let keep = UserSettings.HistoryKeep.value
// Load histories from defaults up to their maximum
for playitem in items.suffix(keep) {
let item = playitem as! Dictionary <String,AnyObject>
let name = item[k.name] as! String
let path = item[k.link] as! String
let time = item[k.time] as? TimeInterval
let link = URL.init(string: path)
let rank = item[k.rank] as! Int
let temp = PlayItem(name:name, link:link!, time:time!, rank:rank)
// Non-visible (tableView) cells
temp.rect = item[k.rect]?.rectValue ?? NSZeroRect
temp.label = item[k.label]?.boolValue ?? false
temp.hover = item[k.hover]?.boolValue ?? false
temp.alpha = item[k.alpha]?.intValue ?? 60
temp.trans = item[k.trans]?.intValue ?? 0
self.histories.append(temp)
}
// Swift.print("histories restored")
}
if let items = self.defaults.array(forKey: UserSettings.Searches.keyPath) {
for search in items {
self.recentSearches.append(search as! String)
}
// Swift.print("searches restored")
}
}
// Remember item actions; use when toggle audio/video
NotificationCenter.default.addObserver(
self,
selector: #selector(handleItemAction(_:)),
name: NSNotification.Name(rawValue: "HeliumItemAction"),
object: nil)
// Synchronize our app menu visibility
self.syncAppMenuVisibility()
/* NYI // Register our URL protocol(s)
URLProtocol.registerClass(HeliumURLProtocol.self) */
// If started via login item, launch the login items playlist
if launchedAsLogInItem {
Swift.print("We were launched as a startup item")
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Forget key down monitoring
NSEvent.removeMonitor(localKeyDownMonitor!)
NSEvent.removeMonitor(globalKeyDownMonitor!)
// Save sandbox bookmark urls when necessary
if isSandboxed() != saveBookmarks() {
Swift.print("Yoink, unable to save booksmarks")
}
// Save histories to defaults up to their maxiumum
let keep = UserSettings.HistoryKeep.value
var temp = Array<Any>()
for item in histories.sorted(by: { (lhs, rhs) -> Bool in return lhs.rank < rhs.rank}).suffix(keep) {
let test = item.dictionary()
temp.append(test)
}
defaults.set(temp, forKey: UserSettings.HistoryList.keyPath)
// Save searches to defaults up to their maximum
temp = Array<String>()
for item in recentSearches.suffix(254) {
temp.append(item as String)
}
defaults.set(temp, forKey: UserSettings.Searches.keyPath)
defaults.synchronize()
}
func applicationDockMenu(sender: NSApplication) -> NSMenu? {
let menu = NSMenu(title: "Helium")
var item: NSMenuItem
item = NSMenuItem(title: "Open", action: #selector(menuClicked(_:)), keyEquivalent: "")
menu.addItem(item)
let subOpen = NSMenu()
item.submenu = subOpen
item = NSMenuItem(title: "File…", action: #selector(AppDelegate.openFilePress(_:)), keyEquivalent: "")
item.target = self
subOpen.addItem(item)
item = NSMenuItem(title: "URL…", action: #selector(AppDelegate.openLocationPress(_:)), keyEquivalent: "")
item.target = self
subOpen.addItem(item)
item = NSMenuItem(title: "Window", action: #selector(AppDelegate.newDocument(_:)), keyEquivalent: "")
item.isAlternate = true
item.target = self
subOpen.addItem(item)
item = NSMenuItem(title: "Tab", action: #selector(AppDelegate.newDocument(_:)), keyEquivalent: "")
item.keyEquivalentModifierMask = .shift
item.isAlternate = true
item.target = self
item.tag = 1
subOpen.addItem(item)
return menu
}
//MARK: - handleURLEvent(s)
func metadataDictionaryForFileAt(_ fileName: String) -> Dictionary<NSObject,AnyObject>? {
let item = MDItemCreate(kCFAllocatorDefault, fileName as CFString)
if ( item == nil) { return nil };
let list = MDItemCopyAttributeNames(item)
let resDict = MDItemCopyAttributes(item,list) as Dictionary
return resDict
}
@objc fileprivate func haveNewTitle(_ notification: Notification) {
guard let itemURL = notification.object as? URL, itemURL.scheme != "about" else {
return
}
let item : PlayItem = PlayItem.init()
let info = notification.userInfo!
var fileURL : URL? = nil
if let testURL: URL = (itemURL as NSURL).filePathURL {
fileURL = testURL
}
else
if (itemURL as NSURL).isFileReferenceURL() {
fileURL = (itemURL as NSURL).filePathURL
}
// If the title is already seen, update global and playlists
if let fileURL = fileURL, let dict = defaults.dictionary(forKey: fileURL.absoluteString) {
item.update(with: dict)
}
else
{
if fileURL != nil {
let path = fileURL?.absoluteString//.stringByRemovingPercentEncoding
let attr = metadataDictionaryForFileAt((fileURL?.path)!)
let fuzz = (itemURL as AnyObject).deletingPathExtension!!.lastPathComponent as NSString
item.name = fuzz.removingPercentEncoding!
item.link = URL.init(string: path!)!
item.time = attr?[kMDItemDurationSeconds] as? TimeInterval ?? 0
}
else
{
let fuzz = itemURL.deletingPathExtension().lastPathComponent
let name = fuzz.removingPercentEncoding
// Ignore our home page from the history queue
if name! == UserSettings.homePageName.value { return }
item.name = name!
item.link = itemURL
item.time = 0
}
histories.append(item)
item.rank = histories.count
}
if let runs = info[k.runs], (info[k.fini] as AnyObject).boolValue == true {
item.runs += runs as! Int
}
// tell any playlist controller we have updated history
let notif = Notification(name: Notification.Name(rawValue: k.item), object: item)
NotificationCenter.default.post(notif)
}
@objc fileprivate func clearItemAction(_ notification: Notification) {
if let itemURL = notification.object as? URL {
itemActions[itemURL.absoluteString] = nil
}
}
@objc fileprivate func handleItemAction(_ notification: Notification) {
if let item = notification.object as? NSMenuItem {
let webView: MyWebView = item.representedObject as! MyWebView
let name = webView.url?.absoluteString
var dict : Dictionary<String,Any> = itemActions[name!] as? Dictionary<String,Any> ?? Dictionary<String,Any>()
itemActions[name!] = dict
if item.title == "Mute" {
dict["mute"] = item.state == NSOffState
}
else
{
dict["play"] = item.title == "Play"
}
// Cache item for its target/action we use later
dict["item"] = item
Swift.print("action[\(String(describing: name))] -> \(dict)")
}
}
/// Shows alert asking user to input user agent string
/// Process response locally, validate, dispatch via supplied handler
func didRequestUserAgent(_ strings: RequestUserStrings,
onWindow: HeliumPanel?,
title: String?,
acceptHandler: @escaping (String) -> Void) {
// Create alert
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = strings.alertMessageText
// Create urlField
let urlField = URLField(withValue: strings.currentURL, modalTitle: title)
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
// Add urlField and buttons to alert
alert.accessoryView = urlField
let alert1stButton = alert.addButton(withTitle: strings.alertButton1stText)
if let alert1stToolTip = strings.alertButton1stInfo {
alert1stButton.toolTip = alert1stToolTip
}
let alert2ndButton = alert.addButton(withTitle: strings.alertButton2ndText)
if let alert2ndtToolTip = strings.alertButton2ndInfo {
alert2ndButton.toolTip = alert2ndtToolTip
}
if let alert3rdText = strings.alertButton3rdText {
let alert3rdButton = alert.addButton(withTitle: alert3rdText)
if let alert3rdtToolTip = strings.alertButton3rdInfo {
alert3rdButton.toolTip = alert3rdtToolTip
}
}
if let urlWindow = onWindow {
alert.beginSheetModal(for: urlWindow, completionHandler: { response in
// buttons are accept, cancel, default
if response == NSAlertThirdButtonReturn {
let newUA = (alert.accessoryView as! NSTextField).stringValue
if UAHelpers.isValid(uaString: newUA) {
acceptHandler(newUA)
}
else
{
self.userAlertMessage("This apppears to be an invalid User Agent", info: newUA)
}
}
else
if response == NSAlertFirstButtonReturn {
// swiftlint:disable:next force_cast
let newUA = (alert.accessoryView as! NSTextField).stringValue
if UAHelpers.isValid(uaString: newUA) {
acceptHandler(newUA)
}
else
{
self.userAlertMessage("This apppears to be an invalid User Agent", info: newUA)
}
}
})
}
else
{
switch alert.runModal() {
case NSAlertThirdButtonReturn:
let newUA = (alert.accessoryView as! NSTextField).stringValue
if UAHelpers.isValid(uaString: newUA) {
acceptHandler(newUA)
}
else
{
userAlertMessage("This apppears to be an invalid User Agent", info: newUA)
}
break
case NSAlertFirstButtonReturn:
let newUA = (alert.accessoryView as! NSTextField).stringValue
if UAHelpers.isValid(uaString: newUA) {
acceptHandler(newUA)
}
else
{
userAlertMessage("This apppears to be an invalid User Agent", info: newUA)
}
default:// NSAlertSecondButtonReturn:
return
}
}
// Set focus on urlField
alert.accessoryView!.becomeFirstResponder()
}
func didRequestSearch(_ strings: RequestUserStrings,
onWindow: HeliumPanel?,
title: String?,
acceptHandler: @escaping (Bool,URL) -> Void) {
// Create alert
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = strings.alertMessageText
// Create our search field with recent searches
let search = SearchField(withValue: strings.currentURL, modalTitle: title)
search.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
(search.cell as! NSSearchFieldCell).maximumRecents = 254
search.recentSearches = recentSearches
alert.accessoryView = search
// Add urlField and buttons to alert
let alert1stButton = alert.addButton(withTitle: strings.alertButton1stText)
if let alert1stToolTip = strings.alertButton1stInfo {
alert1stButton.toolTip = alert1stToolTip
}
let alert2ndButton = alert.addButton(withTitle: strings.alertButton2ndText)
if let alert2ndtToolTip = strings.alertButton2ndInfo {
alert2ndButton.toolTip = alert2ndtToolTip
}
if let alert3rdText = strings.alertButton3rdText {
let alert3rdButton = alert.addButton(withTitle: alert3rdText)
if let alert3rdtToolTip = strings.alertButton3rdInfo {
alert3rdButton.toolTip = alert3rdtToolTip
}
}
if let urlWindow = onWindow {
alert.beginSheetModal(for: urlWindow, completionHandler: { response in
// buttons are user-search-url, cancel, google-search
switch response {
case NSAlertFirstButtonReturn,NSAlertThirdButtonReturn:
let newUrlFormat = k.searchLinks[ UserSettings.Search.value ]
let rawString = (alert.accessoryView as! NSTextField).stringValue
let newUrlString = rawString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
var urlString = String(format: newUrlFormat, newUrlString!)
let newWindow = (response == NSAlertThirdButtonReturn)
urlString = UrlHelpers.ensureScheme(urlString)
if UrlHelpers.isValid(urlString: urlString) {
acceptHandler(newWindow,URL.init(string: urlString)!)
self.recentSearches.append(rawString)
}
default:
return
}
})
}
else
{
let response = alert.runModal()
switch response {
case NSAlertFirstButtonReturn,NSAlertThirdButtonReturn:
let newUrlFormat = k.searchLinks[ UserSettings.Search.value ]
let rawString = (alert.accessoryView as! NSTextField).stringValue
let newUrlString = rawString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
var urlString = String(format: newUrlFormat, newUrlString!)
let newWindow = (response == NSAlertThirdButtonReturn)
urlString = UrlHelpers.ensureScheme(urlString)
guard UrlHelpers.isValid(urlString: urlString), let searchURL = URL.init(string: urlString) else {
Swift.print("invalid: \(urlString)")
return
}
acceptHandler(newWindow,searchURL)
self.recentSearches.append(rawString)
default:// NSAlertSecondButtonReturn:
return
}
}
// Set focus on urlField
alert.accessoryView!.becomeFirstResponder()
}
func didRequestUserUrl(_ strings: RequestUserStrings,
onWindow: HeliumPanel?,
title: String?,
acceptHandler: @escaping (String) -> Void) {
// Create alert
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = strings.alertMessageText
// Create urlField
let urlField = URLField(withValue: strings.currentURL, modalTitle: title)
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
alert.accessoryView = urlField
// Add urlField and buttons to alert
let alert1stButton = alert.addButton(withTitle: strings.alertButton1stText)
if let alert1stToolTip = strings.alertButton1stInfo {
alert1stButton.toolTip = alert1stToolTip
}
let alert2ndButton = alert.addButton(withTitle: strings.alertButton2ndText)
if let alert2ndtToolTip = strings.alertButton2ndInfo {
alert2ndButton.toolTip = alert2ndtToolTip
}
if let alert3rdText = strings.alertButton3rdText {
let alert3rdButton = alert.addButton(withTitle: alert3rdText)
if let alert3rdtToolTip = strings.alertButton3rdInfo {
alert3rdButton.toolTip = alert3rdtToolTip
}
}
if let urlWindow = onWindow {
alert.beginSheetModal(for: urlWindow, completionHandler: { response in
// buttons are accept, cancel, default
if response == NSAlertThirdButtonReturn {
var newUrl = (alert.buttons[2] as NSButton).toolTip
newUrl = UrlHelpers.ensureScheme(newUrl!)
if UrlHelpers.isValid(urlString: newUrl!) {
acceptHandler(newUrl!)
}
}
else
if response == NSAlertFirstButtonReturn {
// swiftlint:disable:next force_cast
var newUrl = (alert.accessoryView as! NSTextField).stringValue
newUrl = UrlHelpers.ensureScheme(newUrl)
if UrlHelpers.isValid(urlString: newUrl) {
acceptHandler(newUrl)
}
}
})
}
else
{
switch alert.runModal() {
case NSAlertThirdButtonReturn:
var newUrl = (alert.buttons[2] as NSButton).toolTip
newUrl = UrlHelpers.ensureScheme(newUrl!)
if UrlHelpers.isValid(urlString: newUrl!) {
acceptHandler(newUrl!)
}
break
case NSAlertFirstButtonReturn:
var newUrl = (alert.accessoryView as! NSTextField).stringValue
newUrl = UrlHelpers.ensureScheme(newUrl)
if UrlHelpers.isValid(urlString: newUrl) {
acceptHandler(newUrl)
}
default:// NSAlertSecondButtonReturn:
return
}
}
// Set focus on urlField
alert.accessoryView!.becomeFirstResponder()
}
// Called when the App opened via URL.
@objc func handleURLEvent(_ event: NSAppleEventDescriptor, withReply reply: NSAppleEventDescriptor) {
let newWindows = UserSettings.createNewWindows.value
guard let keyDirectObject = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)),
let rawString = keyDirectObject.stringValue else {
return print("No valid URL to handle")
}
// strip helium://
let index = rawString.index(rawString.startIndex, offsetBy: 9)
let urlString = rawString.substring(from: index)
// Handle new window here to narrow cast to new or current hwc
if (!newWindows || !openForBusiness), let wc = NSApp.keyWindow?.windowController {
if let hwc : HeliumPanelController = wc as? HeliumPanelController {
(hwc.contentViewController as! WebViewController).loadURL(text: urlString)
return
}
}
// Temporarily disable new windows as we'll create one now
UserSettings.createNewWindows.value = false
do
{
let next = try NSDocumentController.shared().openUntitledDocumentAndDisplay(true) as! Document
let hwc = next.windowControllers.first?.window?.windowController
(hwc?.contentViewController as! WebViewController).loadURL(text: urlString)
}
catch let error {
NSApp.presentError(error)
Swift.print("Yoink, unable to create new url doc for (\(urlString))")
}
UserSettings.createNewWindows.value = newWindows
return
}
@objc func handleURLPboard(_ pboard: NSPasteboard, userData: NSString, error: NSErrorPointer) {
if let selection = pboard.string(forType: NSPasteboardTypeString) {
// Notice: string will contain whole selection, not just the urls
// So this may (and will) fail. It should instead find url in whole
// Text somehow
NotificationCenter.default.post(name: Notification.Name(rawValue: "HeliumLoadURLString"), object: selection)
}
}
// MARK: Application Events
func application(_ sender: NSApplication, openFile: String) -> Bool {
let urlString = (openFile.hasPrefix("file://") ? openFile : "file://" + openFile)
let fileURL = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
return self.doOpenFile(fileURL: fileURL)
}
func application(_ sender: NSApplication, openFiles: [String]) {
// Create a FileManager instance
let fileManager = FileManager.default
for path in openFiles {
do {
let files = try fileManager.contentsOfDirectory(atPath: path)
for file in files {
_ = self.application(sender, openFile: file)
}
}
catch let error as NSError {
if fileManager.fileExists(atPath: path) {
_ = self.application(sender, openFile: path)
}
else
{
print("Yoink \(error.localizedDescription)")
}
}
}
}
// MARK:- Sandbox Support
var bookmarks = [URL: Data]()
func isSandboxed() -> Bool {
let bundleURL = Bundle.main.bundleURL
var staticCode:SecStaticCode?
var isSandboxed:Bool = false
let kSecCSDefaultFlags:SecCSFlags = SecCSFlags(rawValue: SecCSFlags.RawValue(0))
if SecStaticCodeCreateWithPath(bundleURL as CFURL, kSecCSDefaultFlags, &staticCode) == errSecSuccess {
if SecStaticCodeCheckValidityWithErrors(staticCode!, SecCSFlags(rawValue: kSecCSBasicValidateOnly), nil, nil) == errSecSuccess {
let appSandbox = "entitlement[\"com.apple.security.app-sandbox\"] exists"
var sandboxRequirement:SecRequirement?
if SecRequirementCreateWithString(appSandbox as CFString, kSecCSDefaultFlags, &sandboxRequirement) == errSecSuccess {
let codeCheckResult:OSStatus = SecStaticCodeCheckValidityWithErrors(staticCode!, SecCSFlags(rawValue: kSecCSBasicValidateOnly), sandboxRequirement, nil)
if (codeCheckResult == errSecSuccess) {
isSandboxed = true
}
}
}
}
return isSandboxed
}
func bookmarkPath() -> String?
{
if var documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
documentsPathURL = documentsPathURL.appendingPathComponent("Bookmarks.dict")
return documentsPathURL.path
}
else
{
return nil
}
}
func loadBookmarks() -> Bool
{
// Ignore loading unless configured
guard isSandboxed() else
{
return false
}
let fm = FileManager.default
guard let path = bookmarkPath(), fm.fileExists(atPath: path) else {
return saveBookmarks()
}
var restored = 0
bookmarks = NSKeyedUnarchiver.unarchiveObject(withFile: path) as! [URL: Data]
var iterator = bookmarks.makeIterator()
while let bookmark = iterator.next()
{
// stale bookmarks get dropped
if !fetchBookmark(bookmark) {
bookmarks.removeValue(forKey: bookmark.key)
}
else
{
restored += 1
}
}
return restored == bookmarks.count
}
func saveBookmarks() -> Bool
{
// Ignore saving unless configured
guard isSandboxed() else
{
return false
}
if let path = bookmarkPath() {
return NSKeyedArchiver.archiveRootObject(bookmarks, toFile: path)
}
else
{
return false
}
}
func storeBookmark(url: URL) -> Bool
{
// Peek to see if we've seen this key before
if let data = bookmarks[url] {
if self.fetchBookmark(key: url, value: data) {
// Swift.print ("= \(url.absoluteString)")
return true
}
}
do
{
let options:URL.BookmarkCreationOptions = [.withSecurityScope,.securityScopeAllowOnlyReadAccess]
let data = try url.bookmarkData(options: options, includingResourceValuesForKeys: nil, relativeTo: nil)
bookmarks[url] = data
return self.fetchBookmark(key: url, value: data)
}
catch let error
{
NSApp.presentError(error)
Swift.print ("Error storing bookmark: \(url)")
return false
}
}
func fetchBookmark(_ bookmark: (key: URL, value: Data)) -> Bool
{
let restoredUrl: URL?
var isStale = true
do
{
restoredUrl = try URL.init(resolvingBookmarkData: bookmark.value, options: URL.BookmarkResolutionOptions.withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
}
catch let error
{
Swift.print("! \(bookmark.key) \n\(error.localizedDescription)")
return false
}
guard !isStale, let url = restoredUrl, url.startAccessingSecurityScopedResource() else {
Swift.print ("? \(bookmark.key)")
return false
}
// Swift.print ("+ \(bookmark.key)")
return true
}
}
| 39.037061 | 183 | 0.571899 |
e83b9d411fdd4fe88cc640bf7aaedc5434b32777 | 978 | import Foundation
extension DispatchTimeInterval {
internal var timeInterval: TimeInterval {
#if swift(>=3.2)
switch self {
case let .seconds(s):
return TimeInterval(s)
case let .milliseconds(ms):
return TimeInterval(TimeInterval(ms) / 1000.0)
case let .microseconds(us):
return TimeInterval(Int64(us) * Int64(NSEC_PER_USEC)) / TimeInterval(NSEC_PER_SEC)
case let .nanoseconds(ns):
return TimeInterval(ns) / TimeInterval(NSEC_PER_SEC)
case .never:
return .infinity
}
#else
switch self {
case let .seconds(s):
return TimeInterval(s)
case let .milliseconds(ms):
return TimeInterval(TimeInterval(ms) / 1000.0)
case let .microseconds(us):
return TimeInterval(Int64(us) * Int64(NSEC_PER_USEC)) / TimeInterval(NSEC_PER_SEC)
case let .nanoseconds(ns):
return TimeInterval(ns) / TimeInterval(NSEC_PER_SEC)
}
#endif
}
}
| 30.5625 | 90 | 0.643149 |
d655481445765db1e56bdd529c6427c07ae79dfe | 466 | import UIKit
import Flutter
import Firebase
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
GeneratedPluginRegistrant.register(with: self)
return true
//return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| 27.411765 | 89 | 0.783262 |
462bb33801f7b426faae05109e39d8271322d674 | 3,728 | //
// iTunesCategory.swift
//
// Copyright (c) 2017 Ben Murphy
//
// 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
/// Users can browse podcast subject categories in the iTunes Store by choosing
/// a category from the Podcasts pop-up menu in the navigation bar. Use the
/// <itunes:category> tag to specify the browsing category for your podcast.
///
/// You can also define a subcategory if one is available within your category.
/// Although you can specify more than one category and subcategory in your
/// feed, the iTunes Store only recognizes the first category and subcategory.
/// For a complete list of categories and subcategories, see Podcasts Connect
/// categories.
///
/// Note: When specifying categories and subcategories, be sure to properly
/// escape ampersands:
///
/// Single category:
/// <itunes:category text="Music" />
///
/// Category with ampersand:
/// <itunes:category text="TV & Film" />
///
/// Category with subcategory:
/// <itunes:category text="Society & Culture">
/// <itunes:category text="History" />
/// </itunes:category>
///
/// Multiple categories:
/// <itunes:category text="Society & Culture">
/// <itunes:category text="History" />
/// </itunes:category>
/// <itunes:category text="Technology">
/// <itunes:category text="Gadgets" />
/// </itunes:category>
public class ITunesCategory {
/// The attributes of the element.
public class Attributes {
/// The primary iTunes Category.
public var text: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The iTunes SubCategory.
public var subcategory: ITunesSubCategory?
public init() { }
}
// MARK: - Initializers
extension ITunesCategory {
convenience init(attributes attributesDict: [String: String]) {
self.init()
self.attributes = ITunesCategory.Attributes(attributes: attributesDict)
}
}
extension ITunesCategory.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.text = attributeDict["text"]
}
}
// MARK: - Equatable
extension ITunesCategory: Equatable {
public static func ==(lhs: ITunesCategory, rhs: ITunesCategory) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension ITunesCategory.Attributes: Equatable {
public static func ==(lhs: ITunesCategory.Attributes, rhs: ITunesCategory.Attributes) -> Bool {
return lhs.text == rhs.text
}
}
| 30.557377 | 99 | 0.681867 |
9c378c3d9b1c0c8bc73f1526c63ee720b9a96b37 | 20,318 | //
// LegendRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartLegendRenderer)
open class LegendRenderer: Renderer
{
/// the legend object this renderer renders
@objc open var legend: Legend?
@objc public init(viewPortHandler: ViewPortHandler, legend: Legend?)
{
super.init(viewPortHandler: viewPortHandler)
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
@objc open func computeLegend(data: ChartData)
{
guard let legend = legend else { return }
if !legend.isLegendCustom
{
var entries: [LegendEntry] = []
// loop for building up the colors and labels used in the legend
for i in 0..<data.dataSetCount
{
guard let dataSet = data.getDataSetByIndex(i) else { continue }
var clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.entryCount
// if we have a barchart with stacked bars
if dataSet is IBarChartDataSet &&
(dataSet as! IBarChartDataSet).isStacked
{
let bds = dataSet as! IBarChartDataSet
var sLabels = bds.stackLabels
for j in 0..<min(clrs.count, bds.stackSize)
{
entries.append(
LegendEntry(
label: sLabels[j % sLabels.count],
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is IPieChartDataSet
{
let pds = dataSet as! IPieChartDataSet
for j in 0..<min(clrs.count, entryCount)
{
entries.append(
LegendEntry(
label: (pds.entryForIndex(j) as? PieChartDataEntry)?.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is ICandleChartDataSet &&
(dataSet as! ICandleChartDataSet).decreasingColor != nil
{
let candleDataSet = dataSet as! ICandleChartDataSet
entries.append(
LegendEntry(
label: nil,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.decreasingColor
)
)
entries.append(
LegendEntry(
label: dataSet.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.increasingColor
)
)
}
else
{ // all others
for j in 0..<min(clrs.count, entryCount)
{
let label: String?
// if multiple colors are set for a DataSet, group them
if j < clrs.count - 1 && j < entryCount - 1
{
label = nil
}
else
{ // add label to the last entry
label = dataSet.label
}
entries.append(
LegendEntry(
label: label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
}
}
legend.entries = entries + legend.extraEntries
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
@objc open func renderLegend(context: CGContext)
{
guard let legend = legend else { return }
if !legend.enabled
{
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
var entries = legend.entries
let defaultFormSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let yEntrySpace = legend.yEntrySpace
let orientation = legend.orientation
let horizontalAlignment = legend.horizontalAlignment
let verticalAlignment = legend.verticalAlignment
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
var originPosX: CGFloat = 0.0
switch horizontalAlignment
{
case .left:
if orientation == .vertical
{
originPosX = xoffset
}
else
{
originPosX = viewPortHandler.contentLeft + xoffset
}
if direction == .rightToLeft
{
originPosX += legend.neededWidth
}
case .right:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth - xoffset
}
else
{
originPosX = viewPortHandler.contentRight - xoffset
}
if direction == .leftToRight
{
originPosX -= legend.neededWidth
}
case .center:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth / 2.0
}
else
{
originPosX = viewPortHandler.contentLeft
+ viewPortHandler.contentWidth / 2.0
}
originPosX += (direction == .leftToRight
? +xoffset
: -xoffset)
// Horizontally layed out legends do the center offset on a line basis,
// So here we offset the vertical ones only.
if orientation == .vertical
{
if direction == .leftToRight
{
originPosX -= legend.neededWidth / 2.0 - xoffset
}
else
{
originPosX += legend.neededWidth / 2.0 - xoffset
}
}
}
switch orientation
{
case .horizontal:
var calculatedLineSizes = legend.calculatedLineSizes
var calculatedLabelSizes = legend.calculatedLabelSizes
var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
switch verticalAlignment
{
case .top:
posY = yoffset
case .bottom:
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
case .center:
posY = (viewPortHandler.chartHeight - legend.neededHeight) / 2.0 + yoffset
}
var lineIndex: Int = 0
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if i < calculatedLabelBreakPoints.count &&
calculatedLabelBreakPoints[i]
{
posX = originPosX
posY += labelLineHeight + yEntrySpace
}
if posX == originPosX &&
horizontalAlignment == .center &&
lineIndex < calculatedLineSizes.count
{
posX += (direction == .rightToLeft
? calculatedLineSizes[lineIndex].width
: -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex += 1
}
let isStacked = e.label == nil // grouped forms have null labels
if drawingForm
{
if direction == .rightToLeft
{
posX -= formSize
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if !isStacked
{
if drawingForm
{
posX += direction == .rightToLeft ? -formToTextSpace : formToTextSpace
}
if direction == .rightToLeft
{
posX -= calculatedLabelSizes[i].width
}
drawLabel(
context: context,
x: posX,
y: posY,
label: e.label!,
font: labelFont,
textColor: labelTextColor)
if direction == .leftToRight
{
posX += calculatedLabelSizes[i].width
}
posX += direction == .rightToLeft ? -xEntrySpace : xEntrySpace
}
else
{
posX += direction == .rightToLeft ? -stackSpace : stackSpace
}
}
case .vertical:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posY: CGFloat = 0.0
switch verticalAlignment
{
case .top:
posY = (horizontalAlignment == .center
? 0.0
: viewPortHandler.contentTop)
posY += yoffset
case .bottom:
posY = (horizontalAlignment == .center
? viewPortHandler.chartHeight
: viewPortHandler.contentBottom)
posY -= legend.neededHeight + yoffset
case .center:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
var posX = originPosX
if drawingForm
{
if direction == .leftToRight
{
posX += stack
}
else
{
posX -= formSize - stack
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if e.label != nil
{
if drawingForm && !wasStacked
{
posX += direction == .leftToRight ? formToTextSpace : -formToTextSpace
}
else if wasStacked
{
posX = originPosX
}
if direction == .rightToLeft
{
posX -= (e.label! as NSString).size(withAttributes: [.font: labelFont]).width
}
if !wasStacked
{
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
else
{
posY += labelLineHeight + yEntrySpace
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
// make a step down
posY += labelLineHeight + yEntrySpace
stack = 0.0
}
else
{
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
private var _formLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
/// Draws the Legend-form at the given position with the color at the given index.
@objc open func drawForm(
context: CGContext,
x: CGFloat,
y: CGFloat,
entry: LegendEntry,
legend: Legend)
{
guard
let formColor = entry.formColor,
formColor != NSUIColor.clear
else { return }
var form = entry.form
if form == .default
{
form = legend.form
}
let formSize = entry.formSize.isNaN ? legend.formSize : entry.formSize
context.saveGState()
defer { context.restoreGState() }
switch form
{
case .none:
// Do nothing
break
case .empty:
// Do not draw, but keep space for the form
break
case .default: fallthrough
case .circle:
context.setFillColor(formColor.cgColor)
context.fillEllipse(in: CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .square:
context.setFillColor(formColor.cgColor)
context.fill(CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .line:
let formLineWidth = entry.formLineWidth.isNaN ? legend.formLineWidth : entry.formLineWidth
let formLineDashPhase = entry.formLineDashPhase.isNaN ? legend.formLineDashPhase : entry.formLineDashPhase
let formLineDashLengths = entry.formLineDashLengths == nil ? legend.formLineDashLengths : entry.formLineDashLengths
context.setLineWidth(formLineWidth)
if formLineDashLengths != nil && formLineDashLengths!.count > 0
{
context.setLineDash(phase: formLineDashPhase, lengths: formLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(formColor.cgColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formSize
_formLineSegmentsBuffer[1].y = y
context.strokeLineSegments(between: _formLineSegmentsBuffer)
}
}
/// Draws the provided label at the given position.
@objc open func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .left, attributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor])
}
}
| 35.583187 | 200 | 0.420219 |
9b5a53b864d544408bdf6e8091d5da13fc631960 | 12,104 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements helpers for constructing non-cryptographic hash
// functions.
//
// This code was ported from LLVM's ADT/Hashing.h.
//
// Currently the algorithm is based on CityHash, but this is an implementation
// detail. Even more, there are facilities to mix in a per-execution seed to
// ensure that hash values differ between executions.
//
import SwiftShims
@_frozen // FIXME(sil-serialize-all)
public // @testable
enum _HashingDetail {
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal static func getExecutionSeed() -> UInt64 {
// FIXME: This needs to be a per-execution seed. This is just a placeholder
// implementation.
return 0xff51afd7ed558ccd
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal static func hash16Bytes(_ low: UInt64, _ high: UInt64) -> UInt64 {
// Murmur-inspired hashing.
let mul: UInt64 = 0x9ddfea08eb382d69
var a: UInt64 = (low ^ high) &* mul
a ^= (a >> 47)
var b: UInt64 = (high ^ a) &* mul
b ^= (b >> 47)
b = b &* mul
return b
}
}
//
// API functions.
//
//
// _mix*() functions all have type (T) -> T. These functions don't compress
// their inputs and just exhibit avalanche effect.
//
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixUInt32(_ value: UInt32) -> UInt32 {
// Zero-extend to 64 bits, hash, select 32 bits from the hash.
//
// NOTE: this differs from LLVM's implementation, which selects the lower
// 32 bits. According to the statistical tests, the 3 lowest bits have
// weaker avalanche properties.
let extendedValue = UInt64(value)
let extendedResult = _mixUInt64(extendedValue)
return UInt32((extendedResult >> 3) & 0xffff_ffff)
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixInt32(_ value: Int32) -> Int32 {
return Int32(bitPattern: _mixUInt32(UInt32(bitPattern: value)))
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixUInt64(_ value: UInt64) -> UInt64 {
// Similar to hash_4to8_bytes but using a seed instead of length.
let seed: UInt64 = _HashingDetail.getExecutionSeed()
let low: UInt64 = value & 0xffff_ffff
let high: UInt64 = value >> 32
return _HashingDetail.hash16Bytes(seed &+ (low << 3), high)
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixInt64(_ value: Int64) -> Int64 {
return Int64(bitPattern: _mixUInt64(UInt64(bitPattern: value)))
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixUInt(_ value: UInt) -> UInt {
#if arch(i386) || arch(arm)
return UInt(_mixUInt32(UInt32(value)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return UInt(_mixUInt64(UInt64(value)))
#endif
}
// FIXME(hasher): Remove
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _mixInt(_ value: Int) -> Int {
#if arch(i386) || arch(arm)
return Int(_mixInt32(Int32(value)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return Int(_mixInt64(Int64(value)))
#endif
}
/// Returns a new value that combines the two given hash values.
///
/// Combining is performed using [a hash function][ref] described by T.C. Hoad
/// and J. Zobel, which is also adopted in the Boost C++ libraries.
///
/// This function is used by synthesized implementations of `hashValue` to
/// combine the hash values of individual `struct` fields and associated values
/// of `enum`s. It is factored out into a standard library function so that the
/// specific hashing logic can be refined without requiring major changes to the
/// code that creates the synthesized AST nodes.
///
/// [ref]: https://pdfs.semanticscholar.org/03bf/7be88e88ba047c6ab28036d0f28510299226.pdf
@_transparent
public // @testable
func _combineHashValues(_ firstValue: Int, _ secondValue: Int) -> Int {
// Use a magic number based on the golden ratio
// (0x1.9e3779b97f4a7c15f39cc0605cedc8341082276bf3a27251f86c6a11d0c18e95p0).
#if arch(i386) || arch(arm)
let magic = 0x9e3779b9 as UInt
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
let magic = 0x9e3779b97f4a7c15 as UInt
#endif
var x = UInt(bitPattern: firstValue)
x ^= UInt(bitPattern: secondValue) &+ magic &+ (x &<< 6) &+ (x &>> 2)
return Int(bitPattern: x)
}
// FIXME(hasher): This hasher emulates Swift 4.1 hashValues. It is purely for
// benchmarking; to be removed.
internal struct _LegacyHasher {
internal var _hash: Int
@inline(__always)
internal init(key: (UInt64, UInt64) = (0, 0)) { // key is ignored
_hash = 0
}
@inline(__always)
internal mutating func append(_ value: Int) {
_hash = (_hash == 0 ? value : _combineHashValues(_hash, value))
}
@inline(__always)
internal mutating func append(_ value: UInt) {
append(Int(bitPattern: value))
}
@inline(__always)
internal mutating func append(_ value: UInt32) {
append(Int(truncatingIfNeeded: value))
}
@inline(__always)
internal mutating func append(_ value: UInt64) {
if UInt64.bitWidth > Int.bitWidth {
append(Int(truncatingIfNeeded: value ^ (value &>> 32)))
} else {
append(Int(truncatingIfNeeded: value))
}
}
@inline(__always)
internal mutating func finalize() -> UInt64 {
return UInt64(
_truncatingBits: UInt(bitPattern: _mixInt(_hash))._lowWord)
}
}
// NOT @_fixed_layout
@_fixed_layout // FIXME - remove - radar 38549901
public struct _Hasher {
internal typealias Core = _SipHash13
// NOT @usableFromInline
internal var _core: Core
// NOT @inlinable
@effects(releasenone)
public init() {
self._core = Core(key: _Hasher._seed)
}
// NOT @inlinable
@effects(releasenone)
public init(seed: (UInt64, UInt64)) {
self._core = Core(key: seed)
}
/// Indicates whether we're running in an environment where hashing needs to
/// be deterministic. If this is true, the hash seed is not random, and hash
/// tables do not apply per-instance perturbation that is not repeatable.
/// This is not recommended for production use, but it is useful in certain
/// test environments where randomization may lead to unwanted nondeterminism
/// of test results.
public // SPI
static var _isDeterministic: Bool {
@inlinable
@inline(__always)
get {
return _swift_stdlib_Hashing_parameters.deterministic;
}
}
/// The 128-bit hash seed used to initialize the hasher state. Initialized
/// once during process startup.
public // SPI
static var _seed: (UInt64, UInt64) {
@inlinable
@inline(__always)
get {
// The seed itself is defined in C++ code so that it is initialized during
// static construction. Almost every Swift program uses hash tables, so
// initializing the seed during the startup seems to be the right
// trade-off.
return (
_swift_stdlib_Hashing_parameters.seed0,
_swift_stdlib_Hashing_parameters.seed1)
}
}
@inlinable
@inline(__always)
public mutating func append<H: Hashable>(_ value: H) {
value._hash(into: &self)
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: UInt) {
_core.append(bits)
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: UInt32) {
_core.append(bits)
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: UInt64) {
_core.append(bits)
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: Int) {
_core.append(UInt(bitPattern: bits))
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: Int32) {
_core.append(UInt32(bitPattern: bits))
}
// NOT @inlinable
@effects(releasenone)
public mutating func append(bits: Int64) {
_core.append(UInt64(bitPattern: bits))
}
// NOT @inlinable
@effects(releasenone)
public mutating func finalize() -> Int {
return Int(truncatingIfNeeded: _core.finalize())
}
}
/// This protocol is only used for compile-time checks that
/// every buffer type implements all required operations.
internal protocol _HashBuffer {
associatedtype Key
associatedtype Value
associatedtype Index
associatedtype SequenceElement
associatedtype SequenceElementWithoutLabels
var startIndex: Index { get }
var endIndex: Index { get }
func index(after i: Index) -> Index
func formIndex(after i: inout Index)
func index(forKey key: Key) -> Index?
func assertingGet(_ i: Index) -> SequenceElement
func assertingGet(_ key: Key) -> Value
func maybeGet(_ key: Key) -> Value?
@discardableResult
mutating func updateValue(_ value: Value, forKey key: Key) -> Value?
@discardableResult
mutating func insert(
_ value: Value, forKey key: Key
) -> (inserted: Bool, memberAfterInsert: Value)
@discardableResult
mutating func remove(at index: Index) -> SequenceElement
@discardableResult
mutating func removeValue(forKey key: Key) -> Value?
mutating func removeAll(keepingCapacity keepCapacity: Bool)
var count: Int { get }
static func fromArray(_ elements: [SequenceElementWithoutLabels]) -> Self
}
/// The inverse of the default hash table load factor. Factored out so that it
/// can be used in multiple places in the implementation and stay consistent.
/// Should not be used outside `Dictionary` implementation.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal var _hashContainerDefaultMaxLoadFactorInverse: Double {
return 1.0 / 0.75
}
#if _runtime(_ObjC)
/// Call `[lhs isEqual: rhs]`.
///
/// This function is part of the runtime because `Bool` type is bridged to
/// `ObjCBool`, which is in Foundation overlay.
/// FIXME(sil-serialize-all): this should be internal
@usableFromInline // FIXME(sil-serialize-all)
@_silgen_name("swift_stdlib_NSObject_isEqual")
internal func _stdlib_NSObject_isEqual(_ lhs: AnyObject, _ rhs: AnyObject) -> Bool
#endif
/// A temporary view of an array of AnyObject as an array of Unmanaged<AnyObject>
/// for fast iteration and transformation of the elements.
///
/// Accesses the underlying raw memory as Unmanaged<AnyObject> using untyped
/// memory accesses. The memory remains bound to managed AnyObjects.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct _UnmanagedAnyObjectArray {
/// Underlying pointer.
@usableFromInline // FIXME(sil-serialize-all)
internal var value: UnsafeMutableRawPointer
@inlinable // FIXME(sil-serialize-all)
internal init(_ up: UnsafeMutablePointer<AnyObject>) {
self.value = UnsafeMutableRawPointer(up)
}
@inlinable // FIXME(sil-serialize-all)
internal init?(_ up: UnsafeMutablePointer<AnyObject>?) {
guard let unwrapped = up else { return nil }
self.init(unwrapped)
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(i: Int) -> AnyObject {
get {
let unmanaged = value.load(
fromByteOffset: i * MemoryLayout<AnyObject>.stride,
as: Unmanaged<AnyObject>.self)
return unmanaged.takeUnretainedValue()
}
nonmutating set(newValue) {
let unmanaged = Unmanaged.passUnretained(newValue)
value.storeBytes(of: unmanaged,
toByteOffset: i * MemoryLayout<AnyObject>.stride,
as: Unmanaged<AnyObject>.self)
}
}
}
| 30.26 | 90 | 0.698695 |
ac54d9a83176a0ce69a1c5c7030a79c7dd42ca5b | 3,374 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import Foundation
import SoraKeystore
import SoraCrypto
import SoraFoundation
import IrohaCommunication
import RobinHood
struct EthereumUserServiceFactory {
private func createRegistrationService() -> EthereumUserService? {
let logger = Logger.shared
do {
let config: ApplicationConfigProtocol = ApplicationConfig.shared
let keychain = Keychain()
let userStoreFacade = UserStoreFacade.shared
let operationManager = OperationManagerFacade.sharedManager
guard let requestSigner = DARequestSigner.createDefault(with: logger) else {
return nil
}
let primitiveFactory = WalletPrimitiveFactory(keychain: keychain,
settings: SettingsManager.shared,
localizationManager: LocalizationManager.shared)
let publicKey = try primitiveFactory.createOperationSettings().publicKey
let accountIdString = try primitiveFactory.createAccountId()
let accountId = try IRAccountIdFactory.account(withIdentifier: accountIdString)
let signer = IRSigningDecorator(keystore: keychain,
identifier: KeystoreKey.privateKey.rawValue)
let registrationFactory = try EthereumRegistrationFactory(signer: signer,
publicKey: publicKey,
sender: accountId)
let mapper = SidechainInitDataMapper<EthereumInitUserInfo>()
let repository: CoreDataRepository<EthereumInit, CDSidechainInit> =
userStoreFacade.createCoreDataCache(mapper: AnyCoreDataMapper(mapper))
let observer = CoreDataContextObservable<EthereumInit, CDSidechainInit>(
service: userStoreFacade.databaseService,
mapper: AnyCoreDataMapper(mapper),
predicate: { _ in true })
observer.start { error in
if let error = error {
logger.error("Can't start observer: \(error)")
}
}
return EthereumUserService(registrationFactory: registrationFactory,
serviceUnit: config.defaultWalletUnit,
requestSigner: requestSigner,
repository: AnyDataProviderRepository(repository),
repositoryObserver: observer,
operationManager: operationManager,
keystore: keychain,
logger: logger)
} catch {
logger.error("Can't create registration service: \(error)")
return nil
}
}
}
extension EthereumUserServiceFactory: UserApplicationServiceFactoryProtocol {
func createServices() -> [UserApplicationServiceProtocol] {
if let registrationService = createRegistrationService() {
return [registrationService]
} else {
return []
}
}
}
| 41.654321 | 106 | 0.570539 |
4b76e3e002e63a34da232f66a499173925a93d0f | 49,900 | // CometChatGroupDetail.swift
// CometChatUIKit
// Created by CometChat Inc. on 20/09/19.
// Copyright © 2020 CometChat Inc. All rights reserved.
// MARK: - Importing Frameworks.
import UIKit
import QuickLook
import AVKit
import AVFoundation
import CometChatPro
/* ----------------------------------------------------------------------------------------- */
class CometChatGroupDetail: UIViewController {
// MARK: - Declaration of Variables
var tableView: UITableView! = nil
var safeArea: UILayoutGuide!
var settingsItems:[Int] = [Int]()
var supportItems:[Int] = [Int]()
var members:[GroupMember] = [GroupMember]()
var administrators:[GroupMember] = [GroupMember]()
var moderators:[GroupMember] = [GroupMember]()
var bannedMembers:[GroupMember] = [GroupMember]()
var bannedMemberRequest: BannedGroupMembersRequest?
var memberRequest: GroupMembersRequest?
var currentGroup: Group?
lazy var previewItem = NSURL()
var quickLook = QLPreviewController()
static let GROUP_INFO_CELL = 0
static let ADMINISTRATOR_CELL = 1
static let MODERATORS_CELL = 2
static let ADD_MEMBER_CELL = 3
static let BANNED_MEMBER_CELL = 4
static let MEMBERS_CELL = 5
static let DELETE_AND_EXIT_CELL = 6
static let EXIT_CELL = 7
// MARK: - View controller lifecycle methods
override public func loadView() {
super.loadView()
UIFont.loadCometChatFonts()
view.backgroundColor = .white
safeArea = view.layoutMarginsGuide
self.setupTableView()
self.setupNavigationBar()
self.setupItems()
self.addObsevers()
}
override func viewWillAppear(_ animated: Bool) {
self.addObsevers()
}
// MARK: - Public Instance methods
/**
This method specifies the **Group** Object to along wih Group Members to present details in it.
- Parameter group: This specifies `Group` Object.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func set(group: Group){
currentGroup = group
self.getGroup(group: group)
if members.isEmpty {
if currentGroup?.scope == .admin || currentGroup?.scope == .moderator {
self.fetchBannedMembers(for: group)
}
self.fetchGroupMembers(group: group)
}
}
/**
This method specifies the navigation bar title for CometChatGroupDetail.
- Parameters:
- title: This takes the String to set title for CometChatGroupDetail.
- mode: This specifies the TitleMode such as :
* .automatic : Automatically use the large out-of-line title based on the state of the previous item in the navigation bar.
* .never: Never use a larger title when this item is topmost.
* .always: Always use a larger title when this item is topmost.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
@objc public func set(title : String, mode: UINavigationItem.LargeTitleDisplayMode){
if navigationController != nil{
navigationItem.title = NSLocalizedString(title, tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
navigationItem.largeTitleDisplayMode = mode
switch mode {
case .automatic:
navigationController?.navigationBar.prefersLargeTitles = true
case .always:
navigationController?.navigationBar.prefersLargeTitles = true
case .never:
navigationController?.navigationBar.prefersLargeTitles = false
@unknown default:break }
}
}
// MARK: - Private Instance methods
/**
This method observers for the notifications of certain events.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
private func addObsevers() {
CometChat.groupdelegate = self
NotificationCenter.default.addObserver(self, selector:#selector(self.didRefreshGroupDetails(_:)), name: NSNotification.Name(rawValue: "refreshGroupDetails"), object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(self.didRefreshGroupDetails(_:)), name: NSNotification.Name(rawValue: "didRefreshMembers"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/**
This method sets the list of items needs to be display in CometChatGroupDetail.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
private func setupItems() {
settingsItems.removeAll()
supportItems.removeAll()
if currentGroup?.scope == .admin || currentGroup?.owner == LoggedInUser.uid || currentGroup?.scope == .moderator {
if currentGroup?.scope == .moderator {
supportItems = [CometChatGroupDetail.EXIT_CELL]
settingsItems = [CometChatGroupDetail.GROUP_INFO_CELL, CometChatGroupDetail.MODERATORS_CELL, CometChatGroupDetail.BANNED_MEMBER_CELL]
}else {
settingsItems = [CometChatGroupDetail.GROUP_INFO_CELL, CometChatGroupDetail.ADMINISTRATOR_CELL, CometChatGroupDetail.MODERATORS_CELL, CometChatGroupDetail.BANNED_MEMBER_CELL]
supportItems = [CometChatGroupDetail.DELETE_AND_EXIT_CELL,CometChatGroupDetail.EXIT_CELL ]
}
}else{
settingsItems = [CometChatGroupDetail.GROUP_INFO_CELL]
supportItems = [CometChatGroupDetail.EXIT_CELL]
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
/**
This method setup the tableview to load CometChatGroupDetail.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
private func setupTableView() {
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
} else { }
tableView = UITableView()
self.view.addSubview(self.tableView)
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.tableView.topAnchor.constraint(equalTo: self.safeArea.topAnchor).isActive = true
self.tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView(frame: .zero)
self.registerCells()
}
/**
This method register the cells for CometChatGroupDetail.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
private func registerCells() {
// register cells using type
tableView.register(.CometChatDetailView)
tableView.register(.NotificationsView)
tableView.register(.AdministratorView)
tableView.register(.AddMemberView)
tableView.register(.MembersView)
tableView.register(.SupportView)
tableView.register(.SharedMediaView)
}
private func getGroup(group: Group){
CometChat.getGroup(GUID: group.guid, onSuccess: { (group) in
self.currentGroup = group
self.setupItems()
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("error in fetching group info: \(String(describing: error?.errorDescription))")
}
}
/**
This method fetches the **Group Members** for particular group.
- Parameter group: This specifies `Group` Object.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func fetchGroupMembers(group: Group){
memberRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid).set(limit: 100).build()
memberRequest?.fetchNext(onSuccess: { (groupMember) in
self.members = groupMember
self.administrators = groupMember.filter {$0.scope == .admin}
self.moderators = groupMember.filter {$0.scope == .moderator}
DispatchQueue.main.async {self.tableView.reloadData() }
}, onError: { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("Group Member list fetching failed with exception:" + error!.errorDescription);
})
}
private func fetchBannedMembers(for group: Group){
bannedMemberRequest = BannedGroupMembersRequest.BannedGroupMembersRequestBuilder(guid: currentGroup?.guid ?? "").set(limit: 100).build()
bannedMemberRequest?.fetchNext(onSuccess: { (groupMembers) in
self.bannedMembers = groupMembers
DispatchQueue.main.async { self.tableView.reloadData() }
}, onError: { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("fetchBannedMembers error:\(String(describing: error?.errorDescription))")
})
}
/**
This method refreshes te group details when triggered.
- Parameter group: This specifies `Group` Object.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
@objc func didRefreshGroupDetails(_ notification: NSNotification) {
if let group = currentGroup {
self.fetchBannedMembers(for: group)
self.getGroup(group: group)
}
if let guid = notification.userInfo?["guid"] as? String {
memberRequest = GroupMembersRequest.GroupMembersRequestBuilder(guid: guid).set(limit: 100).build()
memberRequest?.fetchNext(onSuccess: { (groupMember) in
self.members = groupMember
self.administrators = groupMember.filter {$0.scope == .admin}
self.moderators = groupMember.filter {$0.scope == .moderator}
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}, onError: { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("Group Member list fetching failed with exception:" + error!.errorDescription);
})
}
}
/**
This method setup navigationBar for CometChatGroupDetail viewController.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
private func setupNavigationBar() {
if navigationController != nil{
// NavigationBar Appearance
if #available(iOS 13.0, *) {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.titleTextAttributes = [.font: UIFont (name: "SFProDisplay-Regular", size: 20) as Any]
navBarAppearance.largeTitleTextAttributes = [.font: UIFont(name: "SFProDisplay-Bold", size: 35) as Any]
navBarAppearance.shadowColor = .clear
navigationController?.navigationBar.standardAppearance = navBarAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
self.navigationController?.navigationBar.isTranslucent = true
}
let closeButton = UIBarButtonItem(title: NSLocalizedString("CLOSE", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .plain, target: self, action: #selector(closeButtonPressed))
self.navigationItem.rightBarButtonItem = closeButton
}
}
/**
This method triggers when user clicks on close button.
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
@objc func closeButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
}
/* ----------------------------------------------------------------------------------------- */
// MARK: - Table view Methods
extension CometChatGroupDetail: UITableViewDelegate , UITableViewDataSource {
/// This method specifies the number of sections to display list of items.
/// - Parameter tableView: An object representing the table view requesting this information.
public func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
/// This method specifies height for section in CometChatGroupDetail
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section of tableView .
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 || section == 2 {
return 0
}else{
return 30
}
}
/// This method specifies the view for header in CometChatGroupDetail
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section of tableView .
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: 5, y: 5, width: view.frame.size.width, height: 25))
let sectionTitle = UILabel(frame: CGRect(x: 10, y: 2, width: view.frame.size.width, height: 20))
if section == 0 {
sectionTitle.text = ""
}else if section == 1{
sectionTitle.text = NSLocalizedString("MEMBERS_", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
}else if section == 2{
sectionTitle.text = ""
}else if section == 3{
sectionTitle.text = NSLocalizedString("PRIVACY_&_SUPPORT", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
}else if section == 4{
sectionTitle.text = NSLocalizedString("SHARED_MEDIA", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
}
sectionTitle.font = UIFont(name: "SFProDisplay-Medium", size: 13)
if #available(iOS 13.0, *) {
sectionTitle.textColor = .lightGray
returnedView.backgroundColor = .clear
} else { }
returnedView.addSubview(sectionTitle)
return returnedView
}
/// This method specifiesnumber of rows in CometChatGroupDetail
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section of tableView .
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return settingsItems.count
case 1: return 1
case 2: return members.count
case 3: return supportItems.count
case 4: return 1
default: return 0
}
}
/// This method specifies the view for user in CometChatGroupDetail
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section of tableView .
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 100
}else if currentGroup?.owner == LoggedInUser.uid && indexPath.section == 1 {
return 60
}else if currentGroup?.scope != .admin && indexPath.section == 1 {
return 0
}else if indexPath.section == 4 {
return 320
}else{
return 60
}
}
/// This method specifies the view for user in CometChatGroupDetail
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section of tableView .
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell()
switch indexPath.section {
case 0:
switch settingsItems[safe:indexPath.row] {
case CometChatGroupDetail.GROUP_INFO_CELL:
let groupDetail = tableView.dequeueReusableCell(with: .CometChatDetailView, for: indexPath) as! CometChatDetailView
groupDetail.group = currentGroup
groupDetail.detailViewDelegate = self
groupDetail.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
if let memberCount = currentGroup?.membersCount {
if memberCount == 1 {
groupDetail.detail.text = "1 Member"
}else{
groupDetail.detail.text = "\(memberCount)" + NSLocalizedString("MEMBERS", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
}
}
return groupDetail
case CometChatGroupDetail.ADMINISTRATOR_CELL:
let administratorCell = tableView.dequeueReusableCell(with: .AdministratorView, for: indexPath) as! AdministratorView
administratorCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
administratorCell.title.text = "Administrators"
return administratorCell
case CometChatGroupDetail.MODERATORS_CELL:
let administratorCell = tableView.dequeueReusableCell(with: .AdministratorView, for: indexPath) as! AdministratorView
administratorCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
administratorCell.title.text = "Moderators"
return administratorCell
case CometChatGroupDetail.BANNED_MEMBER_CELL:
let administratorCell = tableView.dequeueReusableCell(with: .AdministratorView, for: indexPath) as! AdministratorView
administratorCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
administratorCell.title.text = "Banned Members"
return administratorCell
default:break
}
case 1:
let addMemberCell = tableView.dequeueReusableCell(with: .AddMemberView, for: indexPath) as! AddMemberView
addMemberCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
return addMemberCell
case 2:
if let member = members[safe: indexPath.row] {
let membersCell = tableView.dequeueReusableCell(with: .MembersView, for: indexPath) as! MembersView
membersCell.member = member
if member.uid == currentGroup?.owner {
membersCell.scope.text = NSLocalizedString("Owner", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
}
membersCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
return membersCell
}
case 3:
switch supportItems[safe:indexPath.row] {
case CometChatGroupDetail.DELETE_AND_EXIT_CELL:
let supportCell = tableView.dequeueReusableCell(with: .SupportView, for: indexPath) as! SupportView
supportCell.textLabel?.text = NSLocalizedString("DELETE_&_EXIT", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
supportCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
return supportCell
case CometChatGroupDetail.EXIT_CELL:
let supportCell = tableView.dequeueReusableCell(with: .SupportView, for: indexPath) as! SupportView
supportCell.textLabel?.text = NSLocalizedString("LEAVE_GROUP", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
supportCell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
return supportCell
default:break
}
case 4:
if let group = currentGroup {
let sharedMediaCell = tableView.dequeueReusableCell(with: .SharedMediaView, for: indexPath) as! SharedMediaView
sharedMediaCell.refreshMediaMessages(for: group, type: .group)
sharedMediaCell.sharedMediaDelegate = self
return sharedMediaCell
}
default: break
}
return cell
}
/// This method triggers when particular cell is clicked by the user .
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - indexPath: specifies current index for TableViewCell.
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.section {
case 0:
switch settingsItems[safe:indexPath.row] {
case CometChatGroupDetail.GROUP_INFO_CELL: break
case CometChatGroupDetail.ADMINISTRATOR_CELL:
let addAdmins = CometChatAddAdministrators()
addAdmins.mode = .fetchAdministrators
guard let group = currentGroup else { return }
addAdmins.set(group: group)
let navigationController: UINavigationController = UINavigationController(rootViewController: addAdmins)
self.present(navigationController, animated: true, completion: nil)
case CometChatGroupDetail.MODERATORS_CELL:
let addModerators = CometChatAddModerators()
addModerators.mode = .fetchModerators
guard let group = currentGroup else { return }
addModerators.set(group: group)
let navigationController: UINavigationController = UINavigationController(rootViewController: addModerators)
self.present(navigationController, animated: true, completion: nil)
case CometChatGroupDetail.BANNED_MEMBER_CELL:
let bannedMembers = CometChatBannedMembers()
guard let group = currentGroup else { return }
bannedMembers.set(group: group)
let navigationController: UINavigationController = UINavigationController(rootViewController: bannedMembers)
self.present(navigationController, animated: true, completion: nil)
default:break }
case 1:
let addMembers = CometChatAddMembers()
guard let group = currentGroup else { return }
addMembers.set(group: group)
let navigationController: UINavigationController = UINavigationController(rootViewController: addMembers)
self.present(navigationController, animated: true, completion: nil)
case 2:
if #available(iOS 13.0, *) {
}else{
if let selectedCell = tableView.cellForRow(at: indexPath) as? MembersView {
let memberName = (tableView.cellForRow(at: indexPath) as? MembersView)?.member?.name ?? ""
let groupName = self.currentGroup?.name ?? ""
let alert = UIAlertController(title: nil, message: "Perform an action to remove or ban \(memberName) from \(groupName).", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Remove Member", style: .default, handler: { action in
CometChat.kickGroupMember(UID: selectedCell.member?.uid ?? "", GUID: self.currentGroup?.guid ?? "", onSuccess: { (success) in
DispatchQueue.main.async {
if let group = self.currentGroup {
let data:[String: String] = ["guid": group.guid]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshGroupDetails"), object: nil, userInfo: data)
}
let message = (selectedCell.member?.name ?? "") + NSLocalizedString("REMOVED_SUCCESSFULLY", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("BAN_MEMBER", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .default, handler: { action in
CometChat.banGroupMember(UID: selectedCell.member?.uid ?? "", GUID: self.currentGroup?.guid ?? "", onSuccess: { (success) in
DispatchQueue.main.async {
if let group = self.currentGroup {
let data:[String: String] = ["guid": group.guid]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshGroupDetails"), object: nil, userInfo: data)
}
let message = (selectedCell.member?.name ?? "") + NSLocalizedString("BANNED_SUCCESSFULLY", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .cancel, handler: { action in
}))
if LoggedInUser.uid == self.currentGroup?.owner || self.currentGroup?.scope == .admin || self.currentGroup?.scope == .moderator {
if selectedCell.member?.scope == .participant || selectedCell.member?.scope == .moderator {
self.present(alert, animated: true)
}else if LoggedInUser.uid == self.currentGroup?.owner && selectedCell.member?.scope == .admin && selectedCell.member?.uid != LoggedInUser.uid {
self.present(alert, animated: true)
}
}
}
}
case 3:
switch supportItems[safe:indexPath.row] {
case CometChatGroupDetail.DELETE_AND_EXIT_CELL:
if let guid = currentGroup?.guid {
CometChat.deleteGroup(GUID: guid, onSuccess: { (success) in
DispatchQueue.main.async {
self.dismiss(animated: true) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didGroupDeleted"), object: nil, userInfo: nil)
}
let message = (self.currentGroup?.name ?? "") + NSLocalizedString(
"DELETED_SUCCESSFULLY", comment: "")
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("error while deleting the group:\(String(describing: error?.errorDescription))")
}
}
case CometChatGroupDetail.EXIT_CELL:
if let guid = currentGroup?.guid {
CometChat.leaveGroup(GUID: guid, onSuccess: { (success) in
DispatchQueue.main.async {
self.dismiss(animated: true) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didGroupDeleted"), object: nil, userInfo: nil)
let message = NSLocalizedString("YOU_LEFT_FROM", tableName: nil, bundle: CCPType.bundle, value: "", comment: "") + (self.currentGroup?.name ?? "") + "."
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
print("error while leaving the group:\(String(describing: error?.errorDescription))")
}
}
default:break }
default: break
}
}
/// This method triggers the `UIMenu` when user holds on TableView cell.
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - indexPath: specifies current index for TableViewCell.
/// - point: A structure that contains a point in a two-dimensional coordinate system.
@available(iOS 13.0, *)
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in
if let selectedCell = (tableView.cellForRow(at: indexPath) as? CometChatDetailView){
let audioCall = UIAction(title: NSLocalizedString("AUDIO_CALL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), image: .fromBundle(named: "audioCall")) { action in
if let group = selectedCell.group {
CometChatCallManager().makeCall(call: .audio, to: group)
}
}
let videoCall = UIAction(title: NSLocalizedString("VIDEO_CALL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), image: .fromBundle(named: "videoCall")) { action in
if let group = selectedCell.group {
CometChatCallManager().makeCall(call: .video, to: group)
}
}
return UIMenu(title: "", children: [audioCall,videoCall])
}
if let selectedCell = tableView.cellForRow(at: indexPath) as? MembersView {
let removeMember = UIAction(title: NSLocalizedString("REMOVE_MEMBER", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { action in
CometChat.kickGroupMember(UID: selectedCell.member?.uid ?? "", GUID: self.currentGroup?.guid ?? "", onSuccess: { (success) in
DispatchQueue.main.async {
if let group = self.currentGroup {
let data:[String: String] = ["guid": group.guid ]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshGroupDetails"), object: nil, userInfo: data)
}
let message = (selectedCell.member?.name ?? "") + NSLocalizedString("REMOVED_SUCCESSFULLY", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
}
}
let banMember = UIAction(title: NSLocalizedString("BAN_MEMBER", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), image: UIImage(systemName: "exclamationmark.octagon.fill"), attributes: .destructive){ action in
CometChat.banGroupMember(UID: selectedCell.member?.uid ?? "", GUID: self.currentGroup?.guid ?? "", onSuccess: { (success) in
DispatchQueue.main.async {
if let group = self.currentGroup {
let data:[String: String] = ["guid": group.guid ]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshGroupDetails"), object: nil, userInfo: data)
}
let message = (selectedCell.member?.name ?? "") + NSLocalizedString("BANNED_SUCCESSFULLY", tableName: nil, bundle: CCPType.bundle, value: "", comment: "")
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: message, duration: .short)
snackbar.show()
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: errorMessage, duration: .short)
snackbar.show()
}
}
}
}
let memberName = (tableView.cellForRow(at: indexPath) as? MembersView)?.member?.name ?? ""
let groupName = self.currentGroup?.name ?? ""
if LoggedInUser.uid == self.currentGroup?.owner || self.currentGroup?.scope == .admin || self.currentGroup?.scope == .moderator {
if selectedCell.member?.scope == .participant || selectedCell.member?.scope == .moderator {
return UIMenu(title: "Perform an action to remove or ban \(memberName) from \(groupName)." , children: [removeMember, banMember])
}else if LoggedInUser.uid == self.currentGroup?.owner && selectedCell.member?.scope == .admin && selectedCell.member?.uid != LoggedInUser.uid || selectedCell.member?.scope == .moderator {
return UIMenu(title: "Perform an action to remove or ban \(memberName) from \(groupName)." , children: [removeMember, banMember])
}
}
}
return UIMenu(title: "")
})
}
}
/* ----------------------------------------------------------------------------------------- */
// MARK: - CometChatGroupDelegate Delegate
extension CometChatGroupDetail: CometChatGroupDelegate {
/**
This method triggers when someone joins group.
- Parameters
- action: Spcifies `ActionMessage` Object
- joinedUser: Specifies `User` Object
- joinedGroup: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onGroupMemberJoined(action: ActionMessage, joinedUser: User, joinedGroup: Group) {
if let group = currentGroup {
if group == joinedGroup {
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone lefts group.
- Parameters
- action: Spcifies `ActionMessage` Object
- leftUser: Specifies `User` Object
- leftGroup: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) {
if let group = currentGroup {
if group == leftGroup {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone kicked from the group.
- Parameters
- action: Spcifies `ActionMessage` Object
- kickedUser: Specifies `User` Object
- kickedBy: Specifies `User` Object
- kickedFrom: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onGroupMemberKicked(action: ActionMessage, kickedUser: User, kickedBy: User, kickedFrom: Group) {
if let group = currentGroup {
if group == kickedFrom {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone banned from the group.
- Parameters
- action: Spcifies `ActionMessage` Object
- bannedUser: Specifies `User` Object
- bannedBy: Specifies `User` Object
- bannedFrom: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
- See Also:
[CometChatMessageList Documentation](https://prodocs.cometchat.com/docs/ios-ui-screens#section-4-comet-chat-message-list)
*/
public func onGroupMemberBanned(action: ActionMessage, bannedUser: User, bannedBy: User, bannedFrom: Group) {
if let group = currentGroup {
if group == bannedFrom {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone unbanned from the group.
- Parameters
- action: Spcifies `ActionMessage` Object
- unbannedUser: Specifies `User` Object
- unbannedBy: Specifies `User` Object
- unbannedFrom: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onGroupMemberUnbanned(action: ActionMessage, unbannedUser: User, unbannedBy: User, unbannedFrom: Group) {
if let group = currentGroup {
if group == unbannedFrom {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone's scope changed in the group.
- Parameters
- action: Spcifies `ActionMessage` Object
- scopeChangeduser: Specifies `User` Object
- scopeChangedBy: Specifies `User` Object
- scopeChangedTo: Specifies `User` Object
- scopeChangedFrom: Specifies description for scope changed
- group: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) {
if let group = currentGroup {
if group == group {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
/**
This method triggers when someone added in the group.
- Parameters:
- action: Spcifies `ActionMessage` Object
- addedBy: Specifies `User` Object
- addedUser: Specifies `User` Object
- addedTo: Specifies `Group` Object
- Author: CometChat Team
- Copyright: © 2020 CometChat Inc.
*/
public func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) {
if let group = currentGroup {
if group == group {
getGroup(group: group)
fetchGroupMembers(group: group)
}
}
}
}
/* ----------------------------------------------------------------------------------------- */
// MARK: - QuickLook Preview Delegate
extension CometChatGroupDetail: QLPreviewControllerDataSource, QLPreviewControllerDelegate {
/**
This method will open quick look preview controller.
- Author: CometChat Team
- Copyright: © 2019 CometChat Inc.
- See Also:
[CometChatMessageList Documentation](https://prodocs.cometchat.com/docs/ios-ui-screens#section-4-comet-chat-message-list)
*/
private func presentQuickLook() {
DispatchQueue.main.async {
let previewController = QLPreviewController()
previewController.modalPresentationStyle = .popover
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
}
/**
This method will preview media message under quick look preview controller.
- Parameters:
- url: this specifies the `url` of Media Message.
- completion: This handles the completion of method.
- Author: CometChat Team
- Copyright: © 2019 CometChat Inc.
- See Also:
[CometChatMessageList Documentation](https://prodocs.cometchat.com/docs/ios-ui-screens#section-4-comet-chat-message-list)
*/
func previewMediaMessage(url: String, completion: @escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: url)
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(itemUrl?.lastPathComponent ?? "")
if FileManager.default.fileExists(atPath: destinationUrl.path) {
completion(true, destinationUrl)
} else {
let snackbar: CometChatSnackbar = CometChatSnackbar.init(message: "Downloading...", duration: .forever)
snackbar.animationType = .slideFromBottomToTop
snackbar.show()
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
snackbar.dismiss()
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
completion(true, destinationUrl)
} catch let error as NSError {
snackbar.dismiss()
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
/// Invoked when the Quick Look preview controller needs to know the number of preview items to include in the preview navigation list.
/// - Parameter controller: A specialized view for previewing an item.
public func numberOfPreviewItems(in controller: QLPreviewController) -> Int { return 1 }
/// Invoked when the Quick Look preview controller needs the preview item for a specified index position.
/// - Parameters:
/// - controller: A specialized view for previewing an item.
/// - index: The index position, within the preview navigation list, of the item to preview.
public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}
/* ----------------------------------------------------------------------------------------- */
extension CometChatGroupDetail: SharedMediaDelegate {
func didPhotoSelected(photo: MediaMessage) {
self.previewMediaMessage(url: photo.attachment?.fileUrl ?? "", completion: {(success, fileURL) in
if success {
if let url = fileURL {
self.previewItem = url as NSURL
self.presentQuickLook()
}
}
})
}
func didVideoSelected(video: MediaMessage) {
self.previewMediaMessage(url: video.attachment?.fileUrl ?? "", completion: {(success, fileURL) in
if success {
var player = AVPlayer()
if let videoURL = fileURL,
let url = URL(string: videoURL.absoluteString) {
player = AVPlayer(url: url)
}
DispatchQueue.main.async{
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
})
}
func didDocumentSelected(document: MediaMessage) {
self.previewMediaMessage(url: document.attachment?.fileUrl ?? "", completion: {(success, fileURL) in
if success {
if let url = fileURL {
self.previewItem = url as NSURL
self.presentQuickLook()
}
}
})
}
}
/* ----------------------------------------------------------------------------------------- */
extension CometChatGroupDetail: DetailViewDelegate {
func didCallButtonPressed(for: AppEntity) {
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let audioCall: UIAlertAction = UIAlertAction(title: NSLocalizedString("AUDIO_CALL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .default) { action -> Void in
if let group = self.currentGroup {
CometChatCallManager().makeCall(call: .audio, to: group)
}
}
let videoCall: UIAlertAction = UIAlertAction(title: NSLocalizedString("VIDEO_CALL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .default) { action -> Void in
if let group = self.currentGroup {
CometChatCallManager().makeCall(call: .video, to: group)
}
}
let cancelAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("CANCEL", tableName: nil, bundle: CCPType.bundle, value: "", comment: ""), style: .cancel) { action -> Void in
}
cancelAction.setValue(UIColor.red, forKey: "titleTextColor")
actionSheetController.addAction(audioCall)
actionSheetController.addAction(videoCall)
actionSheetController.addAction(cancelAction)
// Added ActionSheet support for iPad
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
if let currentPopoverpresentioncontroller =
actionSheetController.popoverPresentationController{
currentPopoverpresentioncontroller.sourceView = self.view
self.present(actionSheetController, animated: true, completion: nil)
}
}else{
self.present(actionSheetController, animated: true, completion: nil)
}
}
}
| 47.980769 | 241 | 0.583647 |
56f4d3aa659de1aafef4b8bfd6809286a2532d62 | 222 | //
// AttributeValueParser.swift
// Pods
//
// Created by Bartosz Tułodziecki on 28/10/2016.
//
//
public protocol AttributeValueParser {
func parsed(attributes: [NSAttributedString.Key : Any]) -> [TagAttribute]
}
| 18.5 | 77 | 0.702703 |
487fc49bfa3c9497c6181c5fe50ccdb952dccfed | 2,852 | //
// LocalNotification.swift
// LochaMeshChat
//
// Created by Kevin Velasco on 1/2/20.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
import UserNotifications
@objc(LocalNotification)
class LocalNoticication: RCTEventEmitter, UNUserNotificationCenterDelegate {
@objc
func requestPermission() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
if granted {
print("hello \(granted)")
}
}
} else {
print("not found")
}
}
override func supportedEvents() -> [String]! {
return ["NoticationReceiver"]
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var res = [
"id" : response.notification.request.identifier,
"title": response.notification.request.content.title,
"message":response.notification.request.content.body
]
sendEvent(withName: "NoticationReceiver", body: res )
completionHandler()
}
@objc func createNotification(_ details:NSDictionary) {
if #available(iOS 10.0, *) {
print("entro aqui")
let content = UNMutableNotificationContent()
content.title = details["title"] as! String
content.body = details["message"] as! String
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1 , repeats: false)
// let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: details["id"] as! String,
content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
print("hay un error Ï")
}
}
} else {
// Fallback on earlier versions
}
}
@available(iOS 10.0, *)
@objc func clearNotificationID(id:NSNumber) {
let identificator:String = id.stringValue
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identificator] )
}
@available(iOS 10.0, *)
@objc func clearNotificationAll() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
}
| 30.021053 | 205 | 0.675316 |
62ddbe138d7e93fb201a2cf67441f117070dc605 | 1,108 | //
// CFUUID+CSAuthSample.swift
// CSAuthSampleCommon
//
// Created by Charles Srstka on 7/22/21.
//
import CoreFoundation
import XPC
extension CFUUID: XPCConvertible {
public static func fromXPCObject(_ xpcObject: xpc_object_t) -> Self? {
guard let uuid = xpc_uuid_get_bytes(xpcObject) else { return nil }
return CFUUIDCreateWithBytes(
kCFAllocatorDefault,
uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]
).map { unsafeDowncast($0, to: self) }
}
public func toXPCObject() -> xpc_object_t? {
let bytes = CFUUIDGetUUIDBytes(self)
let uuid = [
bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5,
bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11,
bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15
]
return uuid.withUnsafeBufferPointer {
xpc_uuid_create($0.baseAddress!)
}
}
}
| 30.777778 | 91 | 0.620036 |
1d3707cb32e60fe4c17d55add6f307c6331f8278 | 7,681 | //
// HTTPManager.swift
// fir-mac
//
// Created by isaced on 2017/5/8.
//
//
import Foundation
import Alamofire
import Alamofire_SwiftyJSON
import SwiftyJSON
enum UploadAppType: String {
case ios = "ios"
case android = "android"
}
class HTTPManager {
static let shared = HTTPManager()
var APIToken: String?
func fetchApps(callback: @escaping ((_ apps: [FIRApp])->Void)) {
guard let APIToken = APIToken else {
callback([])
return
}
Alamofire.request("http://api.fir.im/apps", parameters: ["api_token": APIToken]).responseSwiftyJSON { (response) in
var apps: [FIRApp] = []
if let items = response.value?["items"].array {
for item in items {
let app = FIRApp(json: item)
apps.append(app)
}
}
callback(apps)
}
}
func fatchAppDetail(app: FIRApp, callback: @escaping (()->Void)) {
guard let APIToken = APIToken else {
callback()
return
}
Alamofire.request("http://api.fir.im/apps/\(app.ID)", method: .get, parameters: ["api_token": APIToken]).responseSwiftyJSON { (response) in
app.fillDetail(with: response.value)
callback()
}
}
private func prepareUploadApp(bundleID: String, type:UploadAppType, callback:@escaping ((JSON?)->Void)) {
guard let APIToken = APIToken else {
callback(nil)
return
}
Alamofire.request("http://api.fir.im/apps", method: .post, parameters: ["api_token": APIToken, "bundle_id":bundleID,"type": type.rawValue]).responseSwiftyJSON { (response) in
callback(response.value)
}
}
private func uploadFile(uploadUrl: String,
qiniuKey: String,
qiniuToken: String,
prefix: String,
file: Data?,
fileURL: URL?,
appName: String? = nil,
version: String? = nil,
build: String? = nil,
iosReleaseType: String? = nil,
encodingRequestSuccess: ((UploadRequest)->Void)? = nil,
uploadProgress: Request.ProgressHandler?,
complate: @escaping ((_ success: Bool)->Void)) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(qiniuKey.data(using: .utf8)!, withName: "key")
multipartFormData.append(qiniuToken.data(using: .utf8)!, withName: "token")
if let file = file {
multipartFormData.append(file, withName: "file")
}
if let fileURL = fileURL {
multipartFormData.append(fileURL, withName: "file")
}
if let appName = appName {
multipartFormData.append(appName.data(using: .utf8)!, withName: "\(prefix)name")
}
if let version = version {
multipartFormData.append(version.data(using: .utf8)!, withName: "\(prefix)version") // prefix + "version"
}
if let build = build {
multipartFormData.append(build.data(using: .utf8)!, withName: "\(prefix)build") // prefix + "build"
}
if let iosReleaseType = iosReleaseType {
multipartFormData.append(iosReleaseType.data(using: .utf8)!, withName: "\(prefix)release_type") // prefix + "release_type"
}
if let fileURL = fileURL {
multipartFormData.append(fileURL, withName: "file")
}
}, to: uploadUrl) { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
encodingRequestSuccess?(upload)
upload.uploadProgress(closure: { (progress) in
uploadProgress?(progress)
})
upload.responseJSON { response in
debugPrint(response)
complate(response.result.isSuccess)
}
case .failure(let encodingError):
print(encodingError)
complate(false)
}
}
}
func uploadApp(appInfo: ParsedAppInfo,
encodingRequestSuccess: ((UploadRequest)->Void)? = nil,
uploadProgress: Request.ProgressHandler?,
complate: @escaping ((_ success: Bool)->Void))
{
guard let bundleID = appInfo.bundleID,
let appName = appInfo.appName,
let version = appInfo.version,
let build = appInfo.build,
let type = appInfo.type,
let souceFile = appInfo.sourceFileURL else {
complate(false)
return
}
prepareUploadApp(bundleID: bundleID, type: type) { (response) in
if let uploadFieldPrefix = response?.dictionary?["cert"]?["prefix"].string {
// upload icon
if let iconQiniuKey = response?.dictionary?["cert"]?["icon"]["key"].string,
let iconQiniuToken = response?.dictionary?["cert"]?["icon"]["token"].string,
let iconUploadUrl = response?.dictionary?["cert"]?["icon"]["upload_url"].url?.absoluteString
{
if let iconData = appInfo.iconImage?.tiffRepresentation(using: .JPEG, factor: 0.9) {
self.uploadFile(uploadUrl: iconUploadUrl,
qiniuKey: iconQiniuKey,
qiniuToken: iconQiniuToken,
prefix: uploadFieldPrefix,
file: iconData,
fileURL: nil,
uploadProgress: nil, complate: { (success) in
if !success {
print("icon upload error...")
}
})
}
}
// upload package
if let binaryQiniuKey = response?.dictionary?["cert"]?["binary"]["key"].string,
let binaryQiniuToken = response?.dictionary?["cert"]?["binary"]["token"].string,
let binaryUploadUrl = response?.dictionary?["cert"]?["binary"]["upload_url"].url?.absoluteString
{
self.uploadFile(uploadUrl: binaryUploadUrl,
qiniuKey: binaryQiniuKey,
qiniuToken: binaryQiniuToken,
prefix: uploadFieldPrefix,
file: nil,
fileURL: souceFile,
appName: appName,
version: version,
build: build,
iosReleaseType: appInfo.iosReleaseType?.rawValue,
encodingRequestSuccess: encodingRequestSuccess,
uploadProgress: { (p) in
uploadProgress?(p)
}, complate: { (success) in
complate(success)
})
}
} else {
complate(false)
}
}
}
}
| 40.640212 | 182 | 0.481968 |
56c8c177b013b7cc317936804f7e2bc4a408330a | 3,997 | import UIKit
import app
import SwiftUI
import Combine
class MoviesModel: ObservableObject {
var disposable = Set<AnyCancellable>()
@Published
var movies: [Movie] = []
init(store: Store<FracturedState>) {
disposable.insert(createPublisher(flow: store.select(listSelector: SelectorsKt_.moviesSelector))
.sink(receiveCompletion: {_ in }) { movies in
self.movies = movies as! [Movie]
})
}
}
struct HomeView: View {
@ObservedObject
var moviesModel: MoviesModel
private let store: Store<FracturedState>
init(store: Store<FracturedState>) {
self.store = store
self.moviesModel = MoviesModel(store: store)
}
var body: some View {
VStack {
Text("Name")
ForEach(moviesModel.movies, id: \.self) {
Text($0.name)
}
Spacer(minLength: 10)
NavigationView {
NavigationLink(destination: HomeView2(store: newStore)) {
Text("Launch Swift Only Store")
.padding()
.accentColor(Color.green)
.border(Color.green, width: 1)
}
}
HStack {
Button(action: {
self.store.dispatch(action: MovieActions.AddMovie(movie: Movie(id: 0, name: "Random Movie \(self.moviesModel.movies.count + 1)", description: "I am a movie")))
}) {
Text("Add Movie")
.padding()
.accentColor(Color.blue)
.border(Color.blue, width: 1)
}
Spacer().frame(width: 10)
Button(action: {
if let last = self.moviesModel.movies.last {
self.store.dispatch(action: MovieActions.RemoveMovie(movie: last))
}
}) {
Text("Remove Movie")
.accentColor(Color.red)
.padding()
.border(Color.red, width: 1)
}
}
}
}
}
class MoviesModel2: ObservableObject {
var disposable = Set<AnyCancellable>()
@Published
var movies: [Movie] = []
init(store: Store<MoviesState>) {
disposable.insert(createPublisher(flow: store.select(listSelector: moviesSelector)).sink(receiveCompletion: { _ in }) { movies in
self.movies = movies as! [Movie]
})
}
}
struct HomeView2: View {
@ObservedObject
var moviesModel: MoviesModel2
private let store: Store<MoviesState>
init(store: Store<MoviesState>) {
self.store = store
self.moviesModel = MoviesModel2(store: store)
}
var body: some View {
VStack {
Text("Name")
ForEach(moviesModel.movies, id: \.self) {
Text($0.name)
}
Spacer(minLength: 10)
HStack {
Button(action: {
self.store.dispatch(action: MovieActions.AddMovie(movie: Movie(id: 0, name: "Random Movie \(self.moviesModel.movies.count + 1)", description: "I am a movie")))
}) {
Text("Add Movie")
.padding()
.accentColor(Color.blue)
.border(Color.blue, width: 1)
}
Spacer().frame(width: 10)
Button(action: {
if let last = self.moviesModel.movies.last {
self.store.dispatch(action: MovieActions.RemoveMovie(movie: last))
}
}) {
Text("Remove Movie")
.accentColor(Color.red)
.padding()
.border(Color.red, width: 1)
}
}
}
}
}
| 31.226563 | 179 | 0.482362 |
f8551a09c82834f36cf5d1d27fed5b8aa371f61d | 172 | //
// AA.swift
// HLSSDK
//
// Created by HeartlessSoy on 2019/1/22.
//
import Foundation
public class AA {
public class func aa() {
print("123");
}
}
| 11.466667 | 41 | 0.563953 |
1e31a5db682a6ad67beb43a2ab679d709ea504d0 | 2,725 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the code to download the feed of recent earthquakes.
*/
import Foundation
class DownloadEarthquakesOperation: GroupOperation {
// MARK: Properties
let cacheFile: URL
// MARK: Initialization
/// - parameter cacheFile: The file `URL` to which the earthquake feed will be downloaded.
init(cacheFile: URL) {
self.cacheFile = cacheFile
super.init(operations: [])
name = "Download Earthquakes"
/*
Since this server is out of our control and does not offer a secure
communication channel, we'll use the http version of the URL and have
added "earthquake.usgs.gov" to the "NSExceptionDomains" value in the
app's Info.plist file. When you communicate with your own servers,
or when the services you use offer secure communication options, you
should always prefer to use https.
*/
let url = URL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")!
let task = URLSession.shared.downloadTask(with: url) { url, response, error in
self.downloadFinished(url, response: response as? HTTPURLResponse, error: OperationErrorCode.temp)
}
let taskOperation = URLSessionTaskOperation(task: task)
let reachabilityCondition = ReachabilityCondition(host: url)
taskOperation.addCondition(reachabilityCondition)
let networkObserver = NetworkObserver()
taskOperation.addObserver(networkObserver)
addOperation(operation: taskOperation)
}
func downloadFinished(_ url: URL?, response: HTTPURLResponse?, error: OperationErrorCode?) {
if let localURL = url {
do {
/*
If we already have a file at this location, just delete it.
Also, swallow the error, because we don't really care about it.
*/
try FileManager.default.removeItem(at: cacheFile)
}
catch { }
do {
try FileManager.default.moveItem(at: localURL, to: cacheFile)
}
catch{
// let error as Error
aggregateError(OperationErrorCode.temp)
}
}
else if let error = error {
aggregateError(error)
}
else {
// Do nothing, and the operation will automatically finish.
}
}
}
| 34.0625 | 110 | 0.592294 |
4822ce0e51faed1dca6d599475bebab9a6578bc2 | 1,182 | //
// ViewController.swift
// Examples
//
// Created by Alex Melnichuk on 5/6/19.
// Copyright © 2019 Alex Melnichuk. All rights reserved.
//
import UIKit
import NEMCore
import CryptoCore
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let privateKey = Crypto.data(fromHex: "a3786a75fe252391738a19678bc883d97cd1483516bbc78e5d74ba7691886d17")!
guard let publicKey = NEMCore.publicKey(privateKey: privateKey) else {
print("Unable to generate public key")
return
}
print(Crypto.hex(fromData: publicKey))
guard let address = NEMCore.address(publicKey: publicKey) else {
print("Unable to generate address")
return
}
print(address)
let normalizedAddress = NEMCore.normalize(address: address)
print(normalizedAddress)
let denormalizedAddress = NEMCore.denormalize(address: normalizedAddress)
print(denormalizedAddress)
let positiveValidation = NEMCore.valid(address: address)
print(positiveValidation)
}
}
| 25.695652 | 114 | 0.64044 |
16962b105435a4a55f73ecac91d4eb511d83cc3d | 996 | //
// UIView+AppExtensions.swift
// Pokipedia
//
// Created by Haoxin Li on 7/4/18.
// Copyright © 2018 Haoxin Li. All rights reserved.
//
import UIKit
extension UIView {
func activateLayoutAnchorsWithSuperView(insets: UIEdgeInsets = .zero) {
guard let superview = superview else {
assertionFailure("\(#function) super view not found")
return
}
translatesAutoresizingMaskIntoConstraints = false // Note: layout goes wrong if this is not set to false
NSLayoutConstraint.activate([topAnchor.constraint(equalTo: superview.topAnchor, constant: insets.top),
leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: insets.left),
bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: insets.bottom),
trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: insets.right)])
}
}
| 39.84 | 123 | 0.645582 |
89cc19e4620e5700205d8356cff892286cfea2bc | 14,967 | //
// KeenKeyboard.swift
// KeenKeyboard
//
// Created by chongzone on 2021/1/26.
//
import UIKit
public extension KeenKeyboardAtrributes {
/// 键盘样式
enum Style {
/// 数字样式
case number
/// 金额样式 数字 & 小数点
case decimal
/// 身份证样式 数字 & X
case identityCard
}
/// 布局样式
enum LayoutMode {
/// 分割线
case separator
/// 固定(间隔固定 等分布局)
case fixed
}
}
//MARK: - 属性参数
public struct KeenKeyboardAtrributes {
/// 视图背景色 默认 #F5F5F5
public var viewBackColor: UIColor = UIColor.color(hexString: "#F5F5F5")
/// 样式 默认 number
public var style: KeenKeyboardAtrributes.Style = .number
/// 布局样式 默认 fixed
public var layout: KeenKeyboardAtrributes.LayoutMode = .fixed
/// 是否添加阴影 默认 false
public var showShadow: Bool = false
/// 阴影颜色 默认 #848688
public var shadowColor: UIColor = UIColor.color(hexString: "#848688")
/// 阴影透明度 默认 0.15
public var shadowOpacity: Float = 0.15
/// 数值是否随机 默认 false
public var displayRandom: Bool = false
/// 键盘高度 默认 X 系列键盘距离其安全区域底部高度为 34
public var keyboardHeight: CGFloat = 216 + .safeAreaBottomHeight
/// 控件间隔 默认 6pt 仅对 fixed 布局生效
public var itemSpacing: CGFloat = 6
/// 控件圆角 默认 5pt 仅对 fixed 布局生效
public var itemRadius: CGFloat = 5
/// 阴影颜色 默认 #848688 仅对 fixed 布局生效
public var itemShadowColor: UIColor = UIColor.color(hexString: "#848688")
/// 阴影透明度 默认 0.15 仅对 fixed 布局生效
public var itemShadowOpacity: Float = 0.15
/// 分割线的大小 默认 0.5 pt 仅对 separator 布局生效
public var separatorScale: CGFloat = 0.5
/// 分割线的颜色 默认 #EFEFEF 仅对 separator 布局生效
public var separatorColor: UIColor = UIColor.color(hexString: "#EFEFEF")
/// 字体 默认系统 medium 24pt
public var titleFont: UIFont = UIFont.systemFont(ofSize: 24, weight: .medium)
/// 颜色 默认 #333333
public var titleColor: UIColor = UIColor.color(hexString: "#333333")
/// 高亮颜色 默认 #151515
public var titleHighlightedColor: UIColor = UIColor.color(hexString: "#151515")
/// 背景色 默认 #FFFFFF
public var titleBackColor: UIColor = UIColor.color(hexString: "#FFFFFF")
/// 高亮时背景色 默认 #E6E6E6
public var titleHighlightedBackColor: UIColor = UIColor.color(hexString: "#E6E6E6")
/// 左下角的标题 默认 nil 其中仅当对应的图片为 nil 才会显示标题 仅对 number 样式生效
public var titleOfOther: String? = nil
/// 左下角的图片 默认 nil 优先显示图片 仅对 number 样式生效
public var imageOfOther: UIImage? = nil
/// 左下角标题的字体 默认系统 medium 16pt 仅对 number 样式生效
public var fontOfOther: UIFont = UIFont.systemFont(ofSize: 16, weight: .medium)
/// 左下角标题的颜色 默认 #333333 仅对 number 样式生效
public var colorOfOther: UIColor = UIColor.color(hexString: "#333333")
/// 左下角标题高亮时的颜色 默认 #151515 仅对 number 样式生效
public var highlightedColorOfOther: UIColor = UIColor.color(hexString: "#151515")
/// 左下角背景色 默认 #F5F5F5 仅对 number 样式生效
public var backColorOfOther: UIColor = UIColor.color(hexString: "#F5F5F5")
/// 左下角高亮时背景色 默认 #E6E6E6 仅对 number 样式生效
public var highlightedBackColorOfOther: UIColor = UIColor.color(hexString: "#E6E6E6")
/// 右下角的标题 默认 nil 仅图片为 nil 才会显示标题
public var titleOfDelete: String? = nil
/// 右下角的图片 优先显示图片
public var imageOfDelete: UIImage? = Bundle.imageResouce(
of: KeenKeyboard.self,
bundle: "KeenKeyboard",
name: "ic_keyboard_delete"
)
/// 右下角标题的字体 默认系统 medium 16pt
public var fontOfDelete: UIFont = UIFont.systemFont(ofSize: 16, weight: .medium)
/// 右下角标题的颜色 默认 #333333
public var colorOfDelete: UIColor = UIColor.color(hexString: "#333333")
/// 右下角标题高亮时颜色 默认 #151515
public var highlightedColorOfDelete: UIColor = UIColor.color(hexString: "#151515")
/// 右下角背景色 默认 #F5F5F5
public var backColorOfDelete: UIColor = UIColor.color(hexString: "#F5F5F5")
/// 右下角高亮时背景色 默认 #E6E6E6
public var highlightedBackColorOfDelete: UIColor = UIColor.color(hexString: "#E6E6E6")
public init() { }
}
//MARK: - 协议
public protocol KeenKeyboardDelegate: AnyObject {
/// 输入事件
func insert(_ keyboard: KeenKeyboard, text: String)
/// 删除事件
func delete(_ keyboard: KeenKeyboard, text: String)
/// 其他事件 仅对 number 样式生效
func other(_ keyboard: KeenKeyboard, text: String)
/// 属性参数 不设置取默认值
/// - Returns: 属性对象
func attributesOfKeyboard(for keyboard: KeenKeyboard) -> KeenKeyboardAtrributes
}
public extension KeenKeyboardDelegate {
func insert(_ keyboard: KeenKeyboard, text: String) {}
func delete(_ keyboard: KeenKeyboard, text: String) {}
func other(_ keyboard: KeenKeyboard, text: String) {}
func attributesOfKeyboard(for keyboard: KeenKeyboard) -> KeenKeyboardAtrributes {
return KeenKeyboardAtrributes()
}
}
//MARK: - KeenKeyboard 类
public class KeenKeyboard: UIView {
/// 代理
public weak var delegate: KeenKeyboardDelegate?
/// 输入内容
private var content: String = ""
/// 文本框
private var textField: UITextField!
/// 左下角 item 标记 仅对 number 样式生效
private let tagOfOther: Int = LONG_MAX - 215
/// 右下角 item 标记
private let tagOfDelete: Int = LONG_MAX - 216
/// 右下角 item 标识
private let identifierOfDelete: String = "rightIdentifier"
/// 属性参数
private lazy var attributes: KeenKeyboardAtrributes = {
if let d = delegate {
return d.attributesOfKeyboard(for: self)
}else {
return KeenKeyboardAtrributes()
}
}()
/// 数据源 数据元素为空时该键不允许点击
private lazy var datas: [String] = {
let leftTitle: String!
var nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
switch attributes.style {
case .number: leftTitle = attributes.titleOfOther ?? ""
case .decimal: leftTitle = "."
case .identityCard: leftTitle = "X"
}
if attributes.displayRandom { nums = nums.shuffled() }
let endEle = nums.suffix(1)
nums = Array(nums.prefix(9))
nums.append(leftTitle)
nums.append(endEle.first!)
nums.append(identifierOfDelete)
return nums
}()
/// 初始化
/// - Parameters:
/// - field: 文本框
/// - delegate: 属性代理
public init(field: UITextField, delegate: KeenKeyboardDelegate?) {
super.init(frame: .zero)
self.delegate = delegate
var viewFrame = frame
viewFrame.origin.x = 0
viewFrame.size.width = CGFloat.screenWidth
viewFrame.size.height = attributes.keyboardHeight
viewFrame.origin.y = .screenHeight - attributes.keyboardHeight
self.frame = viewFrame
self.backColor(attributes.viewBackColor)
textField = field
createSubviews()
}
/// 绑定自定义键盘 其中代理不设置的话 属性参数取默认值 回调事件可选
/// - Parameters:
/// - field: 文本框
/// - delegate: 属性代理
public static func bindCustomKeyboard(
field: UITextField,
delegate: KeenKeyboardDelegate?
) {
_ = KeenKeyboard(
field: field,
delegate: delegate
)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 布局|配置
private extension KeenKeyboard {
/// 布局控件
func createSubviews() {
/// View 阴影
if attributes.showShadow {
viewShadow(
color: attributes.shadowColor,
opacity: attributes.shadowOpacity,
radius: 3,
offset: CGSize(width: 0, height: -1)
)
}
var index = 0
let row: Int = 4, column: Int = 3;
let safeAreaHeight = attributes.keyboardHeight - 216
let space = attributes.layout == .separator ? 0 : attributes.itemSpacing
let hSpaces = CGFloat(row)*space + CGFloat((column-1))*attributes.separatorScale
let vSpaces = CGFloat(row + 1) * space + CGFloat(row) * attributes.separatorScale
let itemW = (frame.width - hSpaces) / CGFloat(column)
let itemH = (frame.height - vSpaces - safeAreaHeight) / CGFloat(row)
for idx in 0..<4 {
for ikx in 0..<3 {
let itemX = space + CGFloat(ikx) * (itemW+space) + 0.5 * CGFloat((ikx+1))
let itemY = space + CGFloat(idx) * (itemH+space) + 0.5 * CGFloat((idx+1))
let item = UIButton(type: .custom)
.frame(CGRect(x: itemX, y: itemY, width: itemW, height: itemH))
.title(datas[index])
.font(attributes.titleFont)
.titleColor(attributes.titleColor, .normal)
.titleColor(attributes.titleHighlightedColor, .highlighted)
.isUserInteractionEnabled(!datas[index].isEmpty)
.addViewTo(self)
if datas[index].isEmpty {
index += 1
continue
}else {
item.backColor(attributes.titleBackColor, .normal)
.backColor(attributes.titleHighlightedBackColor, .highlighted)
}
item.addTarget(
self,
action: #selector(clickKeyboardAction(_:)),
for: .touchUpInside
)
/// 处理左下角
if idx == row - 1, ikx == 0, attributes.style == .number {
item.tag(tagOfOther)
.font(attributes.fontOfOther)
.titleColor(attributes.colorOfOther, .normal)
.titleColor(attributes.highlightedColorOfOther, .highlighted)
.backColor(attributes.backColorOfOther, .normal)
.backColor(attributes.highlightedBackColorOfOther, .highlighted)
/// item 内容
if attributes.imageOfOther != nil {
item.title(nil)
.image(attributes.imageOfOther)
}else {
item.title(attributes.titleOfOther, .normal, .highlighted)
}
}
/// 处理右下角
if idx == row - 1, ikx == 2 {
item.tag(tagOfDelete)
.font(attributes.fontOfDelete)
.titleColor(attributes.colorOfDelete, .normal)
.titleColor(attributes.highlightedColorOfDelete, .highlighted)
.backColor(attributes.backColorOfDelete, .normal)
.backColor(attributes.highlightedBackColorOfDelete, .highlighted)
/// item 内容
if attributes.imageOfDelete != nil {
item.title(nil)
.image(attributes.imageOfDelete)
}else {
item.title(attributes.titleOfDelete, .normal, .highlighted)
}
}
/// 圆角阴影
if attributes.layout == .fixed {
if datas[index].isEmpty == false,
datas[index] != identifierOfDelete {
item.viewCornerShadow(
superview: self,
rect: item.frame,
radius: attributes.itemRadius,
corner: .allCorners,
shadowColor: attributes.itemShadowColor,
shadowOpacity: attributes.itemShadowOpacity,
shadowRadius: 0,
shadowOffset: CGSize(width: 0, height: 1)
)
}else {
item.viewCorner(size: item.size, radius: attributes.itemRadius)
}
}
/// 竖线
if attributes.layout == .separator {
let lineH = frame.height - safeAreaHeight
let lineX = (itemW + attributes.separatorScale) * CGFloat(ikx + 1)
UIView(x: lineX, y: 0, width: 0.5, height: lineH)
.backColor(attributes.separatorColor)
.addViewTo(self)
}
index += 1
}
/// 横线
if attributes.layout == .separator {
let lineY = (itemH + attributes.separatorScale) * CGFloat(idx)
UIView(x: 0, y: lineY, width: frame.width, height: attributes.separatorScale)
.backColor(attributes.separatorColor)
.addViewTo(self)
}
}
textField.inputView = self
}
/// 点击键盘
@objc func clickKeyboardAction(_ sender: UIButton) {
if sender.tag == tagOfDelete {
if content.count > 0 {
content.removeLast()
if let d = delegate {
d.delete(self, text: content)
}
}
}else if sender.tag == tagOfOther {
if attributes.style == .number {
textField.resignFirstResponder()
if let d = delegate {
d.other(self, text: content)
}
return
}
}else {
content += sender.currentTitle!
if let d = delegate {
d.insert(self, text: content)
}
}
var range = selectedTextRange(of: textField)
let isDelete = sender.tag == tagOfDelete
if isDelete {
if range.length == 0, range.location > 0 {
range.location -= 1
range.length = 1
}
}
let flag = textField.delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: isDelete ? "" : sender.currentTitle!)
if flag != false {
if isDelete {
textField.deleteBackward()
}else {
textField.insertText(sender.currentTitle!)
}
}
}
func selectedTextRange(of field: UITextField) -> NSRange {
let from = field.selectedTextRange!.start
let to = field.selectedTextRange!.end
let location = field.offset(from: field.beginningOfDocument, to: from)
let length = field.offset(from: from, to: to)
return NSRange(location: location, length: length)
}
}
extension KeenKeyboard: UIInputViewAudioFeedback {
public var enableInputClicksWhenVisible: Bool { true }
}
//MARK: - UITextField 扩展
extension UITextField {
/// 绑定自定义键盘 其中代理不设置的话 属性参数取默认值 回调事件可选
/// - Parameters:
/// - delegate: 属性代理
/// - field: 文本框
@discardableResult
public func bindCustomKeyboard(
delegate: KeenKeyboardDelegate?
) -> Self {
_ = KeenKeyboard(field: self, delegate: delegate)
return self
}
}
| 36.152174 | 150 | 0.560567 |
906890886177eeb51a401db03b5c21c8ee9c8bc8 | 221 | class Point {
var x: Int = 0
var y: Int = 0
}
func move(_ p: Point, left dx: Int, up dy: Int) {
p.x += dx
p.y += dy
}
var p = Point()
move(p, left: 10, up: -2)
assert(p.x == 10 && p.y == -2) // changed
| 15.785714 | 49 | 0.488688 |
f9ea7a4b5b3220607d737b72566f1ecded5454cd | 2,792 | import Foundation
/// Represents a test name in a format "ClassName/testMethodName".
public final class TestName: CustomStringConvertible, Codable, Hashable {
public let className: String
public let methodName: String
public init(className: String, methodName: String) {
self.className = className
self.methodName = methodName
}
public var stringValue: String {
return className + "/" + methodName
}
public var description: String {
return stringValue
}
enum CodingKeys: String, CodingKey {
case className
case methodName
}
public init(from decoder: Decoder) throws {
let testName: TestName
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
testName = TestName(
className: try container.decode(String.self, forKey: .className),
methodName: try container.decode(String.self, forKey: .methodName)
)
} catch {
let container = try decoder.singleValueContainer()
testName = try TestName.createFromTestNameString(
stringValue: try container.decode(String.self)
)
}
self.className = testName.className
self.methodName = testName.methodName
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(className, forKey: .className)
try container.encode(methodName, forKey: .methodName)
}
public enum TestNameError: Error, CustomStringConvertible {
case unableToExctractClassAndMethodNames(stringValue: String)
public var description: String {
switch self {
case .unableToExctractClassAndMethodNames(let stringValue):
return "Unable to extract class or method from the string value '\(stringValue)'. It should have 'ClassName/testMethod' format."
}
}
}
private static func createFromTestNameString(stringValue: String) throws -> TestName {
let components = stringValue.components(separatedBy: "/")
guard components.count == 2, let className = components.first, let methodName = components.last else {
throw TestNameError.unableToExctractClassAndMethodNames(stringValue: stringValue)
}
return TestName(className: className, methodName: methodName)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(className)
hasher.combine(methodName)
}
public static func == (left: TestName, right: TestName) -> Bool {
return left.className == right.className
&& left.methodName == right.methodName
}
}
| 34.9 | 145 | 0.649713 |
fc3635ef827cf82d60f7cf21adda6ac33a194b64 | 14,217 | //
// AppDelegate.swift
// GeoTag
//
// Created by Marco S Hyman on 6/11/14.
// Copyright 2014-2019 Marco S Hyman
//
// 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 AppKit
@NSApplicationMain
final class AppDelegate: NSObject, NSApplicationDelegate {
// instantiate openundomanager when needed
lazy var undoManager = UndoManager()
// I like modified over isDocumentEdited
var modified: Bool {
get {
return window.isDocumentEdited
}
set {
window.isDocumentEdited = newValue
}
}
// user interface outlets
@IBOutlet var window: NSWindow!
@IBOutlet var tableViewController: TableViewController!
@IBOutlet weak var mapViewController: MapViewController!
@IBOutlet var progressIndicator: NSProgressIndicator!
//MARK: App start up
func applicationDidFinishLaunching(_ aNotification: Notification) {
window.delegate = self
#if DEBUG
print("Debug enabled")
// if UI testing clear any existing preferences.
if let uitests = ProcessInfo.processInfo.environment["UITESTS"],
uitests == "1" {
Preferences.resetDefaults()
}
#endif
// Open a preferences window if a backup (save) folder location hasn't
// yet been selected
if Preferences.saveFolder() == nil {
perform(#selector(openPreferences(_:)), with: nil, afterDelay: 0)
}
}
/// don't enable save menu item unless something has been modified
@objc
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard let action = item.action else { return false }
switch action {
case #selector(showOpenPanel(_:)):
return true
case #selector(save(_:)):
return modified
case #selector(openPreferences(_:)):
return true
case #selector(showHelp(_:)):
return true
default:
print("#function \(item) not handled")
}
return false
}
//MARK: open panel handling
/// action bound to File -> Open
/// - Parameter AnyObject: unused
///
/// Allows selection of image files and/or directories. If a directory
/// is selected all files within the directory and any enclosed sub-directories
/// will be added to the table of images. The same file can not be added
/// to the table multiple times. If duplicates are detected the user
/// will be alerted that some files were not opened.
@IBAction
func showOpenPanel(_: AnyObject) {
let panel = NSOpenPanel()
panel.allowedFileTypes = CGImageSourceCopyTypeIdentifiers() as? [String]
panel.allowedFileTypes?.append("gpx")
panel.allowsMultipleSelection = true
panel.canChooseFiles = true
panel.canChooseDirectories = true
if panel.runModal() == NSApplication.ModalResponse.OK {
var urls = [URL]()
for url in panel.urls {
if !addUrlsInFolder(url: url, toUrls: &urls) {
if !isGpxFile(url) {
urls.append(url)
}
}
}
let dups = tableViewController.addImages(urls: urls)
if dups {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("CLOSE", comment: "Close"))
alert.messageText = NSLocalizedString("WARN_TITLE", comment: "Files not opened")
alert.informativeText = NSLocalizedString("WARN_DESC", comment: "Files not opened")
alert.runModal()
}
}
}
//MARK: Open File (UTI support)
/// process files give to us via "Open With..."
///
/// - parameter sender: unused
/// - parameter fileName: path of file to process
/// - returns: true
///
/// this function handles both Image and GPX files. File open is queued
/// to run on the main queue. That delay is necessary as otherwise dragging
/// images onto the app icon to launch the app results in a crash.
func application(_ sender: NSApplication,
openFile filename: String) -> Bool {
DispatchQueue.main.async() {
let url = URL(fileURLWithPath: filename)
if !self.isGpxFile(url) {
var urls = [URL]()
urls.append(url)
let _ = self.tableViewController.addImages(urls: urls)
}
}
return true
}
//MARK: Save image changes (if any)
/// action bound to File -> Save
/// - Parameter saveSource: nil if function called from saveOrDontSave in
/// which case the window will be closed if the save was successful.
///
/// Save all images with updated geolocation information and clear all
/// undo actions.
@IBAction
func save(_ saveSource: AnyObject?) {
guard let folder = Preferences.saveFolder(),
FileManager.default.fileExists(atPath: folder.path) else {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("CLOSE", comment: "Close"))
alert.messageText = NSLocalizedString("NO_BACKUP_TITLE",
comment: "No Backup folder")
alert.informativeText += NSLocalizedString("NO_BACKUP_DESC",
comment: "no backup folder")
alert.informativeText += NSLocalizedString("NO_BACKUP_REASON",
comment: "no backup folder")
alert.runModal()
return
}
tableViewController.saveAllImages {
errorCode in
if errorCode == 0 {
self.modified = false
self.undoManager.removeAllActions()
if saveSource == nil {
self.window.close()
} else {
// tell the user that the images have been saved?
}
} else {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("CLOSE", comment: "Close"))
alert.messageText = NSLocalizedString("SAVE_ERROR_TITLE",
comment: "Save error")
alert.informativeText += NSLocalizedString("SAVE_ERROR_DESC",
comment: "save error")
alert.informativeText += "\(errorCode)"
alert.runModal()
}
}
}
@IBAction
func openPreferences(_ sender: AnyObject!) {
openPreferencesWindow()
}
@IBAction
func showHelp(_ sender: AnyObject) {
let helpPagePath = "https://www.snafu.org/GeoTag/NewGeoTagHelp/"
let helpPage = URL(string: helpPagePath)!
NSWorkspace.shared.open(helpPage)
}
//MARK: app termination
func applicationShouldTerminateAfterLastWindowClosed(_ theApplication: NSApplication) -> Bool {
return true
}
/// Give the user a chance to save changes
/// - Returns: true if all changes have been saved, false otherwise
///
/// Alert the user if there are unsaved geo location changes and allow
/// the user to save or discard the changes before terminating the
/// application. The user can also cancel program termination without
/// saving any changes.
func saveOrDontSave() -> Bool {
if modified {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("SAVE",
comment: "Save"))
alert.addButton(withTitle: NSLocalizedString("CANCEL",
comment: "Cancel"))
alert.addButton(withTitle: NSLocalizedString("DONT_SAVE",
comment: "Don't Save"))
alert.messageText = NSLocalizedString("UNSAVED_TITLE",
comment: "Unsaved Changes")
alert.informativeText = NSLocalizedString("UNSAVED_DESC",
comment: "Unsaved Changes")
alert.beginSheetModal(for: window) {
(response: NSApplication.ModalResponse) -> Void in
switch response {
case .alertFirstButtonReturn:
// Save
self.save(nil)
return
case .alertSecondButtonReturn:
// Cancel -- Close/terminate cancelled
return
default:
// Don't bother saving
break
}
self.modified = false
self.window.close()
}
return false
}
return true
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
if saveOrDontSave() {
tableViewController.clear(self)
return .terminateNow
}
return .terminateCancel
}
}
/// File/Url handling
extension AppDelegate {
/// enumerate the files in a folder adding URLs for all files found to an array
/// - Parameter url: a URL of the folder to enumerate
/// - Parameter toUrls: the array to add the url of found files
/// - Returns: true if the URL was a folder, false otherwise
///
/// Non-hidden files are added to the inout toUrls parameter. Hidden files
/// and internal folders are not added to the array. Internal folders are
/// also enumerated.
public
func addUrlsInFolder(url: URL,
toUrls urls: inout [URL]) -> Bool {
let fileManager = FileManager.default
var dir = ObjCBool(false)
if fileManager.fileExists(atPath: url.path, isDirectory: &dir) && dir.boolValue {
guard let urlEnumerator =
fileManager.enumerator(at: url,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles],
errorHandler: nil) else { return false }
while let fileUrl = urlEnumerator.nextObject() as? URL {
guard
let resources =
try? fileUrl.resourceValues(forKeys: [.isDirectoryKey]),
let directory = resources.isDirectory
else { continue }
if !directory {
if !isGpxFile(fileUrl) {
urls.append(fileUrl)
}
}
}
return true
}
return false
}
/// check if the given url is a gpx file.
/// - Parameter url: URL of file to check
/// - Returns: true if file was a GPX file, otherwise false
///
/// GPX files are parsed and any tracks found in the file are added to
/// the map view
public
func isGpxFile(_ url: URL) -> Bool {
if url.pathExtension.lowercased() == "gpx" {
if let gpx = Gpx(contentsOf: url) {
progressIndicator.startAnimation(self)
if gpx.parse() {
// add the track to the map
Gpx.gpxTracks.append(gpx)
mapViewController.addTracks(gpx: gpx)
// put up an alert
let alert = NSAlert()
alert.alertStyle = NSAlert.Style.informational
alert.addButton(withTitle: NSLocalizedString("CLOSE", comment: "Close"))
alert.messageText = NSLocalizedString("GPX_LOADED_TITLE", comment: "GPX file loaded")
alert.informativeText = url.path
alert.informativeText += NSLocalizedString("GPX_LOADED_DESC", comment: "GPX file loaded")
alert.beginSheetModal(for: window)
} else {
// put up an alert
let alert = NSAlert()
alert.alertStyle = NSAlert.Style.informational
alert.addButton(withTitle: NSLocalizedString("CLOSE", comment: "Close"))
alert.messageText = NSLocalizedString("BAD_GPX_TITLE", comment: "Bad GPX file")
alert.informativeText = url.path
alert.informativeText += NSLocalizedString("BAD_GPX_DESC", comment: "Bad GPX file")
alert.beginSheetModal(for: window)
}
progressIndicator.stopAnimation(self)
}
return true
}
return false
}
}
/// Window delegate functions
extension AppDelegate: NSWindowDelegate {
func windowShouldClose(_: NSWindow) -> Bool {
return saveOrDontSave()
}
func windowWillReturnUndoManager(_ window: NSWindow) -> UndoManager? {
return undoManager
}
}
| 39.057692 | 109 | 0.570866 |
c118d05449b043f5d2a213e69eb217a77f6a7b8e | 3,689 | //
// StatusItemMagic.swift
// LocalSwitch
//
// Created by Arthur Ginzburg on 08/09/2019.
// Copyright © 2019 DaFuqtor. All rights reserved.
//
import Cocoa
public extension NSImage {
func rotated(_ angle: CGFloat) -> NSImage {
let img = NSImage(size: self.size, flipped: false, drawingHandler: { rect -> Bool in
let (width, height) = (rect.size.width, rect.size.height)
let transform = NSAffineTransform()
transform.translateX(by: width / 2, yBy: height / 2)
transform.rotate(byDegrees: angle)
transform.translateX(by: -width / 2, yBy: -height / 2)
transform.concat()
self.draw(in: rect)
return true
})
img.isTemplate = self.isTemplate // preserve the underlying image's template setting
return img
}
}
var iconDegrees = 0
extension NSStatusBarButton {
func spin(from: Int = 0, to: Int = -940) {
let theImage = NSImage(named: "statusIcon")
if iconDegrees <= to {
iconDegrees = from
self.image = theImage?.rotated(CGFloat(iconDegrees))
} else {
if iconDegrees > from {
iconDegrees -= 1
} else if iconDegrees < from - 10 && iconDegrees > from - 30 {
iconDegrees -= 2
} else if iconDegrees < from - 30 && iconDegrees > from - 60 {
iconDegrees -= 3
} else if iconDegrees < from - 60 && iconDegrees > from - 100 {
iconDegrees -= 4
} else if iconDegrees < from - 100 && iconDegrees > from - 150 {
iconDegrees -= 5
} else if iconDegrees < from - 150 && iconDegrees > from - 220 {
iconDegrees -= 6
} else if iconDegrees < from - 220 && iconDegrees > from - 300 {
iconDegrees -= 7
} else if iconDegrees < from - 300 && iconDegrees > from - 390 {
iconDegrees -= 8
} else if iconDegrees < from - 390 && iconDegrees > to + 450 {
iconDegrees -= 9
} else if iconDegrees < to + 450 && iconDegrees > to + 360 {
iconDegrees -= 8
} else if iconDegrees < to + 360 && iconDegrees > to + 280 {
iconDegrees -= 7
} else if iconDegrees < to + 280 && iconDegrees > to + 210 {
iconDegrees -= 6
} else if iconDegrees < to + 210 && iconDegrees > to + 150 {
iconDegrees -= 5
} else if iconDegrees < to + 150 && iconDegrees > to + 100 {
iconDegrees -= 4
} else if iconDegrees < to + 100 && iconDegrees > to + 60 {
iconDegrees -= 3
} else if iconDegrees < to + 60 && iconDegrees > to + 30 {
iconDegrees -= 3
} else if iconDegrees < to + 30 && iconDegrees > to + 10 {
iconDegrees -= 2
} else if iconDegrees < to + 10 && iconDegrees > to {
iconDegrees -= 1
}
else {
iconDegrees -= 1
}
self.image = theImage?.rotated(CGFloat(iconDegrees))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.0000001) {
self.spin()
}
}
}
func fadeOut(_ step: CGFloat = 0.01) {
if !self.appearsDisabled {
self.alphaValue -= step
if self.alphaValue > 0.3 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.005) {
self.fadeOut()
}
} else {
self.appearsDisabled = true
self.alphaValue = 1
}
}
}
func fadeIn(_ step: CGFloat = 0.02) {
if self.alphaValue == 1 {
self.appearsDisabled = false
self.alphaValue = 0.3
}
self.alphaValue += step
if self.alphaValue < 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.005) {
self.fadeIn()
}
} else {
self.appearsDisabled = false
self.alphaValue = 1
}
}
}
| 30.487603 | 88 | 0.566007 |
ed5bd506dea4ba0b3a8d6d51519d9e875e13b418 | 808 | import Models
struct VehicleCodable: Vehicle {
let id: String
var name: String
var description: String
var vehicleClass: String
}
extension VehicleCodable: Decodable {
enum CodingKeys: String, CodingKey {
case id
case name
case description
case vehicleClass = "vehicle_class"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
description = try container.decode(String.self, forKey: .description)
vehicleClass = try container.decode(String.self, forKey: .vehicleClass)
}
}
| 26.064516 | 90 | 0.615099 |
262f0eeca7b7c39b2c4ebafd5effbeac5723053e | 5,639 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// String Creation Helpers
//===----------------------------------------------------------------------===//
internal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool {
// NOTE: Avoiding for-in syntax to avoid bounds checks
//
// TODO(String performance): Vectorize and/or incorporate into validity
// checking, perhaps both.
//
let ptr = input.baseAddress._unsafelyUnwrappedUnchecked
var i = 0
while i < input.count {
guard ptr[i] <= 0x7F else { return false }
i &+= 1
}
return true
}
extension String {
@usableFromInline
internal static func _fromASCII(
_ input: UnsafeBufferPointer<UInt8>
) -> String {
_internalInvariant(_allASCII(input), "not actually ASCII")
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let storage = __StringStorage.create(initializingFrom: input, isASCII: true)
return storage.asString
}
@usableFromInline
internal static func _tryFromUTF8(
_ input: UnsafeBufferPointer<UInt8>
) -> String? {
guard case .success(let extraInfo) = validateUTF8(input) else {
return nil
}
return String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII)
}
@usableFromInline
internal static func _fromUTF8Repairing(
_ input: UnsafeBufferPointer<UInt8>
) -> (result: String, repairsMade: Bool) {
switch validateUTF8(input) {
case .success(let extraInfo):
return (String._uncheckedFromUTF8(
input, asciiPreScanResult: extraInfo.isASCII
), false)
case .error(let initialRange):
return (repairUTF8(input, firstKnownBrokenRange: initialRange), true)
}
}
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>
) -> String {
return _uncheckedFromUTF8(input, isASCII: _allASCII(input))
}
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>,
isASCII: Bool
) -> String {
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let storage = __StringStorage.create(
initializingFrom: input, isASCII: isASCII)
return storage.asString
}
// If we've already pre-scanned for ASCII, just supply the result
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>, asciiPreScanResult: Bool
) -> String {
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let isASCII = asciiPreScanResult
let storage = __StringStorage.create(
initializingFrom: input, isASCII: isASCII)
return storage.asString
}
@usableFromInline
internal static func _uncheckedFromUTF16(
_ input: UnsafeBufferPointer<UInt16>
) -> String {
// TODO(String Performance): Attempt to form smol strings
// TODO(String performance): Skip intermediary array, transcode directly
// into a StringStorage space.
var contents: [UInt8] = []
contents.reserveCapacity(input.count)
let repaired = transcode(
input.makeIterator(),
from: UTF16.self,
to: UTF8.self,
stoppingOnError: false,
into: { contents.append($0) })
_internalInvariant(!repaired, "Error present")
return contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) }
}
internal func _withUnsafeBufferPointerToUTF8<R>(
_ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R
) rethrows -> R {
return try self.withUnsafeBytes { rawBufPtr in
let rawPtr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked
return try body(UnsafeBufferPointer(
start: rawPtr.assumingMemoryBound(to: UInt8.self),
count: rawBufPtr.count))
}
}
@usableFromInline @inline(never) // slow-path
internal static func _fromCodeUnits<
Input: Collection,
Encoding: Unicode.Encoding
>(
_ input: Input,
encoding: Encoding.Type,
repair: Bool
) -> (String, repairsMade: Bool)?
where Input.Element == Encoding.CodeUnit {
// TODO(String Performance): Attempt to form smol strings
// TODO(String performance): Skip intermediary array, transcode directly
// into a StringStorage space.
var contents: [UInt8] = []
contents.reserveCapacity(input.underestimatedCount)
let repaired = transcode(
input.makeIterator(),
from: Encoding.self,
to: UTF8.self,
stoppingOnError: false,
into: { contents.append($0) })
guard repair || !repaired else { return nil }
let str = contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) }
return (str, repaired)
}
public // @testable
static func _fromInvalidUTF16(
_ utf16: UnsafeBufferPointer<UInt16>
) -> String {
return String._fromCodeUnits(utf16, encoding: UTF16.self, repair: true)!.0
}
@usableFromInline
internal static func _fromSubstring(
_ substring: __shared Substring
) -> String {
if substring._offsetRange == substring._wholeString._offsetRange {
return substring._wholeString
}
return substring._withUTF8 { return String._uncheckedFromUTF8($0) }
}
}
| 30.481081 | 80 | 0.668736 |
6a5b95d3e9f9c10633d0a51451ebfb43b06128f7 | 1,342 | //
// ArrowView.swift
// AboutLayout
//
// Created by NixonShih on 2017/1/20.
// Copyright © 2017年 Nixon. All rights reserved.
//
import UIKit
@IBDesignable
/** 畫顆朝下的箭頭啦~!!!!! */
class ArrowView: UIView {
fileprivate var arrowLayer: CAShapeLayer?
override init(frame: CGRect) {
super.init(frame: frame)
drawArrow()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawArrow()
}
override func layoutSubviews() {
super.layoutSubviews()
// 每次 layoutSubviews 的時候都重會一次線。
arrowLayer?.path = arrowPath().cgPath
}
fileprivate func drawArrow() {
arrowLayer = CAShapeLayer()
guard let theArrowLayer = arrowLayer else { return }
theArrowLayer.frame = bounds
theArrowLayer.path = arrowPath().cgPath
theArrowLayer.fillColor = UIColor.white.cgColor
layer.addSublayer(theArrowLayer)
}
fileprivate func arrowPath() -> UIBezierPath {
let viewSize = bounds.size
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: viewSize.width / 2, y: viewSize.height))
path.addLine(to: CGPoint(x: viewSize.width, y: 0))
path.close()
return path
}
}
| 23.54386 | 76 | 0.598361 |
56ea6527cdef093c1305f6bd001243caa0b8d20a | 294 | //
// CalculatorAPI.swift
// BeiraDoRio
//
// Created by Tiago Chaves on 03/03/20.
// Copyright © 2020 Tempest. All rights reserved.
//
import Foundation
struct CalculatorAPI: SumWorkerProtocol {
func sum(_ value1:Int, with value2:Int) -> Int {
return value1 + value2
}
}
| 18.375 | 52 | 0.666667 |
c120eec82a4b84a25526ea28e72740056eb190f4 | 4,350 | //
// ViewController.swift
// SoundQ
//
// Created by Nishil Shah on 4/24/16.
// Copyright © 2016 Nishil Shah. All rights reserved.
//
import UIKit
import Soundcloud
import Alamofire
import RealmSwift
import Firebase
class ViewController: UIViewController {
var user: User?
var userIsLoggedIn: Bool = false
@IBOutlet weak var connectButton: UIButton!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let ref = Firebase(url: "https://soundq.firebaseio.com")
let realm = try! Realm()
userIsLoggedIn = (ref.authData != nil)
if userIsLoggedIn {
let realmUser = realm.objects(RealmUser).first
if realmUser != nil {
connectButton.hidden = true
user = User(fromRealmUser: realmUser!)
} else {
userIsLoggedIn = false;
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
//set background image
let backgroundImage = UIImage(named: "login_background")
let imageView = UIImageView(frame: self.view.bounds)
imageView.image = backgroundImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if(userIsLoggedIn) {
loadHomeViewController()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "HomeSegue") {
self.navigationController?.navigationBarHidden = false;
let nextViewController = segue.destinationViewController as! HomeViewController
nextViewController.user = self.user
}
}
@IBAction func connectButtonPressed(sender: AnyObject) {
hideStatusBar()
Session.login(self, completion:{ result in
self.loadUser()
})
}
func loadUser() {
Soundcloud.session?.me({ result in
self.user = result.response.result
if self.user != nil {
self.loadHomeViewController()
self.authenticateWithFirebase()
self.storeUser()
}
})
}
func storeUser() {
let realmUser = RealmUser(fromUser: user!)
let realm = try! Realm()
//get older versions of users stored with same ID
//let otherRealmUsers = realm.objects(RealmUser).filter("identifier == \(user?.identifier)")
try! realm.write {
//realm.delete(otherRealmUsers)
realm.deleteAll()
realm.add(realmUser)
}
}
func authenticateWithFirebase() {
let ref = Firebase(url: "https://soundq.firebaseio.com/")
Alamofire.request(.GET, "http://sound-q.herokuapp.com/gettoken/", parameters: ["uid": user!.identifier, "auth_data": ""]).responseString { response in
if let auth_token = response.result.value {
ref.authWithCustomToken(auth_token, withCompletionBlock: { error, authData in
if error == nil {
self.updateUserInFirebase()
}
})
}
}
}
func updateUserInFirebase() {
let userURL = "https://soundq.firebaseio.com/users/"+String(self.user!.identifier)
let userRef = Firebase(url: userURL)
userRef.observeSingleEventOfType(.Value, withBlock: { userSnapshot in
userRef.childByAppendingPath("fullName").setValue(self.user!.fullname)
if(!userSnapshot.hasChild("queues")) {
userRef.childByAppendingPath("queues").setValue("null");
}
})
}
func loadHomeViewController() {
self.performSegueWithIdentifier("HomeSegue", sender: self)
}
func hideStatusBar() {
UIApplication.sharedApplication().statusBarHidden = true
}
}
| 30 | 158 | 0.584138 |
5b383e7b3cb7655b2af7739af3bc75410b0ccd13 | 3,008 | //
// ViewController.swift
// movieJson
//
// Created by Mitchell Phillips on 2/11/16.
// Copyright © 2016 Mitchell Phillips. All rights reserved.
//
import UIKit
typealias JSONDictionary = [String:AnyObject]
typealias JSONArray = [JSONDictionary]
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var currentMovie: Movie?
var moviesArray = [Movie]()
@IBOutlet weak var moviesList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let (jsonString, popular) = loadJSONFile("popular", fileType: "json")
print(jsonString)
if let popular = popular {
do {
let object = try NSJSONSerialization.JSONObjectWithData(popular, options: .AllowFragments)
if let dict = object as? JSONDictionary {
if let results = dict["results"] as? JSONArray {
for result in results {
let m = Movie(dict: result)
self.moviesArray.append(m)
}
}
}
} catch {
print("Unable to parse JSON string")
}
}
}
// MARK: - Table View Functions
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.currentMovie = self.moviesArray[indexPath.row]
self.performSegueWithIdentifier("movieDeetsSegue", sender: self)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
self.currentMovie = self.moviesArray[indexPath.row]
if let title = self.currentMovie?.title {
cell.textLabel?.text = "\(title)"
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moviesArray.count
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "movieDeetsSegue" {
let movieDeetsViewController = segue.destinationViewController as! MovieDeetsViewController
movieDeetsViewController.movie = currentMovie
}
}
// MARK: - Load JSON
func loadJSONFile(filename: String, fileType: String) -> (String, NSData?) {
var returnString = ""
var data: NSData? = nil
guard let filePath = NSBundle.mainBundle().URLForResource(filename, withExtension: fileType) else { return (returnString, data) }
if let jsondata = NSData(contentsOfURL: filePath) {
if let jsonString = NSString(data: jsondata, encoding: NSUTF8StringEncoding) {
returnString = jsonString as String
data = jsondata
}
}
return (returnString, data)
}
}
| 33.797753 | 137 | 0.594415 |
299fbb48f741bb26ac627aa5d8aa9995d14c1ca8 | 9,999 | //
// DBUtils.swift
// Potatso
//
// Created by LEI on 8/3/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import Realm
import RealmSwift
open class DBUtils {
fileprivate static func currentRealm(_ realm: Realm?) -> Realm {
var mRealm = realm
if mRealm == nil {
mRealm = try! Realm()
}
return mRealm!
}
open static func add(_ object: BaseModel, update: Bool = true, setModified: Bool = true, inRealm realm: Realm? = nil) throws {
let mRealm = currentRealm(realm)
mRealm.beginWrite()
if setModified {
object.setModified()
}
mRealm.add(object, update: update)
try mRealm.commitWrite()
}
open static func add<S: Sequence>(_ objects: S, update: Bool = true, setModified: Bool = true, inRealm realm: Realm? = nil) throws where S.Iterator.Element: BaseModel {
let mRealm = currentRealm(realm)
mRealm.beginWrite()
objects.forEach({
if setModified {
$0.setModified()
}
})
mRealm.add(objects, update: update)
try mRealm.commitWrite()
}
open static func softDelete<T: BaseModel>(_ id: String, type: T.Type, inRealm realm: Realm? = nil) throws {
let mRealm = currentRealm(realm)
guard let object: T = DBUtils.get(id, type: type, inRealm: mRealm) else {
return
}
mRealm.beginWrite()
object.deleted = true
object.setModified()
try mRealm.commitWrite()
}
open static func softDelete<T: BaseModel>(_ ids: [String], type: T.Type, inRealm realm: Realm? = nil) throws {
for id in ids {
try softDelete(id, type: type, inRealm: realm)
}
}
open static func hardDelete<T: BaseModel>(_ id: String, type: T.Type, inRealm realm: Realm? = nil) throws {
let mRealm = currentRealm(realm)
guard let object: T = DBUtils.get(id, type: type, inRealm: mRealm) else {
return
}
mRealm.beginWrite()
mRealm.delete(object)
try mRealm.commitWrite()
}
open static func hardDelete<T: BaseModel>(_ ids: [String], type: T.Type, inRealm realm: Realm? = nil) throws {
for id in ids {
try hardDelete(id, type: type, inRealm: realm)
}
}
open static func mark<T: BaseModel>(_ id: String, type: T.Type, synced: Bool, inRealm realm: Realm? = nil) throws {
let mRealm = currentRealm(realm)
guard let object: T = DBUtils.get(id, type: type, inRealm: mRealm) else {
return
}
mRealm.beginWrite()
object.synced = synced
try mRealm.commitWrite()
}
open static func markAll(syncd: Bool) throws {
let mRealm = try! Realm()
mRealm.beginWrite()
for proxy in mRealm.objects(Proxy.self) {
proxy.synced = false
}
for ruleset in mRealm.objects(RuleSet.self) {
ruleset.synced = false
}
for group in mRealm.objects(ConfigurationGroup.self) {
group.synced = false
}
try mRealm.commitWrite()
}
}
// Query
extension DBUtils {
public static func allNotDeleted<T: BaseModel>(_ type: T.Type, filter: String? = nil, sorted: String? = nil, inRealm realm: Realm? = nil) -> Results<T> {
let deleteFilter = "deleted = false"
var mFilter = deleteFilter
if let filter = filter {
mFilter += " && " + filter
}
return all(type, filter: mFilter, sorted: sorted, inRealm: realm)
}
public static func all<T: BaseModel>(_ type: T.Type, filter: String? = nil, sorted: String? = nil, inRealm realm: Realm? = nil) -> Results<T> {
let mRealm = currentRealm(realm)
var res = mRealm.objects(type)
if let filter = filter {
res = res.filter(filter)
}
if let sorted = sorted {
res = res.sorted(byKeyPath: sorted)
}
return res
}
public static func get<T: BaseModel>(_ uuid: String, type: T.Type, filter: String? = nil, sorted: String? = nil, inRealm realm: Realm? = nil) -> T? {
let mRealm = currentRealm(realm)
var mFilter = "uuid = '\(uuid)'"
if let filter = filter {
mFilter += " && " + filter
}
var res = mRealm.objects(type).filter(mFilter)
if let sorted = sorted {
res = res.sorted(byKeyPath: sorted)
}
return res.first
}
public static func modify<T: BaseModel>(_ type: T.Type, id: String, inRealm realm: Realm? = nil, modifyBlock: ((Realm, T) -> Error?)) throws {
let mRealm = currentRealm(realm)
guard let object: T = DBUtils.get(id, type: type, inRealm: mRealm) else {
return
}
mRealm.beginWrite()
if let error = modifyBlock(mRealm, object) {
throw error
}
do {
try object.validate(inRealm: mRealm)
}catch {
mRealm.cancelWrite()
throw error
}
object.setModified()
try mRealm.commitWrite()
}
}
// Sync
extension DBUtils {
public static func allObjectsToSyncModified() -> [BaseModel] {
let mRealm = currentRealm(nil)
let filter = "synced == false && deleted == false"
let proxies = mRealm.objects(Proxy.self).filter(filter).map({ $0 })
let rulesets = mRealm.objects(RuleSet.self).filter(filter).map({ $0 })
let groups = mRealm.objects(ConfigurationGroup.self).filter(filter).map({ $0 })
var objects: [BaseModel] = []
// var iterator1: LazyMapIterator<RLMIterator<Proxy>, Proxy>? = nil
// iterator1 = proxies.makeIterator()
// iterator1?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
//
// var iterator2: LazyMapIterator<RLMIterator<RuleSet>, RuleSet>? = nil
// iterator2 = rulesets.makeIterator()
// iterator2?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
//
// var iterator3: LazyMapIterator<RLMIterator<ConfigurationGroup>, ConfigurationGroup>? = nil
// iterator3 = groups.makeIterator()
// iterator3?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
let iterator1 = proxies.makeIterator()
iterator1.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
let iterator2 = rulesets.makeIterator()
iterator2.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
let iterator3 = groups.makeIterator()
iterator3.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
return objects
}
public static func allObjectsToSyncDeleted() -> [BaseModel] {
let mRealm = currentRealm(nil)
let filter = "synced == false && deleted == true"
let proxies = mRealm.objects(Proxy.self).filter(filter).map({ $0 })
let rulesets = mRealm.objects(RuleSet.self).filter(filter).map({ $0 })
let groups = mRealm.objects(ConfigurationGroup.self).filter(filter).map({ $0 })
var objects: [BaseModel] = []
// var iterator1: LazyMapIterator<RLMIterator<Proxy>, Proxy>? = nil
// iterator1 = proxies.makeIterator()
// iterator1?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
//
// var iterator2: LazyMapIterator<RLMIterator<RuleSet>, RuleSet>? = nil
// iterator2 = rulesets.makeIterator()
// iterator2?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
//
// var iterator3: LazyMapIterator<RLMIterator<ConfigurationGroup>, ConfigurationGroup>? = nil
// iterator3 = groups.makeIterator()
// iterator3?.forEach({ (tObj) in
// objects.append(tObj as BaseModel)
// })
let iterator1 = proxies.makeIterator()
iterator1.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
let iterator2 = rulesets.makeIterator()
iterator2.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
let iterator3 = groups.makeIterator()
iterator3.forEach({ (tObj) in
objects.append(tObj as BaseModel)
})
return objects
}
}
// BaseModel API
extension BaseModel {
func setModified() {
updatedAt = Date().timeIntervalSince1970
synced = false
}
}
// Config Group API
extension ConfigurationGroup {
public static func changeProxy(forGroupId groupId: String, proxyId: String?) throws {
try DBUtils.modify(ConfigurationGroup.self, id: groupId) { (realm, group) -> Error? in
group.proxies.removeAll()
if let proxyId = proxyId, let proxy = DBUtils.get(proxyId, type: Proxy.self, inRealm: realm){
group.proxies.append(proxy)
}
return nil
}
}
public static func appendRuleSet(forGroupId groupId: String, rulesetId: String) throws {
try DBUtils.modify(ConfigurationGroup.self, id: groupId) { (realm, group) -> Error? in
if let ruleset = DBUtils.get(rulesetId, type: RuleSet.self, inRealm: realm) {
group.ruleSets.append(ruleset)
}
return nil
}
}
public static func changeDNS(forGroupId groupId: String, dns: String?) throws {
try DBUtils.modify(ConfigurationGroup.self, id: groupId) { (realm, group) -> Error? in
group.dns = dns ?? ""
return nil
}
}
public static func changeName(forGroupId groupId: String, name: String) throws {
try DBUtils.modify(ConfigurationGroup.self, id: groupId) { (realm, group) -> Error? in
group.name = name
return nil
}
}
}
| 32.891447 | 172 | 0.581458 |
08701e7ab9f12b55210b8e717db4e7efe7bea514 | 162 | //
// MyClass.swift
// OCToSwift
//
// Created by MA806P on 2019/1/22.
// Copyright © 2019 myz. All rights reserved.
//
import Foundation
class MyClass {
}
| 12.461538 | 46 | 0.654321 |
216189cf78829ec217869e864ffeb4fd3329a15a | 10,208 | //
// TableViewWrapper.swift
// RAMReel
//
// Created by Mikhail Stepkin on 4/9/15.
// Copyright (c) 2015 Ramotion. All rights reserved.
//
import UIKit
// MARK: - Collection view wrapper
/**
WrapperProtocol
--
Helper protocol for CollectionViewWrapper.
*/
protocol WrapperProtocol : class {
/// Number of cells in collection
var numberOfCells: Int { get }
/**
Cell constructor, replaces standard Apple way of doing it.
- parameters:
- collectionView `UICollectionView` instance in which cell should be created.
- indexPath `NSIndexPath` where to put cell to.
- returns: Fresh (or reused) cell.
*/
func createCell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell
/**
Attributes of cells in some rect.
- parameter rect Area in which you want to probe for attributes.
*/
func cellAttributes(_ rect: CGRect) -> [UICollectionViewLayoutAttributes]
}
/**
CollectionViewWrapper
--
Wraps collection view and set's collection view data source.
*/
open class CollectionViewWrapper
<
DataType,
CellClass: UICollectionViewCell>: FlowDataDestination, WrapperProtocol
where
CellClass: ConfigurableCell,
DataType == CellClass.DataType
{
private var lock : NSLock = NSLock()
var data: [DataType] = [] {
didSet {
self.scrollDelegate.itemIndex = nil
self.collectionView.reloadData()
self.updateOffset()
self.scrollDelegate.adjustScroll(self.collectionView)
}
}
/**
FlowDataDestination protocol implementation method.
- seealso: FlowDataDestination
This method processes data from data flow.
- parameter data: Data array to process.
*/
open func processData(_ data: [DataType]) {
self.data = data
}
let collectionView: UICollectionView
let cellId: String = "ReelCell"
let dataSource = CollectionViewDataSource()
let collectionLayout = RAMCollectionViewLayout()
let scrollDelegate: ScrollViewDelegate
let rotationWrapper = NotificationCallbackWrapper(name: UIDevice.orientationDidChangeNotification.rawValue, object: UIDevice.current)
let keyboardWrapper = NotificationCallbackWrapper(name: UIResponder.keyboardDidChangeFrameNotification.rawValue)
var theme: Theme
/**
- parameters:
- collectionView: Collection view to wrap around.
- theme: Visual theme of collection view.
*/
public init(collectionView: UICollectionView, theme: Theme) {
self.collectionView = collectionView
self.theme = theme
self.scrollDelegate = ScrollViewDelegate(itemHeight: collectionLayout.itemHeight)
self.scrollDelegate.itemIndexChangeCallback = { [weak self] idx in
guard let `self` = self else { return }
guard let index = idx , 0 <= index && index < self.data.count else {
self.selectedItem = nil
return
}
let item = self.data[index]
self.selectedItem = item
// TODO: Update cell appearance maybe?
// Toggle selected?
let indexPath = IndexPath(item: index, section: 0)
let cell = collectionView.cellForItem(at: indexPath)
cell?.isSelected = true
}
collectionView.register(CellClass.self, forCellWithReuseIdentifier: cellId)
dataSource.wrapper = self
collectionView.dataSource = dataSource
collectionView.collectionViewLayout = collectionLayout
collectionView.bounces = false
let scrollView = collectionView as UIScrollView
scrollView.delegate = scrollDelegate
rotationWrapper.callback = { [weak self] notification in
guard let `self` = self else {
return
}
self.adjustScroll(notification as Notification)
}
keyboardWrapper.callback = { [weak self] notification in
guard let `self` = self else {
return
}
self.adjustScroll(notification as Notification)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
var selectedItem: DataType?
// MARK Implementation of WrapperProtocol
func createCell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CellClass
let row = (indexPath as NSIndexPath).row
let dat = self.data[row]
cell.configureCell(dat)
cell.theme = self.theme
return cell as UICollectionViewCell
}
var numberOfCells:Int {
return data.count
}
func cellAttributes(_ rect: CGRect) -> [UICollectionViewLayoutAttributes] {
let layout = collectionView.collectionViewLayout
guard let attributes = layout.layoutAttributesForElements(in: rect) else {
return []
}
return attributes
}
// MARK: Update & Adjust
func updateOffset(_ notification: Notification? = nil) {
let durationNumber = (notification as NSNotification?)?.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber
let duration = durationNumber?.doubleValue ?? 0.1
UIView.animate(withDuration: duration, animations: {
let number = self.collectionView.numberOfItems(inSection: 0)
let itemIndex = self.scrollDelegate.itemIndex ?? number/2
guard itemIndex > 0 else {
return
}
let inset = self.collectionView.contentInset.top
let itemHeight = self.collectionLayout.itemHeight
let offset = CGPoint(x: 0, y: CGFloat(itemIndex) * itemHeight - inset)
self.collectionView.contentOffset = offset
})
}
func adjustScroll(_ notification: Notification? = nil) {
collectionView.contentInset = UIEdgeInsets.zero
collectionLayout.updateInsets()
self.updateOffset(notification)
}
}
class CollectionViewDataSource: NSObject, UICollectionViewDataSource {
weak var wrapper: WrapperProtocol!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let number = self.wrapper.numberOfCells
return number
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.wrapper.createCell(collectionView, indexPath: indexPath)
return cell
}
}
class ScrollViewDelegate: NSObject, UIScrollViewDelegate {
typealias ItemIndexChangeCallback = (Int?) -> ()
var itemIndexChangeCallback: ItemIndexChangeCallback?
fileprivate(set) var itemIndex: Int? = nil {
willSet (newIndex) {
if let callback = itemIndexChangeCallback {
callback(newIndex)
}
}
}
let itemHeight: CGFloat
init (itemHeight: CGFloat) {
self.itemHeight = itemHeight
super.init()
}
func adjustScroll(_ scrollView: UIScrollView) {
let inset = scrollView.contentInset.top
let currentOffsetY = scrollView.contentOffset.y + inset
let floatIndex = currentOffsetY/itemHeight
let scrollDirection = ScrollDirection.scrolledWhere(scrollFrom, scrollTo)
let itemIndex: Int
switch scrollDirection {
case .noScroll:
itemIndex = Int(floatIndex)
case .up:
itemIndex = Int(floor(floatIndex))
case .down:
itemIndex = Int(ceil(floatIndex))
}
if itemIndex >= 0 {
self.itemIndex = itemIndex
}
// Perform no animation if no scroll is needed
if case .noScroll = scrollDirection {
return
}
let adjestedOffsetY = CGFloat(itemIndex) * itemHeight - inset
// Difference between actual and designated position in pixels
let Δ = abs(scrollView.contentOffset.y - adjestedOffsetY)
// Allowed differenct between actual and designated position in pixels
let ε:CGFloat = 0.5
// If difference is larger than allowed, then adjust position animated
if Δ > ε {
UIView.animate(withDuration: 0.25,
delay: 0.0,
options: UIView.AnimationOptions.curveEaseOut,
animations: {
let newOffset = CGPoint(x: 0, y: adjestedOffsetY)
scrollView.contentOffset = newOffset
},
completion: nil)
}
}
var scrollFrom: CGFloat = 0
var scrollTo: CGFloat = 0
enum ScrollDirection {
case up
case down
case noScroll
static func scrolledWhere(_ from: CGFloat, _ to: CGFloat) -> ScrollDirection {
if from < to {
return .down
}
else if from > to {
return .up
}
else {
return .noScroll
}
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollFrom = scrollView.contentOffset.y
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollTo = scrollView.contentOffset.y
adjustScroll(scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollTo = scrollView.contentOffset.y
adjustScroll(scrollView)
}
}
}
| 30.201183 | 137 | 0.605114 |
2f448cb722e8c0a377e0c2cec3412e8146f5747c | 344 | // Copyright (c) 2017-2019 Coinbase Inc. See LICENSE
import Foundation
// Represents an HTTP method
public enum HTTPMethod: String {
/// Post request method
case post = "POST"
/// Get request method
case get = "GET"
/// Put request method
case put = "PUT"
/// Delete request method
case delete = "DELETE"
}
| 18.105263 | 52 | 0.636628 |
0ad24c2cc96dff9956ea57ffedca27f36b7c4fd0 | 238 | //
// HasInitial.swift
// FitnessTrackerKit
//
// Created by Swain Molster on 7/27/18.
// Copyright © 2018 Swain Molster. All rights reserved.
//
import Foundation
public protocol HasInitial {
static var initial: Self { get }
}
| 17 | 56 | 0.693277 |
f7afdfa6ffceb73d159b8f85072753f8f77e6cb9 | 753 | import AsyncDisplayKit
extension ASTextCellNode {
convenience init(text: String? = nil, insets: UIEdgeInsets? = nil, font: UIFont? = nil, colour: UIColor? = nil, alignment: NSParagraphStyle? = nil, selectionStyle: UITableViewCell.SelectionStyle? = nil, accessoryType: UITableViewCell.AccessoryType? = nil) {
self.init(
attributes: [
NSAttributedString.Key.font: font ?? .circularStdBook(size: .labelFontSize),
NSAttributedString.Key.foregroundColor: colour ?? .label,
NSAttributedString.Key.paragraphStyle: alignment ?? .leftAligned
],
insets: insets ?? .cellNode
)
self.text = text ?? ""
self.selectionStyle = selectionStyle ?? .default
self.accessoryType = accessoryType ?? .none
}
}
| 41.833333 | 259 | 0.698539 |
9c7ed0420cadef0d01b2288bf028e81b7eacc4ba | 4,153 | //
// SceneDelegate.swift
// Xchangerator
//
// Created by 张一唯 on 2020-01-21.
// Copyright © 2020 YYES. All rights reserved.
//
import FirebaseUI
import SwiftUI
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
let stateStore = ReduxRootStateStore() // state store init
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
stateStore.isLandscape = (windowScene.interfaceOrientation.isLandscape == true)
let window = UIWindow(windowScene: windowScene)
// if user is already logged in
if let user = Auth.auth().currentUser {
stateStore.curRoute = .content
// fetch user profile
let userProfile = User_Profile(email: user.email ?? "New_\(user.uid)@Xchangerator.com", photoURL: user.photoURL, deviceTokens: [], name: user.displayName ?? "Loyal User")
let userDoc = User_DBDoc(profile: userProfile)
stateStore.setDoc(userDoc: userDoc)
// fetch user alerts
DatabaseManager.shared.asyncGetUserAlerts(user) { docSnapShots in
for i in 0 ..< 2 {
DatabaseManager.shared.setAlertToLocalStore(stateStore, docSnapShots, id: i)
}
}
}
// fetch exchange rates
stateStore.syncFetchCountries()
window.rootViewController = UIHostingController(rootView: LoginView().environmentObject(stateStore))
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
// added this function to register when the device is rotated
func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) {
// stateStore.isLandscape.toggle()
// Logger.debug("stateStore.isLandscape:\(stateStore.isLandscape)")
}
}
| 47.735632 | 241 | 0.683843 |
f9217bc8ab60af4d2d26f94c5d44f85fb98b2fe7 | 3,273 | import NIO
import NIOHTTP1
/// An HTTP response from a server back to the client.
///
/// let httpRes = HTTPResponse(status: .ok)
///
/// See `HTTPClient` and `HTTPServer`.
public struct HTTPResponse: HTTPMessage {
/// The HTTP version that corresponds to this response.
public var version: HTTPVersion
/// The HTTP response status.
public var status: HTTPResponseStatus
/// The header fields for this HTTP response.
/// The `"Content-Length"` and `"Transfer-Encoding"` headers will be set automatically
/// when the `body` property is mutated.
public var headers: HTTPHeaders
/// The `HTTPBody`. Updating this property will also update the associated transport headers.
///
/// httpRes.body = HTTPBody(string: "Hello, world!")
///
/// Also be sure to set this message's `contentType` property to a `MediaType` that correctly
/// represents the `HTTPBody`.
public var body: HTTPBody {
didSet { self.headers.updateTransportHeaders(for: self.body) }
}
public var upgrader: HTTPServerProtocolUpgrader?
/// Get and set `HTTPCookies` for this `HTTPResponse`
/// This accesses the `"Set-Cookie"` header.
public var cookies: HTTPCookies {
get { return HTTPCookies.parse(setCookieHeaders: self.headers[.setCookie]) ?? [:] }
set { newValue.serialize(into: &self) }
}
/// See `CustomStringConvertible`
public var description: String {
var desc: [String] = []
desc.append("HTTP/\(self.version.major).\(self.version.minor) \(self.status.code) \(self.status.reasonPhrase)")
desc.append(self.headers.debugDescription)
desc.append(self.body.description)
return desc.joined(separator: "\n")
}
// MARK: Init
/// Creates a new `HTTPResponse`.
///
/// let httpRes = HTTPResponse(status: .ok)
///
/// - parameters:
/// - status: `HTTPResponseStatus` to use. This defaults to `HTTPResponseStatus.ok`
/// - version: `HTTPVersion` of this response, should usually be (and defaults to) 1.1.
/// - headers: `HTTPHeaders` to include with this response.
/// Defaults to empty headers.
/// The `"Content-Length"` and `"Transfer-Encoding"` headers will be set automatically.
/// - body: `HTTPBody` for this response, defaults to an empty body.
/// See `LosslessHTTPBodyRepresentable` for more information.
public init(
status: HTTPResponseStatus = .ok,
version: HTTPVersion = .init(major: 1, minor: 1),
headers: HTTPHeaders = .init(),
body: HTTPBody = .empty
) {
self.init(
status: status,
version: version,
headersNoUpdate: headers,
body: body.convertToHTTPBody()
)
self.headers.updateTransportHeaders(for: self.body)
}
/// Internal init that creates a new `HTTPResponse` without sanitizing headers.
public init(
status: HTTPResponseStatus,
version: HTTPVersion,
headersNoUpdate headers: HTTPHeaders,
body: HTTPBody
) {
self.status = status
self.version = version
self.headers = headers
self.body = body
}
}
| 35.576087 | 119 | 0.626642 |
1d82799146440aa9e4f871c0be9c87d5429a6ef6 | 865 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
//@f:0
let package = Package(
name: "Pullman",
platforms: [ .macOS(.v11), .tvOS(.v14), .iOS(.v14), .watchOS(.v7) ],
products: [
.library(name: "Pullman", targets: [ "Pullman" ]),
],
dependencies: [
.package(name: "Rubicon", url: "https://github.com/GalenRhodes/Rubicon.git", .upToNextMinor(from: "0.10.2")),
.package(name: "RedBlackTree", url: "https://github.com/GalenRhodes/RedBlackTree.git", .upToNextMajor(from: "2.0.5"))
],
targets: [
.target(name: "Pullman", dependencies: [ "Rubicon", "RedBlackTree" ], exclude: [ "Info.plist", ]),
.testTarget(name: "PullmanTests", dependencies: [ "Pullman" ], exclude: [ "Info.plist", ]),
])
//@f:1
| 39.318182 | 125 | 0.623121 |
69fc3c3372b410ebc88a18d821f4f9e7a0c33bfe | 967 | import ArgumentParser
import Foundation
import AdventKit
// Define our parser.
struct Day20: ParsableCommand {
//Declare optional argument. Drag the input file to terminal!
@Option(name: [.short, .customLong("inputFile")], help: "Specify the path to the input file.")
var inputFile : String = ""
func run() throws {
var input: String = ""
if !inputFile.isEmpty {
let url = URL(fileURLWithPath: inputFile)
guard let inputFile = try? String(contentsOf: url) else {fatalError()}
input = inputFile
} else {
print("Running Day20 Challenge with input from the website\n")
guard let url = Bundle.module.url(forResource: "input", withExtension: "txt") else { fatalError()}
//guard let url = Bundle.module.url(forResource: "Day17-example", withExtension: "txt") else { fatalError()}
guard let inputFile = try? String(contentsOf: url) else {fatalError()}
input = inputFile
}
print(input)
}
}
// Run the parser.
Day20.main()
| 25.447368 | 111 | 0.695967 |
f925a9858bccf023ad7fffbdcf9238d94ea5fc7a | 3,813 | //
// ConsolesTableViewController.swift
// MyGames
//
// Created by Douglas Frari on 16/05/20.
// Copyright © 2020 Douglas Frari. All rights reserved.
//
import UIKit
import CoreData
class ConsolesTableViewController: UITableViewController {
var fetchedResultController:NSFetchedResultsController<Console>!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// se ocorrer mudancas na entidade Console, a atualização automatica não irá ocorrer porque nosso NSFetchResultsController esta monitorando a entidade Game. Caso tiver mudanças na entidade Console precisamos atualizar a tela com a tabela de alguma forma: reloadData :)
loadConsoles()
}
func loadConsoles() {
ConsolesManager.shared.loadConsoles(with: context)
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return ConsolesManager.shared.consoles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ConsoleTableViewCell
let console = ConsolesManager.shared.consoles[indexPath.row]
cell.prepare(with: console)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let console = ConsolesManager.shared.consoles[indexPath.row]
//
// deselecionar atual cell
tableView.deselectRow(at: indexPath, animated: false)
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
ConsolesManager.shared.deleteConsole(index: indexPath.row, context: context)
tableView.deleteRows(at: [indexPath], with: .fade)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier! == "editConsole" {
print("editConsole")
let vc = segue.destination as! AddEditConsoleViewController
vc.console = ConsolesManager.shared.consoles[tableView.indexPathForSelectedRow!.row]
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
} // fim da classe
| 33.156522 | 279 | 0.672699 |
4b05e93e1120cc469f24295a4fe020bda05da915 | 1,099 | //
// PXBodyViewModelHelper.swift
// MercadoPagoSDK
//
// Created by AUGUSTO COLLERONE ALFONSO on 11/27/17.
// Copyright © 2017 MercadoPago. All rights reserved.
//
import UIKit
internal extension PXResultViewModel {
func getBodyComponentProps() -> PXBodyProps {
let props = PXBodyProps(paymentResult: self.paymentResult, amountHelper: self.amountHelper, instruction: getInstrucion(), callback: getBodyAction())
return props
}
func buildBodyComponent() -> PXComponentizable? {
let bodyProps = getBodyComponentProps()
return PXBodyComponent(props: bodyProps)
}
}
// MARK: Build Helpers
internal extension PXResultViewModel {
func getBodyAction() -> (() -> Void) {
return { [weak self] in self?.executeBodyCallback() }
}
func executeBodyCallback() {
self.callback(PaymentResult.CongratsState.call_FOR_AUTH)
}
func getInstrucion() -> PXInstruction? {
guard let instructionsInfo = self.instructionsInfo else {
return nil
}
return instructionsInfo.getInstruction()
}
}
| 27.475 | 156 | 0.681529 |
169958b0de1a1d664901b6ef69c6c8da22b6c0d1 | 3,703 | /*
* 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 UIKit
import BeagleUI
struct Style {
static let theme = AppTheme(styles: [
.BUTTON_BLACK_TEXT_STYLE: Style.blackTextNormalStyle,
.TEXT_HELLO_WORD_STYLE: Style.designSystemTextHelloWord,
.TEXT_IMAGE_STYLE: Style.designSystemTextImage,
.TEXT_ACTION_CLICK_STYLE: Style.designSystemTextActionClick,
.TEXT_STYLISH_STYLE: Style.designSystemStylishButton,
.BUTTON_WITH_APPEARANCE_STYLE: Style.designSystemStylishButtonAndAppearance,
.FORM_SUBMIT_STYLE: Style.formButton,
.NAVIGATION_BAR_GREEN_STYLE: Style.designSystemStyleNavigationBar,
.NAVIGATION_BAR_DEFAULT_STYLE: Style.designSystemStyleNavigationBarDefault,
.TAB_VIEW_STYLE: Style.tabView
]
)
static func blackTextNormalStyle() -> (UITextView?) -> Void {
return BeagleStyle.text(font: .systemFont(ofSize: 16) ,color: .black)
}
static func designSystemTextHelloWord() -> (UITextView?) -> Void {
return BeagleStyle.text(font: .boldSystemFont(ofSize: 18), color: .darkGray)
}
static func designSystemTextImage() -> (UITextView?) -> Void {
return BeagleStyle.text(font: .boldSystemFont(ofSize: 12), color: .black)
}
static func designSystemTextActionClick() -> (UITextView?) -> Void {
return BeagleStyle.text(font: .boldSystemFont(ofSize: 40), color: .black)
}
static func designSystemStylishButton() -> (UIButton?) -> Void {
return BeagleStyle.button(withTitleColor: .black)
<> {
$0?.titleLabel |> BeagleStyle.label(withFont: .systemFont(ofSize: 16, weight: .semibold))
}
}
static func designSystemStylishButtonAndAppearance() -> (UIButton?) -> Void {
return BeagleStyle.button(withTitleColor: .white)
<> {
$0?.titleLabel |> BeagleStyle.label(withFont: .systemFont(ofSize: 16, weight: .semibold))
}
}
static func designSystemStyleNavigationBar() -> (UINavigationBar?) -> Void {
return {
$0?.barTintColor = .green
$0?.isTranslucent = false
}
}
static func designSystemStyleNavigationBarDefault() -> (UINavigationBar?) -> Void {
return {
$0?.barTintColor = nil
$0?.isTranslucent = true
}
}
static func formButton() -> (UIButton?) -> Void {
return {
$0?.layer.cornerRadius = 4
$0?.setTitleColor(.white, for: .normal)
$0?.backgroundColor = $0?.isEnabled ?? false ? UIColor(hex: .GREEN_COLOR) : UIColor(hex: .GRAY_COLOR)
$0?.alpha = $0?.isHighlighted ?? false ? 0.7 : 1
}
}
static func tabView() -> (UIView?) -> Void {
return BeagleStyle.tabView(backgroundColor: .clear, indicatorColor: UIColor(hex: .ORANGE_COLOR), selectedTextColor: UIColor(hex: .ORANGE_COLOR), unselectedTextColor: UIColor(hex: .DARK_GRAY_COLOR), selectedIconColor: UIColor(hex: .ORANGE_COLOR), unselectedIconColor: UIColor(hex: .DARK_GRAY_COLOR))
}
}
| 39.393617 | 306 | 0.658925 |
e4253a93566a6d0d42f29e93161f67e6f20a6470 | 2,720 | //
// TableScrollNavigationViewController.swift
// Pods
//
// Created by ChanCyrus on 3/24/16.
//
//
import UIKit
public class TableScrollNavigationViewController: UIViewController {
// MARK: - properties
//scrollView that is used to scroll with the Table Navigation Controller
var scrollableView: UIScrollView?
var titleView: UILabel!
var backView: UIButton!
// MARK: - lifecycles
override public func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
if let nvc = navigationController as? TableScrollNavigationController{
if let sv = scrollableView {
// Adjust the frame of the scrollableView due to the change of the tableView in Navigation Controller
sv.contentInset.top = nvc.fullNavBarHeight
sv.scrollIndicatorInsets.top = sv.contentInset.top
// change the back button to custom one in order to animate
if nvc.viewControllers.count > 1{
let icon = UIImage(named: "Collapse Arrow")
let iconButton = UIButton(frame: CGRect(origin: CGPointZero, size: CGSize(width: 20, height: 20)))
iconButton.addTarget(self, action: "backBarClicked:", forControlEvents: .TouchUpInside)
iconButton.setBackgroundImage(icon, forState: .Normal)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: iconButton)
}
}
}
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let navigationController = self.navigationController as? TableScrollNavigationController {
if let scrollableView = scrollableView{
navigationController.followScrollView(scrollableView, scrollUpDelay: 0, scrollDownDelay: 50)
}
}
}
override public func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if let navigationController = self.navigationController as? TableScrollNavigationController {
navigationController.stopFollowingScrollView()
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func attachScrollableView(view: UIScrollView){
scrollableView = view
}
public func backBarClicked (sender: UIBarButtonItem){
if let nvc = navigationController as? TableScrollNavigationController{
nvc.popViewControllerAnimated(true)
}
}
}
| 36.756757 | 118 | 0.65 |
ef3bfb0527fdd13fa3be5e5277d9c5a240588299 | 1,833 | //
// GameScene.swift
// FPLabelNodeDemo
//
// Created by Kuo-Chuan Pan on 11/10/15.
// Copyright (c) 2015 Kuo-Chuan Pan. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
let label = FPLabelNode(fontNamed:"Helvetica")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
backgroundColor = SKColor.blackColor()
label.width = CGRectGetMaxX(self.frame)
label.height = CGRectGetMaxY(self.frame) - 200
label.fontColor = SKColor.whiteColor()
//label.fontSize = 30
//label.spacing = 1.5
//label.buffer = 80
label.verticalAlignmentMode = .Center
label.horizontalAlignmentMode = .Center
label.position = CGPoint(x: 0, y: CGRectGetMaxY(self.frame) - 200)
self.addChild(label)
// Pushing many texts
label.pushTexts(["Each String will become a line.",
"If you want to break your String to multi-lines, just split it to an array of String.", "",
"You can also push a very long string. FPLabelNode will automatically break the string for you, depending on the width of your FPLabelNode."
])
// Push a long string with "\n"
label.pushString("This \nstring\nislike\nthe\nold\nway.")
label.pushText("Tap the screen to add more text...")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
label.pushText("You can also push more texts later. If the string exceeds its maximun height, it will automatically clear the previous text for you. ")
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| 33.944444 | 159 | 0.624113 |
914ad52e3fca49d71d5fc8f73b2872e13dd7f1fd | 1,795 | //
// SILGattProjectMarker.swift
// BlueGecko
//
// Created by Kamil Czajka on 2.8.2021.
// Copyright © 2021 SiliconLabs. All rights reserved.
//
import Foundation
import AEXML
import RealmSwift
struct SILGattProjectMarker: SILGattXmlMarkerType {
var element: AEXMLElement
typealias GattConfigurationEntity = SILGattProjectEntity
let helper = SILGattImportHelper.shared
func parse() -> Result<SILGattProjectEntity, SILGattXmlParserError> {
var projectEntity = SILGattProjectEntity()
guard element.name == "project" else {
return .failure(.parsingError(description: helper.errorNotAllowedElementName(element: element, expectedName: "<project>")))
}
guard element.children.count == 1 else {
return .failure(.parsingError(description: helper.errorMustContainElementInside(name: "<gatt>", inMarker: "<project>", onlyOne: true)))
}
guard helper.hasLessOrEqualThanChild(element: element, childName: "gatt", count: 1) else {
return .failure(.parsingError(description: helper.errorTooManyMarkers(name: "<gatt>", inMarker: "<project>")))
}
for (_, attribute) in element.attributes.enumerated() {
let attributeName = attribute.key as String
let attributeValue = attribute.value as String
if attributeName == "device" {
projectEntity.additionalXmlAttributes.append(SILGattXMLAttribute(name: attributeName, value: attributeValue))
} else {
return .failure(.parsingError(description: helper.errorNotAllowedAttributeName(name: attributeName, inMarker: "<project>")))
}
}
return .success(projectEntity)
}
}
| 36.632653 | 147 | 0.65571 |
bf90cf9415a7cc72a49567367b3bafba64b010bb | 4,138 | //
// BusinessDetailView.swift
// veterans-code-a-thon
//
// Created by Leonard Box on 5/23/21.
//
import SwiftUI
import CoreLocation
import SDWebImageSwiftUI
struct BusinessDetailView: View {
var business: Business
/*
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: park.latitude,
longitude: park.longitude)
}
*/
var body: some View {
VStack {
//MapDetailView(coordinate: coordinate)
//.edgesIgnoringSafeArea(.top)
//.frame(height: 300)
CircleImage(business: business)
.offset(x: 0, y: -150)
.padding(.bottom, -150)
VStack(alignment: .leading) {
Text(business.name)
.font(.title)
.bold()
.padding(.bottom)
HStack(alignment: .top) {
VStack(alignment: .leading) {
HStack {
Text(business.address1)
.font(.subheadline)
Text(business.address2)
.font(.subheadline)
}
HStack {
Text("\(business.city), \(business.state)")
.font(.subheadline)
}
}
.padding(.bottom)
HStack {
Spacer()
//NavigationLink(destination: DirectionsView(coordinate: coordinate, name: business.name)) {
// Text("Get Directions")
// .foregroundColor(.blue)
//}
Spacer()
}
.padding(.bottom)
HStack {
Text("Categories:")
.bold()
.underline()
}
HStack {
GeometryReader { geometry in
ScrollView {
Text(verbatim: self.business.businessType.rawValue)
.frame(width: geometry.size.width)
}
}
}
List {
HStack {
Text("Business Information:")
.bold()
.underline()
}
Section {
VStack {
HStack {
if(business.disabled == true) {
Image(systemName: "checkmark.square")
} else {
Image(systemName: "square")
}
Text(" Disabled Veteran Owned")
Spacer()
if(business.minority == true) {
Image(systemName: "checkmark.square")
} else {
Image(systemName: "square")
}
Text(" Minority Veteran Owned")
}
HStack {
if(business.women == true) {
Image(systemName: "checkmark.square")
} else {
Image(systemName: "square")
}
Text(" Woman Veteran Owned")
Spacer()
//
}
}
}
}
.padding()
}
}
Spacer()
}
.edgesIgnoringSafeArea(.top)
}
}
| 35.367521 | 112 | 0.32842 |
7527c76d509ad1fafa2915b9c15d55e18e1ac0a8 | 768 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType {
struct ConditionalContent { }
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.ConditionalContent: SingleViewContent {
static func child(_ content: Content) throws -> Content {
let storage = try Inspector.attribute(label: "storage", value: content.view)
if let trueContent = try? Inspector.attribute(label: "trueContent", value: storage) {
return try Inspector.unwrap(view: trueContent, modifiers: [])
}
let falseContent = try Inspector.attribute(label: "falseContent", value: storage)
return try Inspector.unwrap(view: falseContent, modifiers: [])
}
}
| 34.909091 | 93 | 0.684896 |
db4048225cb38c823da35f090b9d14c78f07f2de | 1,124 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
var CollectionTests = TestSuite("Collection")
// Test collections using value types as elements.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
}
runAllTests()
| 28.820513 | 91 | 0.653915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.