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
|
---|---|---|---|---|---|
69bc80d05bd92cd66260092204b59e603d946d0f | 7,635 | //
// AppConfigurationFetchTests.swift
// DuckDuckGo
//
// Copyright © 2021 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import BackgroundTasks
@testable import DuckDuckGo
class AppConfigurationFetchTests: XCTestCase {
let testGroupName = "configurationFetchTestGroup"
override func setUp() {
UserDefaults(suiteName: testGroupName)?.removePersistentDomain(forName: testGroupName)
}
func testBackgroundRefreshCompletionStatusSuccess() {
XCTAssertFalse(AppConfigurationFetch.BackgroundRefreshCompletionStatus.expired.success)
XCTAssertTrue(AppConfigurationFetch.BackgroundRefreshCompletionStatus.noData.success)
XCTAssertTrue(AppConfigurationFetch.BackgroundRefreshCompletionStatus.newData.success)
}
// MARK: - Test Expired
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenExpiredWithNoPreviousStatus() {
assert(current: .expired, previous: nil)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenExpiredWithPreviousExpiration() {
assert(current: .expired, previous: .expired)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenExpiredWithPreviousNoDataSuccess() {
assert(current: .expired, previous: .noData)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenExpiredWithPreviousNewDataSuccess() {
assert(current: .expired, previous: .newData)
}
// MARK: - Test Success With No Data
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNoDataAndNoPreviousStatus() {
assert(current: .noData, previous: nil)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNoDataAndPreviousExpiration() {
assert(current: .noData, previous: .expired)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNoDataAndPreviousNoData() {
assert(current: .noData, previous: .noData)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNoDataAndPreviousNewData() {
assert(current: .noData, previous: .newData)
}
// MARK: - Test Success With New Data
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNewDataAndNoPreviousStatus() {
assert(current: .newData, previous: nil)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNewDataAndPreviousExpiration() {
assert(current: .newData, previous: .expired)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNewDataAndPreviousNoData() {
assert(current: .newData, previous: .noData)
}
@available(iOS 13.0, *)
func testBackgroundRefreshCompletionHandlerWhenSucceededWithNewDataAndPreviousNewData() {
assert(current: .newData, previous: .newData)
}
func testWhenTheCompletionHandlerTriesToUpdateStatisticsThenTheCountCannotBeNegative() {
// Using @available at the function/class level still allowed these unit tests to run pre iOS 13, so a guard statement is used.
guard #available(iOS 13.0, *) else {
return
}
let store = AppUserDefaults(groupName: testGroupName)
let task = MockBackgroundTask()
store.backgroundFetchTaskExpirationCount = 0
store.backgroundNoDataCount = 0
store.backgroundNewDataCount = 0
let newStatus = MockAppConfigurationFetch.backgroundRefreshTaskCompletionHandler(store: store,
refreshStartDate: Date(),
task: task,
status: .noData,
previousStatus: .expired)
XCTAssertEqual(newStatus, .noData)
XCTAssertEqual(store.backgroundFetchTaskExpirationCount, 0)
XCTAssertEqual(store.backgroundNoDataCount, 0)
XCTAssertEqual(store.backgroundNewDataCount, 0)
}
// This function sets up the environment that the completion handler expects when called. Specifically:
//
// - It expects `backgroundFetchTaskExpirationCount` to only be incremented if there is no previous status
// - `backgroundNoDataCount` and `backgroundNewDataCount` will be incremented even if there is a previous status
private func assert(current: AppConfigurationFetch.BackgroundRefreshCompletionStatus,
previous: AppConfigurationFetch.BackgroundRefreshCompletionStatus?) {
// Using @available at the function/class level still allowed these unit tests to run pre iOS 13, so a guard statement is used.
guard #available(iOS 13.0, *) else {
return
}
let store = AppUserDefaults(groupName: testGroupName)
let task = MockBackgroundTask()
// Set up the counts for the current and previous statuses. The completion handler expects that the statistic counts have already been
// updated before completion.
switch current {
case .expired:
// This counter will have only been incremented if there was no previous completion.
if previous == nil {
store.backgroundFetchTaskExpirationCount += 1
}
case .noData:
store.backgroundNoDataCount += 1
case .newData:
store.backgroundNewDataCount += 1
}
let newStatus = MockAppConfigurationFetch.backgroundRefreshTaskCompletionHandler(store: store,
refreshStartDate: Date(),
task: task,
status: current,
previousStatus: previous)
XCTAssertEqual(newStatus, current)
XCTAssertEqual(store.backgroundFetchTaskExpirationCount, (current == .expired && previous == nil) ? 1 : 0)
XCTAssertEqual(store.backgroundNoDataCount, current == .noData ? 1 : 0)
XCTAssertEqual(store.backgroundNewDataCount, current == .newData ? 1 : 0)
}
}
private class MockAppConfigurationFetch: AppConfigurationFetch {
func fetchConfigurationFiles(isBackground: Bool) -> Bool {
return true
}
}
@available(iOS 13.0, *)
private class MockBackgroundTask: BGTask {
/// Used to instantiate background tasks, as `BGTask` marks its `init` unavailable.
init(_ unusedValue: String? = nil) {}
override func setTaskCompleted(success: Bool) {
// no-op
}
}
| 38.954082 | 142 | 0.64964 |
699b01185f6d37b507f6893504677d9bc5ab4bd6 | 516 | //
// ViewController.swift
// GoogleMapsPlacesSDK
//
// Created by Zaid Pathan on 01/09/18.
// Copyright © 2018 Zaid Pathan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.846154 | 80 | 0.674419 |
dd5d00d7a43a3c09bee60577f48d97211a0ebb9e | 1,597 | //
// DownloadVodSpec.swift
// Exposure
//
// Created by Viktor Gardart on 2017-09-18.
// Copyright © 2017 emp. All rights reserved.
//
import Quick
import Nimble
@testable import Exposure
class DownloadVodSpec: QuickSpec {
override func spec() {
super.spec()
let base = "https://exposure.empps.ebsd.ericsson.net"
let customer = "BlixtGroup"
let businessUnit = "Blixt"
var env = Environment(baseUrl: base, customer: customer, businessUnit: businessUnit)
env.version = "v2"
let assetId = "assetId1_qwerty"
let sessionToken = SessionToken(value: "token")
let downloadVod = Entitlement(environment: env,
sessionToken: sessionToken)
.download(assetId: assetId)
.use(drm: "UNENCRYPTED")
.use(format: "HLS")
describe("DownloadVod") {
it("should have headers") {
expect(downloadVod.headers).toNot(beNil())
expect(downloadVod.headers!).to(equal(sessionToken.authorizationHeader))
}
it("should generate a correct endpoint url") {
let endpoint = "/entitlement/" + assetId + "/download"
expect(downloadVod.endpointUrl).to(equal(env.apiUrl+endpoint))
}
it("should record DRM and format") {
let drm = downloadVod.drm
let format = downloadVod.format
expect(drm).to(equal("UNENCRYPTED"))
expect(format).to(equal("HLS"))
}
}
}
}
| 29.574074 | 92 | 0.568566 |
f78a084bff5c84ed63c0ddb31bc2ed0e1e5c0d93 | 1,298 | //
// MutableStringWrapper.swift
// TypeErasurePatterns
//
// Copyright (c) 2021 Rocket Insights, Inc.
//
// 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
struct MutableStringWrapper: MutableWrapperProtocol {
var value: String
}
| 40.5625 | 79 | 0.754237 |
0a9d64bf4fa58b0ffaa1d78824304f3d86763ab1 | 2,434 | //
// DefaultWebSocketAdapter.swift
// AmazonChimeSDKMessagingDemo
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
//
import Starscream
public class DefaultWebSocketAdapter: WebSocketAdapter, WebSocketDelegate {
private var socket: WebSocket?
private var observer: WebSocketAdapterObserver?
// MARK: - WebSocketAdapter
public func connect(url: String, observer: WebSocketAdapterObserver) {
self.observer = observer
guard let urlObj = URL(string: url) else {
print("DefaultWebSocketAdapter connect() bad url")
return
}
var request = URLRequest(url: urlObj)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket?.delegate = self
socket?.connect()
}
public func close() {
socket?.disconnect()
}
// MARK: - WebSocketDelegate
public func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event {
case .connected(let headers):
print("DefaultWebSocketAdapter websocket is connected: \(headers)")
observer?.onConnect()
case .disconnected(let reason, let code):
print("DefaultWebSocketAdapter websocket is disconnected: \(reason) with code: \(code)")
observer?.onClose(status: MessagingSessionStatus(code: Int(code), reason: reason))
case .text(let string):
print("DefaultWebSocketAdapter text received")
observer?.onMessage(message: string)
case .binary(let data):
print("DefaultWebSocketAdapter binary received: \(data.count)")
case .ping(_):
print("DefaultWebSocketAdapter ping received")
break
case .pong(_):
print("DefaultWebSocketAdapter pong received")
break
case .viabilityChanged(_):
print("DefaultWebSocketAdapter viability changed")
break
case .reconnectSuggested(_):
print("DefaultWebSocketAdapter reconnect suggested")
break
case .cancelled:
print("DefaultWebSocketAdapter cancelled")
case .error(let error):
print("DefaultWebSocketAdapter error \(String(describing: error))")
}
}
}
| 36.328358 | 104 | 0.60682 |
14d0b8f6d1895bf4fd3618a5d0f4fb51dd99acd0 | 2,334 | import Foundation
//27. Remove Element
//Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
//
//Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
//
//Return k after placing the final result in the first k slots of nums.
//
//Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
//
//Custom Judge:
//
//The judge will test your solution with the following code:
//
//int[] nums = [...]; // Input array
//int val = ...; // Value to remove
//int[] expectedNums = [...]; // The expected answer with correct length.
// // It is sorted with no values equaling val.
//
//int k = removeElement(nums, val); // Calls your implementation
//
//assert k == expectedNums.length;
//sort(nums, 0, k); // Sort the first k elements of nums
//for (int i = 0; i < actualLength; i++) {
// assert nums[i] == expectedNums[i];
//}
//If all assertions pass, then your solution will be accepted.
//
//
//
//Example 1:
//
//Input: nums = [3,2,2,3], val = 3
//Output: 2, nums = [2,2,_,_]
//Explanation: Your function should return k = 2, with the first two elements of nums being 2.
//It does not matter what you leave beyond the returned k (hence they are underscores).
//Example 2:
//
//Input: nums = [0,1,2,2,3,0,4,2], val = 2
//Output: 5, nums = [0,1,4,0,3,_,_,_]
//Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
//Note that the five elements can be returned in any order.
//It does not matter what you leave beyond the returned k (hence they are underscores).
//
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var slowIndex = 0
for number in nums {
if val != number {
nums[slowIndex] = number
slowIndex += 1
}
print(nums)
}
return slowIndex
}
}
| 39.559322 | 354 | 0.658526 |
f4c7507e25042c5c0123b3c01c0a8c1d6301902f | 2,372 | //
// LocationService.swift
// Foodie
//
// Created by Alton Lau on 2016-08-27.
// Copyright © 2016 Alton Lau. All rights reserved.
//
import CoreLocation
protocol LocationService {
func getAddress(fromLocation location: CLLocation, completion: @escaping (String?) -> Void)
func getLocation(fromAddress address: String, completion: @escaping (CLLocation?) -> Void)
}
class LocationServiceImplementation: LocationService {
func getAddress(fromLocation location: CLLocation, completion: @escaping (String?) -> Void) {
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)) { (placemarks, error) in
if let error = error {
Log.error(error.localizedDescription)
completion(.none)
return
}
guard let placemark = placemarks?.first else {
completion(.none)
return
}
let address: String = {
var addressList = [String]()
if let name = placemark.name {
addressList.append(name)
}
if let locality = placemark.locality {
addressList.append(locality)
}
if let administrativeArea = placemark.administrativeArea {
addressList.append(administrativeArea)
}
if let country = placemark.country {
addressList.append(country)
}
return addressList.joined(separator: ", ")
}()
completion(address)
}
}
func getLocation(fromAddress address: String, completion: @escaping (CLLocation?) -> Void) {
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address) { (placemarks, error) in
if let error = error {
Log.error(error.localizedDescription)
completion(.none)
return
}
guard let location = placemarks?.first?.location else {
completion(.none)
return
}
completion(location)
}
}
}
| 32.054054 | 158 | 0.540051 |
617ea84d62cd31ea838d1560ae2998d858157b37 | 406 | import XCTest
@testable import Gallery
final class GalleryTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(Gallery().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 25.375 | 87 | 0.64532 |
67290020b76fb34327d5b38fc739d7dfef6f7976 | 11,075 | /*
* Copyright 2015 Coodly 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 Foundation
import UIKit
import CoreData
private extension Selector {
static let contentSizeChanged = #selector(FetchedCollectionViewController.contentSizeChanged)
}
internal struct ChangeAction {
let sectionIndex: Int?
let indexPath: IndexPath?
let newIndexPath: IndexPath?
let changeType: NSFetchedResultsChangeType
}
let FetchedCollectionCellIdentifier = "FetchedCollectionCellIdentifier"
open class FetchedCollectionViewController<Model: NSManagedObject, Cell: UICollectionViewCell>: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate {
@IBOutlet public var collectionView: UICollectionView!
private var fetchedController: NSFetchedResultsController<Model>?
private var measuringCell: Cell?
private var changeActions = [ChangeAction]()
public var ignoreOffScreenUpdates = false
deinit {
NotificationCenter.default.removeObserver(self)
}
open override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: .contentSizeChanged, name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
if collectionView == nil {
//not loaded from xib
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.clear
view.addSubview(collectionView)
let views: [String: AnyObject] = ["collection": collectionView]
collectionView.translatesAutoresizingMaskIntoConstraints = false
let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[collection]|", options: [], metrics: nil, views: views)
let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|[collection]|", options: [], metrics: nil, views: views)
view.addConstraints(vertical + horizontal)
}
let cellNib = Cell.viewNib()
collectionView.register(cellNib, forCellWithReuseIdentifier: FetchedCollectionCellIdentifier)
measuringCell = Cell.loadInstance() as Cell
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard fetchedController == nil else {
return
}
fetchedController = createFetchedController()
fetchedController!.delegate = self
collectionView.reloadData()
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return fetchedController?.sections?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let controller = fetchedController else {
return 0
}
let sections:[NSFetchedResultsSectionInfo] = controller.sections! as [NSFetchedResultsSectionInfo]
return sections[section].numberOfObjects
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FetchedCollectionCellIdentifier, for: indexPath) as! Cell
let object = fetchedController!.object(at: indexPath)
configure(cell: cell, at: indexPath, with: object, forMeasuring: false)
return cell
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let object = fetchedController!.object(at: indexPath)
configure(cell: measuringCell!, at: indexPath, with: object, forMeasuring: true)
let height = calculateHeightForConfiguredSizingCell(measuringCell!)
return CGSize(width: collectionView.frame.width, height: height)
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let object = fetchedController!.object(at: indexPath)
tappedCell(at: indexPath, object: object)
}
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
Logging.log("controllerWillChangeContent")
changeActions.removeAll()
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
changeActions.append(ChangeAction(sectionIndex: sectionIndex, indexPath: nil, newIndexPath: nil, changeType: type))
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
changeActions.append(ChangeAction(sectionIndex: nil, indexPath: indexPath, newIndexPath: newIndexPath, changeType: type))
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
Logging.log("controllerDidChangeContent: \(changeActions.count) changes")
let visible = collectionView.indexPathsForVisibleItems
let updateClosure = {
// update sections
let sectionActions = self.changeActions.filter({ $0.sectionIndex != nil })
Logging.log("\(sectionActions.count) section actions")
let sectionInserts = sectionActions.filter({ $0.changeType == .insert }).map({ $0.sectionIndex! })
self.collectionView.insertSections(IndexSet(sectionInserts))
let sectionDeletes = sectionActions.filter({ $0.changeType == .insert }).map({ $0.sectionIndex! })
self.collectionView.deleteSections(IndexSet(sectionDeletes))
assert(sectionActions.filter({ $0.changeType != .insert && $0.changeType != .delete}).count == 0)
let cellActions = self.changeActions.filter({ $0.sectionIndex == nil })
Logging.log("\(cellActions.count) cell actions")
var cellUpdates = cellActions.filter({ $0.changeType == .update })
if self.ignoreOffScreenUpdates {
cellUpdates = cellUpdates.filter({ visible.contains($0.indexPath!) })
}
self.collectionView.reloadItems(at: cellUpdates.map({ $0.indexPath! }))
let cellInserts = cellActions.filter({ $0.changeType == .insert }).map({ $0.newIndexPath! })
self.collectionView.insertItems(at: cellInserts)
let cellDeletes = cellActions.filter({ $0.changeType == .delete}).map({ $0.indexPath! })
self.collectionView.deleteItems(at: cellDeletes)
let moveActions = cellActions.filter({ $0.changeType == .move})
for action in moveActions {
self.collectionView.moveItem(at: action.indexPath!, to: action.newIndexPath!)
}
}
let completion: (Bool) -> () = {
finished in
self.contentChanged()
}
collectionView.performBatchUpdates(updateClosure, completion: completion)
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
fatalError()
}
@objc func contentSizeChanged() {
DispatchQueue.main.async { () -> Void in
self.collectionView.reloadData()
}
}
public func isEmpty() -> Bool {
return fetchedController?.fetchedObjects?.count == 0
}
open func contentChanged() {
Logging.log("\(#function)")
}
open func createFetchedController() -> NSFetchedResultsController<Model> {
fatalError("Need to override \(#function)")
}
open func configure(cell: Cell, at indexPath: IndexPath, with object: Model, forMeasuring: Bool) {
Logging.log("configureCell(atIndexPath:\(indexPath))")
}
open func tappedCell(at indexPath: IndexPath, object entity: Model) {
Logging.log("tappedCell(indexPath:\(indexPath))")
}
func calculateHeightForConfiguredSizingCell(_ cell: UICollectionViewCell) -> CGFloat {
var frame = cell.frame
frame.size.width = collectionView.frame.width
cell.frame = frame
cell.setNeedsLayout()
cell.layoutIfNeeded()
let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
return size.height
}
public func hasObject(at indexPath: IndexPath) -> Bool {
guard let controller = fetchedController else {
return false
}
guard let sections = controller.sections, sections.count > indexPath.section else {
return false
}
let section = sections[indexPath.section]
if section.numberOfObjects <= indexPath.row {
return false
}
return true
}
public func object(at indexPath: IndexPath) -> Model {
return fetchedController!.object(at: indexPath)
}
public func updateFetch(predicate: NSPredicate? = nil, sort: [NSSortDescriptor]? = nil) {
guard let controller = fetchedController else {
return
}
var modified = false
if let predicate = predicate {
controller.fetchRequest.predicate = predicate
modified = true
}
if let sort = sort {
controller.fetchRequest.sortDescriptors = sort
modified = true
}
guard modified else {
return
}
do {
try controller.performFetch()
} catch {
fatalError("Fetch failed: \(error)")
}
collectionView.reloadData()
contentChanged()
}
}
| 40.272727 | 240 | 0.662573 |
1e915ff41a3b355cfe34ca22d02618a17d14c9aa | 2,511 | //
// TabBarController.swift
// Live
//
// Created by Beryter on 2019/8/22.
// Copyright © 2019 Beryter. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.selectedViewController?.preferredStatusBarStyle ?? .default
}
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return self.selectedViewController?.shouldAutorotate ?? false
}
override func viewDidLoad() {
super.viewDidLoad()
tabBar.barTintColor = .white
tabBar.tintColor = .black
// UIColor(0x8CA5FF)
tabBar.isTranslucent = false
tabBar.backgroundImage = UIImage(color: .white, size: CGSize(width: 1, height: 1))
tabBar.backgroundColor = .white
tabBar.shadowImage = UIImage()
tabBar.layer.shadowColor = UIColor.lightGray.cgColor
tabBar.layer.shadowOffset = CGSize(width: 0, height: -6)
tabBar.layer.shadowOpacity = 0.1
viewControllers = [categroyNav, featuredNav, meNav]
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
}
//MARK: - Controllers
lazy var categroyNav: BaseNaviController = {
let cv = CategoryListController()
let nav = BaseNaviController(rootViewController: cv)
let item = UITabBarItem(title: nil, image: UIImage(named: "icon_card"), selectedImage: nil)
item.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
nav.tabBarItem = item
return nav
}()
lazy var featuredNav: BaseNaviController = {
let cv = FeaturedController()
let nav = BaseNaviController(rootViewController: cv)
let item = UITabBarItem(title: nil, image: UIImage(named: "icon_about"), selectedImage: nil)
item.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
nav.tabBarItem = item
return nav
}()
lazy var meNav: BaseNaviController = {
let cv = MeController()
let nav = BaseNaviController(rootViewController: cv)
let item = UITabBarItem(title: nil, image: UIImage(named: "personal_icon"), selectedImage: nil)
item.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
nav.tabBarItem = item
return nav
}()
}
extension TabBarController: UITabBarControllerDelegate {
}
| 33.039474 | 103 | 0.648746 |
623871e0fef40d526f8dfce5c5844bc3ef1b4855 | 4,321 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 Swift project authors
*/
import XCTest
@testable import Markdown
final class BasicInlineContainerTests: XCTestCase {
func testFromSequence() {
let expectedChildren = Array(repeating: Text("OK"), count: 3)
let emphasis = Emphasis(expectedChildren)
let gottenChildren = Array(emphasis.children)
XCTAssertEqual(expectedChildren.count, gottenChildren.count)
for (expected, gotten) in zip(expectedChildren, gottenChildren) {
XCTAssertEqual(expected.debugDescription(), gotten.detachedFromParent.debugDescription())
}
}
func testReplacingChildrenInRange() {
let emphasis = Emphasis(Array(repeating: Text("OK"), count: 3))
let id = emphasis._data.id
do { // Insert one
let insertedChild = Text("Inserted")
var newEmphasis = emphasis
newEmphasis.replaceChildrenInRange(0..<0, with: CollectionOfOne(insertedChild))
assertElementDidntChange(emphasis, assertedStructure: Emphasis(Array(repeating: Text("OK"), count: 3)), expectedId: id)
XCTAssertEqual(insertedChild.debugDescription(), (newEmphasis.child(at: 0) as! Text).detachedFromParent.debugDescription())
XCTAssertEqual(4, newEmphasis.childCount)
}
do { // Insert multiple
let insertedChildren = Array(repeating: Text("Inserted"), count: 3)
var newEmphasis = emphasis
newEmphasis.replaceChildrenInRange(0..<0, with: insertedChildren)
assertElementDidntChange(emphasis, assertedStructure: Emphasis(Array(repeating: Text("OK"), count: 3)), expectedId: id)
let expectedDump = """
Emphasis
├─ Text "Inserted"
├─ Text "Inserted"
├─ Text "Inserted"
├─ Text "OK"
├─ Text "OK"
└─ Text "OK"
"""
XCTAssertEqual(expectedDump, newEmphasis.debugDescription())
XCTAssertEqual(6, newEmphasis.childCount)
}
do { // Replace one
let replacementChild = Text("Replacement")
var newEmphasis = emphasis
newEmphasis.replaceChildrenInRange(0..<1, with: CollectionOfOne(replacementChild))
XCTAssertEqual(replacementChild.debugDescription(), (newEmphasis.child(at: 0) as! Text).detachedFromParent.debugDescription())
XCTAssertEqual(3, newEmphasis.childCount)
}
do { // Replace many
let replacementChild = Text("Replacement")
var newEmphasis = emphasis
newEmphasis.replaceChildrenInRange(0..<2, with: CollectionOfOne(replacementChild))
assertElementDidntChange(emphasis, assertedStructure: Emphasis(Array(repeating: Text("OK"), count: 3)), expectedId: id)
let expectedDump = """
Emphasis
├─ Text "Replacement"
└─ Text "OK"
"""
XCTAssertEqual(expectedDump, newEmphasis.debugDescription())
XCTAssertEqual(2, newEmphasis.childCount)
}
do { // Replace all
let replacementChild = Text("Replacement")
var newEmphasis = emphasis
newEmphasis.replaceChildrenInRange(0..<3, with: CollectionOfOne(replacementChild))
let expectedDump = """
Emphasis
└─ Text "Replacement"
"""
XCTAssertEqual(expectedDump, newEmphasis.debugDescription())
XCTAssertEqual(1, newEmphasis.childCount)
}
}
func testSetChildren() {
let document = Paragraph(SoftBreak(), SoftBreak(), SoftBreak())
var newDocument = document
newDocument.setInlineChildren([Text("1"), Text("2")])
let expectedDump = """
Paragraph
├─ Text "1"
└─ Text "2"
"""
XCTAssertEqual(expectedDump, newDocument.debugDescription())
}
}
| 41.548077 | 138 | 0.611201 |
28e9dcee0279c3b84d0f9081be084d614e3bd6d0 | 1,537 | //: Playground - noun: a place where people can play
import Cocoa
let completePath = "/Users/chenji/Desktop/Files.playground"
let completeUrl = URL(fileURLWithPath: completePath)
let home = FileManager.default.homeDirectoryForCurrentUser
let playgroundPath = "Desktop/Files.playground"
let playgroundUrl = home.appendingPathComponent(playgroundPath)
playgroundUrl.path
playgroundUrl.absoluteString
playgroundUrl.absoluteURL
playgroundUrl.baseURL
playgroundUrl.pathComponents
playgroundUrl.lastPathComponent
playgroundUrl.pathExtension
playgroundUrl.isFileURL
playgroundUrl.hasDirectoryPath
var urlForEditing = home
urlForEditing.path
urlForEditing.appendPathComponent("Desktop")
urlForEditing.path
urlForEditing.appendPathComponent("Test file")
urlForEditing.path
urlForEditing.appendPathExtension("txt")
urlForEditing.path
urlForEditing.deletePathExtension()
urlForEditing.path
urlForEditing.deleteLastPathComponent()
urlForEditing.path
let fileUrl = home
.appendingPathComponent("Desktop")
.appendingPathComponent("Test file")
.appendingPathExtension("txt")
fileUrl.path
let desktopUrl = fileUrl.deletingLastPathComponent()
desktopUrl.path
let fileManager = FileManager.default
fileManager.fileExists(atPath: playgroundUrl.path)
let missingFile = URL(fileURLWithPath: "this_file_does_not_exist.missing")
fileManager.fileExists(atPath: missingFile.path)
var isDirectory: ObjCBool = false
fileManager.fileExists(atPath: playgroundUrl.path, isDirectory: &isDirectory)
isDirectory.boolValue
| 19.455696 | 77 | 0.830189 |
91d792c9278a3b5932ee6d4515812aeb36e1ce15 | 626 | //
// AndesCardHierarchyFactory.swift
// AndesUI
//
// Created by Martin Victory on 14/07/2020.
//
import Foundation
internal class AndesCardHierarchyFactory {
static func provide(_ hierarchy: AndesCardHierarchy, forStyle style: AndesCardStyleProtocol, forType type: AndesCardTypeProtocol) -> AndesCardHierarchyProtocol {
switch hierarchy {
case .primary:
return AndesCardHierarchyPrimary(style: style, type: type)
case .secondary:
return AndesCardHierarchySecondary()
case .secondaryDark:
return AndesCardHierarchySecondaryDark()
}
}
}
| 28.454545 | 165 | 0.696486 |
5dc69ff7c7e63634786523bb59f013027ccf9055 | 2,079 | //
// UIWaitingViewExtend.swift
// UIWatingViewController
//
// Created by Cao Phuoc Thanh on 5/16/20.
// Copyright © 2020 Cao Phuoc Thanh. All rights reserved.
//
import UIKit
public protocol UIWaitingViewExtend {
func startWaiting(_ title: String?)
func stopWaiting(_ calback: (() -> ())?)
func setWaitingBackgroundColor() -> UIColor
func setWaitingIndicatorBackgroundColor() -> UIColor
func setWaitingTitleColor() -> UIColor
func setWaitingTitleFont() -> UIFont
}
private var waitingViewController: WaitingHubViewController?
extension UIWaitingViewExtend where Self: UIViewController {
public func setWaitingBackgroundColor() -> UIColor {
return UIColor.black.alpha(0.95)
}
public func setWaitingIndicatorBackgroundColor() -> UIColor {
return UIColor.white.alpha(0.1)
}
public func setWaitingTitleColor() -> UIColor {
return UIColor.white
}
public func setWaitingTitleFont() -> UIFont {
return UIFont.systemFont(ofSize: 14)
}
public func startWaiting(_ title: String? = nil) {
guard let topMostViewController: UIViewController = UIViewController.topMostViewController() else { return }
let waitingIndicater: WaitingHubViewController = WaitingHubViewController()
waitingIndicater.view.backgroundColor = setWaitingBackgroundColor()
waitingIndicater.activityIndicatorView.backgroundColor = setWaitingIndicatorBackgroundColor()
waitingIndicater.titelLabel.textColor = setWaitingTitleColor()
waitingIndicater.titelLabel.font = setWaitingTitleFont()
waitingViewController = waitingIndicater
waitingIndicater.title = title
waitingIndicater.modalPresentationStyle = .overFullScreen
topMostViewController.present(waitingIndicater, animated: false, completion: nil)
}
public func stopWaiting(_ calback: (() -> ())? = nil) {
waitingViewController?.dismiss(animated: false)
waitingViewController = nil
calback?()
}
}
| 33.532258 | 116 | 0.702742 |
034dfacef8b0d7f350abb7b05ec02bb9e9fdc4a2 | 3,299 | //
// BaseMapSceneCharacterHero.swift
// DQ3
//
// Created by aship on 2020/12/23.
//
import SpriteKit
extension BaseMapScene {
internal func setCharacterHeroPosition(positionX: Int,
positionY: Int,
node: SKSpriteNode,
tileMapNode: SKTileMapNode,
scale: CGFloat) {
let mapSize = tileMapNode.mapSize
let mapWidth = Int(mapSize.width)
let mapHeight = Int(mapSize.height)
// 一旦キャラを position(0, 0) の位置に持っていってから
// 希望の position に移動する
// position (0, 0) に移動するための移動量を計算
let values = getMoveToOrigin(mapWidth: mapWidth,
mapHeight: mapHeight)
let characterMoveX: CGFloat = values.0
let characterMoveY: CGFloat = values.1
let actionCharacter = SKAction.moveBy(x: characterMoveX,
y: characterMoveY,
duration: 0)
// position (0, 0) に移動
node.run(actionCharacter)
// 目的の position に移動するための移動量を計算
let characterMoveX2 = CGFloat(positionX * 16)
let characterMoveY2 = CGFloat(positionY * 16)
let actionCharacter2 = SKAction.moveBy(x: characterMoveX2,
y: characterMoveY2,
duration: 0)
// 目的の position に移動
node.run(actionCharacter2)
}
internal func setMapPosition(positionX: Int,
positionY: Int,
tileMapNode: SKTileMapNode,
scale: CGFloat) {
let mapSize = tileMapNode.mapSize
let mapWidth = Int(mapSize.width)
let mapHeight = Int(mapSize.height)
// 一旦マップの position(0, 0) がキャラの標準位置になるように持っていってから
// キャラの位置がキャラの標準位置になるようにの希望の position 分、マップを逆方向に移動する
// マップの position (0, 0) がキャラの標準位置に移動するための移動量を計算
let values = getMoveToOrigin(mapWidth: mapWidth,
mapHeight: mapHeight)
let characterMoveX: CGFloat = values.0
let characterMoveY: CGFloat = values.1
let mapMoveX = -characterMoveX * scale
let mapMoveY = -characterMoveY * scale
let actionMap = SKAction.moveBy(x: mapMoveX,
y: mapMoveY,
duration: 0)
// マップの position (0, 0) がキャラの標準位置に移動
// (キャラの動きとは逆方向)
tileMapNode.run(actionMap)
// 今度はキャラが、キャラの標準位置に移動するためのマップの移動量を計算
let characterMoveX2 = CGFloat(positionX * 16)
let characterMoveY2 = CGFloat(positionY * 16)
let mapMoveX2 = -characterMoveX2 * scale
let mapMoveY2 = -characterMoveY2 * scale
let actionMap2 = SKAction.moveBy(x: mapMoveX2,
y: mapMoveY2,
duration: 0)
// キャラをキャラの標準位置に移動するために、マップを逆方向に動かす
tileMapNode.run(actionMap2)
}
}
| 36.252747 | 70 | 0.500758 |
16e999ab786c2a7fffed4ff0586d926aea536ff8 | 563 | import NIOCore
final class MessageEncoder: MessageToByteEncoder {
typealias OutboundIn = Message
func encode(data: Message, out: inout ByteBuffer) throws {
var message = data
switch message.identifier {
case .none: break
default: if let value = message.identifier.value { out.writeInteger(value) }
}
let writerIndex = out.writerIndex
out.moveWriterIndex(forwardBy: 4)
out.writeBuffer(&message.buffer)
out.setInteger(Int32(out.writerIndex - writerIndex), at: writerIndex)
}
}
| 28.15 | 84 | 0.667851 |
d659733c0632a75ca27cef68bf33bda0dfc8bcd4 | 299 | //
// {Name}Router.swift
// {project}
//
// Created by {author} on {date}.
//
import UIKit
final class {Name}Router: RouterInterface {
weak var presenter: {Name}PresenterRouterInterface!
weak var viewController: UIViewController?
}
extension {Name}Router: {Name}RouterInterface {
}
| 14.95 | 55 | 0.695652 |
7104513129e7760d13cd575ad16d9a6fb6d35923 | 11,136 |
public struct User {
public var avatar: Avatar
public var erroredBackingsCount: Int?
public var facebookConnected: Bool?
public var id: Int
public var isAdmin: Bool?
public var isEmailVerified: Bool?
public var isFriend: Bool?
public var location: Location?
public var name: String
public var needsFreshFacebookToken: Bool?
public var newsletters: NewsletterSubscriptions
public var notifications: Notifications
public var optedOutOfRecommendations: Bool?
public var showPublicProfile: Bool?
public var social: Bool?
public var stats: Stats
public var unseenActivityCount: Int?
public struct Avatar {
public var large: String?
public var medium: String
public var small: String
}
public struct NewsletterSubscriptions {
public var arts: Bool?
public var games: Bool?
public var happening: Bool?
public var invent: Bool?
public var promo: Bool?
public var weekly: Bool?
public var films: Bool?
public var publishing: Bool?
public var alumni: Bool?
public var music: Bool?
public static func all(on: Bool) -> NewsletterSubscriptions {
return NewsletterSubscriptions(
arts: on,
games: on,
happening: on,
invent: on,
promo: on,
weekly: on,
films: on,
publishing: on,
alumni: on,
music: on
)
}
}
public struct Notifications {
public var backings: Bool?
public var commentReplies: Bool?
public var comments: Bool?
public var creatorDigest: Bool?
public var creatorTips: Bool?
public var follower: Bool?
public var friendActivity: Bool?
public var messages: Bool?
public var mobileBackings: Bool?
public var mobileComments: Bool?
public var mobileFollower: Bool?
public var mobileFriendActivity: Bool?
public var mobileMarketingUpdate: Bool?
public var mobileMessages: Bool?
public var mobilePostLikes: Bool?
public var mobileUpdates: Bool?
public var postLikes: Bool?
public var updates: Bool?
}
public struct Stats {
public var backedProjectsCount: Int?
public var createdProjectsCount: Int?
public var draftProjectsCount: Int?
public var memberProjectsCount: Int?
public var starredProjectsCount: Int?
public var unansweredSurveysCount: Int?
public var unreadMessagesCount: Int?
}
public var isCreator: Bool {
return (self.stats.createdProjectsCount ?? 0) > 0
}
public var isRepeatCreator: Bool? {
guard let createdProjectsCount = self.stats.createdProjectsCount else {
return nil
}
return createdProjectsCount > 1
}
}
extension User: Equatable {}
public func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
extension User: CustomDebugStringConvertible {
public var debugDescription: String {
return "User(id: \(self.id), name: \"\(self.name)\")"
}
}
extension User: Decodable {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.avatar = try values.decode(Avatar.self, forKey: .avatar)
self.erroredBackingsCount = try values.decodeIfPresent(Int.self, forKey: .erroredBackingsCount)
self.facebookConnected = try values.decodeIfPresent(Bool.self, forKey: .facebookConnected)
self.id = try values.decode(Int.self, forKey: .id)
self.isAdmin = try values.decodeIfPresent(Bool.self, forKey: .isAdmin)
self.isEmailVerified = try values.decodeIfPresent(Bool.self, forKey: .isEmailVerified)
self.isFriend = try values.decodeIfPresent(Bool.self, forKey: .isFriend)
self.location = try? values.decodeIfPresent(Location.self, forKey: .location)
self.name = try values.decode(String.self, forKey: .name)
self.needsFreshFacebookToken = try values.decodeIfPresent(Bool.self, forKey: .needsFreshFacebookToken)
self.newsletters = try User.NewsletterSubscriptions(from: decoder)
self.notifications = try User.Notifications(from: decoder)
self.optedOutOfRecommendations = try values.decodeIfPresent(Bool.self, forKey: .optedOutOfRecommendations)
self.showPublicProfile = try values.decodeIfPresent(Bool.self, forKey: .showPublicProfile)
self.social = try values.decodeIfPresent(Bool.self, forKey: .social)
self.stats = try User.Stats(from: decoder)
self.unseenActivityCount = try values.decodeIfPresent(Int.self, forKey: .unseenActivityCount)
}
enum CodingKeys: String, CodingKey {
case avatar
case erroredBackingsCount = "errored_backings_count"
case facebookConnected = "facebook_connected"
case id
case isAdmin = "is_admin"
case isEmailVerified = "is_email_verified"
case isFriend = "is_friend"
case location
case name
case needsFreshFacebookToken = "needs_fresh_facebook_token"
case optedOutOfRecommendations = "opted_out_of_recommendations"
case showPublicProfile = "show_public_profile"
case social
case unseenActivityCount = "unseen_activity_count"
}
}
extension User: EncodableType {
public func encode() -> [String: Any] {
var result: [String: Any] = [:]
result["avatar"] = self.avatar.encode()
result["facebook_connected"] = self.facebookConnected ?? false
result["id"] = self.id
result["is_admin"] = self.isAdmin ?? false
result["is_email_verified"] = self.isEmailVerified ?? false
result["is_friend"] = self.isFriend ?? false
result["location"] = self.location?.encode()
result["name"] = self.name
result["opted_out_of_recommendations"] = self.optedOutOfRecommendations ?? false
result["social"] = self.social ?? false
result["show_public_profile"] = self.showPublicProfile ?? false
result = result.withAllValuesFrom(self.newsletters.encode())
result = result.withAllValuesFrom(self.notifications.encode())
result = result.withAllValuesFrom(self.stats.encode())
return result
}
}
extension User.Avatar: Decodable {
enum CodingKeys: String, CodingKey {
case large
case medium
case small
}
}
extension User.Avatar: EncodableType {
public func encode() -> [String: Any] {
var ret: [String: Any] = [
"medium": self.medium,
"small": self.small
]
ret["large"] = self.large
return ret
}
}
extension User.NewsletterSubscriptions: Decodable {
enum CodingKeys: String, CodingKey {
case arts = "arts_culture_newsletter"
case games = "games_newsletter"
case happening = "happening_newsletter"
case invent = "invent_newsletter"
case promo = "promo_newsletter"
case weekly = "weekly_newsletter"
case films = "film_newsletter"
case publishing = "publishing_newsletter"
case alumni = "alumni_newsletter"
case music = "music_newsletter"
}
}
extension User.NewsletterSubscriptions: EncodableType {
public func encode() -> [String: Any] {
var result: [String: Any] = [:]
result["arts_culture_newsletter"] = self.arts
result["games_newsletter"] = self.games
result["happening_newsletter"] = self.happening
result["invent_newsletter"] = self.invent
result["promo_newsletter"] = self.promo
result["weekly_newsletter"] = self.weekly
result["film_newsletter"] = self.films
result["publishing_newsletter"] = self.publishing
result["alumni_newsletter"] = self.alumni
result["music_newsletter"] = self.music
return result
}
}
extension User.NewsletterSubscriptions: Equatable {}
public func == (lhs: User.NewsletterSubscriptions, rhs: User.NewsletterSubscriptions) -> Bool {
return lhs.arts == rhs.arts &&
lhs.games == rhs.games &&
lhs.happening == rhs.happening &&
lhs.invent == rhs.invent &&
lhs.promo == rhs.promo &&
lhs.weekly == rhs.weekly &&
lhs.films == rhs.films &&
lhs.publishing == rhs.publishing &&
lhs.alumni == rhs.alumni
}
extension User.Notifications: Decodable {
enum CodingKeys: String, CodingKey {
case backings = "notify_of_backings"
case commentReplies = "notify_of_comment_replies"
case comments = "notify_of_comments"
case creatorDigest = "notify_of_creator_digest"
case creatorTips = "notify_of_creator_edu"
case follower = "notify_of_follower"
case friendActivity = "notify_of_friend_activity"
case messages = "notify_of_messages"
case mobileBackings = "notify_mobile_of_backings"
case mobileComments = "notify_mobile_of_comments"
case mobileFriendActivity = "notify_mobile_of_friend_activity"
case mobileMarketingUpdate = "notify_mobile_of_marketing_update"
case mobileMessages = "notify_mobile_of_messages"
case mobileFollower = "notify_mobile_of_follower"
case mobilePostLikes = "notify_mobile_of_post_likes"
case mobileUpdates = "notify_mobile_of_updates"
case postLikes = "notify_of_post_likes"
case updates = "notify_of_updates"
}
}
extension User.Notifications: EncodableType {
public func encode() -> [String: Any] {
var result: [String: Any] = [:]
result["notify_of_backings"] = self.backings
result["notify_of_comment_replies"] = self.commentReplies
result["notify_of_comments"] = self.comments
result["notify_of_creator_digest"] = self.creatorDigest
result["notify_of_creator_edu"] = self.creatorTips
result["notify_of_follower"] = self.follower
result["notify_of_friend_activity"] = self.friendActivity
result["notify_of_messages"] = self.messages
result["notify_mobile_of_comments"] = self.mobileComments
result["notify_mobile_of_follower"] = self.mobileFollower
result["notify_mobile_of_friend_activity"] = self.mobileFriendActivity
result["notify_mobile_of_marketing_update"] = self.mobileMarketingUpdate
result["notify_mobile_of_messages"] = self.mobileMessages
result["notify_mobile_of_post_likes"] = self.mobilePostLikes
result["notify_mobile_of_updates"] = self.mobileUpdates
result["notify_of_post_likes"] = self.postLikes
result["notify_of_updates"] = self.updates
result["notify_mobile_of_backings"] = self.mobileBackings
return result
}
}
extension User.Notifications: Equatable {}
extension User.Stats: Decodable {
enum CodingKeys: String, CodingKey {
case backedProjectsCount = "backed_projects_count"
case createdProjectsCount = "created_projects_count"
case draftProjectsCount = "draft_projects_count"
case memberProjectsCount = "member_projects_count"
case starredProjectsCount = "starred_projects_count"
case unansweredSurveysCount = "unanswered_surveys_count"
case unreadMessagesCount = "unread_messages_count"
}
}
extension User.Stats: EncodableType {
public func encode() -> [String: Any] {
var result: [String: Any] = [:]
result["backed_projects_count"] = self.backedProjectsCount
result["created_projects_count"] = self.createdProjectsCount
result["draft_projects_count"] = self.draftProjectsCount
result["member_projects_count"] = self.memberProjectsCount
result["starred_projects_count"] = self.starredProjectsCount
result["unanswered_surveys_count"] = self.unansweredSurveysCount
result["unread_messages_count"] = self.unreadMessagesCount
return result
}
}
| 35.692308 | 110 | 0.725575 |
e58809f07a1db37274a24ebbb07c253df4ebf8c4 | 1,287 | // Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlowLite
class QuantizationParametersTests: XCTestCase {
func testInitWithCustomValues() {
let parameters = QuantizationParameters(scale: 0.5, zeroPoint: 1)
XCTAssertEqual(parameters.scale, 0.5)
XCTAssertEqual(parameters.zeroPoint, 1)
}
func testEquatable() {
let parameters1 = QuantizationParameters(scale: 0.5, zeroPoint: 1)
let parameters2 = QuantizationParameters(scale: 0.5, zeroPoint: 1)
XCTAssertEqual(parameters1, parameters2)
let parameters3 = QuantizationParameters(scale: 0.4, zeroPoint: 1)
XCTAssertNotEqual(parameters1, parameters3)
XCTAssertNotEqual(parameters2, parameters3)
}
}
| 34.783784 | 75 | 0.755245 |
db74236fe01b5a05fdde1a9232c1840e3396dfd0 | 984 | //
// Note+CoreDataProperties.swift
// Notes
//
// Created by Arifin Firdaus on 1/12/18.
// Copyright © 2018 Arifin Firdaus. All rights reserved.
//
//
import Foundation
import CoreData
import UIKit
extension Note {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
return NSFetchRequest<Note>(entityName: "Note")
}
@NSManaged public var content: String?
@NSManaged public var id: String?
@NSManaged public var title: String?
convenience init(id: String?, title: String?, content: String?) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Note", in: managedObjectContext)
self.init(entity: entity!, insertInto: managedObjectContext)
self.id = id
self.title = title
self.content = content
}
}
| 25.230769 | 96 | 0.672764 |
5633322613c79c939d7836df35db5e5842143c80 | 9,464 | //
// Sensors.swift
// ModuleKit
//
// Created by Serhiy Mytrovtsiy on 17/06/2020.
// Using Swift 5.0.
// Running on macOS 10.15.
//
// Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved.
//
import Cocoa
import StatsKit
public struct SensorValue_t {
public let icon: NSImage?
public var value: String
public init(_ value: String, icon: NSImage? = nil){
self.value = value
self.icon = icon
}
}
public class SensorsWidget: Widget {
private var modeState: String = "automatic"
private var iconState: Bool = false
private let store: UnsafePointer<Store>?
private var values: [SensorValue_t] = []
public init(preview: Bool, title: String, config: NSDictionary?, store: UnsafePointer<Store>?) {
self.store = store
if config != nil {
var configuration = config!
if preview {
if let previewConfig = config!["Preview"] as? NSDictionary {
configuration = previewConfig
if let value = configuration["Values"] as? String {
self.values = value.split(separator: ",").map{ (SensorValue_t(String($0)) ) }
}
}
}
}
super.init(frame: CGRect(x: 0, y: Constants.Widget.margin, width: Constants.Widget.width, height: Constants.Widget.height - (2*Constants.Widget.margin)))
self.title = title
self.type = .sensors
self.preview = preview
self.canDrawConcurrently = true
if self.store != nil {
self.modeState = store!.pointee.string(key: "\(self.title)_\(self.type.rawValue)_mode", defaultValue: self.modeState)
self.iconState = store!.pointee.bool(key: "\(self.title)_\(self.type.rawValue)_icon", defaultValue: self.iconState)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard self.values.count != 0 else {
self.setWidth(1)
return
}
let num: Int = Int(round(Double(self.values.count) / 2))
var totalWidth: CGFloat = Constants.Widget.margin // opening space
var x: CGFloat = Constants.Widget.margin
var i = 0
while i < self.values.count {
switch self.modeState {
case "automatic", "twoRows":
let firstSensor: SensorValue_t = self.values[i]
let secondSensor: SensorValue_t? = self.values.indices.contains(i+1) ? self.values[i+1] : nil
var width: CGFloat = 0
if self.modeState == "automatic" && secondSensor == nil {
width += self.drawOneRow(firstSensor, x: x)
} else {
width += self.drawTwoRows(topSensor: firstSensor, bottomSensor: secondSensor, x: x)
}
x += width
totalWidth += width
if num != 1 && (i/2) != num {
x += Constants.Widget.margin
totalWidth += Constants.Widget.margin
}
i += 1
case "oneRow":
let width = self.drawOneRow(self.values[i], x: x)
x += width
totalWidth += width
// add margins between columns
if self.values.count != 1 && i != self.values.count {
x += Constants.Widget.margin
totalWidth += Constants.Widget.margin
}
default: break
}
i += 1
}
totalWidth += Constants.Widget.margin // closing space
if abs(self.frame.width - totalWidth) < 2 {
return
}
self.setWidth(totalWidth)
}
private func drawOneRow(_ sensor: SensorValue_t, x: CGFloat) -> CGFloat {
var width: CGFloat = 0
var paddingLeft: CGFloat = 0
let font: NSFont = NSFont.systemFont(ofSize: 13, weight: .light)
width = sensor.value.widthOfString(usingFont: font).rounded(.up) + 2
if let icon = sensor.icon, self.iconState {
let iconSize: CGFloat = 11
icon.draw(in: NSRect(x: x, y: ((Constants.Widget.height-iconSize)/2)-2, width: iconSize, height: iconSize))
paddingLeft = iconSize + (Constants.Widget.margin*3)
width += paddingLeft
}
let style = NSMutableParagraphStyle()
style.alignment = .center
let rect = CGRect(x: x+paddingLeft, y: (Constants.Widget.height-13)/2, width: width-paddingLeft, height: 13)
let str = NSAttributedString.init(string: sensor.value, attributes: [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: NSColor.textColor,
NSAttributedString.Key.paragraphStyle: style
])
str.draw(with: rect)
return width
}
private func drawTwoRows(topSensor: SensorValue_t, bottomSensor: SensorValue_t?, x: CGFloat) -> CGFloat {
var width: CGFloat = 0
var paddingLeft: CGFloat = 0
let rowHeight: CGFloat = self.frame.height / 2
let font: NSFont = NSFont.systemFont(ofSize: 9, weight: .light)
let style = NSMutableParagraphStyle()
style.alignment = .right
let firstRowWidth = topSensor.value.widthOfString(usingFont: font)
let secondRowWidth = bottomSensor?.value.widthOfString(usingFont: font)
width = max(20, max(firstRowWidth, secondRowWidth ?? 0)).rounded(.up)
if self.iconState && (topSensor.icon != nil || bottomSensor?.icon != nil) {
let iconSize: CGFloat = 8
if let icon = topSensor.icon {
icon.draw(in: NSRect(x: x, y: rowHeight+((rowHeight-iconSize)/2), width: iconSize, height: iconSize))
}
if let icon = bottomSensor?.icon {
icon.draw(in: NSRect(x: x, y: (rowHeight-iconSize)/2, width: iconSize, height: iconSize))
}
paddingLeft = iconSize + (Constants.Widget.margin*3)
width += paddingLeft
}
let attributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: NSColor.textColor,
NSAttributedString.Key.paragraphStyle: style
]
var rect = CGRect(x: x+paddingLeft, y: rowHeight+1, width: width-paddingLeft, height: rowHeight)
var str = NSAttributedString.init(string: topSensor.value, attributes: attributes)
str.draw(with: rect)
if bottomSensor != nil {
rect = CGRect(x: x+paddingLeft, y: 1, width: width-paddingLeft, height: rowHeight)
str = NSAttributedString.init(string: bottomSensor!.value, attributes: attributes)
str.draw(with: rect)
}
return width
}
public override func settings(superview: NSView) {
let rowHeight: CGFloat = 30
let height: CGFloat = ((rowHeight + Constants.Settings.margin) * 1) + Constants.Settings.margin
superview.setFrameSize(NSSize(width: superview.frame.width, height: height))
let view: NSView = NSView(frame: NSRect(x: Constants.Settings.margin, y: Constants.Settings.margin, width: superview.frame.width - (Constants.Settings.margin*2), height: superview.frame.height - (Constants.Settings.margin*2)))
view.addSubview(ToggleTitleRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 1, width: view.frame.width, height: rowHeight),
title: LocalizedString("Pictogram"),
action: #selector(toggleIcom),
state: self.iconState
))
view.addSubview(SelectRow(
frame: NSRect(x: 0, y: (rowHeight + Constants.Settings.margin) * 0, width: view.frame.width, height: rowHeight),
title: LocalizedString("Display mode"),
action: #selector(changeMode),
items: SensorsWidgetMode,
selected: self.modeState
))
superview.addSubview(view)
}
public func setValues(_ values: [SensorValue_t]) {
self.values = values
DispatchQueue.main.async(execute: {
self.display()
})
}
@objc private func toggleIcom(_ sender: NSControl) {
var state: NSControl.StateValue? = nil
if #available(OSX 10.15, *) {
state = sender is NSSwitch ? (sender as! NSSwitch).state: nil
} else {
state = sender is NSButton ? (sender as! NSButton).state: nil
}
self.iconState = state! == .on ? true : false
self.store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_icon", value: self.iconState)
self.display()
}
@objc private func changeMode(_ sender: NSMenuItem) {
guard let key = sender.representedObject as? String else {
return
}
self.modeState = key
store?.pointee.set(key: "\(self.title)_\(self.type.rawValue)_mode", value: key)
self.display()
}
}
| 38.315789 | 234 | 0.566145 |
2f592b9b4d17e417e910b24445bb812a91b2ebdc | 148 | //
// Configuration
// Posy
//
// Copyright (c) 2021 Eugene Egorov.
// License: MIT
//
struct Configuration: Codable {
var layouts: [String]
}
| 12.333333 | 36 | 0.641892 |
0ec153fdd6569249318e7391cc4a2ff81102f01c | 1,345 | // Copyright 2022 Pera Wallet, LDA
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LedgerAccountVerificationViewController+Theme.swift
import MacaroonUIKit
extension LedgerAccountVerificationViewController {
struct Theme: LayoutSheet, StyleSheet {
let backgroundColor: Color
let verifyButtonTheme: ButtonTheme
let ledgerAccountVerificationViewTheme: LedgerAccountVerificationViewTheme
let horizontalInset: LayoutMetric
let bottomInset: LayoutMetric
init(_ family: LayoutFamily) {
backgroundColor = AppColors.Shared.System.background
verifyButtonTheme = ButtonPrimaryTheme()
ledgerAccountVerificationViewTheme = LedgerAccountVerificationViewTheme()
horizontalInset = 20
bottomInset = 16
}
}
}
| 34.487179 | 85 | 0.72342 |
9c09e400a5769289445ed421fbe61bf24604649d | 1,574 | //
// Devices.swift
// xeropan
//
// Created by Zsolt Pete on 2018. 12. 16..
// Copyright © 2018. CodeYard. All rights reserved.
//
import UIKit
enum Devices {
static let IPad: Bool = UIDevice.current.userInterfaceIdiom == .pad
static let IPad129: Bool = IPad && UIScreen.main.bounds.size.height == 1366
static let IPad105: Bool = IPad && UIScreen.main.bounds.size.height == 1112
static let IPad11: Bool = IPad && UIScreen.main.bounds.size.height == 1194
/**
iPad 3, iPad 4, iPad Air, iPad Air 2, 9.7-inch iPad Pro, iPad Mini 2, iPad Mini 3, iPad Mini 4
*/
static let IPadAir: Bool = IPad && UIScreen.main.bounds.size.height == 1024
/**
iPhone 6 Plus, iPhone 6S Plus, iPhone 8 Plus
One dimension is for the simulator and the other for the actual device.
*/
static let iPhone7Plus: Bool = !IPad && UIScreen.main.bounds.size.height == 736
/**
iPhone 5S, iPhone 5
*/
static let iPhoneSE: Bool = !IPad && UIScreen.main.bounds.size.height == 568
/**
iPhone 6, iPhone 6S, iPhone 7, iPhone 8,
*/
static let iPhone7: Bool = !IPad && UIScreen.main.bounds.size.height == 667
/**
iPhone Xs
*/
static let iPhoneX: Bool = !IPad && UIScreen.main.bounds.size.height == 812
/**
iPhone XR and iPhone XS Max
*/
static let iPhoneXr: Bool = !IPad && UIScreen.main.bounds.size.height == 896
static let iPhoneXsMax: Bool = !IPad && UIScreen.main.bounds.size.height == 896
static let iPhoneXLike: Bool = !IPad && (iPhoneX || iPhoneXr || iPhoneXsMax)
}
| 34.217391 | 99 | 0.640407 |
398ade6ba94eb6a5947c7465ca8ad4638ffa4ce7 | 431 | //
// Shadows.swift
// Proba (iOS)
//
// Proprietary and confidential.
// Unauthorized copying of this file or any part thereof is strictly prohibited.
//
// Created by Ahmed Ramy on 23/08/2021.
// Copyright © 2021 Proba B.V. All rights reserved.
//
import Foundation
import SwiftUI
public protocol Shadowable {
var largeShadow: ARShadow { get }
var mediumShadow: ARShadow { get }
var smallShadow: ARShadow { get }
}
| 21.55 | 81 | 0.707657 |
e649794b68da31420b965d5049641577d14a3725 | 606 | // Kevin Li - 9:02 PM - 5/22/20
// https://leetcode.com/problems/move-zeroes/
// Time: O(n)
// Space: O(1)
class Solution {
// 2 pass approach
// 1st pass moves all non-zero numbers to the front of the array
// 2nd pass sets all numbers from the last non-zero index to the end of the array to 0
func moveZeroes(_ nums: inout [Int]) {
var lastNonZeroIndex = 0
for num in nums where num != 0 {
nums[lastNonZeroIndex] = num
lastNonZeroIndex += 1
}
for i in lastNonZeroIndex..<nums.count {
nums[i] = 0
}
}
}
| 23.307692 | 90 | 0.575908 |
39927ddfa40986f3224c2aa5f0e1d3c6ed8cca07 | 3,738 | //
// FitItemsViewController.swift
// CollectionViewExample
//
// Created by Giftbot on 2020/01/28.
// Copyright © 2020 giftbot. All rights reserved.
//
import UIKit
class FitItemsViewController: UIViewController {
private enum UI {
static let itemsInLine: CGFloat = 2
static let linesOnScreen: CGFloat = 2
static let itemSpacing: CGFloat = 10.0
static let lineSpacing: CGFloat = 10.0
static let edgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
}
private let layout = UICollectionViewFlowLayout()
private lazy var collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
private var parkImages = ParkManager.imageNames(of: .nationalPark)
// MARK: LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupNavigationItem()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupFlowLayout()
}
// MARK: Setup CollectionView
private func setupCollectionView() {
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.identifier)
collectionView.backgroundColor = .systemBackground
collectionView.dataSource = self
view.addSubview(collectionView)
}
private func setupFlowLayout() {
layout.minimumInteritemSpacing = UI.itemSpacing
layout.minimumLineSpacing = UI.lineSpacing
layout.sectionInset = UI.edgeInsets
fitItemsAndLinesOnScreen()
}
private func fitItemsAndLinesOnScreen() {
let itemSpacing = UI.itemSpacing * (UI.itemsInLine - 1)
let lineSpacig = UI.lineSpacing * (UI.linesOnScreen - 1)
let horizontalInset = UI.edgeInsets.left + UI.edgeInsets.right
let verticalInset = UI.edgeInsets.top + UI.edgeInsets.bottom + view.safeAreaInsets.top + view.safeAreaInsets.bottom
let isVertical = layout.scrollDirection == .vertical
let horizontalSpacing = (isVertical ? itemSpacing : lineSpacig) + horizontalInset
let verticalSpacing = (isVertical ? itemSpacing : itemSpacing) + verticalInset
let contentWidth = collectionView.frame.width - horizontalSpacing
let contentHeight = collectionView.frame.height - verticalSpacing
let width = contentWidth / (isVertical ? UI.itemsInLine : UI.linesOnScreen)
let height = contentHeight / (isVertical ? UI.linesOnScreen : UI.itemsInLine)
layout.itemSize = CGSize(width: width.rounded(.down), height: height.rounded(.down))
}
// MARK: Setup NavigationItem
func setupNavigationItem() {
let changeDirection = UIBarButtonItem(
barButtonSystemItem: .reply,
target: self,
action: #selector(changeCollectionViewDirection(_:))
)
navigationItem.rightBarButtonItems = [changeDirection]
}
// MARK: - Action
@objc
private func changeCollectionViewDirection(_ sender: Any) {
let direction = layout.scrollDirection
layout.scrollDirection = direction == .horizontal ? .vertical : .horizontal
setupFlowLayout()
}
}
// MARK: - UICollectionViewDataSource
extension FitItemsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return parkImages.count * 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: CustomCell.identifier,
for: indexPath
) as! CustomCell
let item = indexPath.item % parkImages.count
cell.backgroundColor = .black
cell.configure(image: UIImage(named: parkImages[item]), title: parkImages[item])
return cell
}
}
| 31.677966 | 119 | 0.728999 |
9b7482887ef01433f462d67cbb044bdf98034eac | 752 | import XCTest
import LYSpecificViews
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.931034 | 111 | 0.603723 |
89d237aa088f3e1bb488744315b3aa1a88f50241 | 1,280 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
The allowable request method or HTTP operation codes.
URL: http://hl7.org/fhir/http-operations
ValueSet: http://hl7.org/fhir/ValueSet/http-operations
*/
public enum TestScriptRequestMethodCode: String, FHIRPrimitiveType {
/// HTTP DELETE operation.
case delete = "delete"
/// HTTP GET operation.
case get = "get"
/// HTTP OPTIONS operation.
case options = "options"
/// HTTP PATCH operation.
case patch = "patch"
/// HTTP POST operation.
case post = "post"
/// HTTP PUT operation.
case put = "put"
/// HTTP HEAD operation.
case head = "head"
}
| 25.098039 | 76 | 0.705469 |
eb2a387cc6c679900935592483aa18d2eb2d30f2 | 2,055 | //
// DetailViewModel.swift
// PokemonDamageCalculator
//
// Created by Taylor Plimpton on 3/28/18.
// Copyright © 2018 SmallPlanetDigital. All rights reserved.
//
import Foundation
class DetailViewModel {
// required
private(set) public var pokemonModel:PokemonModel
init(PokemonModel pm:PokemonModel) {
pokemonModel = pm
// TODO: calculations
}
func ImageUrl() -> String? {
return pokemonModel.imageUrl
}
func Name() -> String {
return pokemonModel.name
}
func Types() -> Array<PokemonType> {
return pokemonModel.types
}
func Attack() -> Int {
return pokemonModel.attack
}
func Defense() -> Int {
return pokemonModel.defense
}
func Stamina() -> Int {
return pokemonModel.stamina
}
func BestAttackingFastMove(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> PokemonFastMoveModel? {
return pokemonModel.BestAttackingFastMove(Active: isActive, STAB: isSTAB)
}
func BestAttackingChargeMove(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> PokemonChargeMoveModel? {
return pokemonModel.BestAttackingChargeMove(Active: isActive, STAB: isSTAB)
}
func eDPSAttacking(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> Double {
return pokemonModel.eDPSAttacking(Active: isActive, STAB: isSTAB)
}
func BestDefendingFastMove(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> PokemonFastMoveModel? {
return pokemonModel.BestDefendingFastMove(Active: isActive, STAB: isSTAB)
}
func BestDefendingChargeMove(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> PokemonChargeMoveModel? {
return pokemonModel.BestDefendingChargeMove(Active: isActive, STAB: isSTAB)
}
func eDPSDefending(Active isActive:Bool = false, STAB isSTAB:Bool = false) -> Double {
return pokemonModel.eDPSDefending(Active: isActive, STAB: isSTAB)
}
}
| 29.782609 | 117 | 0.66326 |
9c5ecbd5a59d0a934823521ee83b307cf46990a4 | 1,505 | //
// WypokMirkoDetailsPresenter.swift
// wypok
//
// Created by Przemyslaw Jablonski on 08/09/2018.
// Copyright © 2018 Przemyslaw Jablonski. All rights reserved.
//
import Foundation
class WypokMirkoDetailsPresenter: BasePresenter<WypokMirkoDetailsViewState>, MirkoDetailsPresenter {
private let interactor: MirkoDetailsInteractor
init(interactor: MirkoDetailsInteractor) {
self.interactor = interactor
}
override func onAttached(view: View) {
self.view?.render(WypokMirkoDetailsViewState.loading)
}
override func onDetached(view: View) {
}
func onSelectedEntryIdReceived(_ id: Int) {
interactor.getMirkoItemDetails(
for: id,
fetchDidSucceed: { model in
self.view?.render(WypokMirkoDetailsViewState.content(model))
}, fetchDidFailed: { error in
self.view?.render(WypokMirkoDetailsViewState.error(message: self.generateMessage(from: error)))
})
}
//todo: maybe those errors should be in MDI class? So that I can write MDI.Error?
private func generateMessage(from error: MirkoDetailsInteractorError) -> String? {
switch error {
case .apiError(let code, let message):
return message != nil ? message : String(code.rawValue)
case .undefinedApiError(_):
return "Undefined Error" //todo: ui string here
case .generalError(_):
return nil
}
}
}
| 30.1 | 107 | 0.649169 |
5b4b5bb36ddaf2a295a177a9a2ae56e2d892b0e6 | 4,446 | //
// CalendarTableViewController.swift
// StudyUnit
//
// Created by Dabeer Masood on 4/8/18.
// Copyright © 2018 Dabeer Masood. All rights reserved.
//
import UIKit
class CalendarTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, AddEventDelegate {
var events : [String : Event]!
var course : Course!
override func viewDidLoad() {
super.viewDidLoad()
if let tabBar = self.tabBarController as? TabBarController {
self.course = tabBar.selectedCourse
}
self.events = [String : Event]()
self.pullEvents()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.pullEvents()
}
func pullEvents() {
Helper.getUserData { (user) in
if let user = user {
for courseId in user.courseIDs {
COURSES_REF.child(courseId).observeSingleEvent(of: .value, with: { (snapshot) in
if let courseJson = snapshot.value as? [String : AnyObject] {
let course = Course(fromJSON: courseJson)
for eventIds in course.eventIDs {
EVENTS_REF.child(eventIds).observeSingleEvent(of: .value, with: { (snapshot) in
if let eventJson = snapshot.value as? [String : AnyObject] {
let event = Event(fromJson: eventJson)
let eventKey = snapshot.key
if(!self.events.keys.contains(eventKey)){
self.events.updateValue(event, forKey: eventKey)
self.tableView.reloadData()
}
}
})
}
}
})
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.events.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventTableViewCell", for: indexPath) as! EventTableViewCell
// Configure the cell...
let keys = Array(self.events.keys)
let event = self.events[keys[indexPath.row]]!
let formatter = DateFormatter()
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
cell.eventName.text = event.name
cell.location.text = event.location
cell.time.text = event.time
cell.date.text = formatter.string(from: event.date! as Date)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "addEventPopover" {
if let popoverViewController = segue.destination as? AddEventPopoverViewController {
popoverViewController.popoverPresentationController?.delegate = self
popoverViewController.addEventDelegate = self
popoverViewController.course = self.course
}
}
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func addEventToCourseWithId(eventId: String, course: Course) {
var course = course
course.eventIDs.append(eventId)
COURSES_REF.child(course.courseId).setValue(course.toJson()) { (error, ref) in
self.pullEvents()
}
}
}
| 37.05 | 125 | 0.572874 |
9060defa47e9e489da57578b27eb829df7738684 | 1,184 | //
// AntibuddiesUITests.swift
// AntibuddiesUITests
//
// Created by Mackenzie Hampel on 5/16/19.
// Copyright © 2019 WeberStateUniversity. All rights reserved.
//
import XCTest
class AntibuddiesUITests: XCTestCase {
override func 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.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.828571 | 182 | 0.696791 |
8735b66c9ebd168a7f5877e9e0263caf4507b37f | 9,275 | //
// ByteBuffer.swift
// ByteBuffer
//
// Created by Alexander Stonehouse on 25/2/19.
//
import Foundation
public struct ByteBuffer {
// MARK: - Errors
public enum Errors: Error {
case insufficientBytes
}
// MARK: - Bit Manipulators
private struct BitReader {
private var byteOffset: Int = 0
private var currentValue: UInt64 = 0
/// How much space is left in the currentValue
private var bitOverhang: Int = 0
func remainingBytes(_ data: Data) -> Int {
data.count - byteOffset
}
func remainingBits(_ data: Data) -> Int {
return 8 * remainingBytes(data) + bitOverhang
}
mutating func rewind() {
byteOffset = 0
bitOverhang = 0
currentValue = 0
}
mutating func read(bytes: Int, data: inout Data) throws -> UInt64 {
guard remainingBytes(data) >= bytes else {
throw ByteBuffer.Errors.insufficientBytes
}
// Reading full bytes only supported if not partially through a byte
guard bitOverhang == 0 else {
return try read(bits: bytes * 8, data: &data)
}
let subdata = data.subdata(in: byteOffset..<byteOffset+bytes)
byteOffset += bytes
var value: UInt64 = 0
_ = withUnsafeMutableBytes(of: &value, {
subdata.copyBytes(to: $0)
})
return value
}
mutating func read(bits: Int, data: inout Data) throws -> UInt64 {
guard remainingBits(data) >= bits else {
throw ByteBuffer.Errors.insufficientBytes
}
// Collect bytes until we have enough bits
while bitOverhang < bits {
// Move value over and append new byte
currentValue = currentValue | (UInt64(data[byteOffset]) << bitOverhang)
bitOverhang += 8
byteOffset += 1
}
var bitsToRead: UInt64 = 0
for _ in 0..<bits {
bitsToRead = (bitsToRead << 1) + 1
}
// Remove overhang bits
let result = currentValue & bitsToRead
// Shift value to throw away read bits
currentValue = currentValue >> UInt64(bits)
// Rewind bit offset for next read
bitOverhang -= bits
return result
}
}
private struct BitWriter {
private var currentValue: UInt8 = 0
// Index in bits in the current byte (stored in currentValue)
private var bitIndex: Int = 0
mutating func write(bytes: Int, data readData: Data, outData: inout Data) {
guard bitIndex == 0 else {
write(bits: bytes * 8, data: readData, outData: &outData)
return
}
outData.append(readData[0..<bytes])
}
mutating func write(bits: Int, data readData: Data, outData: inout Data) {
var i = 0
var bitsLeft = bits
// To append all the bits, we go byte by byte
while (i * 8) < bits {
// Either read a whole byte or the remaining bits
let bitsToRead = bitsLeft < 8 ? bitsLeft : 8
// Mask to make sure we only read in the indended bits
var bitMask: UInt8 = 0
for _ in 0..<bitsToRead {
bitMask = (bitMask << 1) + 1
}
let inByte = readData[i]
// How far the current value should be shifted (basically tells us how many new
// bits from the new byte should be added to the current byte). Potentially we
// need to add a few bits to a previous byte and then put the remaining bits in
// a new byte.
let mergedByte = currentValue | ((inByte & bitMask) << bitIndex)
var newIndex = bitIndex + bitsToRead
if newIndex >= 8 {
// Commit completed byte
outData.append(mergedByte)
// Remove byte from index
newIndex -= 8
bitIndex = newIndex
var readBitsAnd: UInt8 = 0
for _ in 0..<newIndex {
readBitsAnd = (readBitsAnd << 1) + 1
}
// Wipe read bits from byte
currentValue = inByte & readBitsAnd
} else {
// Save partial byte, continue to next byte from input
currentValue = mergedByte
bitIndex = newIndex
}
i += 1
bitsLeft -= 8
}
}
}
// MARK: - Private
private var reader = BitReader()
private var writer = BitWriter()
private(set) public var data: Data
public init(data: Data) {
self.data = data
}
public init(capacity: Int) {
self.data = Data(capacity: capacity)
}
public init() {
self.data = Data()
}
private mutating func read(bits: Int) throws -> UInt64 {
try reader.read(bits: bits, data: &data)
}
private mutating func read(bytes: Int) throws -> UInt64 {
try reader.read(bytes: bytes, data: &data)
}
private mutating func write(bits: Int, data inData: Data) {
writer.write(bits: bits, data: inData, outData: &data)
}
private mutating func write(bytes: Int, data inData: Data) {
writer.write(bytes: bytes, data: inData, outData: &data)
}
// MARK: - Reading
public var remaining: Int {
return reader.remainingBits(data)
}
public mutating func rewind() {
reader.rewind()
}
public mutating func readBool(bits: Int) throws -> Bool {
return Bool(truncating: try read(bits: bits) as NSNumber)
}
public mutating func readBool() throws -> Bool {
return Bool(truncating: try read(bytes: 1) as NSNumber)
}
public mutating func readByte(bits: Int) throws -> UInt8 {
UInt8(try read(bits: bits))
}
public mutating func readByte() throws -> UInt8 {
UInt8(try read(bytes: 1))
}
public mutating func readShort(bits: Int) throws -> UInt16 {
return UInt16(try read(bits: bits))
}
public mutating func readShort() throws -> UInt16 {
return UInt16(try read(bytes: 2))
}
public mutating func readUInt32(bits: Int) throws -> UInt32 {
return UInt32(try read(bits: bits))
}
public mutating func readUInt32() throws -> UInt32 {
return UInt32(try read(bytes: 4))
}
public mutating func readUInt64(bits: Int) throws -> UInt64 {
return try read(bits: bits)
}
public mutating func readUInt64() throws -> UInt64 {
return try read(bytes: 8)
}
public mutating func readBytes(_ count: Int) throws -> [UInt8] {
return try (0..<count).map { _ in try readByte() }
}
// MARK: - Writing
public mutating func write(bool: Bool, bits: Int) {
write(bits: bits, data: Data(ByteBuffer.toByteArray(bool)))
}
public mutating func write(bool: Bool) {
write(bytes: 1, data: Data(ByteBuffer.toByteArray(bool)))
}
public mutating func write(byte: UInt8, bits: Int) {
write(bits: bits, data: Data([byte]))
}
public mutating func write(byte: UInt8) {
write(bytes: 1, data: Data([byte]))
}
public mutating func write(short: UInt16, bits: Int) {
write(bits: bits, data: Data(ByteBuffer.toByteArray(short)))
}
public mutating func write(short: UInt16) {
write(bytes: 2, data: Data(ByteBuffer.toByteArray(short)))
}
public mutating func write(uint32: UInt32, bits: Int) {
write(bits: bits, data: Data(ByteBuffer.toByteArray(uint32)))
}
public mutating func write(uint32: UInt32) {
write(bytes: 4, data: Data(ByteBuffer.toByteArray(uint32)))
}
public mutating func write(uint64: UInt64, bits: Int) {
write(bits: bits, data: Data(ByteBuffer.toByteArray(uint64)))
}
public mutating func write(uint64: UInt64) {
write(bytes: 8, data: Data(ByteBuffer.toByteArray(uint64)))
}
public mutating func write(bytes: [UInt8]) {
write(bytes: bytes.count, data: Data(bytes))
}
public mutating func write(data inData: Data) {
data.append(inData)
}
// MARK: - Helpers
public static func toByteArray<T>(_ value: T) -> [UInt8] {
var value = value
return withUnsafePointer(to: &value) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.size) {
Array(UnsafeBufferPointer(start: $0, count: MemoryLayout<T>.size))
}
}
}
}
| 31.020067 | 95 | 0.533477 |
4aa3b7349679e8aed918af1575d2f63f65e5fdb4 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
for {
struct A {
protocol c {
class A {
let h = [ {
let b {
class
case ,
| 18.615385 | 87 | 0.714876 |
1d8ef5f1534df4d7e2db7d1859198830e5585cf0 | 1,503 | //
// Network+UploadTask.swift
// NetworkKit
//
// Created by William Lee on 2018/8/9.
// Copyright © 2018 William Lee. All rights reserved.
//
import Foundation
public extension Network {
typealias UploadTaskCompleteAction = (_ data: Data?, _ status: NetworkStatus) -> Void
/// 上传文件内容
///
/// - Parameters:
/// - file: 文件地址
/// - action: 上传完成或出现异常后进行回调,处理上传完成后服务器返回信息及错误信息
func upload(with file: URL, _ action: @escaping UploadTaskCompleteAction) {
//设置内部完成回调
delegate.result.completeAction = { (delegate) in
//执行外部设置的完成回调
action(delegate.result.data, delegate.result.status)
}
//设置代理类型
delegate.taskType = .uploadTask
setupTask({ (session, request) -> URLSessionTask? in
guard let request = request else { return nil }
return session.uploadTask(with: request, fromFile: file)
})
}
/// 上传数据
///
/// - Parameters:
/// - data: 上传的数据,可以认为是httpBody
/// - action: 上传完成或出现异常后进行回调,处理上传完成后服务器返回信息及错误信息
func upload(with data: Data, _ action: @escaping UploadTaskCompleteAction) {
//设置内部完成回调
delegate.result.completeAction = { (delegate) in
action(delegate.result.data, delegate.result.status)
}
//设置代理类型
delegate.taskType = .uploadTask
setupTask({ (session, request) -> URLSessionTask? in
guard let request = request else { return nil }
return session.uploadTask(with: request, from: data)
})
}
}
| 23.123077 | 87 | 0.634065 |
e0e0a4f7f08dd43e85f3d9bc06b8925ccec3b022 | 12,060 | // Generated using the ObjectBox Swift Generator — https://objectbox.io
// DO NOT EDIT
// swiftlint:disable all
import ObjectBox
// MARK: - Entity metadata
extension Author: ObjectBox.__EntityRelatable {
internal typealias EntityType = Author
internal var _id: EntityId<Author> {
return EntityId<Author>(self.id.value)
}
}
extension Author: ObjectBox.EntityInspectable {
internal typealias EntityBindingType = AuthorBinding
/// Generated metadata used by ObjectBox to persist the entity.
internal static var entityInfo = ObjectBox.EntityInfo(name: "Author", id: 1)
internal static var entityBinding = EntityBindingType()
fileprivate static func buildEntity(modelBuilder: ObjectBox.ModelBuilder) throws {
let entityBuilder = try modelBuilder.entityBuilder(for: Author.self, id: 1, uid: 16640)
try entityBuilder.addProperty(name: "id", type: EntityId<Author>.entityPropertyType, flags: [.id], id: 1, uid: 14592)
try entityBuilder.addProperty(name: "name", type: String.entityPropertyType, id: 2, uid: 15616)
try entityBuilder.lastProperty(id: 2, uid: 15616)
}
}
extension Author {
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { Author.id == myId }
internal static var id: Property<Author, EntityId<Author>, EntityId<Author>> { return Property<Author, EntityId<Author>, EntityId<Author>>(propertyId: 1, isPrimaryKey: true) }
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { Author.name.startsWith("X") }
internal static var name: Property<Author, String, Void> { return Property<Author, String, Void>(propertyId: 2, isPrimaryKey: false) }
/// Use `Author.books` to refer to this ToMany relation property in queries,
/// like when using `QueryBuilder.and(property:, conditions:)`.
internal static var books: ToManyProperty<Book> { return ToManyProperty(.valuePropertyId(3)) }
fileprivate func __setId(identifier: ObjectBox.Id) {
self.id = EntityId(identifier)
}
}
extension ObjectBox.Property where E == Author {
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { .id == myId }
internal static var id: Property<Author, EntityId<Author>, EntityId<Author>> { return Property<Author, EntityId<Author>, EntityId<Author>>(propertyId: 1, isPrimaryKey: true) }
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { .name.startsWith("X") }
internal static var name: Property<Author, String, Void> { return Property<Author, String, Void>(propertyId: 2, isPrimaryKey: false) }
/// Use `.books` to refer to this ToMany relation property in queries, like when using
/// `QueryBuilder.and(property:, conditions:)`.
internal static var books: ToManyProperty<Book> { return ToManyProperty(.valuePropertyId(3)) }
}
/// Generated service type to handle persisting and reading entity data. Exposed through `Author.EntityBindingType`.
internal class AuthorBinding: NSObject, ObjectBox.EntityBinding {
internal typealias EntityType = Author
internal typealias IdType = EntityId<Author>
override internal required init() {}
internal func setEntityIdUnlessStruct(of entity: EntityType, to entityId: ObjectBox.Id) {
entity.__setId(identifier: entityId)
}
internal func entityId(of entity: EntityType) -> ObjectBox.Id {
return entity.id.value
}
internal func collect(fromEntity entity: EntityType, id: ObjectBox.Id,
propertyCollector: ObjectBox.FlatBufferBuilder, store: ObjectBox.Store) {
let propertyOffset_name = propertyCollector.prepare(string: entity.name)
propertyCollector.collect(id, at: 2 + 2 * 1)
propertyCollector.collect(dataOffset: propertyOffset_name, at: 2 + 2 * 2)
}
internal func postPut(fromEntity entity: EntityType, id: ObjectBox.Id, store: ObjectBox.Store) {
if entityId(of: entity) == 0 { // Written for first time? Attach ToMany relations:
let books = ToMany<Book>.backlink(
sourceBox: store.box(for: ToMany<Book>.ReferencedType.self),
sourceProperty: ToMany<Book>.ReferencedType.author,
targetId: EntityId<Author>(id.value))
if !entity.books.isEmpty {
books.replace(entity.books)
}
entity.books = books
}
}
internal func createEntity(entityReader: ObjectBox.FlatBufferReader, store: ObjectBox.Store) -> EntityType {
let entity = Author()
entity.id = entityReader.read(at: 2 + 2 * 1)
entity.name = entityReader.read(at: 2 + 2 * 2)
entity.books = ToMany<Book>.backlink(
sourceBox: store.box(for: ToMany<Book>.ReferencedType.self),
sourceProperty: ToMany<Book>.ReferencedType.author,
targetId: EntityId<Author>(entity.id.value))
return entity
}
}
extension Book: ObjectBox.__EntityRelatable {
internal typealias EntityType = Book
internal var _id: EntityId<Book> {
return EntityId<Book>(self.id.value)
}
}
extension Book: ObjectBox.EntityInspectable {
internal typealias EntityBindingType = BookBinding
/// Generated metadata used by ObjectBox to persist the entity.
internal static var entityInfo = ObjectBox.EntityInfo(name: "Book", id: 2)
internal static var entityBinding = EntityBindingType()
fileprivate static func buildEntity(modelBuilder: ObjectBox.ModelBuilder) throws {
let entityBuilder = try modelBuilder.entityBuilder(for: Book.self, id: 2, uid: 21504)
try entityBuilder.addProperty(name: "id", type: EntityId<Book>.entityPropertyType, flags: [.id], id: 1, uid: 17664)
try entityBuilder.addProperty(name: "name", type: String.entityPropertyType, id: 2, uid: 18688)
try entityBuilder.addToOneRelation(name: "author", targetEntityInfo: ToOne<Author>.Target.entityInfo, id: 3, uid: 20736, indexId: 1, indexUid: 19712)
try entityBuilder.lastProperty(id: 3, uid: 20736)
}
}
extension Book {
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { Book.id == myId }
internal static var id: Property<Book, EntityId<Book>, EntityId<Book>> { return Property<Book, EntityId<Book>, EntityId<Book>>(propertyId: 1, isPrimaryKey: true) }
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { Book.name.startsWith("X") }
internal static var name: Property<Book, String, Void> { return Property<Book, String, Void>(propertyId: 2, isPrimaryKey: false) }
internal static var author: Property<Book, EntityId<ToOne<Author>.Target>, ToOne<Author>.Target> { return Property(propertyId: 3) }
fileprivate func __setId(identifier: ObjectBox.Id) {
self.id = EntityId(identifier)
}
}
extension ObjectBox.Property where E == Book {
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { .id == myId }
internal static var id: Property<Book, EntityId<Book>, EntityId<Book>> { return Property<Book, EntityId<Book>, EntityId<Book>>(propertyId: 1, isPrimaryKey: true) }
/// Generated entity property information.
///
/// You may want to use this in queries to specify fetch conditions, for example:
///
/// box.query { .name.startsWith("X") }
internal static var name: Property<Book, String, Void> { return Property<Book, String, Void>(propertyId: 2, isPrimaryKey: false) }
internal static var author: Property<Book, ToOne<Author>.Target.EntityBindingType.IdType, ToOne<Author>.Target> { return Property<Book, ToOne<Author>.Target.EntityBindingType.IdType, ToOne<Author>.Target>(propertyId: 3) }
}
/// Generated service type to handle persisting and reading entity data. Exposed through `Book.EntityBindingType`.
internal class BookBinding: NSObject, ObjectBox.EntityBinding {
internal typealias EntityType = Book
internal typealias IdType = EntityId<Book>
override internal required init() {}
internal func setEntityIdUnlessStruct(of entity: EntityType, to entityId: ObjectBox.Id) {
entity.__setId(identifier: entityId)
}
internal func entityId(of entity: EntityType) -> ObjectBox.Id {
return entity.id.value
}
internal func collect(fromEntity entity: EntityType, id: ObjectBox.Id,
propertyCollector: ObjectBox.FlatBufferBuilder, store: ObjectBox.Store) {
let propertyOffset_name = propertyCollector.prepare(string: entity.name)
propertyCollector.collect(id, at: 2 + 2 * 1)
propertyCollector.collect(entity.author, at: 2 + 2 * 3, store: store)
propertyCollector.collect(dataOffset: propertyOffset_name, at: 2 + 2 * 2)
}
internal func postPut(fromEntity entity: EntityType, id: ObjectBox.Id, store: ObjectBox.Store) {
if entityId(of: entity) == 0 { // Written for first time? Attach ToMany relations:
entity.author.attach(to: store.box(for: Author.self))
}
}
internal func setToOneRelation(_ propertyId: obx_schema_id, of entity: EntityType, to entityId: ObjectBox.Id?) {
switch propertyId {
case 3:
entity.author.targetId = (entityId != nil) ? EntityId<Author>(entityId!) : nil
default:
fatalError("Attempt to change nonexistent ToOne relation with ID \(propertyId)")
}
}
internal func createEntity(entityReader: ObjectBox.FlatBufferReader, store: ObjectBox.Store) -> EntityType {
let entity = Book()
entity.id = entityReader.read(at: 2 + 2 * 1)
entity.name = entityReader.read(at: 2 + 2 * 2)
entity.author = entityReader.read(at: 2 + 2 * 3, store: store)
return entity
}
}
/// Helper function that allows calling Enum(rawValue: value) with a nil value, which will return nil.
fileprivate func optConstruct<T: RawRepresentable>(_ type: T.Type, rawValue: T.RawValue?) -> T? {
guard let rawValue = rawValue else { return nil }
return T(rawValue: rawValue)
}
// MARK: - Store setup
fileprivate func cModel() throws -> OpaquePointer {
let modelBuilder = try ObjectBox.ModelBuilder()
try Author.buildEntity(modelBuilder: modelBuilder)
try Book.buildEntity(modelBuilder: modelBuilder)
modelBuilder.lastEntity(id: 2, uid: 21504)
modelBuilder.lastIndex(id: 1, uid: 19712)
return modelBuilder.finish()
}
extension ObjectBox.Store {
/// A store with a fully configured model. Created by the code generator with your model's metadata in place.
///
/// - Parameters:
/// - directoryPath: Directory path to store database files in.
/// - maxDbSizeInKByte: Limit of on-disk space for the database files. Default is `1024 * 1024` (1 GiB).
/// - fileMode: UNIX-style bit mask used for the database files; default is `0o755`.
/// - maxReaders: Maximum amount of concurrent readers, tailored to your use case. Default is `0` (unlimited).
internal convenience init(directoryPath: String, maxDbSizeInKByte: UInt64 = 1024 * 1024, fileMode: UInt32 = 0o755, maxReaders: UInt32 = 0) throws {
try self.init(
model: try cModel(),
directory: directoryPath,
maxDbSizeInKByte: maxDbSizeInKByte,
fileMode: fileMode,
maxReaders: maxReaders)
}
}
// swiftlint:enable all
| 41.730104 | 225 | 0.68209 |
e4ba1c37c2a311b99788fbc3012a2a18b61d659d | 1,202 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vDSP {
public enum FourierTransformDirection {
case forward
case inverse
public var dftDirection: vDSP_DFT_Direction {
switch self {
case .forward:
return .FORWARD
case .inverse:
return .INVERSE
}
}
public var fftDirection: FFTDirection {
switch self {
case .forward:
return FFTDirection(kFFTDirection_Forward)
case .inverse:
return FFTDirection(kFFTDirection_Inverse)
}
}
}
}
| 31.631579 | 80 | 0.512479 |
76ca0b1a1567190c6a0f9538ed2bd81967fd3a67 | 1,964 | // Copyright 2020 Espressif Systems
//
// 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.
//
// ESPSecurity.swift
// ESPProvision
//
import Foundation
/// Enum which encapsulates errors which can occur in the Security handshake
/// with the device.
enum SecurityError: Error {
/// Session state mismatch between device and application.
case sessionStateError(String)
/// Handshake error between device and application.
case handshakeError(String)
/// Error in generating valid matching keys between device and mobile
case keygenError(String)
}
/// Security interface which abstracts the handshake and crypto behavior supported by a specific
/// class/family of devices.
public protocol ESPCodeable {
/// Get the next request based upon the current session,
/// state and the response data passed to this function
///
/// - Parameter data: Data that was received in the previous step.
/// - Returns: Data to be sent in the next step.
/// - Throws: Security errors.
func getNextRequestInSession(data: Data?) throws -> Data?
/// Encrypt data according to the Security implementation
///
/// - Parameter data: data to be sent
/// - Returns: encrypted version
func encrypt(data: Data) -> Data?
/// Decrypt data according to the security implementation
///
/// - Parameter data: data from device
/// - Returns: decrypted data
func decrypt(data: Data) -> Data?
}
| 35.071429 | 96 | 0.709776 |
0aca962e5ea38a130379f18929d901dd953a7f45 | 254 | import XCTest
@testable import Testing
final class FixtureTests: XCTestCase {
func testFixture() {
fixture("kiss.txt") { data in
XCTAssertEqual(String(data: data, encoding: .utf8), "Keep it simple, stupid!\n")
}
}
}
| 21.166667 | 92 | 0.625984 |
bfcc4bd97206192838608db797fc5663459699ec | 1,631 | // Copyright 2018-2020 Tokamak contributors
//
// 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.
//
// Created by Carson Katri on 7/19/20.
//
import CombineShim
class MountedCompositeElement<R: Renderer>: MountedElement<R> {
let parentTarget: R.TargetType
var state = [Any]()
var subscriptions = [AnyCancellable]()
init<A: App>(_ app: A, _ parentTarget: R.TargetType, _ environmentValues: EnvironmentValues) {
self.parentTarget = parentTarget
super.init(_AnyApp(app), environmentValues)
}
init(_ scene: _AnyScene, _ parentTarget: R.TargetType, _ environmentValues: EnvironmentValues) {
self.parentTarget = parentTarget
super.init(scene, environmentValues)
}
init(_ view: AnyView, _ parentTarget: R.TargetType, _ environmentValues: EnvironmentValues) {
self.parentTarget = parentTarget
super.init(view, environmentValues)
}
}
extension MountedCompositeElement: Hashable {
static func == (lhs: MountedCompositeElement<R>, rhs: MountedCompositeElement<R>) -> Bool {
lhs === rhs
}
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
| 31.980392 | 98 | 0.733906 |
edff76131d52f18d0af8366b37a14159a67350f5 | 7,935 | //
// AppFlowController+CoreTests+Setup.swift
// AppFlowController
//
// Created by Paweł Sporysz on 22.06.2017.
// Copyright © 2017 Paweł Sporysz. All rights reserved.
//
import XCTest
@testable import AppFlowController
class AppFlowController_CoreTests: XCTestCase {
// MARK: - Helpers
class NameViewController: UIViewController {
let name: String
init(name: String) {
self.name = name
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
func newPage(_ name: String = "page", supportVariants: Bool = false) -> FlowPathComponent {
return FlowPathComponent(
name: name,
supportVariants: supportVariants,
viewControllerInit: { NameViewController(name: name) },
viewControllerType: NameViewController.self
)
}
func prepareFlowController() {
let window = UIWindow()
let navigationController = FakeNavigationController()
flowController.prepare(for: window, rootNavigationController: navigationController)
}
// MARK: - Properties
var flowController: AppFlowController!
var currentVCNames: [String] {
return (flowController.rootNavigationController?.viewControllers as? [NameViewController])?.map{ $0.name } ?? []
}
// MARK: - Setup
override func setUp() {
flowController = AppFlowController()
}
// MARK: - Tests
func testShared_shouldBeAlwaysTheSameObject() {
let shared1 = AppFlowController.shared
let shared2 = AppFlowController.shared
XCTAssertTrue(shared1 === shared2)
}
func testPrepare() {
let window = UIWindow()
let navigationController = UINavigationController()
flowController.prepare(for: window, rootNavigationController: navigationController)
XCTAssertEqual(flowController.rootNavigationController, navigationController)
XCTAssertEqual(window.rootViewController, navigationController)
}
func testRegister_path() {
let page = newPage()
do {
try flowController.register(pathComponent: page)
XCTAssertEqual(flowController.rootPathStep, PathStep(pathComponent: page))
} catch _ {
XCTFail()
}
}
func testRegister_arrayOfPaths() {
let pages = newPage("1") => newPage("2")
do {
try flowController.register(pathComponents: pages)
let expectedRoot = PathStep(pathComponent: pages[0])
expectedRoot.add(pathComponent: pages[1])
XCTAssertEqual(flowController.rootPathStep, expectedRoot)
} catch _ {
XCTFail()
}
}
func testRegister_arrayOfPathArrays() {
let pages = newPage("1") =>> [
newPage("2"),
newPage("3")
]
do {
try flowController.register(pathComponents: pages)
let expectedRoot = PathStep(pathComponent: pages[0][0])
expectedRoot.add(pathComponent: pages[0][1])
expectedRoot.add(pathComponent: pages[1][1])
XCTAssertEqual(flowController.rootPathStep, expectedRoot)
} catch _ {
XCTFail()
}
}
func testRegister_stepAlreadyRegistered() {
let page = newPage("1")
do {
try flowController.register(pathComponent: page)
try flowController.register(pathComponent: page)
XCTFail()
} catch let error {
if let afcError = error as? AFCError {
XCTAssertEqual(afcError, AFCError.pathAlreadyRegistered(identifier: "1"))
} else {
XCTFail()
}
}
}
func testRegister_oneOfStepsDoesntHaveForwardTransition() {
let newPage1 = newPage("1")
let newPage2 = newPage("2")
var newPage3 = newPage("3")
newPage3.forwardTransition = nil
newPage3.backwardTransition = PushPopFlowTransition.default
do {
try flowController.register(pathComponents: [
newPage1,
newPage2,
newPage3
])
XCTFail()
} catch let error {
if let afcError = error as? AFCError {
XCTAssertEqual(afcError, AFCError.missingPathStepTransition(identifier: "2"))
} else {
XCTFail()
}
}
}
func testRegister_oneOfStepsDoesntHaveBackwardTransition() {
let newPage1 = newPage("1")
let newPage2 = newPage("2")
var newPage3 = newPage("3")
newPage3.forwardTransition = PushPopFlowTransition.default
newPage3.backwardTransition = nil
do {
try flowController.register(pathComponents: [
newPage1,
newPage2,
newPage3
])
XCTFail()
} catch let error {
if let afcError = error as? AFCError {
XCTAssertEqual(afcError, AFCError.missingPathStepTransition(identifier: "2"))
} else {
XCTFail()
}
}
}
func testRegister_firstPathStepCanHaveNilTransition() {
let newPage1 = newPage("1")
var newPage2 = newPage("2")
var newPage3 = newPage("3")
newPage2.forwardTransition = PushPopFlowTransition.default
newPage2.backwardTransition = PushPopFlowTransition.default
newPage3.forwardTransition = PushPopFlowTransition.default
newPage3.backwardTransition = PushPopFlowTransition.default
do {
try flowController.register(pathComponents: [
newPage1,
newPage2,
newPage3
])
let expectedRoot = PathStep(pathComponent: newPage1)
expectedRoot.add(pathComponent: newPage2).add(pathComponent: newPage3)
XCTAssertEqual(flowController.rootPathStep, expectedRoot)
} catch _ {
XCTFail()
}
}
func testRegister_stepAlreadyRegistered_supportVariants() {
let rootPage = newPage("root", supportVariants: false)
let page1 = newPage("1", supportVariants: true)
var page2 = newPage("2", supportVariants: false)
var page3 = newPage("3", supportVariants: false)
let pages = rootPage =>> [
page2 => page1,
page3 => page1
]
do {
try flowController.register(pathComponents: pages)
let expectedRoot = PathStep(pathComponent: rootPage)
var repeatedPage1_1 = page1
var repeatedPage1_2 = page1
repeatedPage1_1.variantName = "2"
repeatedPage1_2.variantName = "3"
repeatedPage1_1.forwardTransition = PushPopFlowTransition.default
repeatedPage1_1.backwardTransition = PushPopFlowTransition.default
repeatedPage1_2.forwardTransition = PushPopFlowTransition.default
repeatedPage1_2.backwardTransition = PushPopFlowTransition.default
page2.forwardTransition = PushPopFlowTransition.default
page2.backwardTransition = PushPopFlowTransition.default
page3.forwardTransition = PushPopFlowTransition.default
page3.backwardTransition = PushPopFlowTransition.default
expectedRoot.add(pathComponent: page2).add(pathComponent: repeatedPage1_1)
expectedRoot.add(pathComponent: page3).add(pathComponent: repeatedPage1_2)
XCTAssertEqual(flowController.rootPathStep, expectedRoot)
} catch _ {
XCTFail()
}
}
}
| 34.055794 | 120 | 0.598614 |
6ab39dfe8a84aca25a507aa17969f596f72b98a8 | 3,730 | // Copyright SIX DAY LLC. All rights reserved.
import BigInt
struct KNTransactionReceipt: Decodable {
let id: String
let index: String
let blockHash: String
let blockNumber: String
let gasUsed: String
let cumulativeGasUsed: String
let contractAddress: String
let logsData: String
let logsBloom: String
let status: String
}
extension KNTransactionReceipt {
static func from(_ dictionary: JSONDictionary) -> KNTransactionReceipt? {
let id = dictionary["transactionHash"] as? String ?? ""
let index = dictionary["transactionIndex"] as? String ?? ""
let blockHash = dictionary["blockHash"] as? String ?? ""
let blockNumber = dictionary["blockNumber"] as? String ?? ""
let cumulativeGasUsed = dictionary["cumulativeGasUsed"] as? String ?? ""
let gasUsed = dictionary["gasUsed"] as? String ?? ""
let contractAddress = dictionary["contractAddress"] as? String ?? ""
let customRPC: KNCustomRPC = KNEnvironment.default.knCustomRPC!
let logsData: String = {
if let logs: [JSONDictionary] = dictionary["logs"] as? [JSONDictionary] {
for log in logs {
let address = log["address"] as? String ?? ""
let topics = log["topics"] as? [String] ?? []
let data = log["data"] as? String ?? ""
if address == customRPC.networkAddress, topics.first == customRPC.tradeTopic {
return data
}
}
}
return ""
}()
let logsBloom = dictionary["logsBloom"] as? String ?? ""
let status = dictionary["status"] as? String ?? ""
return KNTransactionReceipt(
id: id,
index: index.drop0x,
blockHash: blockHash,
blockNumber: BigInt(blockNumber.drop0x, radix: 16)?.description ?? "",
gasUsed: BigInt(gasUsed.drop0x, radix: 16)?.fullString(units: .ether) ?? "",
cumulativeGasUsed: BigInt(cumulativeGasUsed.drop0x, radix: 16)?.fullString(units: .ether) ?? "",
contractAddress: contractAddress,
logsData: logsData,
logsBloom: logsBloom,
status: status.drop0x
)
}
}
extension KNTransactionReceipt {
func toTransaction(from transaction: KNTransaction, logsDict: JSONDictionary?) -> KNTransaction {
let localObjects: [LocalizedOperationObject] = {
guard let json = logsDict else {
return Array(transaction.localizedOperations)
}
let (valueString, decimals): (String, Int) = {
let value = BigInt(json["destAmount"] as? String ?? "") ?? BigInt(0)
if let token = KNSupportedTokenStorage.shared.supportedTokens.first(where: { $0.contract == (json["dest"] as? String ?? "").lowercased() }) {
return (value.fullString(decimals: token.decimals), token.decimals)
}
return (value.fullString(decimals: 18), 18)
}()
let localObject = LocalizedOperationObject(
from: (json["src"] as? String ?? "").lowercased(),
to: (json["dest"] as? String ?? "").lowercased(),
contract: nil,
type: "exchange",
value: valueString,
symbol: transaction.localizedOperations.first?.symbol,
name: transaction.localizedOperations.first?.name,
decimals: decimals
)
return [localObject]
}()
let newTransaction = KNTransaction(
id: transaction.id,
blockNumber: Int(self.blockNumber) ?? transaction.blockNumber,
from: transaction.from,
to: transaction.to,
value: transaction.value,
gas: transaction.gas,
gasPrice: transaction.gasPrice,
gasUsed: self.gasUsed,
nonce: transaction.nonce,
date: transaction.date,
localizedOperations: localObjects,
state: self.status == "1" ? .completed : .failed
)
return newTransaction
}
}
| 36.213592 | 149 | 0.644504 |
480b6b9f7e0a6ca526049cb16e907749df93854d | 1,165 | import StoriesComponent
import UIKit
final class PreviewController: UIViewController {
// MARK: - Private Properties
private let collectionViewModel = StoriesCollectionViewModel()
// MARK: - Lifecycle
override func loadView() {
super.loadView()
setupViews()
}
private func setupViews() {
guard let navigationController = navigationController else { return }
let collection = StoriesCollection(navigationController: navigationController)
view.addSubview(collection)
setupConstraints(collection)
collection.configure(with: collectionViewModel)
}
private func setupConstraints(_ collection: UIView) {
collection.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[
collection.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collection.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collection.topAnchor.constraint(equalTo: view.topAnchor),
collection.bottomAnchor.constraint(equalTo: view.bottomAnchor),
]
)
}
}
| 31.486486 | 86 | 0.682403 |
3a1a8b05b46cd3ab8850fc86f90f0aeee40298ad | 4,617 | //
// BKVideo.swift
// BilibiliKit
//
// Created by Apollo Zhu on 7/9/17.
// Copyright (c) 2017-2020 ApolloZhu. MIT License.
//
/// Bilibili video, identified by unique bv string (bvid) or [deprecated] av number (aid).
public enum BKVideo {
/// **[Deprecated]** Video identified by av number (aid).
///
/// - Warning: consider using bvid instead:
/// [【升级公告】AV号全面升级至BV号](bilibili.com/read/cv5167957).
case av(Int)
/// Video identified by bv string (bvid).
case bv(String)
/// Initialize a BKVideo with its av number.
/// - Warning: use bv instead [【升级公告】AV号全面升级至BV号](bilibili.com/read/cv5167957).
/// - Parameter aid: av number of the video.
@available(*, unavailable, renamed: "BKVideo.av(_:)", message: "Also consider using the new bvid instead (bilibili.com/read/cv5167957)")
public init(av aid: Int) {
self = .av(aid)
}
}
// MARK: - URL Params
extension BKVideo: CustomStringConvertible {
/// Useful to pass as URL parameter.
public var description: String {
switch self {
case .av(let id):
return "aid=\(id)"
case .bv(let id):
return "bvid=\(id)"
}
}
}
// MARK: - Local conversion between AV and BV
import Foundation
// https://www.zhihu.com/question/381784377/answer/1099438784
extension BKVideo: Equatable {
/// Makes a sequences of bases in radix 58.
fileprivate struct Exp: Sequence, IteratorProtocol {
/// Next value to be returned
private var current: Int64 = 1
/// Advances to the next element and returns it.
mutating func next() -> Int64? {
defer { current *= 58 }
return current
}
}
/// Convert decimal number to radix 58.
private static let itoc = Array("fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF")
/// Convert radix 58 digits back to decimal.
private static let ctoi = [Character: Int64](
uniqueKeysWithValues: zip(itoc, itoc.indices.lazy.map(Int64.init))
)
/// The order in which digits are used.
private static let indices = [11, 10, 3, 8, 4, 6, 2, 9, 5, 7]
/// Modular so numbers are within bounds.
private static let xor: Int64 = 177451812
/// Shift by this magic number. Don't ask why.
private static let add: Int64 = 100618342136696320
/// The associated av number of this video.
/// - Note: it's highly likely that an overflow will happen eventually. In that case, we crash.
public var aid: Int {
switch self {
case .av(let aid):
return aid
case .bv(let bvid):
return BKVideo.aid(fromBV: bvid)
}
}
/// The associated bv string of this video.
/// - Note: it's highly likely that an overflow will happen eventually. In that case, we crash.
public var bvid: String {
switch self {
case .av(let aid):
return BKVideo.bvid(fromAV: aid)
case .bv(let bvid):
return bvid
}
}
/// Converts the given bv ID string to its corresponding av number.
/// - Note: it's highly likely that an overflow will happen eventually. In that case, we crash.
/// - Parameter bvid: the bv ID string to convert from.
public static func aid(fromBV bvid: String) -> Int {
var r: Int64 = 0
let bvid = Array(bvid)
for (i, exp) in zip(0..<10, Exp()) {
r += ctoi[bvid[indices[i]]]! * exp
}
return Int((r - add) ^ xor)
}
/// Converts the given av number to its corresponding bv ID string.
/// - Note: it's highly likely that an overflow will happen eventually. In that case, we crash.
/// - Parameter aid: the av number to convert from.
public static func bvid(fromAV aid: Int) -> String {
let aid = (Int64(aid) ^ xor) + add
var r = Array("BV ")
for (i, exp) in zip(0..<10, Exp()) {
r[indices[i]] = itoc[Int(aid / exp % 58)]
}
return String(r)
}
/// Returns a Boolean value indicating whether two values are equal.
/// Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: BKVideo, rhs: BKVideo) -> Bool {
switch (lhs, rhs) {
case let (.av(id1), .av(id2)):
return id1 == id2
case let (.bv(id1), .bv(id2)):
return id1 == id2
default:
return lhs.bvid == rhs.bvid
}
}
}
| 33.948529 | 140 | 0.595192 |
b983b7f2a78bdbb0ec446c188320db4a5f273208 | 1,562 | //
// ViewController.swift
// ParallaxCarouselExample
//
// Created by Matteo Tagliafico on 03/04/16.
// Copyright © 2016 Matteo Tagliafico. All rights reserved.
//
import UIKit
import TGLParallaxCarousel
class ViewController: UIViewController {
// MARK: - outlets
@IBOutlet weak var carouselView: TGLParallaxCarousel!
// MARK: - view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupCarousel()
}
// MARK: - methods
fileprivate func setupCarousel() {
carouselView.delegate = self
carouselView.margin = 10
carouselView.selectedIndex = 2
carouselView.type = .threeDimensional
carouselView.maxDistance = 20
}
override var prefersStatusBarHidden : Bool {
return true
}
}
// MARK: - TGLParallaxCarouselDelegate
extension ViewController: TGLParallaxCarouselDelegate {
func numberOfItemsInCarouselView(_ carouselView: TGLParallaxCarousel) -> Int {
return 5
}
func carouselView(_ carouselView: TGLParallaxCarousel, itemForRowAtIndex index: Int) -> TGLParallaxCarouselItem {
return CustomView(frame: CGRect(x: 0, y: 0, width: 300, height: 150) , number: index)
}
func carouselView(_ carouselView: TGLParallaxCarousel, didSelectItemAtIndex index: Int) {
print("Tap on item at index \(index)")
}
func carouselView(_ carouselView: TGLParallaxCarousel, willDisplayItem item: TGLParallaxCarouselItem, forIndex index: Int) {
print("")
}
}
| 26.474576 | 128 | 0.674136 |
efc11042c233982e63f5570b469517cd8a525a0b | 636 | extension OfficialAccount {
static let template: OfficialAccount! = tryDecode(
"""
{
"id": "cf73ed17-20b5-4254-b67c-c6539acb4d81",
"avatar": "https://raw.githubusercontent.com/Lebron1992/WeChat-SwiftUI-Database/main/images/guangdongdianxin.jpeg",
"name": "广东电信",
"pinyin": "guangdongdianxin"
}
"""
)
static let template2: OfficialAccount! = tryDecode(
"""
{
"id": "93209b2a-f4d2-43b9-b173-228c417b1a8e",
"avatar": "https://raw.githubusercontent.com/Lebron1992/WeChat-SwiftUI-Database/main/images/kejimeixue.jpeg",
"name": "科技美学",
"pinyin": "kejimeixue"
}
"""
)
}
| 26.5 | 119 | 0.649371 |
f97c0d4ce7f046b09958120116d7a1e1ea8f2535 | 1,552 | //
// ReposDataLoader.swift
// Repo List
//
// Created by Linus Nyberg on 2017-05-13.
// Copyright © 2017 Linus Nyberg. All rights reserved.
//
import Foundation
import CoreData
import UIKit
/// Loads data for the "Repos" view (ReposViewController).
class ReposDataLoader {
weak var delegate: DataLoaderDelegate?
var loadingState: LoadingState = .neverLoaded
/// For loading cached data
var repoStore: RepoStore
/// For fetching data from Github
var repoService: RepoService
/// The last loaded Repos
var repos: [Repo] = []
init(delegate: DataLoaderDelegate, viewController: UIViewController, persistentContainer: NSPersistentContainer) {
self.delegate = delegate
repoStore = RepoStore(withContainer: persistentContainer)
let authenticator = Authenticator(viewController: viewController)
repoService = RepoService(authenticator: authenticator, store: repoStore)
}
}
// MARK: - DataLoader
extension ReposDataLoader: DataLoader {
func startLoadingData(allowCache: Bool) {
guard let delegate = delegate else {
return
}
loadingState = .isLoading
// Load from cache
//----------------
if (allowCache) {
repos = repoStore.loadRepos()
delegate.dataLoaderDidLoadData(dataLoader: self)
}
// Fetch from Github
//------------------
repoService.fetchRepos() { [weak self] (repos: [Repo]?) in
guard let strongSelf = self, let repos = repos else {
return
}
strongSelf.repos = repos
delegate.dataLoaderDidLoadData(dataLoader: strongSelf)
strongSelf.loadingState = .doneLoading
}
}
}
| 24.634921 | 115 | 0.717784 |
e5daad842b52f6925a151c271c3f631ff153c9cf | 8,779 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
@available(iOS 14.0, *)
struct PollTimelineAnswerOptionButton: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
let answerOption: TimelineAnswerOption
let pollClosed: Bool
let showResults: Bool
let totalAnswerCount: UInt
let action: () -> Void
// MARK: Public
var body: some View {
Button(action: action) {
let rect = RoundedRectangle(cornerRadius: 4.0)
answerOptionLabel
.padding(.horizontal, 8.0)
.padding(.top, 12.0)
.padding(.bottom, 4.0)
.clipShape(rect)
.overlay(rect.stroke(borderAccentColor, lineWidth: 1.0))
.accentColor(progressViewAccentColor)
}
}
var answerOptionLabel: some View {
VStack(alignment: .leading, spacing: 12.0) {
HStack(alignment: .top, spacing: 8.0) {
if !pollClosed {
Image(uiImage: answerOption.selected ? Asset.Images.pollCheckboxSelected.image : Asset.Images.pollCheckboxDefault.image)
}
Text(answerOption.text)
.font(theme.fonts.body)
.foregroundColor(theme.colors.primaryContent)
if pollClosed && answerOption.winner {
Spacer()
Image(uiImage: Asset.Images.pollWinnerIcon.image)
}
}
HStack {
ProgressView(value: Double(showResults ? answerOption.count : 0),
total: Double(totalAnswerCount))
.progressViewStyle(LinearProgressViewStyle())
.scaleEffect(x: 1.0, y: 1.2, anchor: .center)
.padding(.vertical, 8.0)
if (showResults) {
Text(answerOption.count == 1 ? VectorL10n.pollTimelineOneVote : VectorL10n.pollTimelineVotesCount(Int(answerOption.count)))
.font(theme.fonts.footnote)
.foregroundColor(pollClosed && answerOption.winner ? theme.colors.accent : theme.colors.secondaryContent)
}
}
}
}
var borderAccentColor: Color {
guard !pollClosed else {
return (answerOption.winner ? theme.colors.accent : theme.colors.quinaryContent)
}
return answerOption.selected ? theme.colors.accent : theme.colors.quinaryContent
}
var progressViewAccentColor: Color {
guard !pollClosed else {
return (answerOption.winner ? theme.colors.accent : theme.colors.quarterlyContent)
}
return answerOption.selected ? theme.colors.accent : theme.colors.quarterlyContent
}
}
@available(iOS 14.0, *)
struct PollTimelineAnswerOptionButton_Previews: PreviewProvider {
static let stateRenderer = MockPollTimelineScreenState.stateRenderer
static var previews: some View {
Group {
VStack {
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 5, winner: false, selected: false),
pollClosed: false, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 5, winner: false, selected: false),
pollClosed: false, showResults: false, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 8, winner: false, selected: true),
pollClosed: false, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 8, winner: false, selected: true),
pollClosed: false, showResults: false, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
count: 200, winner: false, selected: false),
pollClosed: false, showResults: true, totalAnswerCount: 1000, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
count: 200, winner: false, selected: false),
pollClosed: false, showResults: false, totalAnswerCount: 1000, action: {})
}
VStack {
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 5, winner: false, selected: false),
pollClosed: true, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 5, winner: true, selected: false),
pollClosed: true, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 8, winner: false, selected: true),
pollClosed: true, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "", text: "Test", count: 8, winner: true, selected: true),
pollClosed: true, showResults: true, totalAnswerCount: 100, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
count: 200, winner: false, selected: false),
pollClosed: true, showResults: true, totalAnswerCount: 1000, action: {})
PollTimelineAnswerOptionButton(answerOption: TimelineAnswerOption(id: "",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
count: 200, winner: true, selected: false),
pollClosed: true, showResults: true, totalAnswerCount: 1000, action: {})
}
}
}
}
| 56.275641 | 322 | 0.552683 |
e5fa5f39b39c5ea2f9ec193ab6a9970da7aa8f54 | 1,341 | //
// AppDelegate.swift
// Prework
//
// Created by Student on 1/31/22.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.243243 | 179 | 0.744966 |
d947d0eff3302371f14708780d59e6bda299427a | 263 | //
// UIActivityIndicatorView.swift
// LoopKitUI
//
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
extension UIActivityIndicatorView.Style {
static var `default`: UIActivityIndicatorView.Style {
return .medium
}
}
| 16.4375 | 58 | 0.703422 |
6959185cc654b017d9b50cb05ccb4418085d285d | 1,865 | //
// InitialSetupDexcomG6ConnectionWorkerTests.swift
// xDripTests
//
// Created by Artem Kalmykov on 04.04.2020.
// Copyright © 2020 Faifly. All rights reserved.
//
import XCTest
@testable import xDrip
final class InitialSetupDexcomG6ConnectionWorkerTests: XCTestCase {
let sut = InitialSetupDexcomG6ConnectionWorker()
var calledSuccessfulConnectionHandler = false
override func setUp() {
super.setUp()
sut.onSuccessfulConnection = { _ in
self.calledSuccessfulConnectionHandler = true
}
}
func testStartConnection() {
// When
sut.startConnectionProcess()
// Then
XCTAssertTrue(CGMDevice.current.isSetupInProgress)
#if targetEnvironment(simulator)
XCTAssertTrue(CGMController.shared.service is MockedBluetoothService)
#else
XCTAssertTrue(CGMController.shared.service is DexcomG6BluetoothService)
#endif
}
func testHandleSuccessfulConnection() {
// When
sut.startConnectionProcess()
let controller = CGMController.shared
controller.serviceDidUpdateMetadata(.firmwareVersion, value: "123")
XCTAssert(calledSuccessfulConnectionHandler == false)
controller.serviceDidUpdateMetadata(.batteryVoltageA, value: "90")
XCTAssert(calledSuccessfulConnectionHandler == false)
controller.serviceDidUpdateMetadata(.batteryVoltageB, value: "78")
XCTAssert(calledSuccessfulConnectionHandler == false)
controller.serviceDidUpdateMetadata(.transmitterTime, value: "123123123")
XCTAssert(calledSuccessfulConnectionHandler == false)
controller.serviceDidUpdateMetadata(.deviceName, value: "321")
XCTAssert(calledSuccessfulConnectionHandler == true)
}
}
| 32.155172 | 81 | 0.683646 |
abbd0a09fc1d27add88f3ca99f4db9c32d6c150d | 30,679 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
protocol PhotoCaptureDelegate: AnyObject {
// MARK: Still Photo
func photoCaptureDidStartPhotoCapture(_ photoCapture: PhotoCapture)
func photoCapture(_ photoCapture: PhotoCapture, didFinishProcessingAttachment attachment: SignalAttachment)
func photoCapture(_ photoCapture: PhotoCapture, processingDidError error: Error)
// MARK: Video
func photoCaptureDidBeginVideo(_ photoCapture: PhotoCapture)
func photoCaptureDidCompleteVideo(_ photoCapture: PhotoCapture)
func photoCaptureDidCancelVideo(_ photoCapture: PhotoCapture)
// MARK: Utility
func photoCaptureCanCaptureMoreItems(_ photoCapture: PhotoCapture) -> Bool
func photoCaptureDidTryToCaptureTooMany(_ photoCapture: PhotoCapture)
var zoomScaleReferenceHeight: CGFloat? { get }
var captureOrientation: AVCaptureVideoOrientation { get }
func beginCaptureButtonAnimation(_ duration: TimeInterval)
func endCaptureButtonAnimation(_ duration: TimeInterval)
}
@objc
class PhotoCapture: NSObject {
weak var delegate: PhotoCaptureDelegate?
var flashMode: AVCaptureDevice.FlashMode {
return captureOutput.flashMode
}
let session: AVCaptureSession
// There can only ever be one `CapturePreviewView` per AVCaptureSession
lazy private(set) var previewView = CapturePreviewView(session: session)
let sessionQueue = DispatchQueue(label: "PhotoCapture.sessionQueue")
private var currentCaptureInput: AVCaptureDeviceInput?
private let captureOutput: CaptureOutput
var captureDevice: AVCaptureDevice? {
return currentCaptureInput?.device
}
private(set) var desiredPosition: AVCaptureDevice.Position = .back
let recordingAudioActivity = AudioActivity(audioDescription: "PhotoCapture", behavior: .playAndRecord)
override init() {
self.session = AVCaptureSession()
self.captureOutput = CaptureOutput()
}
// MARK: - Dependencies
var audioSession: OWSAudioSession {
return Environment.shared.audioSession
}
// MARK: -
var audioDeviceInput: AVCaptureDeviceInput?
func startAudioCapture() throws {
assertIsOnSessionQueue()
guard audioSession.startAudioActivity(recordingAudioActivity) else {
throw PhotoCaptureError.assertionError(description: "unable to capture audio activity")
}
self.session.beginConfiguration()
defer { self.session.commitConfiguration() }
let audioDevice = AVCaptureDevice.default(for: .audio)
// verify works without audio permissions
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice!)
if session.canAddInput(audioDeviceInput) {
// self.session.addInputWithNoConnections(audioDeviceInput)
session.addInput(audioDeviceInput)
self.audioDeviceInput = audioDeviceInput
} else {
owsFailDebug("Could not add audio device input to the session")
}
}
func stopAudioCapture() {
assertIsOnSessionQueue()
self.session.beginConfiguration()
defer { self.session.commitConfiguration() }
guard let audioDeviceInput = self.audioDeviceInput else {
owsFailDebug("audioDevice was unexpectedly nil")
return
}
session.removeInput(audioDeviceInput)
self.audioDeviceInput = nil
audioSession.endAudioActivity(recordingAudioActivity)
}
func startVideoCapture() -> Promise<Void> {
// If the session is already running, no need to do anything.
guard !self.session.isRunning else { return Promise.value(()) }
return sessionQueue.async(.promise) { [weak self] in
guard let self = self else { return }
self.session.beginConfiguration()
defer { self.session.commitConfiguration() }
self.session.sessionPreset = .medium
try self.updateCurrentInput(position: .back)
guard let photoOutput = self.captureOutput.photoOutput else {
throw PhotoCaptureError.initializationFailed
}
guard self.session.canAddOutput(photoOutput) else {
throw PhotoCaptureError.initializationFailed
}
if let connection = photoOutput.connection(with: .video) {
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
}
self.session.addOutput(photoOutput)
let movieOutput = self.captureOutput.movieOutput
if self.session.canAddOutput(movieOutput) {
self.session.addOutput(movieOutput)
guard let connection = movieOutput.connection(with: .video) else {
throw PhotoCaptureError.initializationFailed
}
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
if #available(iOS 11.0, *) {
guard movieOutput.availableVideoCodecTypes.contains(.h264) else {
throw PhotoCaptureError.initializationFailed
}
// Use the H.264 codec to encode the video rather than HEVC.
// Before iOS11, HEVC wasn't supported and H.264 was the default.
movieOutput.setOutputSettings([AVVideoCodecKey:
AVVideoCodecType.h264], for: connection)
}
}
}.done(on: sessionQueue) {
self.session.startRunning()
}
}
func stopCapture() -> Guarantee<Void> {
return sessionQueue.async(.promise) {
self.session.stopRunning()
}
}
func assertIsOnSessionQueue() {
assertOnQueue(sessionQueue)
}
func switchCamera() -> Promise<Void> {
AssertIsOnMainThread()
let newPosition: AVCaptureDevice.Position
switch desiredPosition {
case .front:
newPosition = .back
case .back:
newPosition = .front
case .unspecified:
newPosition = .front
@unknown default:
owsFailDebug("Unexpected enum value.")
newPosition = .front
break
}
desiredPosition = newPosition
return sessionQueue.async(.promise) { [weak self] in
guard let self = self else { return }
self.session.beginConfiguration()
defer { self.session.commitConfiguration() }
try self.updateCurrentInput(position: newPosition)
}
}
// This method should be called on the serial queue,
// and between calls to session.beginConfiguration/commitConfiguration
func updateCurrentInput(position: AVCaptureDevice.Position) throws {
assertIsOnSessionQueue()
guard let device = captureOutput.videoDevice(position: position) else {
throw PhotoCaptureError.assertionError(description: description)
}
let newInput = try AVCaptureDeviceInput(device: device)
if let oldInput = self.currentCaptureInput {
session.removeInput(oldInput)
NotificationCenter.default.removeObserver(self, name: .AVCaptureDeviceSubjectAreaDidChange, object: oldInput.device)
}
session.addInput(newInput)
NotificationCenter.default.addObserver(self, selector: #selector(subjectAreaDidChange), name: .AVCaptureDeviceSubjectAreaDidChange, object: newInput.device)
currentCaptureInput = newInput
resetFocusAndExposure()
}
func switchFlashMode() -> Guarantee<Void> {
return sessionQueue.async(.promise) {
switch self.captureOutput.flashMode {
case .auto:
Logger.debug("new flashMode: on")
self.captureOutput.flashMode = .on
case .on:
Logger.debug("new flashMode: off")
self.captureOutput.flashMode = .off
case .off:
Logger.debug("new flashMode: auto")
self.captureOutput.flashMode = .auto
@unknown default:
owsFailDebug("unknown flashMode: \(self.captureOutput.flashMode)")
self.captureOutput.flashMode = .auto
}
}
}
func focus(with focusMode: AVCaptureDevice.FocusMode,
exposureMode: AVCaptureDevice.ExposureMode,
at devicePoint: CGPoint,
monitorSubjectAreaChange: Bool) {
sessionQueue.async {
Logger.debug("focusMode: \(focusMode), exposureMode: \(exposureMode), devicePoint: \(devicePoint), monitorSubjectAreaChange:\(monitorSubjectAreaChange)")
guard let device = self.captureDevice else {
owsFailDebug("device was unexpectedly nil")
return
}
do {
try device.lockForConfiguration()
// Setting (focus/exposure)PointOfInterest alone does not initiate a (focus/exposure) operation.
// Call set(Focus/Exposure)Mode() to apply the new point of interest.
if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) {
device.focusPointOfInterest = devicePoint
device.focusMode = focusMode
}
if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) {
device.exposurePointOfInterest = devicePoint
device.exposureMode = exposureMode
}
device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange
device.unlockForConfiguration()
} catch {
owsFailDebug("error: \(error)")
}
}
}
func resetFocusAndExposure() {
let devicePoint = CGPoint(x: 0.5, y: 0.5)
focus(with: .continuousAutoFocus, exposureMode: .continuousAutoExposure, at: devicePoint, monitorSubjectAreaChange: false)
}
@objc
func subjectAreaDidChange(notification: NSNotification) {
resetFocusAndExposure()
}
// MARK: - Zoom
let minimumZoom: CGFloat = 1.0
let maximumZoom: CGFloat = 3.0
var previousZoomFactor: CGFloat = 1.0
func updateZoom(alpha: CGFloat) {
assert(alpha >= 0 && alpha <= 1)
sessionQueue.async {
guard let captureDevice = self.captureDevice else {
owsFailDebug("captureDevice was unexpectedly nil")
return
}
// we might want this to be non-linear
let scale = CGFloatLerp(self.minimumZoom, self.maximumZoom, alpha)
let zoomFactor = self.clampZoom(scale, device: captureDevice)
self.updateZoom(factor: zoomFactor)
}
}
func updateZoom(scaleFromPreviousZoomFactor scale: CGFloat) {
sessionQueue.async {
guard let captureDevice = self.captureDevice else {
owsFailDebug("captureDevice was unexpectedly nil")
return
}
let zoomFactor = self.clampZoom(scale * self.previousZoomFactor, device: captureDevice)
self.updateZoom(factor: zoomFactor)
}
}
func completeZoom(scaleFromPreviousZoomFactor scale: CGFloat) {
sessionQueue.async {
guard let captureDevice = self.captureDevice else {
owsFailDebug("captureDevice was unexpectedly nil")
return
}
let zoomFactor = self.clampZoom(scale * self.previousZoomFactor, device: captureDevice)
Logger.debug("ended with scaleFactor: \(zoomFactor)")
self.previousZoomFactor = zoomFactor
self.updateZoom(factor: zoomFactor)
}
}
private func updateZoom(factor: CGFloat) {
assertIsOnSessionQueue()
guard let captureDevice = self.captureDevice else {
owsFailDebug("captureDevice was unexpectedly nil")
return
}
do {
try captureDevice.lockForConfiguration()
captureDevice.videoZoomFactor = factor
captureDevice.unlockForConfiguration()
} catch {
owsFailDebug("error: \(error)")
}
}
private func clampZoom(_ factor: CGFloat, device: AVCaptureDevice) -> CGFloat {
return min(factor.clamp(minimumZoom, maximumZoom), device.activeFormat.videoMaxZoomFactor)
}
// MARK: - Photo
private func handleTap() {
Logger.verbose("")
guard let delegate = delegate else { return }
guard delegate.photoCaptureCanCaptureMoreItems(self) else {
delegate.photoCaptureDidTryToCaptureTooMany(self)
return
}
delegate.photoCaptureDidStartPhotoCapture(self)
sessionQueue.async {
self.captureOutput.takePhoto(delegate: self)
}
}
// MARK: - Video
private func handleLongPressBegin() {
AssertIsOnMainThread()
Logger.verbose("")
guard let delegate = delegate else { return }
guard delegate.photoCaptureCanCaptureMoreItems(self) else {
delegate.photoCaptureDidTryToCaptureTooMany(self)
return
}
sessionQueue.async(.promise) {
try self.startAudioCapture()
self.captureOutput.beginVideo(delegate: self)
}.done {
self.delegate?.photoCaptureDidBeginVideo(self)
}.catch { error in
self.delegate?.photoCapture(self, processingDidError: error)
}.retainUntilComplete()
}
private func handleLongPressComplete() {
Logger.verbose("")
sessionQueue.async {
self.captureOutput.completeVideo(delegate: self)
self.stopAudioCapture()
}
AssertIsOnMainThread()
// immediately inform UI that capture is stopping
delegate?.photoCaptureDidCompleteVideo(self)
}
private func handleLongPressCancel() {
Logger.verbose("")
AssertIsOnMainThread()
sessionQueue.async {
self.stopAudioCapture()
}
delegate?.photoCaptureDidCancelVideo(self)
}
}
extension PhotoCapture: VolumeButtonObserver {
func didPressVolumeButton(with identifier: VolumeButtons.Identifier) {
delegate?.beginCaptureButtonAnimation(0.5)
}
func didReleaseVolumeButton(with identifier: VolumeButtons.Identifier) {
delegate?.endCaptureButtonAnimation(0.2)
}
func didTapVolumeButton(with identifier: VolumeButtons.Identifier) {
handleTap()
}
func didBeginLongPressVolumeButton(with identifier: VolumeButtons.Identifier) {
handleLongPressBegin()
}
func didCompleteLongPressVolumeButton(with identifier: VolumeButtons.Identifier) {
handleLongPressComplete()
}
func didCancelLongPressVolumeButton(with identifier: VolumeButtons.Identifier) {
handleLongPressCancel()
}
}
extension PhotoCapture: CaptureButtonDelegate {
func didTapCaptureButton(_ captureButton: CaptureButton) {
handleTap()
}
func didBeginLongPressCaptureButton(_ captureButton: CaptureButton) {
handleLongPressBegin()
}
func didCompleteLongPressCaptureButton(_ captureButton: CaptureButton) {
handleLongPressComplete()
}
func didCancelLongPressCaptureButton(_ captureButton: CaptureButton) {
handleLongPressCancel()
}
var zoomScaleReferenceHeight: CGFloat? {
return delegate?.zoomScaleReferenceHeight
}
func longPressCaptureButton(_ captureButton: CaptureButton, didUpdateZoomAlpha zoomAlpha: CGFloat) {
updateZoom(alpha: zoomAlpha)
}
}
extension PhotoCapture: CaptureOutputDelegate {
var captureOrientation: AVCaptureVideoOrientation {
guard let delegate = delegate else { return .portrait }
return delegate.captureOrientation
}
// MARK: - Photo
func captureOutputDidFinishProcessing(photoData: Data?, error: Error?) {
Logger.verbose("")
AssertIsOnMainThread()
if let error = error {
delegate?.photoCapture(self, processingDidError: error)
return
}
guard let photoData = photoData else {
owsFailDebug("photoData was unexpectedly nil")
delegate?.photoCapture(self, processingDidError: PhotoCaptureError.captureFailed)
return
}
let dataSource = DataSourceValue.dataSource(with: photoData, utiType: kUTTypeJPEG as String)
let attachment = SignalAttachment.attachment(dataSource: dataSource, dataUTI: kUTTypeJPEG as String, imageQuality: .medium)
delegate?.photoCapture(self, didFinishProcessingAttachment: attachment)
}
// MARK: - Movie
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
Logger.verbose("")
AssertIsOnMainThread()
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
Logger.verbose("")
AssertIsOnMainThread()
if let error = error {
guard didSucceedDespiteError(error) else {
delegate?.photoCapture(self, processingDidError: error)
return
}
Logger.info("Ignoring error, since capture succeeded.")
}
guard let dataSource = try? DataSourcePath.dataSource(with: outputFileURL, shouldDeleteOnDeallocation: true) else {
delegate?.photoCapture(self, processingDidError: PhotoCaptureError.captureFailed)
return
}
// AVCaptureMovieFileOutput records to .mov, but for compatibility we need to send mp4's.
// Because we take care to record with h264 compression (not hevc), this conversion
// doesn't require re-encoding the media streams and happens quickly.
let (attachmentPromise, _) = SignalAttachment.compressVideoAsMp4(dataSource: dataSource, dataUTI: kUTTypeMPEG4 as String)
attachmentPromise.map { [weak self] attachment in
guard let self = self else { return }
self.delegate?.photoCapture(self, didFinishProcessingAttachment: attachment)
}.retainUntilComplete()
}
/// The AVCaptureFileOutput can return an error even though recording succeeds.
/// I can't find useful documentation on this, but Apple's example AVCam app silently
/// discards these errors, so we do the same.
/// These spurious errors can be reproduced 1/3 of the time when making a series of short videos.
private func didSucceedDespiteError(_ error: Error) -> Bool {
let nsError = error as NSError
guard let successfullyFinished = nsError.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool else {
return false
}
return successfullyFinished
}
}
// MARK: - Capture Adapter
protocol CaptureOutputDelegate: AVCaptureFileOutputRecordingDelegate {
var session: AVCaptureSession { get }
func assertIsOnSessionQueue()
func captureOutputDidFinishProcessing(photoData: Data?, error: Error?)
var captureOrientation: AVCaptureVideoOrientation { get }
}
protocol ImageCaptureOutput: AnyObject {
var avOutput: AVCaptureOutput { get }
var flashMode: AVCaptureDevice.FlashMode { get set }
func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice?
func takePhoto(delegate: CaptureOutputDelegate)
}
class CaptureOutput {
let imageOutput: ImageCaptureOutput
let movieOutput: AVCaptureMovieFileOutput
// MARK: - Init
init() {
if #available(iOS 10.0, *) {
imageOutput = PhotoCaptureOutputAdaptee()
} else {
imageOutput = StillImageCaptureOutput()
}
movieOutput = AVCaptureMovieFileOutput()
// disable movie fragment writing since it's not supported on mp4
// leaving it enabled causes all audio to be lost on videos longer
// than the default length (10s).
movieOutput.movieFragmentInterval = CMTime.invalid
}
var photoOutput: AVCaptureOutput? {
return imageOutput.avOutput
}
var flashMode: AVCaptureDevice.FlashMode {
get { return imageOutput.flashMode }
set { imageOutput.flashMode = newValue }
}
func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
return imageOutput.videoDevice(position: position)
}
func takePhoto(delegate: CaptureOutputDelegate) {
delegate.assertIsOnSessionQueue()
guard let photoOutput = photoOutput else {
owsFailDebug("photoOutput was unexpectedly nil")
return
}
guard let photoVideoConnection = photoOutput.connection(with: .video) else {
owsFailDebug("photoVideoConnection was unexpectedly nil")
return
}
let videoOrientation = delegate.captureOrientation
photoVideoConnection.videoOrientation = videoOrientation
Logger.verbose("videoOrientation: \(videoOrientation)")
return imageOutput.takePhoto(delegate: delegate)
}
// MARK: - Movie Output
func beginVideo(delegate: CaptureOutputDelegate) {
delegate.assertIsOnSessionQueue()
guard let videoConnection = movieOutput.connection(with: .video) else {
owsFailDebug("movieOutputConnection was unexpectedly nil")
return
}
let videoOrientation = delegate.captureOrientation
videoConnection.videoOrientation = videoOrientation
let outputFilePath = OWSFileSystem.temporaryFilePath(withFileExtension: "mp4")
movieOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: delegate)
}
func completeVideo(delegate: CaptureOutputDelegate) {
delegate.assertIsOnSessionQueue()
movieOutput.stopRecording()
}
func cancelVideo(delegate: CaptureOutputDelegate) {
delegate.assertIsOnSessionQueue()
// There's currently no user-visible way to cancel, if so, we may need to do some cleanup here.
owsFailDebug("video was unexpectedly canceled.")
}
}
@available(iOS 10.0, *)
class PhotoCaptureOutputAdaptee: NSObject, ImageCaptureOutput {
let photoOutput = AVCapturePhotoOutput()
var avOutput: AVCaptureOutput {
return photoOutput
}
var flashMode: AVCaptureDevice.FlashMode = .off
override init() {
photoOutput.isLivePhotoCaptureEnabled = false
photoOutput.isHighResolutionCaptureEnabled = true
}
private var photoProcessors: [Int64: PhotoProcessor] = [:]
func takePhoto(delegate: CaptureOutputDelegate) {
delegate.assertIsOnSessionQueue()
let settings = buildCaptureSettings()
let photoProcessor = PhotoProcessor(delegate: delegate, completion: { [weak self] in
self?.photoProcessors[settings.uniqueID] = nil
})
photoProcessors[settings.uniqueID] = photoProcessor
photoOutput.capturePhoto(with: settings, delegate: photoProcessor)
}
func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
// use dual camera where available
return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position)
}
// MARK: -
private func buildCaptureSettings() -> AVCapturePhotoSettings {
let photoSettings = AVCapturePhotoSettings()
photoSettings.flashMode = flashMode
photoSettings.isHighResolutionPhotoEnabled = true
photoSettings.isAutoStillImageStabilizationEnabled =
photoOutput.isStillImageStabilizationSupported
return photoSettings
}
private class PhotoProcessor: NSObject, AVCapturePhotoCaptureDelegate {
weak var delegate: CaptureOutputDelegate?
let completion: () -> Void
init(delegate: CaptureOutputDelegate, completion: @escaping () -> Void) {
self.delegate = delegate
self.completion = completion
}
@available(iOS 11.0, *)
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
let data = photo.fileDataRepresentation()!
DispatchQueue.main.async {
self.delegate?.captureOutputDidFinishProcessing(photoData: data, error: error)
}
completion()
}
// for legacy (iOS10) devices
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
if #available(iOS 11, *) {
owsFailDebug("unexpectedly calling legacy method.")
}
guard let photoSampleBuffer = photoSampleBuffer else {
owsFailDebug("sampleBuffer was unexpectedly nil")
return
}
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(photoSampleBuffer)
DispatchQueue.main.async {
self.delegate?.captureOutputDidFinishProcessing(photoData: data, error: error)
}
completion()
}
}
}
class StillImageCaptureOutput: ImageCaptureOutput {
var flashMode: AVCaptureDevice.FlashMode = .off
let stillImageOutput = AVCaptureStillImageOutput()
var avOutput: AVCaptureOutput {
return stillImageOutput
}
init() {
stillImageOutput.isHighResolutionStillImageOutputEnabled = true
}
// MARK: -
func takePhoto(delegate: CaptureOutputDelegate) {
guard let videoConnection = stillImageOutput.connection(with: .video) else {
owsFailDebug("videoConnection was unexpectedly nil")
return
}
stillImageOutput.captureStillImageAsynchronously(from: videoConnection) { [weak delegate] (sampleBuffer, error) in
guard let sampleBuffer = sampleBuffer else {
owsFailDebug("sampleBuffer was unexpectedly nil")
return
}
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
DispatchQueue.main.async {
delegate?.captureOutputDidFinishProcessing(photoData: data, error: error)
}
}
}
func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let captureDevices = AVCaptureDevice.devices()
guard let device = (captureDevices.first { $0.hasMediaType(.video) && $0.position == position }) else {
Logger.debug("unable to find desired position: \(position)")
return captureDevices.first
}
return device
}
}
extension AVCaptureVideoOrientation {
init?(deviceOrientation: UIDeviceOrientation) {
switch deviceOrientation {
case .portrait: self = .portrait
case .portraitUpsideDown: self = .portraitUpsideDown
case .landscapeLeft: self = .landscapeRight
case .landscapeRight: self = .landscapeLeft
default: return nil
}
}
}
extension AVCaptureDevice.FocusMode: CustomStringConvertible {
public var description: String {
switch self {
case .locked:
return "FocusMode.locked"
case .autoFocus:
return "FocusMode.autoFocus"
case .continuousAutoFocus:
return "FocusMode.continuousAutoFocus"
@unknown default:
return "FocusMode.unknown"
}
}
}
extension AVCaptureDevice.ExposureMode: CustomStringConvertible {
public var description: String {
switch self {
case .locked:
return "ExposureMode.locked"
case .autoExpose:
return "ExposureMode.autoExpose"
case .continuousAutoExposure:
return "ExposureMode.continuousAutoExposure"
case .custom:
return "ExposureMode.custom"
@unknown default:
return "ExposureMode.unknown"
}
}
}
extension AVCaptureVideoOrientation: CustomStringConvertible {
public var description: String {
switch self {
case .portrait:
return "AVCaptureVideoOrientation.portrait"
case .portraitUpsideDown:
return "AVCaptureVideoOrientation.portraitUpsideDown"
case .landscapeRight:
return "AVCaptureVideoOrientation.landscapeRight"
case .landscapeLeft:
return "AVCaptureVideoOrientation.landscapeLeft"
@unknown default:
return "AVCaptureVideoOrientation.unknown"
}
}
}
extension UIDeviceOrientation: CustomStringConvertible {
public var description: String {
switch self {
case .unknown:
return "UIDeviceOrientation.unknown"
case .portrait:
return "UIDeviceOrientation.portrait"
case .portraitUpsideDown:
return "UIDeviceOrientation.portraitUpsideDown"
case .landscapeLeft:
return "UIDeviceOrientation.landscapeLeft"
case .landscapeRight:
return "UIDeviceOrientation.landscapeRight"
case .faceUp:
return "UIDeviceOrientation.faceUp"
case .faceDown:
return "UIDeviceOrientation.faceDown"
@unknown default:
return "UIDeviceOrientation.unknown"
}
}
}
extension UIImage.Orientation: CustomStringConvertible {
public var description: String {
switch self {
case .up:
return "UIImageOrientation.up"
case .down:
return "UIImageOrientation.down"
case .left:
return "UIImageOrientation.left"
case .right:
return "UIImageOrientation.right"
case .upMirrored:
return "UIImageOrientation.upMirrored"
case .downMirrored:
return "UIImageOrientation.downMirrored"
case .leftMirrored:
return "UIImageOrientation.leftMirrored"
case .rightMirrored:
return "UIImageOrientation.rightMirrored"
@unknown default:
return "UIImageOrientation.unknown"
}
}
}
| 34.902162 | 296 | 0.655823 |
8a4d2460c62723c43eff06ca2bdb42fe2d9cd892 | 5,702 | import XCTest
@testable import Mapper
final class MappableValueTests: XCTestCase {
func testNestedMappable() {
struct Test: Mappable {
let nest: Nested
init(map: Mapper) throws {
try self.nest = map.from("nest")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: ["nest": ["string": "hello"]]))
XCTAssertTrue(test?.nest.string == "hello")
}
func testArrayOfMappables() {
struct Test: Mappable {
let nests: [Nested]
init(map: Mapper) throws {
try self.nests = map.from("nests")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: ["nests": [["string": "first"], ["string": "second"]]]))
XCTAssertTrue(test?.nests.count == 2)
}
func testOptionalMappable() {
struct Test: Mappable {
let nest: Nested?
init(map: Mapper) {
self.nest = map.optionalFrom("foo")
}
}
struct Nested: Mappable {
init(map: Mapper) {}
}
let test = Test(map: Mapper(JSON: [:]))
XCTAssertNil(test.nest)
}
func testInvalidArrayOfMappables() {
struct Test: Mappable {
let nests: [Nested]
init(map: Mapper) throws {
try self.nests = map.from("nests")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: ["nests": "not an array"]))
XCTAssertNil(test)
}
func testValidArrayOfOptionalMappables() {
struct Test: Mappable {
let nests: [Nested]?
init(map: Mapper) {
self.nests = map.optionalFrom("nests")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = Test(map: Mapper(JSON: ["nests": [["string": "first"], ["string": "second"]]]))
XCTAssertTrue(test.nests?.count == 2)
}
func testMalformedArrayOfMappables() {
struct Test: Mappable {
let nests: [Nested]
init(map: Mapper) throws {
try self.nests = map.from("nests")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: ["nests": [["foo": "first"], ["string": "second"]]]))
XCTAssertNil(test)
}
func testInvalidArrayOfOptionalMappables() {
struct Test: Mappable {
let nests: [Nested]?
init(map: Mapper) {
self.nests = map.optionalFrom("nests")
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = Test(map: Mapper(JSON: ["nests": "not an array"]))
XCTAssertNil(test.nests)
}
func testMappableArrayOfKeys() {
struct Test: Mappable {
let nest: Nested?
init(map: Mapper) {
self.nest = map.optionalFrom(["a", "b"])
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = Test(map: Mapper(JSON: ["a": ["foo": "bar"], "b": ["string": "hi"]]))
XCTAssertTrue(test.nest?.string == "hi")
}
func testMappableArrayOfKeysReturningNil() {
struct Test: Mappable {
let nest: Nested?
init(map: Mapper) {
self.nest = map.optionalFrom(["a", "b"])
}
}
struct Nested: Mappable {
init(map: Mapper) throws {}
}
if let test = Test.from([:]) {
XCTAssertNil(test.nest)
} else {
XCTFail("Failed to create Test")
}
}
func testMappableArrayOfKeysDoesNotThrow() {
struct Test: Mappable {
let nest: Nested
init(map: Mapper) throws {
try self.nest = map.from(["a", "b"])
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: ["b": ["string": "hi"]]))
XCTAssertTrue(test?.nest.string == "hi")
}
func testMappableArrayOfKeysThrowsWhenMissing() {
struct Test: Mappable {
let nest: Nested
init(map: Mapper) throws {
try self.nest = map.from(["a", "b"])
}
}
struct Nested: Mappable {
let string: String
init(map: Mapper) throws {
try self.string = map.from("string")
}
}
let test = try? Test(map: Mapper(JSON: [:]))
XCTAssertNil(test)
}
}
| 27.023697 | 103 | 0.477727 |
db88288f1f9fd252e4aa4679962c23627e08951d | 2,104 | //
// SessionDefaultsTableViewCell.swift
// InvasivesBC
//
// Created by Amir Shayegh on 2020-07-24.
// Copyright © 2020 Government of British Columbia. All rights reserved.
//
import UIKit
class SessionDefaultsTableViewCell: UITableViewCell {
@IBOutlet weak var container: UIView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
var delegate: InputDelegate?
weak var inputGroup: UIView?
func setup(delegate: InputDelegate) {
inputGroup?.removeFromSuperview()
self.delegate = delegate
let inputGroup = InputGroupView()
self.inputGroup = inputGroup
inputGroup.initialize(with: getFields(), delegate: delegate, in: container)
heightConstraint.constant = InputGroupView.estimateContentHeight(for: getFields())
style()
}
func style() {
container.backgroundColor = .clear
self.backgroundColor = .clear
layoutIfNeeded()
}
func getFields() -> [InputItem] {
var items: [InputItem] = []
let firstName = TextInput(
key: "firstName",
header: "First Name",
editable: true,
width: .Half
)
items.append(firstName)
let lastName = TextInput(
key: "lastName",
header: "Last Name",
editable: true,
width: .Half
)
items.append(lastName)
let jurisdiction = DropdownInput(
key: "jurisdiction",
header: "Jurisdiction",
editable: true,
width: .Half,
dropdownItems: CodeTableService.shared.getDropdowns(type: "JurisdictionCode")
)
items.append(jurisdiction)
let agency = DropdownInput(
key: "agency",
header: "Agency",
editable: true,
width: .Half,
dropdownItems: CodeTableService.shared.getDropdowns(type: "SpeciesAgencyCode")
)
items.append(agency)
return items
}
}
| 26.974359 | 90 | 0.571768 |
de1966227791094ab957f6f44a6f8c2ba5cd423a | 268 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T {class a{
class B:a{
^
class a{ :
let h=1
| 22.333333 | 87 | 0.723881 |
d90acb3e81aac8a346fe5c32e97c88be5cd75e7c | 583 | // Copyright © 2021 Brad Howes. All rights reserved.
import CoreMIDI
/**
Swift collection that dynamically produces known MIDIEndpointRef values.
*/
internal struct Sources: Collection {
typealias Index = Int
typealias Element = MIDIEndpointRef
var startIndex: Index { 0 }
var endIndex: Index { MIDIGetNumberOfSources() }
var displayNames: [String] { map { $0.displayName } }
var uniqueIds: [MIDIUniqueID] { map { $0.uniqueId } }
init() {}
func index(after index: Index) -> Index { index + 1 }
subscript (index: Index) -> Element { MIDIGetSource(index) }
}
| 25.347826 | 73 | 0.699828 |
db9106ea1a1d6f2d3df3d6e1a2e9fb3c172e2e7a | 1,009 | //
// ViewController.swift
// NWAppLogger
//
// Created by hlkim on 11/20/2021.
// Copyright (c) 2021 hlkim. All rights reserved.
//
import UIKit
import NWAppLogger
class ViewController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NWAppLogger.shared.initLogger(self, url: "https://log.vitality.aia.co.kr/depapi/AppLogRequest", isLog: false, userInfo: ["xtUid":"11111","ssId":"22222"] as Dictionary<String,AnyObject>)
NWAppLogger.shared.start(self)
let parmas = NWAppLogger.shared.sendLog(self, paramMap: ["ecId":333333] as Dictionary<String, AnyObject>)
textView.text = parmas
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NWAppLogger.shared.resume(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 26.552632 | 193 | 0.675917 |
1adc3f0a6afec642481892972d5083b5e1cf14f1 | 600 | // swift-tools-version:5.4
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftRegexDSL",
platforms: [
.macOS(.v10_15),
.iOS(.v13)
],
products: [
.library(
name: "SwiftRegexDSL",
targets: ["SwiftRegexDSL"]),
],
targets: [
.target(
name: "SwiftRegexDSL",
dependencies: []),
.testTarget(
name: "SwiftRegexDSLTests",
dependencies: ["SwiftRegexDSL"]),
]
)
| 23.076923 | 96 | 0.553333 |
1a02662749f386a81048e0d68a77b4a1721896c2 | 4,017 | //
// DPAGGroupChatCell.swift
// ginlo
//
// Created by RBU on 24/02/16.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import SIMSmeCore
import UIKit
public protocol DPAGGroupCellProtocol: AnyObject {
func configure(with group: DPAGGroup)
}
class DPAGGroupCell: UITableViewCell, DPAGGroupCellProtocol {
@IBOutlet var viewProfileImage: UIImageView! {
didSet {
// self.viewProfileImage.layer.borderWidth = 2
self.viewProfileImage.layer.cornerRadius = self.viewProfileImage.frame.size.height / 2.0
self.viewProfileImage.layer.masksToBounds = true
self.viewProfileImage.backgroundColor = UIColor.clear
}
}
@IBOutlet var labelName: UILabel! {
didSet {
self.labelName.adjustsFontForContentSizeCategory = true
self.labelName.textColor = DPAGColorProvider.shared[.labelText]
self.labelName.numberOfLines = 1
}
}
@IBOutlet var labelPreview: UILabel! {
didSet {
self.labelPreview.textColor = DPAGColorProvider.shared[.labelText]
self.labelPreview.numberOfLines = 2
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.configContentViews()
}
override func layoutSubviews() {
super.layoutSubviews()
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
self.contentView.setNeedsLayout()
self.contentView.layoutIfNeeded()
self.labelName.preferredMaxLayoutWidth = self.labelName.frame.width
self.labelPreview.preferredMaxLayoutWidth = self.labelPreview.frame.width
}
override var accessibilityLabel: String? {
get {
self.labelName.text
}
set {
super.accessibilityLabel = newValue
}
}
func configContentViews() {
self.labelPreview.adjustsFontForContentSizeCategory = true
self.backgroundColor = DPAGColorProvider.shared[.defaultViewBackground]
self.setSelectionColor()
self.separatorInset = .zero
self.layoutMargins = .zero
self.selectionStyle = .none
self.updateFonts()
self.selectionStyle = .none
self.contentView.backgroundColor = .clear
}
@objc
func updateFonts() {
self.labelName.font = UIFont.kFontHeadline
self.labelPreview.font = .kFontSubheadline
}
func configure(with group: DPAGGroup) {
self.backgroundColor = DPAGColorProvider.shared[.defaultViewBackground]
self.labelName.textColor = DPAGColorProvider.shared[.labelText]
if let encodedImage = group.imageData, let imageData = Data(base64Encoded: encodedImage, options: .ignoreUnknownCharacters) {
self.viewProfileImage.image = UIImage(data: imageData)
} else {
self.viewProfileImage.image = DPAGUIImageHelper.image(forGroupGuid: group.guid, imageType: .chatList)
}
self.labelPreview.textColor = DPAGColorProvider.shared[.labelText]
self.labelName.text = group.name
self.labelPreview.text = group.memberNames
}
open override
func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
self.labelPreview.textColor = DPAGColorProvider.shared[.labelText]
self.labelName.textColor = DPAGColorProvider.shared[.labelText]
self.backgroundColor = DPAGColorProvider.shared[.defaultViewBackground]
}
} else {
DPAGColorProvider.shared.darkMode = false
}
}
}
| 34.042373 | 133 | 0.668409 |
291aa248a6eeb413c3f4da2d7ffe21c8e0639dad | 1,274 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
import EssentialFeed
final class WeakRefVirtualProxy<T: AnyObject> {
private weak var object: T?
init(_ object: T) {
self.object = object
}
}
extension WeakRefVirtualProxy: FeedErrorView where T: FeedErrorView {
func display(_ viewModel: FeedErrorViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedLoadingView where T: FeedLoadingView {
func display(_ viewModel: FeedLoadingViewModel) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy: FeedImageView where T: FeedImageView, T.Image == UIImage {
func display(_ model: FeedImageViewModel<UIImage>) {
object?.display(model)
}
}
extension WeakRefVirtualProxy:
ImageCommentsView
where T: ImageCommentsView {
func display(
_ viewModel: ImageCommentsViewModel
) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy:
ImageCommentsLoadingView
where T: ImageCommentsLoadingView {
func display(
_ viewModel: ImageCommentsLoadingViewModel
) {
object?.display(viewModel)
}
}
extension WeakRefVirtualProxy:
ImageCommentsErrorView
where T: ImageCommentsErrorView {
func display(
_ viewModel: ImageCommentsErrorViewModel
) {
object?.display(viewModel)
}
}
| 20.222222 | 89 | 0.770801 |
767d5c89dc1ad41a84911ad4a8690f42844eea3d | 2,088 | //
// Siri.swift
//
// Copyright (c) 2015-2017 Damien (http://delba.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#if PERMISSION_SIRI
import Intents
internal extension Permission {
var statusSiri: PermissionStatus {
guard #available(iOS 10.0, *) else { fatalError() }
let status = INPreferences.siriAuthorizationStatus()
switch status {
case .authorized: return .authorized
case .restricted, .denied: return .denied
case .notDetermined: return .notDetermined
@unknown default: return .notDetermined
}
}
func requestSiri(_ callback: @escaping Callback) {
guard #available(iOS 10.0, *) else { fatalError() }
guard let _ = Bundle.main.object(forInfoDictionaryKey: .siriUsageDescription) else {
print("WARNING: \(String.siriUsageDescription) not found in Info.plist")
return
}
INPreferences.requestSiriAuthorization({ (status) in
callback(self.statusSiri)
})
}
}
#endif
| 40.941176 | 92 | 0.697318 |
64012b70e865c79a99e4410bc2f183f13836c057 | 808 | //
// KeychainServiceMock.swift
// SecureStorage_Tests
//
// Created by Rahardyan Bisma on 09/02/22.
// Copyright © 2022 CocoaPods. All rights reserved.
//
@testable import SecureStorage
import Foundation
class AESMock: Cryptable {
var isEncryptCalled = false
var isDecryptCalled = false
var isEncryptDataCalled = false
var isDecryptDataCalled = false
func encrypt(_: String) throws -> Data {
isEncryptCalled = true
return Data()
}
func decrypt(_: Data) throws -> String {
isDecryptCalled = true
return ""
}
func encrypt(_: Data) throws -> Data {
isEncryptDataCalled = true
return Data()
}
func decrypt(_: Data) throws -> Data {
isDecryptDataCalled = true
return Data()
}
}
| 21.263158 | 52 | 0.625 |
dd23b922d39a5f0e59e25b6f73b70925fc974fdc | 9,323 | // Sources/SwiftProtobuf/BinaryDelimited.swift - Delimited support
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Helpers to read/write message with a length prefix.
///
// -----------------------------------------------------------------------------
import Foundation
/// Helper methods for reading/writing messages with a length prefix.
public enum BinaryDelimited {
/// Additional errors for delimited message handing.
public enum Error: Swift.Error {
/// If a read/write to the stream fails, but the stream's `streamError` is nil,
/// this error will be throw instead since the stream didn't provide anything
/// more specific. A common cause for this can be failing to open the stream
/// before trying to read/write to it.
case unknownStreamError
/// While reading/writing to the stream, less than the expected bytes was
/// read/written.
case truncated
}
/// Serialize a single size-delimited message from the given stream. Delimited
/// format allows a single file or stream to contain multiple messages,
/// whereas normally writing multiple non-delimited messages to the same
/// stream would cause them to be merged. A delimited message is a varint
/// encoding the message size followed by a message of exactly that size.
///
/// - Parameters:
/// - message: The message to be written.
/// - to: The `OutputStream` to write the message to. The stream is
/// is assumed to be ready to be written to.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - Throws: `BinaryEncodingError` if encoding fails, throws
/// `BinaryDelimited.Error` for some writing errors, or the
/// underlying `OutputStream.streamError` for a stream error.
public static func serialize(
message: Message,
to stream: OutputStream,
partial: Bool = false
) throws {
// TODO: Revisit to avoid the extra buffering when encoding is streamed in general.
let serialized = try message.serializedData(partial: partial)
let totalSize = Varint.encodedSize(of: UInt64(serialized.count)) + serialized.count
var data = Data(count: totalSize)
data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
if let baseAddress = body.baseAddress, body.count > 0 {
var encoder = BinaryEncoder(forWritingInto: baseAddress)
encoder.putBytesValue(value: serialized)
}
}
var written: Int = 0
data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
if let baseAddress = body.baseAddress, body.count > 0 {
// This assumingMemoryBound is technically unsafe, but without SR-11078
// (https://bugs.swift.org/browse/SR-11087) we don't have another option.
// It should be "safe enough".
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
written = stream.write(pointer, maxLength: totalSize)
}
}
if written != totalSize {
if written == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
}
/// Reads a single size-delimited message from the given stream. Delimited
/// format allows a single file or stream to contain multiple messages,
/// whereas normally parsing consumes the entire input. A delimited message
/// is a varint encoding the message size followed by a message of exactly
/// exactly that size.
///
/// - Parameters:
/// - messageType: The type of message to read.
/// - from: The `InputStream` to read the data from. The stream is assumed
/// to be ready to read from.
/// - extensions: An `ExtensionMap` used to look up and decode any
/// extensions in this message or messages nested within this message's
/// fields.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - options: The BinaryDecodingOptions to use.
/// - Returns: The message read.
/// - Throws: `BinaryDecodingError` if decoding fails, throws
/// `BinaryDelimited.Error` for some reading errors, and the
/// underlying InputStream.streamError for a stream error.
public static func parse<M: Message>(
messageType: M.Type,
from stream: InputStream,
extensions: ExtensionMap? = nil,
partial: Bool = false,
options: BinaryDecodingOptions = BinaryDecodingOptions()
) throws -> M {
var message = M()
try merge(into: &message,
from: stream,
extensions: extensions,
partial: partial,
options: options)
return message
}
/// Updates the message by reading a single size-delimited message from
/// the given stream. Delimited format allows a single file or stream to
/// contain multiple messages, whereas normally parsing consumes the entire
/// input. A delimited message is a varint encoding the message size
/// followed by a message of exactly that size.
///
/// - Note: If this method throws an error, the message may still have been
/// partially mutated by the binary data that was decoded before the error
/// occurred.
///
/// - Parameters:
/// - mergingTo: The message to merge the data into.
/// - from: The `InputStream` to read the data from. The stream is assumed
/// to be ready to read from.
/// - extensions: An `ExtensionMap` used to look up and decode any
/// extensions in this message or messages nested within this message's
/// fields.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - options: The BinaryDecodingOptions to use.
/// - Throws: `BinaryDecodingError` if decoding fails, throws
/// `BinaryDelimited.Error` for some reading errors, and the
/// underlying InputStream.streamError for a stream error.
public static func merge<M: Message>(
into message: inout M,
from stream: InputStream,
extensions: ExtensionMap? = nil,
partial: Bool = false,
options: BinaryDecodingOptions = BinaryDecodingOptions()
) throws {
let length = try Int(decodeVarint(stream))
if length == 0 {
// The message was all defaults, nothing to actually read.
return
}
var data = Data(count: length)
var bytesRead: Int = 0
data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
if let baseAddress = body.baseAddress, body.count > 0 {
// This assumingMemoryBound is technically unsafe, but without SR-11078
// (https://bugs.swift.org/browse/SR-11087) we don't have another option.
// It should be "safe enough".
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
bytesRead = stream.read(pointer, maxLength: length)
}
}
if bytesRead != length {
if bytesRead == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
try message.merge(serializedData: data,
extensions: extensions,
partial: partial,
options: options)
}
}
// TODO: This should go away when encoding/decoding are more stream based
// as that should provide a more direct way to do this. This is basically
// a rewrite of BinaryDecoder.decodeVarint().
internal func decodeVarint(_ stream: InputStream) throws -> UInt64 {
// Buffer to reuse within nextByte.
var readBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
#if swift(>=4.1)
defer { readBuffer.deallocate() }
#else
defer { readBuffer.deallocate(capacity: 1) }
#endif
func nextByte() throws -> UInt8 {
let bytesRead = stream.read(readBuffer, maxLength: 1)
if bytesRead != 1 {
if bytesRead == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
return readBuffer[0]
}
var value: UInt64 = 0
var shift: UInt64 = 0
while true {
let c = try nextByte()
value |= UInt64(c & 0x7f) << shift
if c & 0x80 == 0 {
return value
}
shift += 7
if shift > 63 {
throw BinaryDecodingError.malformedProtobuf
}
}
}
| 40.012876 | 87 | 0.659015 |
acb6ef2d7cec87374383c72f2100d8f9423f3bed | 2,627 | //
// TAProgressView.swift
// Time Analytics
//
// A view that contains a progress view and title with % complete.
// -Increments its progress every time it observes a "didProcessMovesDataChunk" notification or "didProcessHealthKitDataChunk" notification
// -Dismisses itself once it reaches 100%
// -It can also be dismissed by calling the removeProgressView method in TAViewController
//
// Created by Chris Leung on 5/20/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import UIKit
class TAProgressView: UIView {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var titleLabel: UILabel!
var defaultText = "Downloading Data"
var totalProgress:Float!
var currentProgress:Float = 0
func addProgress(_ amountProgressed:Float) {
currentProgress += amountProgressed
var percentComplete = currentProgress/totalProgress
// If somehow we got over 100%, adjust the % and dismiss ourselves
if percentComplete > 1 {
percentComplete = 1
currentProgress = totalProgress
}
progressView.setProgress(percentComplete, animated: true)
titleLabel.text = "\(defaultText) (\(Int(percentComplete*100))%)"
}
func didCompleteDataChunk(_ notification:Notification) {
DispatchQueue.main.async {
self.addProgress(1)
// If we're at 100%, dismiss ourself
if self.currentProgress == self.totalProgress {
self.fadeOut() { (finished) in
if finished {
self.removeFromObservers()
self.removeFromSuperview()
}
}
}
}
}
func setupDefaultProperties() {
DispatchQueue.main.async {
self.progressView.setProgress(0, animated: false)
self.titleLabel.text = "\(self.defaultText) (0%)"
NotificationCenter.default.addObserver(self, selector: #selector(TAProgressView.didCompleteDataChunk(_:)), name: Notification.Name("didProcessHealthKitDataChunk"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TAProgressView.didCompleteDataChunk(_:)), name: Notification.Name("didProcessMovesDataChunk"), object: nil)
}
}
func removeFromObservers() {
NotificationCenter.default.removeObserver(self)
}
class func instanceFromNib() -> TAProgressView {
return UINib(nibName: "TAProgressView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! TAProgressView
}
}
| 38.072464 | 188 | 0.652075 |
7aa9535797ca202fb59267705bc5272853e40a88 | 441 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: asserts
[.h{l
return $0
| 36.75 | 79 | 0.741497 |
ff2daa4d4e1800e35acbd585ada86507a240ec2c | 1,964 | //
// KeychainHelper.swift
// AdzerkSDK
//
// Created by Ben Scheirman on 9/25/20.
//
import Foundation
/** Provides easy get/set access for simple values in the Keychain. */
class KeychainHelper {
/**
Saves data to the keychain.
@param key an identifier under which the data will be stored
@param data the data to save
@returns true if the value was set successfully
*/
static func save(_ key: String, data: Data) -> Bool {
let query = [
(kSecClass as String) : (kSecClassGenericPassword as String),
(kSecAttrAccount as String) : key,
(kSecValueData as String) : data
] as CFDictionary
// remove item if it exists already
SecItemDelete(query)
// save item
let status: OSStatus = SecItemAdd(query, nil)
return status == noErr
}
/**
Retrieves a values from the keychain.
@param key the identifier the data was originally saved with
@returns the saved data, or nil if nothing was saved for this key
*/
static func fetch(_ key: String) -> Data? {
let query = [
(kSecClass as String) : (kSecClassGenericPassword as String),
(kSecAttrAccount as String) : key,
(kSecReturnData as String) : kCFBooleanTrue!,
(kSecMatchLimit as String) : kSecMatchLimitOne
] as CFDictionary
var keychainData: AnyObject?
let status: OSStatus = SecItemCopyMatching(query, &keychainData)
if status == noErr {
return keychainData as? Data
} else {
return nil
}
}
/**
Deletes the value for the specified key
*/
static func delete(_ key: String) {
let query = [
(kSecClass as String) : (kSecClassGenericPassword as String),
(kSecAttrAccount as String) : key
]
SecItemDelete(query as CFDictionary)
}
}
| 28.882353 | 73 | 0.596741 |
011dc047aaca9bab807db5f641750829a7c37bbf | 2,999 | //
// EnrolledCoursesFooterView.swift
// edX
//
// Created by Akiva Leffert on 12/23/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
class EnrolledCoursesFooterView : UIView {
private let promptLabel = UILabel()
private let findCoursesButton = UIButton(type:.system)
private let container = UIView()
var findCoursesAction : (() -> Void)?
private var findCoursesTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark())
}
func refreshFooterText(days: Int, date: String) {
guard days > 0 else {
return
}
let findStr: String = Strings.harvardLearnCamp(date: date)
let styles = OEXStyles.shared().filledPrimaryButtonStyle
styles.textStyle.alignment = .center
self.findCoursesButton.applyButtonStyle(style: styles, withTitle: findStr)
}
init() {
super.init(frame: CGRect.zero)
addSubview(container)
container.addSubview(promptLabel)
container.addSubview(findCoursesButton)
self.promptLabel.attributedText = findCoursesTextStyle.attributedString(withText: Strings.EnrollmentList.findCoursesPrompt)
self.promptLabel.textAlignment = .center
let styles = OEXStyles.shared().filledPrimaryButtonStyle
styles.textStyle.alignment = .center
self.findCoursesButton.titleLabel?.numberOfLines = 0
self.findCoursesButton.applyButtonStyle(style: styles, withTitle: Strings.EnrollmentList.findCourses.oex_uppercaseStringInCurrentLocale())
container.backgroundColor = OEXStyles.shared().standardBackgroundColor()
container.applyBorderStyle(style: BorderStyle())
container.snp.makeConstraints { make in
make.top.equalTo(self).offset(CourseCardCell.margin)
make.bottom.equalTo(self)
make.leading.equalTo(self).offset(CourseCardCell.margin)
make.trailing.equalTo(self).offset(-CourseCardCell.margin)
}
self.promptLabel.snp.makeConstraints { make in
make.leading.equalTo(container).offset(StandardHorizontalMargin)
make.trailing.equalTo(container).offset(-StandardHorizontalMargin)
make.top.equalTo(container).offset(StandardVerticalMargin)
}
self.findCoursesButton.snp.makeConstraints { make in
make.leading.equalTo(promptLabel)
make.trailing.equalTo(promptLabel)
make.top.equalTo(promptLabel.snp.bottom).offset(StandardVerticalMargin)
make.bottom.equalTo(container).offset(-StandardVerticalMargin)
}
findCoursesButton.oex_addAction({[weak self] _ in
self?.findCoursesAction?()
}, for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 36.573171 | 146 | 0.668223 |
8f16939608e4df01966c2dae364bed95cda5f3dc | 1,095 | //: [Previous](@previous)
/*:
# 动态规划
## 官解
定义 `dp[i]` 为考虑前 `i` 个元素,以第 `i` 个数字结尾的最长上升子序列长度,包含 `nums[i]`。
从小到大计算 `dp` 数组的值,在计算 `dp[i]` 之前,已经计算出了 `dp[0 ... (i - 1)]` 的值,则状态转移方程为:
`dp[i] = max(dp[j] + 1), when 0 ≤ j ≤ i and nums[j] < nums[i]`
即考虑往 `dp[0 ... (i - 1)]` 中最长的上升子序列后面再接一个 `nums[i]`。由于 `dp[j]` 代表 `nums[0 ... j]` 中以 `nums[j]` 结尾的最长上升子序列,所以如果能从 `dp[j]` 这个状态转移过来,那么 `nums[i]` 必大于 `nums[j]`,才能链接形成更长的上升子序列。
最后,整个数组的最长上升子序列即所有 `dp[i]` 中的最大值。
## 人话
当前这个位置的值要去前面找比它矮的中最高的,这样才能接在那个后面,然后接上它有多少个数,就是那个比它矮的中最高的能组成的单调列个数 + 1。就给每一个数都算出来一个接上它后单调列的长度,找最大的值就是最大单调列了。
时间复杂度:`O(n ^ 2)`
空间复杂度:`O(n)`
*/
class Solution {
func lengthOfLIS(_ nums: [Int]) -> Int {
let length: Int = nums.count
var dp: [Int] = [Int](repeating: 1, count: length)
var result: Int = 1
for i in 0 ..< length {
for j in 0 ..< i {
if nums[j] < nums[i] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
result = max(dp[i], result)
}
return result
}
}
//: [Next](@next)
| 24.333333 | 172 | 0.515982 |
ab15a91381f8f96d886a9ff5a75275318323a289 | 976 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "BlinkAnalogIn",
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/madmachineio/SwiftIO.git", .branch("main")),
.package(url: "https://github.com/madmachineio/MadBoards.git", .branch("main")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "BlinkAnalogIn",
dependencies: [
"SwiftIO",
"MadBoards"]),
.testTarget(
name: "BlinkAnalogInTests",
dependencies: ["BlinkAnalogIn"]),
]
)
| 37.538462 | 116 | 0.630123 |
f8db069998fa7960eceedbf355a01d0bf0f9e137 | 5,519 | //
// WindowManager.swift
// Rectangle, Ported from Spectacle
//
// Created by Ryan Hanson on 6/12/19.
// Copyright © 2019 Ryan Hanson. All rights reserved.
//
import Cocoa
class WindowManager {
private let screenDetection = ScreenDetection()
private let windowMoverChain: [WindowMover]
private let windowCalculationFactory: WindowCalculationFactory
private let windowHistory: WindowHistory
init(windowCalculationFactory: WindowCalculationFactory, windowHistory: WindowHistory) {
self.windowCalculationFactory = windowCalculationFactory
self.windowHistory = windowHistory
windowMoverChain = [
StandardWindowMover(),
// QuantizedWindowMover(), // This was used in Spectacle, but doesn't seem to help on any windows I've tried. It just makes some actions feel more jenky
BestEffortWindowMover()
]
}
func execute(_ parameters: ExecutionParameters) {
guard let frontmostWindowElement = AccessibilityElement.frontmostWindow(),
let windowId = frontmostWindowElement.getIdentifier()
else {
NSSound.beep()
return
}
let action = parameters.action
if action == .restore {
if let restoreRect = windowHistory.restoreRects[windowId] {
frontmostWindowElement.setRectOf(restoreRect)
}
windowHistory.lastRectangleActions.removeValue(forKey: windowId)
return
}
var screens: UsableScreens?
if let screen = parameters.screen {
screens = UsableScreens(currentScreen: screen)
} else {
screens = screenDetection.detectScreens(using: frontmostWindowElement)
}
guard let usableScreens = screens else {
NSSound.beep()
return
}
let currentWindowRect: CGRect = frontmostWindowElement.rectOfElement()
let lastRectangleAction = windowHistory.lastRectangleActions[windowId]
if parameters.updateRestoreRect {
if windowHistory.restoreRects[windowId] == nil
|| currentWindowRect != lastRectangleAction?.rect {
windowHistory.restoreRects[windowId] = currentWindowRect
}
}
if frontmostWindowElement.isSheet()
|| frontmostWindowElement.isSystemDialog()
|| currentWindowRect.isNull
|| usableScreens.frameOfCurrentScreen.isNull
|| usableScreens.visibleFrameOfCurrentScreen.isNull {
NSSound.beep()
return
}
let currentNormalizedRect = AccessibilityElement.normalizeCoordinatesOf(currentWindowRect, frameOfScreen: usableScreens.frameOfCurrentScreen)
let windowCalculation = windowCalculationFactory.calculation(for: action)
guard let calcResult = windowCalculation?.calculate(currentNormalizedRect, lastAction: lastRectangleAction, usableScreens: usableScreens, action: action) else {
NSSound.beep()
return
}
let newNormalizedRect = AccessibilityElement.normalizeCoordinatesOf(calcResult.rect, frameOfScreen: usableScreens.frameOfCurrentScreen)
if currentNormalizedRect.equalTo(newNormalizedRect) {
NSSound.beep()
return
}
let visibleFrameOfDestinationScreen = NSRectToCGRect(calcResult.screen.visibleFrame)
for windowMover in windowMoverChain {
windowMover.moveWindowRect(newNormalizedRect, frameOfScreen: usableScreens.frameOfCurrentScreen, visibleFrameOfScreen: visibleFrameOfDestinationScreen, frontmostWindowElement: frontmostWindowElement, action: action)
}
let resultingRect = frontmostWindowElement.rectOfElement()
var newCount = 1
if lastRectangleAction?.action == calcResult.resultingAction,
let currentCount = lastRectangleAction?.count {
newCount = currentCount + 1
newCount %= 3
}
windowHistory.lastRectangleActions[windowId] = RectangleAction(
action: calcResult.resultingAction,
rect: resultingRect,
count: newCount
)
if Logger.logging {
var srcDestScreens: String = ""
if #available(OSX 10.15, *) {
srcDestScreens += ", srcScreen: \(usableScreens.currentScreen.localizedName)"
srcDestScreens += ", destScreen: \(calcResult.screen.localizedName)"
if let resultScreens = screenDetection.detectScreens(using: frontmostWindowElement) {
srcDestScreens += ", resultScreen: \(resultScreens.currentScreen.localizedName)"
}
}
Logger.log("\(action.name) | display: \(visibleFrameOfDestinationScreen.debugDescription), calculatedRect: \(newNormalizedRect.debugDescription), resultRect: \(resultingRect.debugDescription)\(srcDestScreens)")
}
}
}
struct RectangleAction {
let action: WindowAction
let rect: CGRect
let count: Int
}
struct ExecutionParameters {
let action: WindowAction
let updateRestoreRect: Bool
let screen: NSScreen?
init(_ action: WindowAction, updateRestoreRect: Bool = true, screen: NSScreen? = nil) {
self.action = action
self.updateRestoreRect = updateRestoreRect
self.screen = screen
}
}
| 37.544218 | 227 | 0.651386 |
1843035752fd3fa1feb9a7b7a2c4482a2daa11a2 | 902 | //
// MediaDeviceTypeTests.swift
// AmazonChimeSDK
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@testable import AmazonChimeSDK
import XCTest
class MediaDeviceTypeTests: XCTestCase {
func testDescriptionShouldMatch() {
XCTAssertEqual(MediaDeviceType.audioBluetooth.description, "audioBluetooth")
XCTAssertEqual(MediaDeviceType.audioWiredHeadset.description, "audioWiredHeadset")
XCTAssertEqual(MediaDeviceType.audioBuiltInSpeaker.description, "audioBuiltInSpeaker")
XCTAssertEqual(MediaDeviceType.audioHandset.description, "audioHandset")
XCTAssertEqual(MediaDeviceType.videoFrontCamera.description, "videoFrontCamera")
XCTAssertEqual(MediaDeviceType.videoBackCamera.description, "videoBackCamera")
XCTAssertEqual(MediaDeviceType.other.description, "other")
}
}
| 39.217391 | 94 | 0.778271 |
71848c5a5e7e2545097ee2ec07f47b93fbffc77a | 580 | import Foundation
import ArgumentParser
import AndreyAndreyevich
struct Markov: ParsableCommand {
@Option(name: .shortAndLong)
var count: Int?
@Option(name: .shortAndLong)
var order: Int?
@Option(name: .shortAndLong)
var prior: Double?
@Argument
var input: [String]
mutating func run() throws {
let order = self.order ?? 2
let prior = self.prior ?? 0
let count = self.count ?? 10
let markov = AndreyAndreyevich(input: input, order: order, prior: prior)
for _ in 0..<count {
print(markov.generate())
}
}
}
Markov.main()
| 17.575758 | 76 | 0.660345 |
186163b0db91d765fc38f5dc3a26a8cfd726ed70 | 367 | //
// AddLocationView.swift
// Core
//
// Created by Socratis Michaelides on 07/11/2018.
// Copyright © 2018 Socratis Michaelides. All rights reserved.
//
public protocol AddLocationView: BaseView {
var viewModel: AddLocationViewModel! { get set }
var onHideButtonTap: (() -> Void)? { get set }
var onCompleteAddLocation: ((Location) -> ())? { get set }
}
| 26.214286 | 63 | 0.686649 |
bb2d04d90cba4b70e418a3bc4ef9889afadfa804 | 251 | #if canImport(UIKit) && !os(watchOS)
import Bindings
import UIKit
extension Reactive where Base: UILabel {
public var text: BindingSink<Base, String?> {
BindingSink(owner: base) { $0.text = $1 }
}
}
#endif // canImport(UIKit) && !os(watchOS)
| 22.818182 | 47 | 0.681275 |
bf18e078ef1f5ff8662313d85aad548f31c6c180 | 2,945 | //
// MessagesViewControllerJoining.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 11/14/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import RealmSwift
extension MessagesViewController {
private func showChatPreviewModeView() {
chatPreviewModeView?.removeFromSuperview()
if let previewView = ChatPreviewModeView.instantiateFromNib() {
previewView.delegate = self
previewView.subscription = subscription
previewView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(previewView)
NSLayoutConstraint.activate([
previewView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
previewView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
previewView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
chatPreviewModeView = previewView
updateChatPreviewModeViewConstraints()
previewView.applyTheme()
}
}
func updateJoinedView() {
guard !subscription.isInvalidated else { return }
if subscription.isJoined() {
composerView.isHidden = false
chatPreviewModeView?.removeFromSuperview()
} else {
composerView.isHidden = true
showChatPreviewModeView()
if let view = chatPreviewModeView {
collectionView.contentInset.top = -(view.frame.height + view.bottomInset)
collectionView.scrollIndicatorInsets = collectionView.contentInset
}
}
}
private func updateChatPreviewModeViewConstraints() {
chatPreviewModeView?.bottomInset = view.safeAreaInsets.bottom
}
}
extension MessagesViewController: ChatPreviewModeViewProtocol {
func userDidJoinedSubscription() {
guard let auth = AuthManager.isAuthenticated() else { return }
guard let subscription = self.subscription else { return }
Realm.executeOnMainThread({ realm in
subscription.auth = auth
subscription.open = true
realm.add(subscription, update: true)
})
self.subscription = subscription
///added by steve
///点击加入通道——判断是否是只读通道,如果是,则把j控件都置灰不可操作
///注意这里y需要调接口拉一下数据
let _ = API.current()?.client(SubscriptionsClient.self).api.fetch(RoomInfoRequest.init(roomId: self.subscription?.rid ?? ""), completion: { (response) in
if(self.viewModel.subscription != nil && self.viewModel.subscription?.unmanaged?.roomReadOnly ?? false && AuthManager.currentUser()?.identifier != self.viewModel.subscription?.unmanaged?.roomOwnerId){
self.composerView.leftButton.isEnabled = false
self.composerView.rightButton.isEnabled = false
self.composerView.textView.isEditable = false
}
})
}
}
| 34.244186 | 212 | 0.651613 |
6904050cfac8bd31a1b62b048d7e659b078dc94f | 5,494 | //
// HTDateSwitcherView.swift
// SDKTest
//
// Created by Atul Manwar on 20/02/18.
// Copyright © 2018 www.hypertrack.com. All rights reserved.
//
import UIKit
@objc public protocol HTDateSwitcherViewDelegate: class {
func dateChanged(_ date: Date)
func openCalendar(_ open: Bool, selectedDate: Date)
}
@objc public protocol HTCalendarDelegate: class {
func didSelectDate(_ date: Date)
}
final class HTDateSwitcherView: HTBaseView {
fileprivate (set) var stackView: UIStackView!
fileprivate (set) var containerView: HTBaseView!
fileprivate (set) var middleButton: HTButton!
fileprivate (set) var leftButton: HTButton!
fileprivate (set) var rightButton: HTButton! {
didSet {
rightButton.isHidden = true
}
}
var heightValue: CGFloat = 55
weak var delegate: HTDateSwitcherViewDelegate?
fileprivate (set) var date: Date = Date() {
didSet {
rightButton.isHidden = HTSpaceTimeUtil.instance.isDateToday(date)
delegate?.dateChanged(date)
middleButton.setTitle(HTSpaceTimeUtil.instance.getReadableDate(date), for: .normal)
}
}
var maxSupportedDate: Date {
return (date - 30)
}
var padding: HTPaddingProviderProtocol = HTPaddingProvider.default {
didSet {
removeConstraints(constraints)
containerView.removeConstraints(containerView.constraints)
addConstraints([
stackView.top(),
stackView.left(constant: 35),
stackView.right(constant: -35),
stackView.bottom()
])
containerView.addConstraints([
leftButton.centerY(),
leftButton.top(),
leftButton.bottom(),
leftButton.left(constant: padding.left),
leftButton.right(middleButton, toAttribute: .leading),
leftButton.width(constant: 44),
rightButton.centerY(),
rightButton.top(),
rightButton.bottom(),
rightButton.right(constant: -padding.right),
rightButton.width(constant: 44),
middleButton.centerY(),
middleButton.centerX(),
middleButton.top(),
middleButton.bottom(),
middleButton.right(rightButton, toAttribute: .leading),
])
addConstraints([
height(constant: heightValue)
])
}
}
var middleButtonText: String = "" {
didSet {
middleButton.setTitle(middleButtonText, for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupSubViews(padding)
}
convenience init(frame: CGRect, padding: HTPaddingProviderProtocol) {
self.init(frame: frame)
defer {
self.padding = padding
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubViews(padding)
}
func updateDate(_ date: Date) {
self.date = date
}
fileprivate func setupSubViews(_ padding: HTPaddingProviderProtocol) {
containerView = HTBaseView(frame: .zero)
stackView = UIStackView(frame: .zero)
stackView.axis = .horizontal
containerView.topCornerRadius = 14
leftButton = HTButton(frame: .zero)
leftButton.setImage(UIImage.getImageFromHTBundle(named: HTConstants.ImageNames.leftArrowButton), for: .normal)
leftButton.addTarget(self, action: #selector(dateSwitched(_:)), for: .touchUpInside)
rightButton = HTButton(frame: .zero)
rightButton.setImage(UIImage.getImageFromHTBundle(named: HTConstants.ImageNames.rightArrowButton), for: .normal)
rightButton.addTarget(self, action: #selector(dateSwitched(_:)), for: .touchUpInside)
middleButton = HTButton(frame: .zero)
middleButton.setImage(UIImage.getImageFromHTBundle(named: HTConstants.ImageNames.calendar), for: .normal)
middleButton.addTarget(self, action: #selector(middleButtonClicked), for: .touchUpInside)
middleButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -padding.horizontalInterItem, bottom: 0, right: 0)
middleButtonText = "TODAY"
middleButton.applyStyles([
.textColor(HTProvider.style.colors.text),
.tintColor(HTProvider.style.colors.text),
.font(HTProvider.style.fonts.getFont(.info, weight: .bold))
])
containerView.applyBaseStyles([
.background(HTProvider.style.colors.default)
])
applyBaseStyles([.background(UIColor.clear)])
containerView.addSubview(leftButton)
containerView.addSubview(middleButton)
containerView.addSubview(rightButton)
stackView.addArrangedSubview(containerView)
addSubview(stackView)
self.padding = padding
}
}
extension HTDateSwitcherView {
@objc func dateSwitched(_ sender: UIButton) {
if sender == leftButton {
date = (date - 86400)
} else if sender == rightButton {
date = (date + 86400)
}
}
@objc func middleButtonClicked() {
delegate?.openCalendar(true, selectedDate: date)
}
}
extension HTDateSwitcherView: HTViewProtocol {
}
| 34.124224 | 120 | 0.612668 |
dde23fab85fcff3349cb4fbdf9caa564b6224d2e | 4,969 | //
// GroupChannelViewController+Setting.swift
// BasicGroupChannel
//
// Created by Ernest Hong on 2022/03/04.
//
import UIKit
import SendbirdChatSDK
import CommonModule
extension GroupChannelViewController {
@objc func didTouchSettingButton() {
let actionSheet = UIAlertController(title: "Choose action for channel", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(
UIAlertAction(title: "Member List", style: .default) { [weak self] _ in
self?.pushMemberList()
}
)
actionSheet.addAction(
UIAlertAction(title: "Invite Members", style: .default) { [weak self] _ in
self?.presentInviteMember()
}
)
actionSheet.addAction(
UIAlertAction(title: "Leave Channel", style: .destructive) { [weak self] _ in
self?.presentLeaveChannelAlert()
}
)
actionSheet.addAction(
UIAlertAction(title: "Report Channel", style: .destructive) { [weak self] _ in
self?.reportChannel()
}
)
if channel.myRole == .operator {
actionSheet.addAction(
UIAlertAction(title: "Update Channel Name", style: .default) { [weak self] _ in
self?.presentChangeChannelNameAlert()
}
)
actionSheet.addAction(
UIAlertAction(title: "Delete Channel", style: .destructive) { [weak self] _ in
self?.presentDeleteChannelAlert()
}
)
}
actionSheet.addAction(
UIAlertAction(title: "Cancel", style: .cancel)
)
present(actionSheet, animated: true)
}
private func reportChannel() {
reportUseCase.reportChannel()
}
private func pushMemberList() {
let memberListViewController = GroupMemberListViewController(channel: channel)
navigationController?.pushViewController(memberListViewController, animated: true)
}
private func presentInviteMember() {
let userSelection = UserSelectionViewController(channel: channel) { [weak self] sender, users in
self?.settingUseCase.invite(users: users) { result in
sender.dismiss(animated: true) {
switch result {
case .success:
break
case .failure(let error):
self?.presentAlert(error: error)
}
}
}
}
let navigation = UINavigationController(rootViewController: userSelection)
present(navigation, animated: true)
}
private func presentChangeChannelNameAlert() {
presentTextFieldAlert(title: "Change channel name", message: nil, defaultTextFieldMessage: channel.name) { [weak self] editedName in
self?.settingUseCase.updateChannelName(editedName) { result in
switch result {
case .success:
self?.navigationController?.popToRootViewController(animated: true)
case .failure(let error):
self?.presentAlert(error: error)
}
}
}
}
private func presentLeaveChannelAlert() {
let alert = UIAlertController(title: "Leave Channel", message: "Are you sure you want to leave this channel?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "Leave", style: .destructive) { [weak self] _ in
self?.settingUseCase.leaveChannel { result in
switch result {
case .success:
self?.navigationController?.popToRootViewController(animated: true)
case .failure(let error):
self?.presentAlert(error: error)
}
}
})
present(alert, animated: true)
}
private func presentDeleteChannelAlert() {
let alert = UIAlertController(title: "Delete Channel", message: "Are you sure you want to delete this channel?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
self?.settingUseCase.deleteChannel { result in
switch result {
case .success:
self?.navigationController?.popToRootViewController(animated: true)
case .failure(let error):
self?.presentAlert(error: error)
}
}
})
present(alert, animated: true)
}
}
| 34.748252 | 144 | 0.558865 |
dedb7c8d212411aaf975faca911eb9ad3b0502d5 | 414 | //
// MemeDetailViewController.swift
// MemeMe
//
// Created by Rigoberto Saenz on 12/20/17.
// Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved.
//
import UIKit
class MemeDetailViewController: UIViewController {
@IBOutlet weak var memeImage: UIImageView!
var meme: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
memeImage.image = meme
}
}
| 19.714286 | 67 | 0.676329 |
fe1d89ff027b70e817c5c9797306d75246caea6c | 1,519 | //
// AssetTransaction.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public final class AssetTransaction: Codable, Hashable {
/** Hash of the transaction */
public var txHash: String
/** Transaction index within the block */
public var txIndex: Int
/** Block height */
public var blockHeight: Int
public init(txHash: String, txIndex: Int, blockHeight: Int) {
self.txHash = txHash
self.txIndex = txIndex
self.blockHeight = blockHeight
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case txHash = "tx_hash"
case txIndex = "tx_index"
case blockHeight = "block_height"
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(txHash, forKey: .txHash)
try container.encode(txIndex, forKey: .txIndex)
try container.encode(blockHeight, forKey: .blockHeight)
}
public static func == (lhs: AssetTransaction, rhs: AssetTransaction) -> Bool {
lhs.txHash == rhs.txHash &&
lhs.txIndex == rhs.txIndex &&
lhs.blockHeight == rhs.blockHeight
}
public func hash(into hasher: inout Hasher) {
hasher.combine(txHash.hashValue)
hasher.combine(txIndex.hashValue)
hasher.combine(blockHeight.hashValue)
}
}
| 28.12963 | 82 | 0.657011 |
7543e1057e7cffedac940c8642fb90dea102bcbb | 298 | //
// Interaction.swift
// Gravity
//
// Created by Logan Murray on 2016-02-16.
// Copyright © 2016 Logan Murray. All rights reserved.
//
import Foundation
@available(iOS 9.0, *)
extension Gravity {
@objc public class Interaction: GravityPlugin {
// placeholder for gestures, etc.
}
} | 16.555556 | 55 | 0.684564 |
46e9e93eedf5897bf1cc9e34939ec61be8cd2af8 | 1,261 | //
// STNextViewController.swift
// STBaseProject_Example
//
// Created by song on 2021/1/7.
// Copyright © 2021 STBaseProject. All rights reserved.
//
import UIKit
import SnapKit
import STBaseProject
class STNextViewController: STBaseViewController {
deinit {
STLog("STNextViewController dealloc")
}
override func viewDidLoad() {
super.viewDidLoad()
self.st_showNavBtnType(type: .showLeftBtn)
self.view.backgroundColor = UIColor.orange
self.view.addSubview(self.progressView)
self.progressView.snp.makeConstraints { make in
make.height.equalTo(20)
make.top.equalTo(100)
make.left.right.equalToSuperview()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
for index in 1..<11 {
self.progressView.setProgress(Float(index) * 0.1, animated: true)
}
}
private lazy var progressView: UIProgressView = {
var progress = UIProgressView()
progress.progressTintColor = UIColor.green
// progress.progress = 0.5
progress.trackTintColor = UIColor.blue // huad
return progress
}()
}
| 27.413043 | 79 | 0.643933 |
d661b6416d044cf814ee2aa8a2e3d1d46829d703 | 1,073 | //
// CoreTest.swift
// CoreKit
//
// Created by AMIT on 08/07/17.
// Copyright © 2017 acme. All rights reserved.
//
import XCTest
import CoreKit
class CoreTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testThreeRingView() {
// let threeRings = ThreeRingView()
// DispatchQueue.main.async {
// threeRings.innerRingValue = 1.0
// threeRings.middleRingValue = 1.0
// threeRings.outerRingValue = 1.0
// }
// let _ = expectation(forNotification: RingCompletedNotification, object: nil, handler: nil)
// let _ = expectation(forNotification: AllRingsCompletedNotification, object: nil, handler: nil)
// waitForExpectations(timeout: 0.1, handler: nil)
// }
}
| 30.657143 | 111 | 0.634669 |
fe20ed20ebc3d53656906227cc3be5dc02b4e24e | 392 | //
// KostilalMath.swift
// kostilalMathLib
//
// Created by Илья Костюкевич on 06.04.2020.
// Copyright © 2020 Ilya Kostyukevich. All rights reserved.
//
import Foundation
final class KostilalMath {
public init() {}
public func substruct(a: Int, b: Int) -> Int {
return a - b
}
public func divide(a: Int, b: Int) -> Int {
return a / b
}
}
| 17.818182 | 60 | 0.591837 |
b98b12d56ebeaa723305a9e898beda45e7dc8d84 | 2,386 | import Foundation
public extension Transform {
/// A provided transformation function (see Transform and Mapper for uses) in order to create a dictionary
/// from an array of values. The idea for this is to create a dictionary based on an array of values,
/// using a custom function to extract the key used in the dictionary
///
/// Example:
///
/// // An enum with all possible HintIDs
/// enum HintID: String {
/// ...
/// }
///
/// // A hint struct, which consists of an id and some text
/// struct Hint: Mappable {
/// let id: HintID
/// let text: String
///
/// init(map: Mapper) throws {
/// try id = map.from("id")
/// try text = map.from("text")
/// }
/// }
///
/// // An object that manages all the hints
/// struct HintCoordinator: Mappable {
/// private let hints: [HintID: Hint]
///
/// ...
///
/// init(map: Mapper) throws {
/// // Use the `toDictionary` transformation to create a map of `Hint`s by their `HintID`s
/// try hints = map.from("hints", transformation: Transform.toDictionary { $0.id })
/// }
/// }
///
/// - parameter key: A function to extract the key U from an instance of the Mappable object T
/// - parameter object: The object to attempt to produce the objects and dictionary from, this is
/// Any? to allow uses with transformations (see Mapper)
///
/// - throws: MapperError.convertibleError if the given object is not an array of NSDictionarys
///
/// - returns: A dictionary of [U: T] where the keys U are produced from the passed `key` function and the
/// values T are the objects
public static func toDictionary<T, U>(key getKey: @escaping (T) -> U) ->
(_ object: Any) throws -> [U: T] where T: Mappable, U: Hashable
{
return { object in
guard let objects = object as? [NSDictionary] else {
throw MapperError.convertibleError(value: object, type: [NSDictionary].self)
}
var dictionary: [U: T] = [:]
for object in objects {
let model = try T(map: Mapper(JSON: object))
dictionary[getKey(model)] = model
}
return dictionary
}
}
}
| 37.28125 | 110 | 0.560771 |
20bf8abfc42335c3dbbaa1414f188b7512ba8a2c | 4,989 | //
// UpdateConstants.swift
// FilmFest
//
// Created by Kostia Kolesnyk on 9/24/18.
//
import Foundation
class StoryboardXMLParserHandler: NSObject, XMLParserDelegate {
var identifiers = [String]()
var containsInitialViewController = false
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
switch elementName {
case "viewController":
if let identifier = attributeDict["storyboardIdentifier"] {
identifiers.append(identifier)
}
case "document":
if attributeDict["initialViewController"] != nil {
containsInitialViewController = true
}
default:
break
}
}
}
class StoryboardIdentifiers {
public static func updateStoryboarIDs(srcRoot: String) {
guard let extensionUrl = findSwiftExtension(path: srcRoot) else { return }
var storyboardsExtension = ""
var identificationExtension = ""
let storyboards = findStoryboards(path: srcRoot)
storyboards.forEach { (storyboardURL) in
let realName = storyboardURL.deletingPathExtension().lastPathComponent
let fullName = (realName.lowercased().hasSuffix("storyboard")
? realName
: realName.appending("Storyboard"))
let camelcasedName = self.calmelCased(str: fullName)
guard let parser = XMLParser(contentsOf: storyboardURL) else { return }
let parserHandler = StoryboardXMLParserHandler()
parser.delegate = parserHandler
parser.parse()
if parserHandler.identifiers.count > 0 || parserHandler.containsInitialViewController {
storyboardsExtension.append("\n enum \(fullName): String, ViewControllerInstantiatable {")
storyboardsExtension.append("\n var storyboardName: String { return \"\(realName)\" }\n")
identificationExtension.append("\n static func \(camelcasedName)(_ identifier: UIStoryboard.\(fullName)) -> StoryboardIdentification { return StoryboardIdentification(identifier: identifier) }\n")
if parserHandler.containsInitialViewController {
storyboardsExtension.append("\n case initial")
}
parserHandler.identifiers.forEach({ (identifier) in
let camelcased = self.calmelCased(str: identifier)
storyboardsExtension.append("\n case \(camelcased) = \"\(identifier)\"")
})
storyboardsExtension.append("\n }\n ")
}
}
let swiftCode = self.generateSwiftCode(storyboardExtension: storyboardsExtension,
storyboardIdentificationExtension: identificationExtension)
try? swiftCode.write(to: extensionUrl, atomically: true, encoding: .utf8)
}
private static func findStoryboards(path: String) -> [URL] {
var result = [URL]()
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(atPath: path)
while let element = enumerator?.nextObject() as? String {
if element.hasSuffix("storyboard") {
let url = URL(fileURLWithPath: element)
result.append(url)
}
}
return result
}
private static func findSwiftExtension(path: String) -> URL? {
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(atPath: path)
while let element = enumerator?.nextObject() as? String {
if element.contains("StoryboardIdentifiersUtils.swift") {
let url = URL(fileURLWithPath: element)
return url
}
}
return nil
}
private static func calmelCased(str: String) -> String {
return str.prefix(1).lowercased() + str.suffix(str.count - 1)
}
private static func generateSwiftCode(storyboardExtension: String,
storyboardIdentificationExtension: String) -> String {
let swiftCode = """
//
// UIStoryboard+Identifiers.swift
// Generated by script
//
import StoryboardIdentification
extension UIViewController {
static func instantiate(from identification: StoryboardIdentification) -> Self {
return identification.instantiate()
}
}
extension UIStoryboard {
\(storyboardExtension)
}
extension StoryboardIdentification {
\(storyboardIdentificationExtension)
}
"""
return swiftCode
}
}
| 35.133803 | 215 | 0.592504 |
897831caf7b259960e4293d423bc9b4f8158d2a3 | 1,124 | //
// PasswordCriteria.swift
// Password
//
// Created by jrasmusson on 2022-02-10.
//
import Foundation
struct PasswordCriteria {
static func lengthCriteriaMet(_ text: String) -> Bool {
text.count >= 8 && text.count <= 32
}
static func noSpaceCriteriaMet(_ text: String) -> Bool {
text.rangeOfCharacter(from: NSCharacterSet.whitespaces) == nil
}
static func lengthAndNoSpaceMet(_ text: String) -> Bool {
lengthCriteriaMet(text) && noSpaceCriteriaMet(text)
}
static func uppercaseMet(_ text: String) -> Bool {
text.range(of: "[A-Z]+", options: .regularExpression) != nil
}
static func lowercaseMet(_ text: String) -> Bool {
text.range(of: "[a-z]+", options: .regularExpression) != nil
}
static func digitMet(_ text: String) -> Bool {
text.range(of: "[0-9]+", options: .regularExpression) != nil
}
static func specialCharacterMet(_ text: String) -> Bool {
// regex escaped @:?!()$#,.\/
return text.range(of: "[@:?!()$#,./\\\\]+", options: .regularExpression) != nil
}
}
| 28.1 | 87 | 0.594306 |
39255660b56f43d48180f4d950a7fada8a58c185 | 7,274 | //
// StoreAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
open class StoreAPI: APIBase {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deleteOrder(orderId: String, completion: @escaping ((_ error: Error?) -> Void)) {
deleteOrderWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
completion(error);
}
}
/**
Delete purchase order by ID
- DELETE /store/order/{orderId}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder<Void> {
var path = "/store/order/{orderId}"
path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = NSURLComponents(string: URLString)
let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Returns pet inventories by status
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getInventory(completion: @escaping ((_ data: [String:Int32]?,_ error: Error?) -> Void)) {
getInventoryWithRequestBuilder().execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Returns pet inventories by status
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key
- name: api_key
- examples: [{contentType=application/json, example={
"key" : 0
}}]
- returns: RequestBuilder<[String:Int32]>
*/
open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> {
let path = "/store/inventory"
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = NSURLComponents(string: URLString)
let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getOrderById(orderId: Int64, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) {
getOrderByIdWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Find purchase order by ID
- GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- examples: [{contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}}]
- examples: [{contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}}]
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder<Order> {
var path = "/store/order/{orderId}"
path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil)
let URLString = PetstoreClientAPI.basePath + path
let parameters: [String:Any]? = nil
let url = NSURLComponents(string: URLString)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false)
}
/**
Place an order for a pet
- parameter body: (body) order placed for purchasing the pet
- parameter completion: completion handler to receive the data and the error objects
*/
open class func placeOrder(body: Order, completion: @escaping ((_ data: Order?,_ error: Error?) -> Void)) {
placeOrderWithRequestBuilder(body: body).execute { (response, error) -> Void in
completion(response?.body, error);
}
}
/**
Place an order for a pet
- POST /store/order
-
- examples: [{contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}}]
- examples: [{contentType=application/xml, example=<Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>}, {contentType=application/json, example={
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
}}]
- parameter body: (body) order placed for purchasing the pet
- returns: RequestBuilder<Order>
*/
open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder<Order> {
let path = "/store/order"
let URLString = PetstoreClientAPI.basePath + path
let parameters = body.encodeToJSON() as? [String:AnyObject]
let url = NSURLComponents(string: URLString)
let requestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}
}
| 33.214612 | 130 | 0.65576 |
3a31fae9264ae2cf1e617ba71ac5c0b04295917a | 8,803 | //
// Device.swift
// Device
//
// Created by Lucas Ortis on 30/10/2015.
// Copyright © 2015 Ekhoo. All rights reserved.
//
#if os(iOS)
import UIKit
open class Device {
static fileprivate func getVersionCode() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let versionCode: String = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!)!
return versionCode
}
static fileprivate func getVersion(code: String) -> Version {
switch code {
/*** iPhone ***/
case "iPhone1,1": return .iPhone2G
case "iPhone1,2": return .iPhone3G
case "iPhone2,1": return .iPhone3GS
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return .iPhone4
case "iPhone4,1", "iPhone4,2", "iPhone4,3": return .iPhone4S
case "iPhone5,1", "iPhone5,2": return .iPhone5
case "iPhone5,3", "iPhone5,4": return .iPhone5C
case "iPhone6,1", "iPhone6,2": return .iPhone5S
case "iPhone7,2": return .iPhone6
case "iPhone7,1": return .iPhone6Plus
case "iPhone8,1": return .iPhone6S
case "iPhone8,2": return .iPhone6SPlus
case "iPhone8,3", "iPhone8,4": return .iPhoneSE
case "iPhone9,1", "iPhone9,3": return .iPhone7
case "iPhone9,2", "iPhone9,4": return .iPhone7Plus
case "iPhone10,1", "iPhone10,4": return .iPhone8
case "iPhone10,2", "iPhone10,5": return .iPhone8Plus
case "iPhone10,3", "iPhone10,6": return .iPhoneX
case "iPhone11,2": return .iPhoneXS
case "iPhone11,4", "iPhone11,6": return .iPhoneXS_Max
case "iPhone11,8": return .iPhoneXR
case "iPhone12,1": return .iPhone11
case "iPhone12,3": return .iPhone11Pro
case "iPhone12,5": return .iPhone11Pro_Max
case "iPhone12,8": return .iPhoneSE2
/*** iPad ***/
case "iPad1,1", "iPad1,2": return .iPad1
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2
case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3
case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4
case "iPad6,11", "iPad6,12": return .iPad5
case "iPad7,5", "iPad7,6": return .iPad6
case "iPad7,11", "iPad7,12": return .iPad7
case "iPad11,6", "iPad11,7": return .iPad8
case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir
case "iPad5,3", "iPad5,4": return .iPadAir2
case "iPad11,3", "iPad11,4": return .iPadAir3
case "iPad13,1", "iPad13,2": return .iPadAir4
case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini
case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2
case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3
case "iPad5,1", "iPad5,2": return .iPadMini4
case "iPad11,1", "iPad11,2": return .iPadMini5
/*** iPadPro ***/
case "iPad6,3", "iPad6,4": return .iPadPro9_7Inch
case "iPad6,7", "iPad6,8": return .iPadPro12_9Inch
case "iPad7,1", "iPad7,2": return .iPadPro12_9Inch2
case "iPad7,3", "iPad7,4": return .iPadPro10_5Inch
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return .iPadPro11_0Inch
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return .iPadPro12_9Inch3
case "iPad8,9", "iPad8,10": return .iPadPro11_0Inch2
case "iPad8,11", "iPad8,12": return .iPadPro12_9Inch4
/*** iPod ***/
case "iPod1,1": return .iPodTouch1Gen
case "iPod2,1": return .iPodTouch2Gen
case "iPod3,1": return .iPodTouch3Gen
case "iPod4,1": return .iPodTouch4Gen
case "iPod5,1": return .iPodTouch5Gen
case "iPod7,1": return .iPodTouch6Gen
case "iPod9,1": return .iPodTouch7Gen
/*** Simulator ***/
case "i386", "x86_64": return .simulator
default: return .unknown
}
}
static fileprivate func getType(code: String) -> Type {
let versionCode = getVersionCode()
if versionCode.contains("iPhone") {
return .iPhone
} else if versionCode.contains("iPad") {
return .iPad
} else if versionCode.contains("iPod") {
return .iPod
} else if versionCode == "i386" || versionCode == "x86_64" {
return .simulator
} else {
return .unknown
}
}
static public func version() -> Version {
return getVersion(code: getVersionCode())
}
static public func size() -> Size {
let w: Double = Double(UIScreen.main.bounds.width)
let h: Double = Double(UIScreen.main.bounds.height)
let screenHeight: Double = max(w, h)
switch screenHeight {
case 240,480:
return .screen3_5Inch
case 568:
return .screen4Inch
case 667:
return UIScreen.main.scale == 3.0 ? .screen5_5Inch : .screen4_7Inch
case 736:
return .screen5_5Inch
case 812:
return .screen5_8Inch
case 896:
switch version() {
case .iPhoneXS_Max,.iPhone11Pro_Max:
return .screen6_5Inch
default:
return .screen6_1Inch
}
case 1024:
switch version() {
case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4,.iPadMini5:
return .screen7_9Inch
case .iPadPro10_5Inch:
return .screen10_5Inch
default:
return .screen9_7Inch
}
case 1080:
return .screen10_2Inch
case 1112:
return .screen10_5Inch
case 1180:
return .screen10_9Inch
case 1194:
return .screen11Inch
case 1366:
return .screen12_9Inch
default:
return .unknownSize
}
}
static public func type() -> Type {
return getType(code: getVersionCode())
}
@available(*, deprecated, message: "use == operator instead")
static public func isEqualToScreenSize(_ size: Size) -> Bool {
return size == self.size() ? true : false;
}
@available(*, deprecated, message: "use > operator instead")
static public func isLargerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue < self.size().rawValue ? true : false;
}
@available(*, deprecated, message: "use < operator instead")
static public func isSmallerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue > self.size().rawValue ? true : false;
}
static public func isRetina() -> Bool {
return UIScreen.main.scale > 1.0
}
static public func isPad() -> Bool {
return type() == .iPad
}
static public func isPhone() -> Bool {
return type() == .iPhone
}
static public func isPod() -> Bool {
return type() == .iPod
}
static public func isSimulator() -> Bool {
return type() == .simulator
}
}
#endif
| 43.151961 | 177 | 0.463365 |
79512fbc92abd9815ce7ee86756cdd4666224f02 | 4,914 | import UIKit
extension DrawerPresentationController {
@objc func handleDrawerFullExpansionTap() {
guard let tapGesture = drawerFullExpansionTapGR,
shouldBeginTransition else { return }
let tapY = tapGesture.location(in: presentedView).y
guard tapY < drawerPartialHeight else { return }
NotificationCenter.default.post(notification: DrawerNotification.drawerInteriorTapped)
animateTransition(to: .fullyExpanded)
}
@objc func handleDrawerDismissalTap() {
guard let tapGesture = drawerDismissalTapGR,
shouldBeginTransition else { return }
let tapY = tapGesture.location(in: containerView).y
guard tapY < currentDrawerY else { return }
NotificationCenter.default.post(notification: DrawerNotification.drawerExteriorTapped)
tapGesture.isEnabled = false
presentedViewController.dismiss(animated: true)
}
@objc func handleDrawerDrag() {
guard let panGesture = drawerDragGR,
let view = panGesture.view,
shouldBeginTransition else { return }
switch panGesture.state {
case .began:
startingDrawerStateForDrag = targetDrawerState
fallthrough
case .changed:
applyTranslationY(panGesture.translation(in: view).y)
panGesture.setTranslation(.zero, in: view)
case .ended:
let drawerSpeedY = panGesture.velocity(in: view).y / containerViewHeight
let endingState = GeometryEvaluator.nextStateFrom(currentState: currentDrawerState,
speedY: drawerSpeedY,
drawerPartialHeight: drawerPartialHeight,
containerViewHeight: containerViewHeight,
configuration: configuration)
animateTransition(to: endingState)
case .cancelled:
if let startingState = startingDrawerStateForDrag {
startingDrawerStateForDrag = nil
animateTransition(to: startingState)
}
default:
break
}
}
func applyTranslationY(_ translationY: CGFloat) {
guard shouldBeginTransition else { return }
currentDrawerY += translationY
targetDrawerState = currentDrawerState
currentDrawerCornerRadius = cornerRadius(at: currentDrawerState)
let (startingPositionY, endingPositionY) = positionsY(startingState: currentDrawerState,
endingState: targetDrawerState)
let presentingVC = presentingViewController
let presentedVC = presentedViewController
let presentedViewFrame = presentedView?.frame ?? .zero
var startingFrame = presentedViewFrame
startingFrame.origin.y = startingPositionY
var endingFrame = presentedViewFrame
endingFrame.origin.y = endingPositionY
let geometry = AnimationSupport.makeGeometry(containerBounds: containerViewBounds,
startingFrame: startingFrame,
endingFrame: endingFrame,
presentingVC: presentingVC,
presentedVC: presentedVC)
let info = AnimationSupport.makeInfo(startDrawerState: currentDrawerState,
targetDrawerState: targetDrawerState,
configuration,
geometry,
0.0,
false)
let presentingAnimationActions = self.presentingDrawerAnimationActions
let presentedAnimationActions = self.presentedDrawerAnimationActions
AnimationSupport.clientAnimateAlong(presentingDrawerAnimationActions: presentingAnimationActions,
presentedDrawerAnimationActions: presentedAnimationActions,
info)
}
}
extension DrawerPresentationController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer is UITapGestureRecognizer,
let view = gestureRecognizer.view,
view.isDescendant(of: presentedViewController.view),
let subview = view.hitTest(touch.location(in: view), with: nil) {
return !(subview is UIControl)
} else {
return true
}
}
}
| 44.27027 | 108 | 0.579772 |
e82e876b5b4d8588552aedea50f34c0a7d403836 | 273 | //
// PassData.swift
// News-App
//
// Created by Bakhtovar Umarov on 21/08/21.
//
import Foundation
struct PassUrl {
var categoryName: String?
var id: String?
var searchText: String?
var pageInt: Int
}
struct PassTitle {
var sourceTitle: String
}
| 14.368421 | 44 | 0.659341 |
4af9fdb6e74449aa5391f7ab898ca8cd166250f3 | 695 | //
// WBDiscoverViewController.swift
// LWB
//
// Created by Lee on 2018/11/29.
// Copyright © 2018 Lee. All rights reserved.
//
import UIKit
class WBDiscoverViewController: WBBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// 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.
}
*/
}
| 22.419355 | 106 | 0.664748 |
f8c67e8007772eeeb51b73551e0f2b1ff6213fdb | 77,348 | //
// DO NOT EDIT.
//
// Generated by the protocol buffer compiler.
// Source: telemetry.proto
//
//
// Copyright 2018, gRPC Authors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import GRPC
import NIO
import SwiftProtobuf
/// Usage: instantiate Mavsdk_Rpc_Telemetry_TelemetryServiceClient, then call methods of this protocol to make API calls.
internal protocol Mavsdk_Rpc_Telemetry_TelemetryServiceClientProtocol: GRPCClient {
func subscribePosition(
_ request: Mavsdk_Rpc_Telemetry_SubscribePositionRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_PositionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribePositionRequest, Mavsdk_Rpc_Telemetry_PositionResponse>
func subscribeHome(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHomeRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_HomeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHomeRequest, Mavsdk_Rpc_Telemetry_HomeResponse>
func subscribeInAir(
_ request: Mavsdk_Rpc_Telemetry_SubscribeInAirRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_InAirResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeInAirRequest, Mavsdk_Rpc_Telemetry_InAirResponse>
func subscribeLandedState(
_ request: Mavsdk_Rpc_Telemetry_SubscribeLandedStateRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_LandedStateResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeLandedStateRequest, Mavsdk_Rpc_Telemetry_LandedStateResponse>
func subscribeArmed(
_ request: Mavsdk_Rpc_Telemetry_SubscribeArmedRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_ArmedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeArmedRequest, Mavsdk_Rpc_Telemetry_ArmedResponse>
func subscribeAttitudeQuaternion(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeQuaternionRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeQuaternionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeQuaternionRequest, Mavsdk_Rpc_Telemetry_AttitudeQuaternionResponse>
func subscribeAttitudeEuler(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeEulerRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeEulerResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeEulerRequest, Mavsdk_Rpc_Telemetry_AttitudeEulerResponse>
func subscribeAttitudeAngularVelocityBody(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeAngularVelocityBodyRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeAngularVelocityBodyResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeAngularVelocityBodyRequest, Mavsdk_Rpc_Telemetry_AttitudeAngularVelocityBodyResponse>
func subscribeCameraAttitudeQuaternion(
_ request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeQuaternionRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_CameraAttitudeQuaternionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeQuaternionRequest, Mavsdk_Rpc_Telemetry_CameraAttitudeQuaternionResponse>
func subscribeCameraAttitudeEuler(
_ request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeEulerRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_CameraAttitudeEulerResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeEulerRequest, Mavsdk_Rpc_Telemetry_CameraAttitudeEulerResponse>
func subscribeVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SubscribeVelocityNedRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_VelocityNedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeVelocityNedRequest, Mavsdk_Rpc_Telemetry_VelocityNedResponse>
func subscribeGpsInfo(
_ request: Mavsdk_Rpc_Telemetry_SubscribeGpsInfoRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_GpsInfoResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeGpsInfoRequest, Mavsdk_Rpc_Telemetry_GpsInfoResponse>
func subscribeBattery(
_ request: Mavsdk_Rpc_Telemetry_SubscribeBatteryRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_BatteryResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeBatteryRequest, Mavsdk_Rpc_Telemetry_BatteryResponse>
func subscribeFlightMode(
_ request: Mavsdk_Rpc_Telemetry_SubscribeFlightModeRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_FlightModeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeFlightModeRequest, Mavsdk_Rpc_Telemetry_FlightModeResponse>
func subscribeHealth(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHealthRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_HealthResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHealthRequest, Mavsdk_Rpc_Telemetry_HealthResponse>
func subscribeRcStatus(
_ request: Mavsdk_Rpc_Telemetry_SubscribeRcStatusRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_RcStatusResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeRcStatusRequest, Mavsdk_Rpc_Telemetry_RcStatusResponse>
func subscribeStatusText(
_ request: Mavsdk_Rpc_Telemetry_SubscribeStatusTextRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_StatusTextResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeStatusTextRequest, Mavsdk_Rpc_Telemetry_StatusTextResponse>
func subscribeActuatorControlTarget(
_ request: Mavsdk_Rpc_Telemetry_SubscribeActuatorControlTargetRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_ActuatorControlTargetResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeActuatorControlTargetRequest, Mavsdk_Rpc_Telemetry_ActuatorControlTargetResponse>
func subscribeActuatorOutputStatus(
_ request: Mavsdk_Rpc_Telemetry_SubscribeActuatorOutputStatusRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_ActuatorOutputStatusResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeActuatorOutputStatusRequest, Mavsdk_Rpc_Telemetry_ActuatorOutputStatusResponse>
func subscribeOdometry(
_ request: Mavsdk_Rpc_Telemetry_SubscribeOdometryRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_OdometryResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeOdometryRequest, Mavsdk_Rpc_Telemetry_OdometryResponse>
func subscribePositionVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SubscribePositionVelocityNedRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_PositionVelocityNedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribePositionVelocityNedRequest, Mavsdk_Rpc_Telemetry_PositionVelocityNedResponse>
func subscribeGroundTruth(
_ request: Mavsdk_Rpc_Telemetry_SubscribeGroundTruthRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_GroundTruthResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeGroundTruthRequest, Mavsdk_Rpc_Telemetry_GroundTruthResponse>
func subscribeFixedwingMetrics(
_ request: Mavsdk_Rpc_Telemetry_SubscribeFixedwingMetricsRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_FixedwingMetricsResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeFixedwingMetricsRequest, Mavsdk_Rpc_Telemetry_FixedwingMetricsResponse>
func subscribeImu(
_ request: Mavsdk_Rpc_Telemetry_SubscribeImuRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_ImuResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeImuRequest, Mavsdk_Rpc_Telemetry_ImuResponse>
func subscribeHealthAllOk(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHealthAllOkRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_HealthAllOkResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHealthAllOkRequest, Mavsdk_Rpc_Telemetry_HealthAllOkResponse>
func subscribeUnixEpochTime(
_ request: Mavsdk_Rpc_Telemetry_SubscribeUnixEpochTimeRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_UnixEpochTimeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeUnixEpochTimeRequest, Mavsdk_Rpc_Telemetry_UnixEpochTimeResponse>
func subscribeDistanceSensor(
_ request: Mavsdk_Rpc_Telemetry_SubscribeDistanceSensorRequest,
callOptions: CallOptions?,
handler: @escaping (Mavsdk_Rpc_Telemetry_DistanceSensorResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeDistanceSensorRequest, Mavsdk_Rpc_Telemetry_DistanceSensorResponse>
func setRatePosition(
_ request: Mavsdk_Rpc_Telemetry_SetRatePositionRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRatePositionRequest, Mavsdk_Rpc_Telemetry_SetRatePositionResponse>
func setRateHome(
_ request: Mavsdk_Rpc_Telemetry_SetRateHomeRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateHomeRequest, Mavsdk_Rpc_Telemetry_SetRateHomeResponse>
func setRateInAir(
_ request: Mavsdk_Rpc_Telemetry_SetRateInAirRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateInAirRequest, Mavsdk_Rpc_Telemetry_SetRateInAirResponse>
func setRateLandedState(
_ request: Mavsdk_Rpc_Telemetry_SetRateLandedStateRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateLandedStateRequest, Mavsdk_Rpc_Telemetry_SetRateLandedStateResponse>
func setRateAttitude(
_ request: Mavsdk_Rpc_Telemetry_SetRateAttitudeRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateAttitudeRequest, Mavsdk_Rpc_Telemetry_SetRateAttitudeResponse>
func setRateCameraAttitude(
_ request: Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeRequest, Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeResponse>
func setRateVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SetRateVelocityNedRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateVelocityNedRequest, Mavsdk_Rpc_Telemetry_SetRateVelocityNedResponse>
func setRateGpsInfo(
_ request: Mavsdk_Rpc_Telemetry_SetRateGpsInfoRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateGpsInfoRequest, Mavsdk_Rpc_Telemetry_SetRateGpsInfoResponse>
func setRateBattery(
_ request: Mavsdk_Rpc_Telemetry_SetRateBatteryRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateBatteryRequest, Mavsdk_Rpc_Telemetry_SetRateBatteryResponse>
func setRateRcStatus(
_ request: Mavsdk_Rpc_Telemetry_SetRateRcStatusRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateRcStatusRequest, Mavsdk_Rpc_Telemetry_SetRateRcStatusResponse>
func setRateActuatorControlTarget(
_ request: Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetRequest, Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetResponse>
func setRateActuatorOutputStatus(
_ request: Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusRequest, Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusResponse>
func setRateOdometry(
_ request: Mavsdk_Rpc_Telemetry_SetRateOdometryRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateOdometryRequest, Mavsdk_Rpc_Telemetry_SetRateOdometryResponse>
func setRatePositionVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedRequest, Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedResponse>
func setRateGroundTruth(
_ request: Mavsdk_Rpc_Telemetry_SetRateGroundTruthRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateGroundTruthRequest, Mavsdk_Rpc_Telemetry_SetRateGroundTruthResponse>
func setRateFixedwingMetrics(
_ request: Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsRequest, Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsResponse>
func setRateImu(
_ request: Mavsdk_Rpc_Telemetry_SetRateImuRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateImuRequest, Mavsdk_Rpc_Telemetry_SetRateImuResponse>
func setRateUnixEpochTime(
_ request: Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeRequest, Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeResponse>
func setRateDistanceSensor(
_ request: Mavsdk_Rpc_Telemetry_SetRateDistanceSensorRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateDistanceSensorRequest, Mavsdk_Rpc_Telemetry_SetRateDistanceSensorResponse>
func getGpsGlobalOrigin(
_ request: Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginRequest,
callOptions: CallOptions?
) -> UnaryCall<Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginRequest, Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginResponse>
}
extension Mavsdk_Rpc_Telemetry_TelemetryServiceClientProtocol {
/// Subscribe to 'position' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribePosition.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribePosition(
_ request: Mavsdk_Rpc_Telemetry_SubscribePositionRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_PositionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribePositionRequest, Mavsdk_Rpc_Telemetry_PositionResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribePosition",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'home position' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeHome.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeHome(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHomeRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_HomeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHomeRequest, Mavsdk_Rpc_Telemetry_HomeResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeHome",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to in-air updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeInAir.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeInAir(
_ request: Mavsdk_Rpc_Telemetry_SubscribeInAirRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_InAirResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeInAirRequest, Mavsdk_Rpc_Telemetry_InAirResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeInAir",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to landed state updates
///
/// - Parameters:
/// - request: Request to send to SubscribeLandedState.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeLandedState(
_ request: Mavsdk_Rpc_Telemetry_SubscribeLandedStateRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_LandedStateResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeLandedStateRequest, Mavsdk_Rpc_Telemetry_LandedStateResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeLandedState",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to armed updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeArmed.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeArmed(
_ request: Mavsdk_Rpc_Telemetry_SubscribeArmedRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_ArmedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeArmedRequest, Mavsdk_Rpc_Telemetry_ArmedResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeArmed",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'attitude' updates (quaternion).
///
/// - Parameters:
/// - request: Request to send to SubscribeAttitudeQuaternion.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeAttitudeQuaternion(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeQuaternionRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeQuaternionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeQuaternionRequest, Mavsdk_Rpc_Telemetry_AttitudeQuaternionResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeAttitudeQuaternion",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'attitude' updates (Euler).
///
/// - Parameters:
/// - request: Request to send to SubscribeAttitudeEuler.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeAttitudeEuler(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeEulerRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeEulerResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeEulerRequest, Mavsdk_Rpc_Telemetry_AttitudeEulerResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeAttitudeEuler",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'attitude' updates (angular velocity)
///
/// - Parameters:
/// - request: Request to send to SubscribeAttitudeAngularVelocityBody.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeAttitudeAngularVelocityBody(
_ request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeAngularVelocityBodyRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_AttitudeAngularVelocityBodyResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeAttitudeAngularVelocityBodyRequest, Mavsdk_Rpc_Telemetry_AttitudeAngularVelocityBodyResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeAttitudeAngularVelocityBody",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'camera attitude' updates (quaternion).
///
/// - Parameters:
/// - request: Request to send to SubscribeCameraAttitudeQuaternion.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeCameraAttitudeQuaternion(
_ request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeQuaternionRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_CameraAttitudeQuaternionResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeQuaternionRequest, Mavsdk_Rpc_Telemetry_CameraAttitudeQuaternionResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeCameraAttitudeQuaternion",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'camera attitude' updates (Euler).
///
/// - Parameters:
/// - request: Request to send to SubscribeCameraAttitudeEuler.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeCameraAttitudeEuler(
_ request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeEulerRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_CameraAttitudeEulerResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeEulerRequest, Mavsdk_Rpc_Telemetry_CameraAttitudeEulerResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeCameraAttitudeEuler",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'ground speed' updates (NED).
///
/// - Parameters:
/// - request: Request to send to SubscribeVelocityNed.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SubscribeVelocityNedRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_VelocityNedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeVelocityNedRequest, Mavsdk_Rpc_Telemetry_VelocityNedResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeVelocityNed",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'GPS info' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeGpsInfo.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeGpsInfo(
_ request: Mavsdk_Rpc_Telemetry_SubscribeGpsInfoRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_GpsInfoResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeGpsInfoRequest, Mavsdk_Rpc_Telemetry_GpsInfoResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeGpsInfo",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'battery' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeBattery.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeBattery(
_ request: Mavsdk_Rpc_Telemetry_SubscribeBatteryRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_BatteryResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeBatteryRequest, Mavsdk_Rpc_Telemetry_BatteryResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeBattery",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'flight mode' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeFlightMode.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeFlightMode(
_ request: Mavsdk_Rpc_Telemetry_SubscribeFlightModeRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_FlightModeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeFlightModeRequest, Mavsdk_Rpc_Telemetry_FlightModeResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeFlightMode",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'health' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeHealth.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeHealth(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHealthRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_HealthResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHealthRequest, Mavsdk_Rpc_Telemetry_HealthResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeHealth",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'RC status' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeRcStatus.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeRcStatus(
_ request: Mavsdk_Rpc_Telemetry_SubscribeRcStatusRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_RcStatusResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeRcStatusRequest, Mavsdk_Rpc_Telemetry_RcStatusResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeRcStatus",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'status text' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeStatusText.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeStatusText(
_ request: Mavsdk_Rpc_Telemetry_SubscribeStatusTextRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_StatusTextResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeStatusTextRequest, Mavsdk_Rpc_Telemetry_StatusTextResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeStatusText",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'actuator control target' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeActuatorControlTarget.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeActuatorControlTarget(
_ request: Mavsdk_Rpc_Telemetry_SubscribeActuatorControlTargetRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_ActuatorControlTargetResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeActuatorControlTargetRequest, Mavsdk_Rpc_Telemetry_ActuatorControlTargetResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeActuatorControlTarget",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'actuator output status' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeActuatorOutputStatus.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeActuatorOutputStatus(
_ request: Mavsdk_Rpc_Telemetry_SubscribeActuatorOutputStatusRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_ActuatorOutputStatusResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeActuatorOutputStatusRequest, Mavsdk_Rpc_Telemetry_ActuatorOutputStatusResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeActuatorOutputStatus",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'odometry' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeOdometry.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeOdometry(
_ request: Mavsdk_Rpc_Telemetry_SubscribeOdometryRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_OdometryResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeOdometryRequest, Mavsdk_Rpc_Telemetry_OdometryResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeOdometry",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'position velocity' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribePositionVelocityNed.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribePositionVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SubscribePositionVelocityNedRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_PositionVelocityNedResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribePositionVelocityNedRequest, Mavsdk_Rpc_Telemetry_PositionVelocityNedResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribePositionVelocityNed",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'ground truth' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeGroundTruth.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeGroundTruth(
_ request: Mavsdk_Rpc_Telemetry_SubscribeGroundTruthRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_GroundTruthResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeGroundTruthRequest, Mavsdk_Rpc_Telemetry_GroundTruthResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeGroundTruth",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'fixedwing metrics' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeFixedwingMetrics.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeFixedwingMetrics(
_ request: Mavsdk_Rpc_Telemetry_SubscribeFixedwingMetricsRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_FixedwingMetricsResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeFixedwingMetricsRequest, Mavsdk_Rpc_Telemetry_FixedwingMetricsResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeFixedwingMetrics",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'IMU' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeImu.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeImu(
_ request: Mavsdk_Rpc_Telemetry_SubscribeImuRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_ImuResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeImuRequest, Mavsdk_Rpc_Telemetry_ImuResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeImu",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'HealthAllOk' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeHealthAllOk.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeHealthAllOk(
_ request: Mavsdk_Rpc_Telemetry_SubscribeHealthAllOkRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_HealthAllOkResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeHealthAllOkRequest, Mavsdk_Rpc_Telemetry_HealthAllOkResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeHealthAllOk",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'unix epoch time' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeUnixEpochTime.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeUnixEpochTime(
_ request: Mavsdk_Rpc_Telemetry_SubscribeUnixEpochTimeRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_UnixEpochTimeResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeUnixEpochTimeRequest, Mavsdk_Rpc_Telemetry_UnixEpochTimeResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeUnixEpochTime",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Subscribe to 'Distance Sensor' updates.
///
/// - Parameters:
/// - request: Request to send to SubscribeDistanceSensor.
/// - callOptions: Call options.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func subscribeDistanceSensor(
_ request: Mavsdk_Rpc_Telemetry_SubscribeDistanceSensorRequest,
callOptions: CallOptions? = nil,
handler: @escaping (Mavsdk_Rpc_Telemetry_DistanceSensorResponse) -> Void
) -> ServerStreamingCall<Mavsdk_Rpc_Telemetry_SubscribeDistanceSensorRequest, Mavsdk_Rpc_Telemetry_DistanceSensorResponse> {
return self.makeServerStreamingCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SubscribeDistanceSensor",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler
)
}
/// Set rate to 'position' updates.
///
/// - Parameters:
/// - request: Request to send to SetRatePosition.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRatePosition(
_ request: Mavsdk_Rpc_Telemetry_SetRatePositionRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRatePositionRequest, Mavsdk_Rpc_Telemetry_SetRatePositionResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRatePosition",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'home position' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateHome.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateHome(
_ request: Mavsdk_Rpc_Telemetry_SetRateHomeRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateHomeRequest, Mavsdk_Rpc_Telemetry_SetRateHomeResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateHome",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to in-air updates.
///
/// - Parameters:
/// - request: Request to send to SetRateInAir.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateInAir(
_ request: Mavsdk_Rpc_Telemetry_SetRateInAirRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateInAirRequest, Mavsdk_Rpc_Telemetry_SetRateInAirResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateInAir",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to landed state updates
///
/// - Parameters:
/// - request: Request to send to SetRateLandedState.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateLandedState(
_ request: Mavsdk_Rpc_Telemetry_SetRateLandedStateRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateLandedStateRequest, Mavsdk_Rpc_Telemetry_SetRateLandedStateResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateLandedState",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'attitude' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateAttitude.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateAttitude(
_ request: Mavsdk_Rpc_Telemetry_SetRateAttitudeRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateAttitudeRequest, Mavsdk_Rpc_Telemetry_SetRateAttitudeResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateAttitude",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate of camera attitude updates.
///
/// - Parameters:
/// - request: Request to send to SetRateCameraAttitude.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateCameraAttitude(
_ request: Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeRequest, Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateCameraAttitude",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'ground speed' updates (NED).
///
/// - Parameters:
/// - request: Request to send to SetRateVelocityNed.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SetRateVelocityNedRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateVelocityNedRequest, Mavsdk_Rpc_Telemetry_SetRateVelocityNedResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateVelocityNed",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'GPS info' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateGpsInfo.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateGpsInfo(
_ request: Mavsdk_Rpc_Telemetry_SetRateGpsInfoRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateGpsInfoRequest, Mavsdk_Rpc_Telemetry_SetRateGpsInfoResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateGpsInfo",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'battery' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateBattery.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateBattery(
_ request: Mavsdk_Rpc_Telemetry_SetRateBatteryRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateBatteryRequest, Mavsdk_Rpc_Telemetry_SetRateBatteryResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateBattery",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'RC status' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateRcStatus.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateRcStatus(
_ request: Mavsdk_Rpc_Telemetry_SetRateRcStatusRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateRcStatusRequest, Mavsdk_Rpc_Telemetry_SetRateRcStatusResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateRcStatus",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'actuator control target' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateActuatorControlTarget.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateActuatorControlTarget(
_ request: Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetRequest, Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateActuatorControlTarget",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'actuator output status' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateActuatorOutputStatus.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateActuatorOutputStatus(
_ request: Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusRequest, Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateActuatorOutputStatus",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'odometry' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateOdometry.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateOdometry(
_ request: Mavsdk_Rpc_Telemetry_SetRateOdometryRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateOdometryRequest, Mavsdk_Rpc_Telemetry_SetRateOdometryResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateOdometry",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'position velocity' updates.
///
/// - Parameters:
/// - request: Request to send to SetRatePositionVelocityNed.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRatePositionVelocityNed(
_ request: Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedRequest, Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRatePositionVelocityNed",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'ground truth' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateGroundTruth.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateGroundTruth(
_ request: Mavsdk_Rpc_Telemetry_SetRateGroundTruthRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateGroundTruthRequest, Mavsdk_Rpc_Telemetry_SetRateGroundTruthResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateGroundTruth",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'fixedwing metrics' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateFixedwingMetrics.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateFixedwingMetrics(
_ request: Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsRequest, Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateFixedwingMetrics",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'IMU' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateImu.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateImu(
_ request: Mavsdk_Rpc_Telemetry_SetRateImuRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateImuRequest, Mavsdk_Rpc_Telemetry_SetRateImuResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateImu",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'unix epoch time' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateUnixEpochTime.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateUnixEpochTime(
_ request: Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeRequest, Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateUnixEpochTime",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Set rate to 'Distance Sensor' updates.
///
/// - Parameters:
/// - request: Request to send to SetRateDistanceSensor.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func setRateDistanceSensor(
_ request: Mavsdk_Rpc_Telemetry_SetRateDistanceSensorRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_SetRateDistanceSensorRequest, Mavsdk_Rpc_Telemetry_SetRateDistanceSensorResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/SetRateDistanceSensor",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
/// Get the GPS location of where the estimator has been initialized.
///
/// - Parameters:
/// - request: Request to send to GetGpsGlobalOrigin.
/// - callOptions: Call options.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func getGpsGlobalOrigin(
_ request: Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginRequest,
callOptions: CallOptions? = nil
) -> UnaryCall<Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginRequest, Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginResponse> {
return self.makeUnaryCall(
path: "/mavsdk.rpc.telemetry.TelemetryService/GetGpsGlobalOrigin",
request: request,
callOptions: callOptions ?? self.defaultCallOptions
)
}
}
internal final class Mavsdk_Rpc_Telemetry_TelemetryServiceClient: Mavsdk_Rpc_Telemetry_TelemetryServiceClientProtocol {
internal let channel: GRPCChannel
internal var defaultCallOptions: CallOptions
/// Creates a client for the mavsdk.rpc.telemetry.TelemetryService service.
///
/// - Parameters:
/// - channel: `GRPCChannel` to the service host.
/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.
internal init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
self.channel = channel
self.defaultCallOptions = defaultCallOptions
}
}
/// To build a server, implement a class that conforms to this protocol.
internal protocol Mavsdk_Rpc_Telemetry_TelemetryServiceProvider: CallHandlerProvider {
/// Subscribe to 'position' updates.
func subscribePosition(request: Mavsdk_Rpc_Telemetry_SubscribePositionRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_PositionResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'home position' updates.
func subscribeHome(request: Mavsdk_Rpc_Telemetry_SubscribeHomeRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_HomeResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to in-air updates.
func subscribeInAir(request: Mavsdk_Rpc_Telemetry_SubscribeInAirRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_InAirResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to landed state updates
func subscribeLandedState(request: Mavsdk_Rpc_Telemetry_SubscribeLandedStateRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_LandedStateResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to armed updates.
func subscribeArmed(request: Mavsdk_Rpc_Telemetry_SubscribeArmedRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_ArmedResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'attitude' updates (quaternion).
func subscribeAttitudeQuaternion(request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeQuaternionRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_AttitudeQuaternionResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'attitude' updates (Euler).
func subscribeAttitudeEuler(request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeEulerRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_AttitudeEulerResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'attitude' updates (angular velocity)
func subscribeAttitudeAngularVelocityBody(request: Mavsdk_Rpc_Telemetry_SubscribeAttitudeAngularVelocityBodyRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_AttitudeAngularVelocityBodyResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'camera attitude' updates (quaternion).
func subscribeCameraAttitudeQuaternion(request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeQuaternionRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_CameraAttitudeQuaternionResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'camera attitude' updates (Euler).
func subscribeCameraAttitudeEuler(request: Mavsdk_Rpc_Telemetry_SubscribeCameraAttitudeEulerRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_CameraAttitudeEulerResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'ground speed' updates (NED).
func subscribeVelocityNed(request: Mavsdk_Rpc_Telemetry_SubscribeVelocityNedRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_VelocityNedResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'GPS info' updates.
func subscribeGpsInfo(request: Mavsdk_Rpc_Telemetry_SubscribeGpsInfoRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_GpsInfoResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'battery' updates.
func subscribeBattery(request: Mavsdk_Rpc_Telemetry_SubscribeBatteryRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_BatteryResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'flight mode' updates.
func subscribeFlightMode(request: Mavsdk_Rpc_Telemetry_SubscribeFlightModeRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_FlightModeResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'health' updates.
func subscribeHealth(request: Mavsdk_Rpc_Telemetry_SubscribeHealthRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_HealthResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'RC status' updates.
func subscribeRcStatus(request: Mavsdk_Rpc_Telemetry_SubscribeRcStatusRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_RcStatusResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'status text' updates.
func subscribeStatusText(request: Mavsdk_Rpc_Telemetry_SubscribeStatusTextRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_StatusTextResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'actuator control target' updates.
func subscribeActuatorControlTarget(request: Mavsdk_Rpc_Telemetry_SubscribeActuatorControlTargetRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_ActuatorControlTargetResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'actuator output status' updates.
func subscribeActuatorOutputStatus(request: Mavsdk_Rpc_Telemetry_SubscribeActuatorOutputStatusRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_ActuatorOutputStatusResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'odometry' updates.
func subscribeOdometry(request: Mavsdk_Rpc_Telemetry_SubscribeOdometryRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_OdometryResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'position velocity' updates.
func subscribePositionVelocityNed(request: Mavsdk_Rpc_Telemetry_SubscribePositionVelocityNedRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_PositionVelocityNedResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'ground truth' updates.
func subscribeGroundTruth(request: Mavsdk_Rpc_Telemetry_SubscribeGroundTruthRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_GroundTruthResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'fixedwing metrics' updates.
func subscribeFixedwingMetrics(request: Mavsdk_Rpc_Telemetry_SubscribeFixedwingMetricsRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_FixedwingMetricsResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'IMU' updates.
func subscribeImu(request: Mavsdk_Rpc_Telemetry_SubscribeImuRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_ImuResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'HealthAllOk' updates.
func subscribeHealthAllOk(request: Mavsdk_Rpc_Telemetry_SubscribeHealthAllOkRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_HealthAllOkResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'unix epoch time' updates.
func subscribeUnixEpochTime(request: Mavsdk_Rpc_Telemetry_SubscribeUnixEpochTimeRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_UnixEpochTimeResponse>) -> EventLoopFuture<GRPCStatus>
/// Subscribe to 'Distance Sensor' updates.
func subscribeDistanceSensor(request: Mavsdk_Rpc_Telemetry_SubscribeDistanceSensorRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Telemetry_DistanceSensorResponse>) -> EventLoopFuture<GRPCStatus>
/// Set rate to 'position' updates.
func setRatePosition(request: Mavsdk_Rpc_Telemetry_SetRatePositionRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRatePositionResponse>
/// Set rate to 'home position' updates.
func setRateHome(request: Mavsdk_Rpc_Telemetry_SetRateHomeRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateHomeResponse>
/// Set rate to in-air updates.
func setRateInAir(request: Mavsdk_Rpc_Telemetry_SetRateInAirRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateInAirResponse>
/// Set rate to landed state updates
func setRateLandedState(request: Mavsdk_Rpc_Telemetry_SetRateLandedStateRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateLandedStateResponse>
/// Set rate to 'attitude' updates.
func setRateAttitude(request: Mavsdk_Rpc_Telemetry_SetRateAttitudeRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateAttitudeResponse>
/// Set rate of camera attitude updates.
func setRateCameraAttitude(request: Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateCameraAttitudeResponse>
/// Set rate to 'ground speed' updates (NED).
func setRateVelocityNed(request: Mavsdk_Rpc_Telemetry_SetRateVelocityNedRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateVelocityNedResponse>
/// Set rate to 'GPS info' updates.
func setRateGpsInfo(request: Mavsdk_Rpc_Telemetry_SetRateGpsInfoRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateGpsInfoResponse>
/// Set rate to 'battery' updates.
func setRateBattery(request: Mavsdk_Rpc_Telemetry_SetRateBatteryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateBatteryResponse>
/// Set rate to 'RC status' updates.
func setRateRcStatus(request: Mavsdk_Rpc_Telemetry_SetRateRcStatusRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateRcStatusResponse>
/// Set rate to 'actuator control target' updates.
func setRateActuatorControlTarget(request: Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateActuatorControlTargetResponse>
/// Set rate to 'actuator output status' updates.
func setRateActuatorOutputStatus(request: Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateActuatorOutputStatusResponse>
/// Set rate to 'odometry' updates.
func setRateOdometry(request: Mavsdk_Rpc_Telemetry_SetRateOdometryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateOdometryResponse>
/// Set rate to 'position velocity' updates.
func setRatePositionVelocityNed(request: Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRatePositionVelocityNedResponse>
/// Set rate to 'ground truth' updates.
func setRateGroundTruth(request: Mavsdk_Rpc_Telemetry_SetRateGroundTruthRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateGroundTruthResponse>
/// Set rate to 'fixedwing metrics' updates.
func setRateFixedwingMetrics(request: Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateFixedwingMetricsResponse>
/// Set rate to 'IMU' updates.
func setRateImu(request: Mavsdk_Rpc_Telemetry_SetRateImuRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateImuResponse>
/// Set rate to 'unix epoch time' updates.
func setRateUnixEpochTime(request: Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateUnixEpochTimeResponse>
/// Set rate to 'Distance Sensor' updates.
func setRateDistanceSensor(request: Mavsdk_Rpc_Telemetry_SetRateDistanceSensorRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_SetRateDistanceSensorResponse>
/// Get the GPS location of where the estimator has been initialized.
func getGpsGlobalOrigin(request: Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Telemetry_GetGpsGlobalOriginResponse>
}
extension Mavsdk_Rpc_Telemetry_TelemetryServiceProvider {
internal var serviceName: Substring { return "mavsdk.rpc.telemetry.TelemetryService" }
/// Determines, calls and returns the appropriate request handler, depending on the request's method.
/// Returns nil for methods not handled by this service.
internal func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName {
case "SubscribePosition":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribePosition(request: request, context: context)
}
}
case "SubscribeHome":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeHome(request: request, context: context)
}
}
case "SubscribeInAir":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeInAir(request: request, context: context)
}
}
case "SubscribeLandedState":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeLandedState(request: request, context: context)
}
}
case "SubscribeArmed":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeArmed(request: request, context: context)
}
}
case "SubscribeAttitudeQuaternion":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeAttitudeQuaternion(request: request, context: context)
}
}
case "SubscribeAttitudeEuler":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeAttitudeEuler(request: request, context: context)
}
}
case "SubscribeAttitudeAngularVelocityBody":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeAttitudeAngularVelocityBody(request: request, context: context)
}
}
case "SubscribeCameraAttitudeQuaternion":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeCameraAttitudeQuaternion(request: request, context: context)
}
}
case "SubscribeCameraAttitudeEuler":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeCameraAttitudeEuler(request: request, context: context)
}
}
case "SubscribeVelocityNed":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeVelocityNed(request: request, context: context)
}
}
case "SubscribeGpsInfo":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeGpsInfo(request: request, context: context)
}
}
case "SubscribeBattery":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeBattery(request: request, context: context)
}
}
case "SubscribeFlightMode":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeFlightMode(request: request, context: context)
}
}
case "SubscribeHealth":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeHealth(request: request, context: context)
}
}
case "SubscribeRcStatus":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeRcStatus(request: request, context: context)
}
}
case "SubscribeStatusText":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeStatusText(request: request, context: context)
}
}
case "SubscribeActuatorControlTarget":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeActuatorControlTarget(request: request, context: context)
}
}
case "SubscribeActuatorOutputStatus":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeActuatorOutputStatus(request: request, context: context)
}
}
case "SubscribeOdometry":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeOdometry(request: request, context: context)
}
}
case "SubscribePositionVelocityNed":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribePositionVelocityNed(request: request, context: context)
}
}
case "SubscribeGroundTruth":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeGroundTruth(request: request, context: context)
}
}
case "SubscribeFixedwingMetrics":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeFixedwingMetrics(request: request, context: context)
}
}
case "SubscribeImu":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeImu(request: request, context: context)
}
}
case "SubscribeHealthAllOk":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeHealthAllOk(request: request, context: context)
}
}
case "SubscribeUnixEpochTime":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeUnixEpochTime(request: request, context: context)
}
}
case "SubscribeDistanceSensor":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
self.subscribeDistanceSensor(request: request, context: context)
}
}
case "SetRatePosition":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRatePosition(request: request, context: context)
}
}
case "SetRateHome":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateHome(request: request, context: context)
}
}
case "SetRateInAir":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateInAir(request: request, context: context)
}
}
case "SetRateLandedState":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateLandedState(request: request, context: context)
}
}
case "SetRateAttitude":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateAttitude(request: request, context: context)
}
}
case "SetRateCameraAttitude":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateCameraAttitude(request: request, context: context)
}
}
case "SetRateVelocityNed":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateVelocityNed(request: request, context: context)
}
}
case "SetRateGpsInfo":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateGpsInfo(request: request, context: context)
}
}
case "SetRateBattery":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateBattery(request: request, context: context)
}
}
case "SetRateRcStatus":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateRcStatus(request: request, context: context)
}
}
case "SetRateActuatorControlTarget":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateActuatorControlTarget(request: request, context: context)
}
}
case "SetRateActuatorOutputStatus":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateActuatorOutputStatus(request: request, context: context)
}
}
case "SetRateOdometry":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateOdometry(request: request, context: context)
}
}
case "SetRatePositionVelocityNed":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRatePositionVelocityNed(request: request, context: context)
}
}
case "SetRateGroundTruth":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateGroundTruth(request: request, context: context)
}
}
case "SetRateFixedwingMetrics":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateFixedwingMetrics(request: request, context: context)
}
}
case "SetRateImu":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateImu(request: request, context: context)
}
}
case "SetRateUnixEpochTime":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateUnixEpochTime(request: request, context: context)
}
}
case "SetRateDistanceSensor":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.setRateDistanceSensor(request: request, context: context)
}
}
case "GetGpsGlobalOrigin":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
self.getGpsGlobalOrigin(request: request, context: context)
}
}
default: return nil
}
}
}
| 47.423666 | 246 | 0.76788 |
299e84d89d327a76f09980405fdfe23f8f65cc76 | 663 | //
// TesteCleanCVCCollectionViewCell.swift
// BooksOnTheTable
//
// Created by José Inácio Athayde Ferrarini on 07/04/21.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
// MARK: - Protocols
protocol TesteCleanCVCCollectionViewCellProtocol {
func setup(with value: TesteCleanCVC.UseCase.ViewModel.DisplayData)
}
class TesteCleanCVCCollectionViewCell: UICollectionViewCell, TesteCleanCVCCollectionViewCellProtocol {
// MARK: - Outlets
@IBOutlet weak var label: UILabel!
// MARK: - Public Methods
func setup(with value: TesteCleanCVC.UseCase.ViewModel.DisplayData) {
label.text = value.title
}
}
| 22.1 | 102 | 0.758673 |
200a109267672436b0a23be53a90912e1d5979e1 | 4,616 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import ReactiveKit
import UIKit
private func applyRowUnitChangeSet<C: CollectionChangesetType where C.Collection.Index == Int>(changeSet: C, tableView: UITableView, sectionIndex: Int) {
if changeSet.inserts.count > 0 {
let indexPaths = changeSet.inserts.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
if changeSet.updates.count > 0 {
let indexPaths = changeSet.updates.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
if changeSet.deletes.count > 0 {
let indexPaths = changeSet.deletes.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
}
extension StreamType where Element: ArrayConvertible {
public func bindTo(tableView: UITableView, animated: Bool = true, createCell: (NSIndexPath, [Element.Element], UITableView) -> UITableViewCell) -> Disposable {
return map { CollectionChangeset.initial($0.toArray()) }.bindTo(tableView, animated: animated, createCell: createCell)
}
}
extension StreamType where Element: CollectionChangesetType, Element.Collection.Index == Int, Event.Element == Element {
public func bindTo(tableView: UITableView, animated: Bool = true, createCell: (NSIndexPath, Element.Collection, UITableView) -> UITableViewCell) -> Disposable {
typealias Collection = Element.Collection
let dataSource = tableView.rDataSource
let numberOfItems = Property(0)
let collection = Property<Collection!>(nil)
dataSource.feed(
collection,
to: #selector(UITableViewDataSource.tableView(_:cellForRowAtIndexPath:)),
map: { (value: Collection!, tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell in
return createCell(indexPath, value, tableView)
})
dataSource.feed(
numberOfItems,
to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)),
map: { (value: Int, _: UITableView, _: Int) -> Int in value }
)
dataSource.feed(
Property(1),
to: #selector(UITableViewDataSource.numberOfSectionsInTableView(_:)),
map: { (value: Int, _: UITableView) -> Int in value }
)
tableView.reloadData()
let serialDisposable = SerialDisposable(otherDisposable: nil)
serialDisposable.otherDisposable = observeNext { [weak tableView] event in
ImmediateOnMainExecutionContext {
guard let tableView = tableView else { serialDisposable.dispose(); return }
let justReload = collection.value == nil
collection.value = event.collection
numberOfItems.value = event.collection.count
if justReload || !animated || event.inserts.count + event.deletes.count + event.updates.count == 0 {
tableView.reloadData()
} else {
tableView.beginUpdates()
applyRowUnitChangeSet(event, tableView: tableView, sectionIndex: 0)
tableView.endUpdates()
}
}
}
return serialDisposable
}
}
extension UITableView {
public var rDelegate: ProtocolProxy {
return protocolProxyFor(UITableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var rDataSource: ProtocolProxy {
return protocolProxyFor(UITableViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
| 40.849558 | 162 | 0.72812 |
f5ce40ebf6fd42a8242a55aa57a9f457e816dd07 | 3,217 | //
// ViewController.swift
// Consulta de sitios
//
// Created by d182_raul_j on 02/03/18.
// Copyright © 2018 d182_raul_j. All rights reserved.
//
//Si la extension la haces al protocolo obligas a la clase a usarla
import UIKit
import Foundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var userTxt: UITextField!
@IBOutlet weak var passTxt: UITextField!
@IBOutlet var loading: UIActivityIndicatorView!
@IBOutlet weak var checkBoxButton: UIButton!
//@IBAction weak var accessButton: UIButton!
@IBAction func login(_ sender: UIButton) {
print("Accede"+userTxt.text!+","+passTxt.text!)
/***Conexion******///
let username = "ARREN\\TST01"
let password = "JXF83V"
var resultadoString = ""
//let username = "ARREN\\"+userTxt.text!
//let password = passTxt.text!
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString3 = loginData.base64EncodedString()
if let someURL = URL(string: "https://apptelesitestest.azurewebsites.net/login") {
var req = URLRequest(url: someURL)
// This changes the HTTP method in the request line
req.httpMethod = "GET"
req.setValue("Basic \(base64LoginString3)", forHTTPHeaderField: "Authorization")
req.setValue("2", forHTTPHeaderField: "AUTHMODE")
NSURLConnection.sendAsynchronousRequest(req, queue: OperationQueue.main) {(response, data, error) in
//print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
var resultado = (NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
print(resultado!)
resultadoString = resultado! as String
//if( resultado == "\"OK\""){
print("todo bien")
let alert = UIAlertController(title: "¿Almacenar credenciales?", message: "¿Deseas guardar tus credenciales para iniciar sesión?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Si", style: .default) { action in
debugPrint(action)
self.performSegue(withIdentifier: "Menu", sender: nil)
}
let cancelAction = UIAlertAction(title: "No", style: .destructive) { action in
debugPrint(action)
self.performSegue(withIdentifier: "Menu", sender: nil)
}
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
//}
}
}
/***Fin Conexion******///
}
}
| 37.406977 | 170 | 0.585639 |
7aa4e9f8bad2e727dc578ea8b6e732e7932ae8a7 | 19,520 | //
// SIMSChannel.swift
// ginlo
//
// Created by RBU on 19/10/15.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import CoreData
import Foundation
class SIMSChannel: SIMSManagedObject {
@NSManaged var aes_key: String?
@NSManaged var checksum: String?
@NSManaged var iv: String?
@NSManaged var layout: String?
@NSManaged var name_long: String?
@NSManaged var name_short: String?
@NSManaged var options: String?
@NSManaged var subscribed: NSNumber?
@NSManaged var additionalData: String?
@NSManaged var assets: Set<SIMSChannelAsset>?
@NSManaged var rootOptions: NSOrderedSet?
@NSManaged var stream: SIMSChannelStream?
@NSManaged var feedType: NSNumber?
@objc
public class func entityName() -> String {
DPAGStrings.CoreData.Entities.CHANNEL
}
var validFeedType: DPAGChannelType {
DPAGChannelType(rawValue: self.feedType?.intValue ?? DPAGChannelType.channel.rawValue) ?? .channel
}
private lazy var extendedDict: [String: Any] = [:]
private var _promotedCategoryIdents: [String]?
private var _promotedCategoryExternalUrls: [String: String]?
func updateWithDictionary(_ dict: [String: Any]) {
self.name_long = dict[DPAGStrings.JSON.Channel.DESC] as? String
self.name_short = dict[DPAGStrings.JSON.Channel.DESC_SHORT] as? String
self.options = dict[DPAGStrings.JSON.Channel.OPTIONS] as? String
self.aes_key = dict[DPAGStrings.JSON.Channel.AES_KEY] as? String
self.iv = dict[DPAGStrings.JSON.Channel.IV] as? String
self.updateTextsWithDict(dict)
self.updatePromotedWithDict(dict)
if let dictLayout = dict[DPAGStrings.JSON.Channel.LAYOUT] as? [String: Any] {
self.updateLayoutWithDict(dictLayout)
}
if let rootOptions = self.rootOptions {
let rootOptionsOld = NSOrderedSet(orderedSet: rootOptions)
for rootOption in rootOptionsOld {
(rootOption as? SIMSChannelOption)?.channel = nil
}
}
if let items = dict[DPAGStrings.JSON.ChannelOption.SUBITEMS] as? [[String: Any]] {
for item in items {
if let managedObjectContext = self.managedObjectContext, let rootOption = SIMSChannelOption.optionForDict(item, channel: self.guid ?? "???", in: managedObjectContext) {
rootOption.channel = self
}
}
}
if let channelDefinition = dict.JSONString {
self.layout = channelDefinition
}
}
func loadExtendedData() {
if self.layout == nil {
return
}
if let data = self.layout?.data(using: .utf8) {
do {
if let item = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
self.loadExtendedDataWithDict(item)
}
} catch {
DPAGLog(error)
}
}
}
func loadExtendedDataWithDict(_ dict: [String: Any]) {
DPAGLog("loadExtendedDataWithDict for channel %@", self.guid ?? "")
self.updateTextsWithDict(dict)
self.updatePromotedWithDict(dict)
self.updateLayoutWithDict(dict)
self.updateAdditionalDataWithDict(dict)
}
func updatePromotedWithDict(_ dict: [String: Any]) {
if let dictPromoted = dict[DPAGStrings.JSON.Channel.PROMOTED] as? [String: Any], let promEnabled = dictPromoted[DPAGStrings.JSON.Channel.PROMOTED_ENABLED] as? String {
self.extendedDict["_promoted"] = NSNumber(value: (promEnabled.lowercased() == "true") as Bool)
self.extendedDict["_externalURL"] = dictPromoted[DPAGStrings.JSON.Channel.PROMOTED_EXTERNAL_URL] as? String
} else {
self.extendedDict.removeValue(forKey: "_promoted")
self.extendedDict.removeValue(forKey: "_externalURL")
}
self._promotedCategoryIdents = []
self._promotedCategoryExternalUrls = [:]
if let arrPromotedCategory = dict[DPAGStrings.JSON.Channel.PROMOTED_CATEGORY] as? [[String: Any]] {
for dictPromoCat in arrPromotedCategory {
if let catIdent = dictPromoCat[DPAGStrings.JSON.Channel.PROMOTED_CATEGORY_IDENT] as? String {
self._promotedCategoryIdents?.append(catIdent)
if let externalURL = dictPromoCat[DPAGStrings.JSON.Channel.PROMOTED_EXTERNAL_URL] as? String {
self._promotedCategoryExternalUrls?[catIdent] = externalURL
}
}
}
}
}
func promotedCategoryExternalUrls() -> [String: String]? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> [String: String]? in
if self._promotedCategoryExternalUrls == nil {
if self.layout == nil {
return nil
}
self.loadExtendedData()
}
return self._promotedCategoryExternalUrls
}
}
func promotedCategoryIdents() -> [String]? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> [String]? in
if self._promotedCategoryIdents == nil {
if self.layout == nil {
return []
}
self.loadExtendedData()
}
return self._promotedCategoryIdents
}
}
func updateAdditionalDataWithDict(_ dict: [String: Any]) {
if let serviceID = dict[DPAGStrings.JSON.Channel.SERVICE_ID] as? String {
self.extendedDict["_serviceID"] = serviceID
}
}
func updateTextsWithDict(_ dict: [String: Any]) {
self.extendedDict["_searchText"] = dict[DPAGStrings.JSON.Channel.SEARCH_TEXT] as? String ?? ""
self.extendedDict["_welcomeText"] = dict[DPAGStrings.JSON.Channel.WELCOME_TEXT] as? String ?? ""
self.extendedDict["_recommendationText"] = dict[DPAGStrings.JSON.Channel.RECOMMENDATION_TEXT] as? String ?? ""
self.extendedDict["_contentLinkReplacer"] = dict[DPAGStrings.JSON.Channel.LINK_REPLACER] as? String ?? ""
self.extendedDict["_contentLinkReplacerRegex"] = dict[DPAGStrings.JSON.Channel.LINK_REPLACER] as? [[String: String]] ?? []
if let dictFeedback = dict[DPAGStrings.JSON.Channel.FEEDBACK_CONTACT] as? [String: Any] {
self.extendedDict["_feedbackContactNickname"] = dictFeedback[DPAGStrings.JSON.Channel.FEEDBACK_CONTACT_NICKNAME] as? String ?? ""
self.extendedDict["_feedbackContactPhoneNumber"] = dictFeedback[DPAGStrings.JSON.Channel.FEEDBACK_CONTACT_PHONENUMBER] as? String ?? ""
} else {
self.extendedDict["_feedbackContactNickname"] = ""
self.extendedDict["_feedbackContactPhoneNumber"] = ""
}
}
func updateLayoutWithDict(_ dict: [String: Any]) {
let dictLayout = dict[DPAGStrings.JSON.Channel.LAYOUT] as? [String: Any] ?? dict
self.scanDict(dictLayout, forColorKey: DPAGStrings.JSON.Channel.LAYOUT_COLOR_LABEL_DISABLED, valueKey: "_colorDetailsLabelDisabled")
self.scanDict(dictLayout, forColorKey: DPAGStrings.JSON.Channel.LAYOUT_COLOR_LABEL_ENABLED, valueKey: "_colorDetailsLabelEnabled")
self.scanDict(dictLayout, forColorKey: DPAGStrings.JSON.Channel.LAYOUT_COLOR_TEXT, valueKey: "_colorDetailsText")
self.scanDict(dictLayout, forColorKey: "settings_color_toggle", valueKey: "_colorDetailsToggle")
self.scanDict(dictLayout, forColorKey: "settings_color_toggle_off", valueKey: "_colorDetailsToggleOff")
self.scanDict(dictLayout, forColorKey: "settings_color_button_follow", valueKey: "_colorDetailsButtonFollow")
self.scanDict(dictLayout, forColorKey: "settings_color_button_follow_text", valueKey: "_colorDetailsButtonFollowText")
self.scanDict(dictLayout, forColorKey: "settings_color_button_follow_disabled", valueKey: "_colorDetailsButtonFollowDisabled")
self.scanDict(dictLayout, forColorKey: "settings_color_button_follow_text_disabled", valueKey: "_colorDetailsButtonFollowTextDisabled")
self.scanDict(dictLayout, forColorKey: "asset_ib_color", valueKey: "_colorDetailsBackgroundLogo")
self.scanDict(dictLayout, forColorKey: "asset_cb_color", valueKey: "_colorDetailsBackground")
self.scanDict(dictLayout, forColorKey: "overview_color_time", valueKey: "_colorChatListDate")
self.scanDict(dictLayout, forColorKey: "overview_color_name", valueKey: "_colorChatListName")
self.scanDict(dictLayout, forColorKey: "overview_color_preview", valueKey: "_colorChatListPreview")
self.scanDict(dictLayout, forColorKey: "overview_bkcolor_bubble", valueKey: "_colorChatListBadge")
self.scanDict(dictLayout, forColorKey: "overview_color_bubble", valueKey: "_colorChatListBadgeText")
self.scanDict(dictLayout, forColorKey: "asset_ib_color", valueKey: "_colorChatListBackground")
self.scanDict(dictLayout, forColorKey: "asset_cb_color", valueKey: "_colorChatBackground")
self.scanDict(dictLayout, forColorKey: "asset_ib_color", valueKey: "_colorChatBackgroundLogo")
self.scanDict(dictLayout, forColorKey: "msg_color_time", valueKey: "_colorChatMessageDate")
self.scanDict(dictLayout, forColorKey: "msg_color_section_active", valueKey: "_colorChatMessageSection")
self.scanDict(dictLayout, forColorKey: "msg_color_section_inactive", valueKey: "_colorChatMessageSectionPre")
self.scanDict(dictLayout, forColorKey: "msg_color_bubble", valueKey: "_colorChatMessageBubble")
self.scanDict(dictLayout, forColorKey: "msg_color_bubble_welcome", valueKey: "_colorChatMessageBubbleWelcome")
self.scanDict(dictLayout, forColorKey: "msg_color_bubble_welcome_text", valueKey: "_colorChatMessageBubbleWelcomeText")
self.scanDict(dictLayout, forColorKey: "head_bkcolor", valueKey: "_colorNavigationbar")
self.scanDict(dictLayout, forColorKey: "head_color", valueKey: "_colorNavigationbarText")
self.scanDict(dictLayout, forColorKey: "menu_bkcolor", valueKey: "_colorMenu")
self.scanDict(dictLayout, forColorKey: "menu_color", valueKey: "_colorMenuText")
}
func scanDict(_ dictLayout: [String: Any], forColorKey dictKey: String, valueKey: String) {
if let colorToParseDict = dictLayout[dictKey] as? String {
if let color = UIColor.scanColor(colorToParseDict) {
self.extendedDict[valueKey] = color
}
}
}
func colorWithKey(_ colorKey: String, colorDefault: UIColor?) -> UIColor? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> UIColor? in
if self.extendedDict[colorKey] == nil {
if self.layout == nil {
return colorDefault
}
self.loadExtendedData()
}
return (self.extendedDict[colorKey] as? UIColor) ?? colorDefault
}
}
func textWithKey(_ textKey: String) -> String? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> String? in
if self.extendedDict[textKey] == nil {
if self.layout == nil {
return nil
}
self.loadExtendedData()
}
return self.extendedDict[textKey] as? String
}
}
func additionalDataWithKey(_ key: String) -> String? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> String? in
if self.extendedDict[key] == nil {
if self.layout == nil {
return nil
}
self.loadExtendedData()
}
return self.extendedDict[key] as? String
}
}
var colorDetailsLabelEnabled: UIColor? {
self.colorWithKey("_colorDetailsLabelEnabled", colorDefault: nil)
}
var colorDetailsLabelDisabled: UIColor? {
self.colorWithKey("_colorDetailsLabelDisabled", colorDefault: nil)
}
var colorDetailsText: UIColor? {
self.colorWithKey("_colorDetailsText", colorDefault: nil)
}
var colorDetailsToggle: UIColor? {
self.colorWithKey("_colorDetailsToggle", colorDefault: nil)
}
var colorDetailsToggleOff: UIColor? {
self.colorWithKey("_colorDetailsToggleOff", colorDefault: nil)
}
var colorDetailsButtonFollow: UIColor? {
self.colorWithKey("_colorDetailsButtonFollow", colorDefault: nil)
}
var colorDetailsButtonFollowText: UIColor? {
self.colorWithKey("_colorDetailsButtonFollowText", colorDefault: nil)
}
var colorDetailsButtonFollowDisabled: UIColor? {
self.colorWithKey("_colorDetailsButtonFollowDisabled", colorDefault: nil)
}
var colorDetailsButtonFollowTextDisabled: UIColor? {
self.colorWithKey("_colorDetailsButtonFollowTextDisabled", colorDefault: nil)
}
var colorDetailsBackground: UIColor? {
self.colorWithKey("_colorDetailsBackground", colorDefault: nil)
}
var colorDetailsBackgroundLogo: UIColor? {
self.colorWithKey("_colorDetailsBackgroundLogo", colorDefault: nil)
}
var colorChatListDate: UIColor? {
self.colorWithKey("_colorChatListDate", colorDefault: nil)
}
var colorChatListName: UIColor? {
self.colorWithKey("_colorChatListName", colorDefault: nil)
}
var colorChatListPreview: UIColor? {
self.colorWithKey("_colorChatListPreview", colorDefault: nil)
}
var colorChatListBadge: UIColor? {
self.colorWithKey("_colorChatListBadge", colorDefault: nil)
}
var colorChatListBadgeText: UIColor? {
self.colorWithKey("_colorChatListBadgeText", colorDefault: nil)
}
var colorChatListBackground: UIColor? {
self.colorWithKey("_colorChatListBackground", colorDefault: nil)
}
var colorChatBackground: UIColor? {
self.colorWithKey("_colorChatBackground", colorDefault: nil)
}
var colorChatBackgroundLogo: UIColor? {
self.colorWithKey("_colorChatBackgroundLogo", colorDefault: nil)
}
var colorChatMessageDate: UIColor? {
self.colorWithKey("_colorChatMessageDate", colorDefault: nil)
}
var colorChatMessageSection: UIColor? {
self.colorWithKey("_colorChatMessageSection", colorDefault: nil)
}
var colorChatMessageSectionPre: UIColor? {
self.colorWithKey("_colorChatMessageSectionPre", colorDefault: nil)
}
var colorChatMessageBubble: UIColor? {
self.colorWithKey("_colorChatMessageBubble", colorDefault: nil)
}
var colorChatMessageBubbleWelcome: UIColor? {
self.colorWithKey("_colorChatMessageBubbleWelcome", colorDefault: nil)
}
var colorChatMessageBubbleWelcomeText: UIColor? {
self.colorWithKey("_colorChatMessageBubbleWelcomeText", colorDefault: nil)
}
var colorNavigationbar: UIColor? {
self.colorWithKey("_colorNavigationbar", colorDefault: nil)
}
var colorNavigationbarText: UIColor? {
switch self.validFeedType {
case .channel:
return self.colorWithKey("_colorNavigationbarText", colorDefault: nil)
}
}
var colorNavigationbarAction: UIColor? {
self.colorWithKey("_colorNavigationbarText", colorDefault: nil)
}
var colorMenu: UIColor? {
self.colorWithKey("_colorMenu", colorDefault: nil)
}
var colorMenuText: UIColor? {
self.colorWithKey("_colorMenuText", colorDefault: nil)
}
var searchText: String? {
self.textWithKey("_searchText")
}
var welcomeText: String? {
self.textWithKey("_welcomeText")
}
var recommendationText: String? {
self.textWithKey("_recommendationText")
}
var contentLinkReplacer: String? {
self.textWithKey("_contentLinkReplacer")
}
var contentLinkReplacerRegex: [DPAGContentLinkReplacerString]? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> [DPAGContentLinkReplacerString] in
if self.extendedDict["_contentLinkReplacerRegex"] == nil {
if self.layout == nil {
return []
}
self.loadExtendedData()
}
if let replacerArr = self.extendedDict["_contentLinkReplacerRegex"] as? [[String: String]] {
var retVal: [DPAGContentLinkReplacerString] = []
for replacerItem in replacerArr {
if let regEx = replacerItem["regex"], let replacer = replacerItem["value"] {
retVal.append(DPAGContentLinkReplacerString(pattern: regEx, replacer: replacer))
}
}
return retVal
}
return []
}
}
var feedbackContactPhoneNumber: String? {
self.textWithKey("_feedbackContactPhoneNumber")
}
var feedbackContactNickname: String? {
self.textWithKey("_feedbackContactNickname")
}
var serviceID: String? {
self.additionalDataWithKey("_serviceID")
}
var isHidden: Bool {
self.options?.components(separatedBy: ",").contains("hiddenChannel") ?? false
}
var isReadOnly: Bool {
self.options?.components(separatedBy: ",").contains("readOnly") ?? false
}
var isMandatory: Bool {
self.options?.components(separatedBy: ",").contains("mandatory") ?? false
}
var isRecommended: Bool {
self.options?.components(separatedBy: ",").contains("recommended") ?? false
}
var isPromoted: Bool {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> Bool in
if self.extendedDict["_promoted"] == nil {
if self.layout == nil {
return false
}
self.loadExtendedData()
}
return (self.extendedDict["_promoted"] as? NSNumber)?.boolValue ?? false
}
}
var externalURL: String? {
DPAGFunctionsGlobal.synchronizedReturn(self) { () -> String? in
if self.extendedDict["_externalURL"] == nil, self.isPromoted {
if self.layout == nil {
return nil
}
}
return self.extendedDict["_externalURL"] as? String
}
}
var notificationEnabled: Bool {
get {
if let value = DPAGApplicationFacade.preferences[String(format: "%@-%@", self.guid ?? "-", DPAGPreferences.PropString.kNotificationChannelChatEnabled.rawValue)] as? String {
return value != DPAGPreferences.kValueNotificationDisabled
}
// default ist true
return true
}
set {
let key = String(format: "%@-%@", self.guid ?? "-", DPAGPreferences.PropString.kNotificationChannelChatEnabled.rawValue)
DPAGApplicationFacade.preferences[key] = newValue ? DPAGPreferences.kValueNotificationEnabled : DPAGPreferences.kValueNotificationDisabled
}
}
func currentFilter() -> String {
var dictFilter: [String: [String]] = [:]
if let rootOptions = self.rootOptions {
for rootOptionObj in rootOptions {
if let rootOption = rootOptionObj as? SIMSChannelOption {
dictFilter = DPAGChannelOption.mergeFilterDicts(dictFilter, dict2: rootOption.filterForCurrentValue())
}
}
}
return DPAGChannel.joinFilter(dictFilter)
}
}
| 40.582121 | 185 | 0.652715 |
5003e4ac05fee13b5fc65dacc649093ed4f82210 | 2,660 | //
// Set.swift
// LearnDataStructures
//
// Created by Weipeng Qi on 2020/3/28.
// Copyright © 2020 Weipeng Qi. All rights reserved.
//
import Foundation
/*
集合协议,这里为了不和系统重名,命名为 MySet
集合分为有序集合与无序集合;二分搜索树实现的集合,包括 Java 中的 TreeSet 使用红黑树实现,都是有序集合,因为这个集合中的元素是有序排列的。
但是很多时候可能使用集合不会使用到集合到有序性,那么性能更好的无序集合就更适合。这里使用链表实现的集合虽然也是无序的,但是性能不好,但是如果使用哈希表实现,性能就很好了。
*/
public protocol MySet {
associatedtype Element
var isEmpty: Bool { get }
var count: Int { get }
func insert(_ newMember: Element)
func remove(_ member: Element)
func contains(_ member: Element) -> Bool
}
/*
链表实现的集合。
各个操作时间复杂度:
func insert(_ newMember: Element) O(n)
func remove(_ member: Element) O(n)
func contains(_ member: Element) -> Bool O(n)
对于链表来说,由于没有索引,删除指定元素和查询指定元素都需要遍历,复杂度为 O(n),添加元素操作由于要判重,也需要进行一次遍历,所以复杂度也是 O(n)。
*/
public struct LinkedListSet<Element: Equatable>: MySet {
private let linkedList = LinkedList<Element>()
public var isEmpty: Bool {
return linkedList.isEmpty
}
public var count: Int {
return linkedList.count
}
public func insert(_ newMember: Element) {
if !linkedList.contains(newMember) {
linkedList.insert(newMember, at: 0)
}
}
public func remove(_ member: Element) {
linkedList.removeAll { $0 == member }
}
public func contains(_ member: Element) -> Bool {
return linkedList.contains(member)
}
}
/*
二分搜索树实现的集合。
各个操作时间复杂度: 复杂度 平均 最差
func insert(_ newMember: Element) O(h) O(logn) O(n)
func remove(_ member: Element) O(h) O(logn) O(n)
func contains(_ member: Element) -> Bool O(h) O(logn) O(n)
对于二分搜索树集合,它的增查删其实只是寻找了树的层树,我们用 h 表示
最好的情况,也就是树是满的情况下层数和元素数的关系是 2^h - 1 = n,h = log(n + 1) (log底是 2)
那么最好情况的复杂度就是 O(logn) 级别的,这其实很接近 O(1) 级别,在数据量大的时候要比 O(n) 好得多
但是对于二分搜索树来说,如果添加元素的时候恰好是从小到大或者相反地插入元素,这棵树就退化成链表了。
要解决这个问题,就要使用平衡二叉树。
二分搜索树实现的集合整体性能是高于链表集合的。
*/
public struct BinarySearchTreeSet<Element: Comparable>: MySet {
private let binarySearchTree = BinarySearchTree<Element>()
public var isEmpty: Bool {
return binarySearchTree.isEmpty
}
public var count: Int {
return binarySearchTree.count
}
public func insert(_ newMember: Element) {
binarySearchTree.insert(newMember)
}
public func remove(_ member: Element) {
binarySearchTree.remove(member)
}
public func contains(_ member: Element) -> Bool {
binarySearchTree.contains(member)
}
}
| 24.62963 | 86 | 0.635714 |
22ed4346967f2826d9de5301fc57be3b19cb43e7 | 322 | //
// UIImageView+Extensions.swift
//
// Created by Vignesh J on 09/10/20.
//
import UIKit
extension UIImageView {
public func set(imageColor color: UIColor) {
let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
}
| 18.941176 | 74 | 0.661491 |
677d4b84f6e44c1042160cc7ee7241c0b3698ad8 | 391 | //
// DoubleEndedQueueProtocol.swift
// Deque
//
// Created by Beka on 31/07/21.
//
import Foundation
protocol DoubleEndedQueue {
associatedtype Element
var isEmpty: Bool { get }
func peek(from direction: Direction) -> Element?
mutating func enqueue(_ element: Element, to direction: Direction) -> Bool
mutating func dequeue(from direction: Direction) -> Element?
}
| 20.578947 | 76 | 0.705882 |