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
|
---|---|---|---|---|---|
b98244bf1cee7d1b8bc4f55c9ae0779dc09f0e8e | 385 | //
// WinningConditions.swift
// MyLotto
//
// Created by Andre Heß on 17/04/16.
// Copyright © 2016 Andre Heß. All rights reserved.
//
import UIKit
class WinningConditions: NSObject {
var winningNumbers:NSInteger
var needsSuperZahl:Bool
var needsZusatzZahl:Bool
override init() {
self.winningNumbers = 0
self.needsSuperZahl = false
self.needsZusatzZahl = false
}
}
| 17.5 | 52 | 0.727273 |
7283d9ce7f4c4e6d26718fd2ad4e18f4723ee53b | 4,510 | /*
Copyright © 2019 OST.com 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
*/
import Foundation
class OstLogoutAllSessionSigner {
private let nullAddress = "0x0000000000000000000000000000000000000000"
private let abiMethodNameForLogout = "logout"
private let userId: String
private let keyManagerDelegate: OstKeyManagerDelegate
/// Initialize
///
/// - Parameters:
/// - userId: User Id
/// - keyManagerDelegate: OstKeyManagerDelegate
init(userId: String,
keyManagerDelegate: OstKeyManagerDelegate) {
self.userId = userId
self.keyManagerDelegate = keyManagerDelegate
}
/// Get Api parameters for logout all sessions
///
/// - Returns: Api parameters
/// - Throws: OstError
func getApiParams() throws -> [String: Any] {
guard let user = try OstUser.getById(self.userId) else {
throw OstError("s_ecki_lass_gap_1", .invalidUserId)
}
guard let deviceManager: OstDeviceManager = try OstDeviceManager.getById(user.deviceManagerAddress!) else {
throw OstError("s_ecki_lass_gap_2", .deviceManagerNotFound)
}
let encodedABIHex = try TokenHolder().getLogoutExecutableData()
let deviceManagerNonce: Int = deviceManager.nonce
let typedDataInput: [String: Any] = try GnosisSafe().getSafeTxData(verifyingContract: deviceManager.address!,
to: user.tokenHolderAddress!,
value: "0",
data: encodedABIHex,
operation: "0",
safeTxGas: "0",
dataGas: "0",
gasPrice: "0",
gasToken: self.nullAddress,
refundReceiver: self.nullAddress,
nonce: OstUtils.toString(deviceManagerNonce)!)
let eip712: EIP712 = EIP712(types: typedDataInput["types"] as! [String: Any],
primaryType: typedDataInput["primaryType"] as! String,
domain: typedDataInput["domain"] as! [String: String],
message: typedDataInput["message"] as! [String: Any])
let signingHash = try! eip712.getEIP712Hash()
let signature = try self.keyManagerDelegate.signWithDeviceKey(signingHash)
let signer = self.keyManagerDelegate.getDeviceAddress()
let rawCallData: String = getRawCallData()
let params: [String: Any] = ["to": user.tokenHolderAddress!,
"value": "0",
"calldata": encodedABIHex,
"raw_calldata": rawCallData,
"operation": "0",
"safe_tx_gas": "0",
"data_gas": "0",
"gas_price": "0",
"nonce": OstUtils.toString(deviceManagerNonce)!,
"gas_token": self.nullAddress,
"refund_receiver": self.nullAddress,
"signers": [signer],
"signatures": signature
]
try deviceManager.incrementNonce()
return params
}
/// Get raw call data for logout
///
/// - Returns: Raw calldata JSON string
private func getRawCallData() -> String {
let callData: [String: Any] = ["method": self.abiMethodNameForLogout,
"parameters":[]]
return try! OstUtils.toJSONString(callData)!
}
}
| 45.1 | 121 | 0.46918 |
2991a361ee957cd6ecf2251b02061802da689234 | 831 | //
// CalendarDateRangePickerHeaderView.swift
// CalendarDateRangePickerViewController
//
// Created by Miraan on 15/10/2017.
// Copyright © 2017 Miraan. All rights reserved.
//
import UIKit
class CalendarDateRangePickerHeaderView: UICollectionReusableView {
var label: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
initLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
initLabel()
}
func initLabel() {
label = UILabel(frame: frame)
label.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
label.font = .busyBeesTitle
label.textColor = UIColor.darkGray
label.textAlignment = NSTextAlignment.center
self.addSubview(label)
}
}
| 23.742857 | 81 | 0.641396 |
9b1f3a32cc8236292578d162d1337c18069a0fd0 | 164 | //
// Decade_of_MoviesUITests.swift
// Decade of MoviesUITests
//
// Created by marko nazmy on 7/17/20.
// Copyright © 2020 MarkoNazmy. All rights reserved.
//
| 20.5 | 53 | 0.70122 |
2133508e117289e937688a9904b6db1b4221d969 | 50,575 | //
// Copyright © 2019 Frollo. 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 CoreData
import XCTest
@testable import FrolloSDK
import OHHTTPStubs
#if canImport(OHHTTPStubsSwift)
import OHHTTPStubsSwift
#endif
class ReportsTests: XCTestCase {
let keychainService = "ReportsTests"
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
HTTPStubs.removeAllStubs()
Keychain(service: keychainService).removeAll()
}
// MARK: - Account Balance Report Tests
func testFetchAccountBalanceReports() {
let expectation1 = expectation(description: "Completion")
let config = FrolloSDKConfiguration.testConfig()
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let managedObjectContext = database.newBackgroundContext()
managedObjectContext.performAndWait {
let testReport1 = ReportAccountBalance(context: managedObjectContext)
testReport1.populateTestData()
testReport1.dateString = "2018-02-01"
testReport1.period = .day
let testReport2 = ReportAccountBalance(context: managedObjectContext)
testReport2.populateTestData()
testReport2.dateString = "2018-01"
testReport2.period = .month
let testReport3 = ReportAccountBalance(context: managedObjectContext)
testReport3.populateTestData()
testReport3.dateString = "2018-01-01"
testReport3.period = .day
let testReport4 = ReportAccountBalance(context: managedObjectContext)
testReport4.populateTestData()
testReport4.dateString = "2018-01-01"
testReport4.period = .day
try! managedObjectContext.save()
}
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2017-06-01")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-01-31")!
let fetchedReports = reports.accountBalanceReports(context: database.viewContext, from: fromDate, to: toDate, period: .day)
XCTAssertNotNil(fetchedReports)
XCTAssertEqual(fetchedReports?.count, 2)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 5)
}
func testRefreshingAccountBalanceReportsFailsIfLoggedOut() {
let expectation1 = expectation(description: "Network Request 1")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_day_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication(valid: false)
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .day, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTAssertNotNil(error)
if let loggedOutError = error as? DataError {
XCTAssertEqual(loggedOutError.type, .authentication)
XCTAssertEqual(loggedOutError.subType, .missingAccessToken)
} else {
XCTFail("Wrong error type returned")
}
case .success:
XCTFail("User logged out, request should fail")
}
expectation1.fulfill()
}
}
wait(for: [expectation1], timeout: 10.0)
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsByDay() {
let expectation1 = expectation(description: "Network Request 1")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_day_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .day, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let context = database.viewContext
// Check for overall reports
let fetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
fetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.day.rawValue])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedReports = try context.fetch(fetchRequest)
XCTAssertEqual(fetchedReports.count, 661)
if let firstReport = fetchedReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10-28")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .day)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-1191.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
}
}
}
wait(for: [expectation1], timeout: 10.0)
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsByMonth() {
let expectation1 = expectation(description: "Network Request 1")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_month_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .month, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let context = database.viewContext
// Check for overall reports
let fetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
fetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.month.rawValue])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedReports = try context.fetch(fetchRequest)
XCTAssertEqual(fetchedReports.count, 31)
if let firstReport = fetchedReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .month)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "208.55"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
}
}
}
wait(for: [expectation1], timeout: 10.0)
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsByWeek() {
let expectation1 = expectation(description: "Network Request 1")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_week_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .week, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let context = database.viewContext
// Check for overall reports
let fetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
fetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.week.rawValue])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedReports = try context.fetch(fetchRequest)
XCTAssertEqual(fetchedReports.count, 122)
if let firstReport = fetchedReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10-4")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .week)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-1191.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
}
}
}
wait(for: [expectation1], timeout: 10.0)
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsByAccountID() {
let expectation1 = expectation(description: "Network Request 1")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_day_account_id_937_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .day, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let context = database.viewContext
// Check for overall reports
let fetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
fetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@ && " + #keyPath(ReportAccountBalance.accountID) + " == %ld", argumentArray: [ReportAccountBalance.Period.day.rawValue, 937])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedReports = try context.fetch(fetchRequest)
XCTAssertEqual(fetchedReports.count, 94)
if let firstReport = fetchedReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10-28")
XCTAssertEqual(firstReport.accountID, 937)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .day)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-2641.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
expectation1.fulfill()
}
}
}
}
wait(for: [expectation1], timeout: 10.0)
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsByAccountType() {
let expectation1 = expectation(description: "Database Setup")
let expectation2 = expectation(description: "Network Request 1")
let expectation3 = expectation(description: "Network Request 2")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + AggregationEndpoint.accounts.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "accounts_valid", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_day_container_bank_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
aggregation.refreshAccounts() { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
expectation2.fulfill()
}
}
wait(for: [expectation2], timeout: 3.0)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .day, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
expectation3.fulfill()
}
}
wait(for: [expectation3], timeout: 5.0)
let context = database.viewContext
// Check for overall reports
let fetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
fetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@ && " + #keyPath(ReportAccountBalance.account.accountTypeRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.day.rawValue, Account.AccountType.bank.rawValue])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedReports = try context.fetch(fetchRequest)
XCTAssertEqual(fetchedReports.count, 376)
if let lastReport = fetchedReports.last {
XCTAssertEqual(lastReport.dateString, "2019-01-29")
XCTAssertEqual(lastReport.accountID, 938)
XCTAssertEqual(lastReport.currency, "AUD")
XCTAssertEqual(lastReport.period, .day)
XCTAssertEqual(lastReport.value, NSDecimalNumber(string: "42000"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
HTTPStubs.removeAllStubs()
}
func testFetchingAccountBalanceReportsUpdatesExisting() {
let expectation1 = expectation(description: "Database Setup")
let expectation2 = expectation(description: "Network Request 1")
let expectation3 = expectation(description: "Network Request 2")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
if let requestURL = request.url, let queryItems = URLComponents(url: requestURL, resolvingAgainstBaseURL: true)?.queryItems {
var fromDate: String = ""
for queryItem in queryItems {
if queryItem.name == "from_date", let value = queryItem.value {
fromDate = value
}
}
if fromDate == "2018-10-29" {
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_month_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
} else if fromDate == "2018-11-01" {
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_month_2018-11-01_2019-02-01", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
}
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_month_2018-11-01_2019-02-01", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let oldFromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let oldToDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .month, from: oldFromDate, to: oldToDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
// Allow Core Data to sync
expectation2.fulfill()
}
}
wait(for: [expectation2], timeout: 5.0)
let context = database.viewContext
let oldFetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
oldFetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@ && " + #keyPath(ReportAccountBalance.dateString) + " == %@", argumentArray: [ReportAccountBalance.Period.month.rawValue, "2018-10"])
oldFetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
let newFetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
newFetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@ && " + #keyPath(ReportAccountBalance.dateString) + " == %@", argumentArray: [ReportAccountBalance.Period.month.rawValue, "2019-02"])
newFetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
// Check old reports exist
do {
let fetchedOldReports = try context.fetch(oldFetchRequest)
XCTAssertEqual(fetchedOldReports.count, 8)
if let firstReport = fetchedOldReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .month)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "208.55"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
// Check new reports don't exist
do {
let fetchedNewReports = try context.fetch(newFetchRequest)
XCTAssertEqual(fetchedNewReports.count, 0)
XCTAssertNil(fetchedNewReports.first)
} catch {
XCTFail(error.localizedDescription)
}
let newFromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-11-01")!
let newToDate = ReportAccountBalance.dailyDateFormatter.date(from: "2019-02-01")!
reports.refreshAccountBalanceReports(period: .month, from: newFromDate, to: newToDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
// Wait for Core Data to sync
expectation3.fulfill()
}
}
wait(for: [expectation3], timeout: 5.0)
// Check old reports still exist
do {
let fetchedOldReports = try context.fetch(oldFetchRequest)
XCTAssertEqual(fetchedOldReports.count, 8)
if let firstReport = fetchedOldReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .month)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-1191.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
// Check new reports exist
do {
let fetchedNewReports = try context.fetch(newFetchRequest)
XCTAssertEqual(fetchedNewReports.count, 7)
if let firstReport = fetchedNewReports.first {
XCTAssertEqual(firstReport.dateString, "2019-02")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .month)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "1823.85"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
}
func testFetchingAccountBalanceReportsCommingling() {
let expectation1 = expectation(description: "Database setup")
let expectation2 = expectation(description: "Network Request 1")
let expectation3 = expectation(description: "Network Request 2")
let expectation4 = expectation(description: "Network Request 3")
let expectation5 = expectation(description: "Fetch")
let config = FrolloSDKConfiguration.testConfig()
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.accountBalance.path)) { (request) -> HTTPStubsResponse in
if let requestURL = request.url, let queryItems = URLComponents(url: requestURL, resolvingAgainstBaseURL: true)?.queryItems {
var period: String = ""
for queryItem in queryItems {
if queryItem.name == "period", let value = queryItem.value {
period = value
}
}
if period == "by_day" {
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_day_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
} else if period == "by_week" {
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_week_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
}
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "account_balance_reports_by_month_2018-10-29_2019-01-29", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = Reports.dailyDateFormatter.date(from: "2019-01-29")!
reports.refreshAccountBalanceReports(period: .day, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
expectation2.fulfill()
}
reports.refreshAccountBalanceReports(period: .month, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
expectation3.fulfill()
}
reports.refreshAccountBalanceReports(period: .week, from: fromDate, to: toDate) { (result) in
switch result {
case .failure(let error):
XCTFail(error.localizedDescription)
case .success:
break
}
expectation4.fulfill()
}
wait(for: [expectation2, expectation3, expectation4], timeout: 5.0)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let context = database.viewContext
// Check for day reports
let dayFetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
dayFetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.day.rawValue])
dayFetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedDayReports = try context.fetch(dayFetchRequest)
XCTAssertEqual(fetchedDayReports.count, 661)
if let firstReport = fetchedDayReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10-28")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .day)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-1191.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
// Check for month reports
let monthFetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
monthFetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.month.rawValue])
monthFetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedMonthReports = try context.fetch(monthFetchRequest)
XCTAssertEqual(fetchedMonthReports.count, 31)
if let firstReport = fetchedMonthReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .month)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "208.55"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
// Check for week reports
let weekFetchRequest: NSFetchRequest<ReportAccountBalance> = ReportAccountBalance.fetchRequest()
weekFetchRequest.predicate = NSPredicate(format: #keyPath(ReportAccountBalance.periodRawValue) + " == %@", argumentArray: [ReportAccountBalance.Period.week.rawValue])
weekFetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ReportAccountBalance.dateString), ascending: true), NSSortDescriptor(key: #keyPath(ReportAccountBalance.accountID), ascending: true)]
do {
let fetchedWeekReports = try context.fetch(weekFetchRequest)
XCTAssertEqual(fetchedWeekReports.count, 122)
if let firstReport = fetchedWeekReports.first {
XCTAssertEqual(firstReport.dateString, "2018-10-4")
XCTAssertEqual(firstReport.accountID, 542)
XCTAssertEqual(firstReport.currency, "AUD")
XCTAssertEqual(firstReport.period, .week)
XCTAssertEqual(firstReport.value, NSDecimalNumber(string: "-1191.45"))
} else {
XCTFail("Reports not found")
}
} catch {
XCTFail(error.localizedDescription)
}
expectation5.fulfill()
}
wait(for: [expectation5], timeout: 5.0)
}
// MARK: - Transaction Report Tests
func testFetchTransactionReport_GroupedByBudgetCategory() {
let expectation1 = expectation(description: "Database setup")
let budgetCategory = BudgetCategory.income
let filter = TransactionReportFilter.budgetCategory(id: budgetCategory.id)
let transactionHistoryPath = ReportsEndpoint.transactionsHistory(entity: filter.entity, id: filter.id)
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + transactionHistoryPath.path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "transaction_reports_txn_budget_category_monthly_2019_01_01_2019_12_31", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = Reports.dailyDateFormatter.date(from: "2019-01-29")!
let expectation2 = expectation(description: "Network Call")
var fetchResult: Result<[ReportResponse<BudgetCategoryGroupReport>], Error>?
reports.fetchTransactionBudgetCategoryReports(budgetCategory, period: .weekly, from: fromDate, to: toDate) { (result) in
fetchResult = result
expectation2.fulfill()
}
wait(for: [expectation2], timeout: 3.0)
switch fetchResult {
case .success(let response):
guard response.count > 5 else { XCTFail(); return }
let secondItem = response[5]
guard secondItem.groupReports.count > 2 else { XCTFail(); return }
let secondReport = secondItem.groupReports[1]
XCTAssertEqual(secondReport.budgetCategory, BudgetCategory.lifestyle)
default:
XCTFail()
}
}
func testFetchTransactionReport_GroupedByCategory() {
let expectation1 = expectation(description: "Database setup")
let filter = TransactionReportFilter.category(id: 1)
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.transactionsHistory(entity: filter.entity, id: filter.id).path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "transaction_reports_txn_category_monthly_2019_01_01_2019_12_31", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = Reports.dailyDateFormatter.date(from: "2019-01-29")!
let expectation2 = expectation(description: "Network Call")
var fetchResult: Result<[ReportResponse<TransactionCategoryGroupReport>], Error>?
reports.fetchTransactionReports(filtering: filter, grouping: TransactionCategoryGroupReport.self, period: .weekly, from: fromDate, to: toDate) { (result) in
fetchResult = result
expectation2.fulfill()
}
wait(for: [expectation2], timeout: 3.0)
switch fetchResult {
case .success(let response):
guard response.count > 5 else { XCTFail(); return }
let secondItem = response[6]
guard secondItem.groupReports.count > 2 else { XCTFail(); return }
let secondReport = secondItem.groupReports[1]
XCTAssertEqual(secondReport.id, 67)
default:
XCTFail()
}
}
func testFetchTransactionReport_GroupedByMerchant() {
let expectation1 = expectation(description: "Database setup")
let filter = TransactionReportFilter.category(id: 1)
stub(condition: isHost(config.serverEndpoint.host!) && isPath("/" + ReportsEndpoint.transactionsHistory(entity: filter.entity, id: filter.id).path)) { (request) -> HTTPStubsResponse in
return fixture(filePath: Bundle(for: type(of: self)).path(forResource: "transaction_reports_merchant_monthly_2019_01_01_2019_12_31", ofType: "json")!, headers: [ HTTPHeader.contentType.rawValue: "application/json"])
}
let mockAuthentication = MockAuthentication()
let authentication = Authentication(configuration: config)
authentication.dataSource = mockAuthentication
authentication.delegate = mockAuthentication
let network = Network(serverEndpoint: config.serverEndpoint, authentication: authentication)
let service = APIService(serverEndpoint: config.serverEndpoint, network: network)
let database = Database(path: tempFolderPath())
database.setup { (error) in
XCTAssertNil(error)
expectation1.fulfill()
}
wait(for: [expectation1], timeout: 3.0)
let aggregation = Aggregation(database: database, service: service)
let reports = Reports(database: database, service: service, aggregation: aggregation)
let fromDate = ReportAccountBalance.dailyDateFormatter.date(from: "2018-10-29")!
let toDate = Reports.dailyDateFormatter.date(from: "2019-01-29")!
let expectation2 = expectation(description: "Network Call")
var fetchResult: Result<[ReportResponse<MerchantGroupReport>], Error>?
reports.fetchTransactionReports(filtering: filter, grouping: MerchantGroupReport.self, period: .weekly, from: fromDate, to: toDate) { (result) in
fetchResult = result
expectation2.fulfill()
}
wait(for: [expectation2], timeout: 3.0)
switch fetchResult {
case .success(let response):
guard response.count > 5 else { XCTFail(); return }
let secondItem = response[5]
guard secondItem.groupReports.count > 2 else { XCTFail(); return }
let secondReport = secondItem.groupReports[1]
XCTAssertEqual(secondReport.id, 44)
default:
XCTFail()
}
}
}
| 50.123885 | 280 | 0.596856 |
03bf03de3520768d5a94577a9f8161ddbfa79c36 | 465 | import Cocoa
import ProExtensionHost
class WorkflowViewController: NSViewController {
override func awakeFromNib() {
super.awakeFromNib()
}
override var nibName: NSNib.Name? {
return NSNib.Name("WorkflowViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
}
var hostInfoString: String {
let host = ProExtensionHostSingleton() as! FCPXHost
return String(format:"%@ %@", host.name, host.versionString)
}
}
| 19.375 | 68 | 0.705376 |
ddcc527070138813b814fcc50043841b3f64fc74 | 18,346 | //
// main.swift
// ReinforcementLearning
//
// Created by Don Teo on 2019-05-18.
// Copyright © 2019 Don Teo. All rights reserved.
//
import Foundation
import SwiftPlot
import AGGRenderer
let nRuns = 2000
let nTimeStepsPerRun = 1000
// greedy strategy
func getMaxActionValueEstimateIndex(avEstimate: [Int: Double]) -> Int {
let maxVal = avEstimate.values.max()
let optimalActions = avEstimate.filter { $0.value == maxVal }
let optimalActionIndices = Array(optimalActions.keys)
return optimalActionIndices.randomElement()!
}
// random strategy
func getRandomActionIndex(avEstimate: [Int: Double]) -> Int {
return Array(avEstimate.keys).randomElement()!
}
// epsilon-greedy strategy
func getEpsilonGreedyIndex(avEstimate: [Int: Double], epsilon: Double) -> Int {
let d = Double.random(in: 0...1)
if d <= epsilon {
return getRandomActionIndex(avEstimate: avEstimate)
}
return getMaxActionValueEstimateIndex(avEstimate: avEstimate)
}
// upper-confidence-bound strategy
func getUCBActionIndex(avEstimate: [Int: Double], actionCounter: [Int: Int], iTimeStep: Int, c: Double) -> Int {
// if there are any actions that have yet to be taken, these are maximizing actions
let optimalActions = actionCounter.filter { $0.value == 0 }
if optimalActions.count > 0 {
let optimalActionIndices = Array(optimalActions.keys)
return optimalActionIndices.randomElement()!
}
var ucbAvEstimate = [Int: Double]()
for index in avEstimate.keys {
ucbAvEstimate[index] = avEstimate[index]! + c * sqrt(log(Double(iTimeStep)) / Double(actionCounter[index]!))
}
return getMaxActionValueEstimateIndex(avEstimate: ucbAvEstimate)
}
func getStrategyIndex(avEstimate: [Int: Double], epsilon: Double, c: Double,
actionCounter: [Int: Int], iTimeStep: Int) -> Int {
if c > 0 {
return getUCBActionIndex(avEstimate: avEstimate, actionCounter: actionCounter, iTimeStep: iTimeStep, c: c)
}
return getEpsilonGreedyIndex(avEstimate: avEstimate, epsilon: epsilon)
}
// soft-max distribution sampling strategy
func getGradientBanditActionIndex(energy: [Double]) -> (Int, [Double]) {
let partitionFunction = energy.map { exp($0) }.reduce(0, +)
let probDist = energy.map { exp($0) / partitionFunction }
let discreteDistribution = DiscreteDistribution(randomSource: random, distribution: probDist)
return (discreteDistribution.nextInt(), probDist)
}
class ActionTracker {
// Row i stores the reward of each run for time step i
var allRewards = Array(repeating: Array(repeating: 0.0, count: nRuns), count: nTimeStepsPerRun)
var averageRewards = Array(repeating: 0.0, count: nTimeStepsPerRun)
var actionTaken = Array(repeating: Array(repeating: -1, count: nRuns), count: nTimeStepsPerRun)
var optimalAction = Array(repeating: [Int](), count: nRuns)
var averageOptimal = Array(repeating: 0.0, count: nTimeStepsPerRun)
var meanAverageReward: Double = 0
// We need to keep track of the estimated value of each action.
// Here, we use the sample average estimate.
// These are reset at every run.
var actionValueEstimate: [Int: Double] = [:]
var actionCounter: [Int: Int] = [:]
func computeAverageReward() {
for iTimestep in 0...self.allRewards.count-1 {
self.averageRewards[iTimestep] = self.allRewards[iTimestep].reduce(0, +) / Double(self.allRewards[iTimestep].count)
}
}
func computeAverageOptimal() {
for iTimeStep in 0...self.allRewards.count-1 {
var nOptimalActionTaken = 0
for iRun in 0...nRuns-1 {
let optimal = self.optimalAction[iRun]
if optimal.contains(self.actionTaken[iTimeStep][iRun]) {
nOptimalActionTaken += 1
}
}
self.averageOptimal[iTimeStep] = Double(nOptimalActionTaken) / Double(nRuns)
}
}
func computeMeanAverageReward() {
self.meanAverageReward = Double(self.averageRewards.reduce(0, +)) / Double(self.averageRewards.count)
}
}
func simulate(actionTracker: ActionTracker,
iRun: Int,
epsilon: Double,
c: Double,
testbed: TenArmedTestbed,
initialActionValueEstimate: Double,
stepSize: Double) {
actionTracker.optimalAction[iRun] = testbed.indicesOfOptimalAction
// initialize
for iAction in 0...testbed.arms.count-1 {
actionTracker.actionValueEstimate[iAction] = initialActionValueEstimate
actionTracker.actionCounter[iAction] = 0
}
for iTimeStep in 0...nTimeStepsPerRun-1 {
// determine next action
//let actionIndex = strategy(actionTracker.actionValueEstimate)
let actionIndex = getStrategyIndex(avEstimate: actionTracker.actionValueEstimate,
epsilon: epsilon,
c: c,
actionCounter: actionTracker.actionCounter,
iTimeStep: iTimeStep)
actionTracker.actionTaken[iTimeStep][iRun] = actionIndex
actionTracker.actionCounter[actionIndex]! += 1
let reward = Double(testbed.arms[actionIndex].nextFloat())
actionTracker.allRewards[iTimeStep][iRun] = Double(reward)
let currentActionValue = actionTracker.actionValueEstimate[actionIndex]!
let theStepSize = stepSize > 0 ? stepSize : 1 / Double(actionTracker.actionCounter[actionIndex]!)
let nextActionValue = currentActionValue + theStepSize * (reward - currentActionValue)
// update action value estimate
actionTracker.actionValueEstimate[actionIndex] = nextActionValue
}
}
func simulateAll(actionTrackers: [ActionTracker], epsilons: [Double],
cs: [Double],
initialActionValueEstimates: [Double],
stepSize: Double = -1.0) {
for iRun in 0...nRuns-1 {
let testbed = TenArmedTestbed(mean: 0)
for (((actionTracker, c), epsilon), initialActionValueEstimate) in zip(zip(zip(actionTrackers, cs), epsilons), initialActionValueEstimates) {
simulate(actionTracker: actionTracker, iRun: iRun, epsilon: epsilon, c: c, testbed: testbed,
initialActionValueEstimate: initialActionValueEstimate, stepSize: stepSize)
}
}
for actionTracker in actionTrackers {
actionTracker.computeAverageReward()
actionTracker.computeAverageOptimal()
}
}
func make_figure_2_2() {
print("Generating Figure 2.2...")
let greedyActionTracker = ActionTracker()
let epsilonGreedy1ActionTracker = ActionTracker()
let epsilonGreedy2ActionTracker = ActionTracker()
let actionTrackers = [greedyActionTracker, epsilonGreedy1ActionTracker, epsilonGreedy2ActionTracker]
let epsilons = [0, 0.1, 0.01]
let initialActionValueEstimates = [0.0, 0.0, 0.0]
let cs = [-1.0, -1.0, -1.0]
simulateAll(actionTrackers: actionTrackers, epsilons: epsilons, cs: cs, initialActionValueEstimates: initialActionValueEstimates)
let labels = ["eps=0", "eps=0.1", "eps=0.01"]
let colors = [Color.blue, Color.orange, Color.green]
let aggRenderer: AGGRenderer = AGGRenderer()
var subplot = SubPlot(layout: .vertical)
var lineGraph1 = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
for (actionTracker, (color, label)) in zip(actionTrackers, zip(colors, labels)) {
lineGraph1.addSeries(Array(1...nTimeStepsPerRun).map { Double($0) }, actionTracker.averageRewards, label: label, color: color)
}
lineGraph1.plotLabel.xLabel = "Steps"
lineGraph1.plotLabel.yLabel = "Average reward"
var lineGraph2 = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
for (actionTracker, (color, label)) in zip(actionTrackers, zip(colors, labels)) {
lineGraph2.addSeries(Array(1...nTimeStepsPerRun).map { Double($0) }, actionTracker.averageOptimal, label: label, color: color)
}
lineGraph2.plotLabel.xLabel = "Steps"
lineGraph2.plotLabel.yLabel = "% Optimal award"
subplot.plots = [lineGraph1, lineGraph2]
try? subplot.drawGraphAndOutput(fileName: "Output/Chapter2/Fig_2.2", renderer: aggRenderer)
}
func make_figure_2_3() {
print("Generating Figure 2.3...")
let epsilonGreedy1ActionConstantStepTracker = ActionTracker()
let optimisticGreedyActionConstantStepTracker = ActionTracker()
let actionTrackers = [epsilonGreedy1ActionConstantStepTracker, optimisticGreedyActionConstantStepTracker]
let epsilons = [0.1, 0]
let cs = [-1.0, -1.0]
let stepSize = 0.1
let initialActionValueEstimates = [0.0, 5.0]
simulateAll(actionTrackers: actionTrackers, epsilons: epsilons, cs: cs,
initialActionValueEstimates: initialActionValueEstimates,
stepSize: stepSize)
let aggRenderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map { Double($0) }, actionTrackers[0].averageOptimal, label: "Q1=0, eps=0.1", color: Color.blue)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map { Double($0) }, actionTrackers[1].averageOptimal, label: "Q1=5, eps=0", color: Color.orange)
lineGraph.plotLabel.xLabel = "Steps"
lineGraph.plotLabel.yLabel = "% Optimal award"
try? lineGraph.drawGraphAndOutput(fileName: "output/Chapter2/Fig_2.3", renderer: aggRenderer)
}
func make_figure_2_4() {
print("Generating Figure 2.4...")
let epsilonGreedy1ActionTracker = ActionTracker()
let ucbActionTracker = ActionTracker()
let actionTrackers = [epsilonGreedy1ActionTracker, ucbActionTracker]
let epsilons = [0.1, 0.0]
let initialActionValueEstimates = [0.0, 0.0]
let cs = [-1.0, 2.0]
simulateAll(actionTrackers: actionTrackers, epsilons: epsilons, cs: cs, initialActionValueEstimates: initialActionValueEstimates)
let aggRenderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
let labels = ["eps-greedy eps=0.1", "UCB c=2"]
let colors = [Color.blue, Color.orange]
for (actionTracker, (label, color)) in zip(actionTrackers, zip(labels, colors)) {
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map { Double($0) }, actionTracker.averageRewards, label: label, color: color)
}
lineGraph.plotLabel.xLabel = "Steps"
lineGraph.plotLabel.yLabel = "Average reward"
try? lineGraph.drawGraphAndOutput(fileName: "output/Chapter2/Fig_2.4", renderer: aggRenderer)
}
func gradientBanditSimulate(actionTracker: ActionTracker,
iRun: Int,
alpha: Double,
testbed: TenArmedTestbed,
withBaseline: Bool) {
actionTracker.optimalAction[iRun] = testbed.indicesOfOptimalAction
var energy = Array(repeating: 0.0, count: testbed.arms.count)
var averageReward = 0.0
for iTimeStep in 0...nTimeStepsPerRun-1 {
let (actionIndex, probDist) = getGradientBanditActionIndex(energy: energy)
actionTracker.actionTaken[iTimeStep][iRun] = actionIndex
let reward = Double(testbed.arms[actionIndex].nextFloat())
actionTracker.allRewards[iTimeStep][iRun] = Double(reward)
averageReward += (1 / Double(iTimeStep + 1)) * (reward - averageReward)
let baseline = withBaseline ? averageReward : 0
for iAction in 0...testbed.arms.count-1 {
if iAction == actionIndex {
energy[iAction] += alpha * (reward - baseline) * (1 - probDist[iAction])
} else {
energy[iAction] -= alpha * (reward - baseline) * probDist[iAction]
}
}
}
}
func gradientBanditSimulateAll(actionTrackers: [ActionTracker],
alphas: [Double],
withBaselineFlags: [Bool],
mean: Float) {
for iRun in 0...nRuns-1 {
let testbed = TenArmedTestbed(mean: mean)
for ((actionTracker, alpha), withBaseline) in zip(zip(actionTrackers, alphas), withBaselineFlags) {
gradientBanditSimulate(actionTracker: actionTracker, iRun: iRun, alpha: alpha, testbed: testbed,
withBaseline: withBaseline)
}
}
for actionTracker in actionTrackers {
actionTracker.computeAverageReward()
actionTracker.computeAverageOptimal()
}
}
func make_figure_2_5() {
print("Generating Figure 2.5...")
let gradientBasedActionTracker1 = ActionTracker()
let gradientBasedActionTracker2 = ActionTracker()
let gradientBasedActionTracker3 = ActionTracker()
let gradientBasedActionTracker4 = ActionTracker()
let actionTrackers = [gradientBasedActionTracker1, gradientBasedActionTracker2,
gradientBasedActionTracker3, gradientBasedActionTracker4]
let alphas = [0.1, 0.4, 0.1, 0.4]
let withBaselineFlags = [false, false, true, true]
gradientBanditSimulateAll(actionTrackers: actionTrackers, alphas: alphas,
withBaselineFlags: withBaselineFlags, mean: 4)
let aggRenderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map{ Double($0) }, actionTrackers[0].averageOptimal, label: "alpha=0.1 (w/o baseline)", color: Color.blue)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map{ Double($0) }, actionTrackers[1].averageOptimal, label: "alpha=0.4 (w/o baseline)", color: Color.orange)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map{ Double($0) }, actionTrackers[2].averageOptimal, label: "alpha=0.1 (w/ baseline)" , color: Color.green)
lineGraph.addSeries(Array(1...nTimeStepsPerRun).map{ Double($0) }, actionTrackers[3].averageOptimal, label: "alpha=0.4 (w/ baseline)" , color: Color.red)
lineGraph.plotLabel.xLabel = "Steps"
lineGraph.plotLabel.yLabel = "% Optimal award"
try? lineGraph.drawGraphAndOutput(fileName: "output/Chapter2/Fig_2.5", renderer: aggRenderer)
}
func make_figure_2_6() {
print("Generating Figure 2.6...")
// greedy with optimistic init
var greedyOptimActionTrackers = [ActionTracker]()
let optInitialActionValueEstimates = [1.0/4.0, 1.0/2.0, 1.0, 2.0, 4.0]
let greedyEpsilons = Array(repeating: 0.0, count: optInitialActionValueEstimates.count)
let greedyCs = Array(repeating: -1.0, count: greedyEpsilons.count)
let stepSize = 0.1
for _ in greedyEpsilons {
greedyOptimActionTrackers.append(ActionTracker())
}
simulateAll(actionTrackers: greedyOptimActionTrackers, epsilons: greedyEpsilons, cs: greedyCs,
initialActionValueEstimates: optInitialActionValueEstimates, stepSize: stepSize)
var greedyOptimMeanAverageReward = [Double]()
for actionTracker in greedyOptimActionTrackers {
actionTracker.computeMeanAverageReward()
greedyOptimMeanAverageReward.append(actionTracker.meanAverageReward)
}
// epsilon greedy
var epsilonGreedyActionTrackers = [ActionTracker]()
let epsilons = [1.0/128.0, 1.0/64.0, 1.0/32.0, 1.0/16.0, 1.0/8.0, 1.0/4.0]
let cs = Array(repeating: -1.0, count: epsilons.count)
let initialActionValueEstimates = Array(repeating: 0.0, count: epsilons.count)
for _ in epsilons {
epsilonGreedyActionTrackers.append(ActionTracker())
}
simulateAll(actionTrackers: epsilonGreedyActionTrackers, epsilons: epsilons, cs: cs, initialActionValueEstimates: initialActionValueEstimates)
var epsilonGreedyMeanAverageReward = [Double]()
for actionTracker in epsilonGreedyActionTrackers {
actionTracker.computeMeanAverageReward()
epsilonGreedyMeanAverageReward.append(actionTracker.meanAverageReward)
}
// UCB
var ucbActionTrackers = [ActionTracker]()
let ucbCs = [1.0/16.0, 1.0/8.0, 1.0/4.0, 1.0/2.0, 1.0, 2.0, 4.0]
let ucbEpsilons = Array(repeating: 0.0, count: ucbCs.count)
let ucbInitialActionValueEstimates = Array(repeating: 0.0, count: ucbCs.count)
for _ in ucbCs {
ucbActionTrackers.append(ActionTracker())
}
simulateAll(actionTrackers: ucbActionTrackers, epsilons: ucbEpsilons, cs: ucbCs, initialActionValueEstimates: ucbInitialActionValueEstimates)
var ucbMeanAverageReward = [Double]()
for actionTracker in ucbActionTrackers {
actionTracker.computeMeanAverageReward()
ucbMeanAverageReward.append(actionTracker.meanAverageReward)
}
// gradient bandit
var gradActionTrackers = [ActionTracker]()
let alphas = [1.0/32.0, 1.0/16.0, 1.0/8.0, 1.0/4.0, 1.0/2.0, 1.0, 2.0, 4.0]
for _ in alphas {
gradActionTrackers.append(ActionTracker())
}
let withBaselineFlags = Array(repeating: true, count: alphas.count)
gradientBanditSimulateAll(actionTrackers: gradActionTrackers, alphas: alphas,
withBaselineFlags: withBaselineFlags, mean: 0)
var gradMeanAverageReward = [Double]()
for actionTracker in gradActionTrackers {
actionTracker.computeMeanAverageReward()
gradMeanAverageReward.append(actionTracker.meanAverageReward)
}
// plot everything
let aggRenderer: AGGRenderer = AGGRenderer()
var lineGraph = LineGraph<Double, Double>(enablePrimaryAxisGrid: true)
lineGraph.addSeries(optInitialActionValueEstimates.map{ log2($0) }, greedyOptimMeanAverageReward, label: "greedy with opt. init, step=0.1", color: Color.blue)
lineGraph.addSeries(epsilons.map{ log2($0) }, epsilonGreedyMeanAverageReward, label: "eps-greedy", color: Color.orange)
lineGraph.addSeries(ucbCs.map{ log2($0) }, ucbMeanAverageReward, label: "UCB", color: Color.green)
lineGraph.addSeries(alphas.map{ log2($0) }, gradMeanAverageReward, label: "gradient bandit", color: Color.red)
lineGraph.plotLabel.xLabel = "log2( eps alpha c Q_0 )"
lineGraph.plotLabel.yLabel = "Average reward over first 1000 steps"
try? lineGraph.drawGraphAndOutput(fileName: "output/Chapter2/Fig_2.6", renderer: aggRenderer)
}
make_figure_2_2()
make_figure_2_3()
make_figure_2_4()
make_figure_2_5()
make_figure_2_6()
| 44.529126 | 162 | 0.686853 |
46dff1961d716aa08d096d1648c7d5de4e894e42 | 1,734 | #if !canImport(ObjectiveC)
import XCTest
extension ZipTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__ZipTests = [
("testAddedCustomFileExtensionIsValid", testAddedCustomFileExtensionIsValid),
("testDefaultFileExtensionsIsNotRemoved", testDefaultFileExtensionsIsNotRemoved),
("testDefaultFileExtensionsIsValid", testDefaultFileExtensionsIsValid),
("testFileExtensionIsInvalidForInvalidUrl", testFileExtensionIsInvalidForInvalidUrl),
("testFileExtensionIsNotInvalidForValidUrl", testFileExtensionIsNotInvalidForValidUrl),
("testImplicitProgressUnzip", testImplicitProgressUnzip),
("testImplicitProgressZip", testImplicitProgressZip),
("testQuickUnzip", testQuickUnzip),
("testQuickUnzipNonExistingPath", testQuickUnzipNonExistingPath),
("testQuickUnzipNonZipPath", testQuickUnzipNonZipPath),
("testQuickUnzipOnlineURL", testQuickUnzipOnlineURL),
("testQuickUnzipProgress", testQuickUnzipProgress),
("testQuickUnzipSubDir", testQuickUnzipSubDir),
("testQuickZip", testQuickZip),
("testQuickZipFolder", testQuickZipFolder),
("testRemovedCustomFileExtensionIsInvalid", testRemovedCustomFileExtensionIsInvalid),
("testUnzip", testUnzip),
("testUnzipPermissions", testUnzipPermissions),
("testUnzipWithUnsupportedPermissions", testUnzipWithUnsupportedPermissions),
("testZip", testZip),
("testZipUnzipPassword", testZipUnzipPassword),
]
}
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(ZipTests.__allTests__ZipTests),
]
}
#endif
| 44.461538 | 95 | 0.737024 |
5098fa49a470523e2432ab503eb1761b5d946725 | 83 | import Foundation
struct Bitcoin {
static let satoshi: Double = 100_000_000
}
| 13.833333 | 44 | 0.746988 |
64612f562bbfc6fb06115bc753be93210bdc4460 | 1,704 | //
// Button+Ext.swift
// HHWeiBo
//
// Created by Mac on 2018/5/6.
// Copyright © 2018年 Mac. All rights reserved.
//
import Foundation
import UIKit
extension UIButton {
///带背景图的按钮
convenience init(imageName:String ,backImageName:String) {
self.init()
setImage(UIImage(named: imageName), for: .normal)
setImage(UIImage(named: imageName+"_highlighted"), for: .highlighted)
setBackgroundImage(UIImage(named: backImageName), for: .normal)
setBackgroundImage(UIImage(named: backImageName+"_highlighted"), for: .highlighted)
sizeToFit()
}
///带背景图和文字的按钮
convenience init(title: String,color:UIColor,backImageName:String) {
self.init()
setTitle(title, for: .normal)
setTitleColor(color, for: .normal)
setBackgroundImage(UIImage(named: backImageName), for: .normal)
sizeToFit()
}
///带图和文字的按钮
convenience init(title: String, fontSize: CGFloat = 16, color: UIColor, imageName: String) {
self.init(title: title, color: color, backImageName: imageName)
titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
sizeToFit()
}
///带背景图和文字的按钮和点击事件
convenience init(title:String,fontSize:CGFloat = 16,target:AnyObject?,action:Selector,isBack:Bool = false)
{
self.init(title: title, fontSize: 16, color: .black, imageName: "1")
if isBack {
setImage(UIImage(named: "cp_back"), for: .normal)
setImage(UIImage(named: "cp_back"), for: .highlighted)
sizeToFit()
}
addTarget(target, action: action, for: .touchUpInside)
}
}
| 30.428571 | 110 | 0.621479 |
335eeae2d3cf2e0123e9205ab95b2f780d247110 | 4,113 | //
// ViewController.swift
// Two Astronauts Clock Meme
//
// Created by George Nick Gorzynski on 03/10/2020.
//
import UIKit
class ViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet weak private var sizePicker: UISegmentedControl!
@IBOutlet weak private var sizeWidthConstraint: NSLayoutConstraint!
@IBOutlet weak private var widgetPreview: UIView!
@IBOutlet weak private var timeLabel: UILabel!
// MARK: Properties
private var timeUpdateTimer: Timer!
// MARK: View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupView()
}
// MARK: Methods
private func setupView() {
self.timeUpdateTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
guard let displayedTime = self.timeLabel.text else { return }
let currentTimeFormatter = DateFormatter()
currentTimeFormatter.dateFormat = "HH:mm"
let currentTime = currentTimeFormatter.string(from: Date())
if currentTime != displayedTime {
DispatchQueue.main.async {
self.timeLabel.text = currentTime
}
}
}
}
private func showAttribution() {
let license = """
\n
MIT License
Copyright (c) 2020 1di4r
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.
"""
let alert = UIAlertController(title: "\nAttribution Message", message: "\nThis widget was inspired by GitHub user 1di4r's project called 'ReachInfo', where widgets appear in reachability. This is one of the widgets provided by ReachInfo. The images are licensed from 1di4r under the MIT license. The following copyright notice is the license from https://github.com/1DI4R/ReachInfo/blob/master/LICENSE: \(license)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// MARK: IBActions
@IBAction private func sizePickerChangedValue(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
self.sizeWidthConstraint.constant = 200
self.widgetPreview.setNeedsUpdateConstraints()
UIView.animate(withDuration: 0.3) {
self.widgetPreview.layoutIfNeeded()
}
case 1:
self.sizeWidthConstraint.constant = 300
self.widgetPreview.setNeedsUpdateConstraints()
UIView.animate(withDuration: 0.3) {
self.widgetPreview.layoutIfNeeded()
}
default:
break
}
}
@IBAction private func showAttributionTapped(_ sender: UIButton) {
self.showAttribution()
}
}
| 38.083333 | 447 | 0.644299 |
d6966a712cb416d8ca008929fd81ab8a6b46cd7e | 258 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
b (
let
a = [
{
class A {
protocol d {
enum S {
let a {
func g {
struct S {
class
case ,
| 15.176471 | 87 | 0.70155 |
8f897c5618cb18c914baded9a27656e6be74b9f4 | 584 | import CoreData
import Foundation
import AlecrimCoreData
@objc(WABaseEntity)
class WABaseEntity: NSManagedObject {
@NSManaged var identifier: String
static let identifier = AlecrimCoreData.Attribute<String>("identifier")
}
extension AlecrimCoreData.AttributeProtocol where Self.ValueType: WABaseEntity {
var identifier: AlecrimCoreData.Attribute<String> {
return AlecrimCoreData.Attribute<String>("identifier", self)
}
}
extension NSManagedObjectContext {
var entities: AlecrimCoreData.Table<WABaseEntity> {
return AlecrimCoreData.Table<WABaseEntity>(context: self)
}
}
| 25.391304 | 80 | 0.809932 |
acaf421b7e64c4c6524b5f93ed3ed99d402f95b3 | 2,551 | //
// Text.swift
// Split
//
// Created by Hugo Queinnec on 05/01/2022.
//
import Foundation
import UIKit
import Vision
class TextModel: Identifiable {
var id: String
var list: [PairProductPrice] = []
var image: IdentifiedImage
var name: String
init() {
id = UUID().uuidString
image = IdentifiedImage(id: self.id)
name = ""
}
}
struct PairProductPrice: Identifiable, Equatable {
var id: String
var name: String = ""
var price: Double = 0
var isNewItem: Bool = false
var chosenBy: [UUID] = []
var imageId: String?
var box: VNDetectedObjectObservation?
init() {
id = UUID().uuidString
}
//only for preview
init(id: String, name: String, price: Double) {
self.id = id
self.name = name
self.price = price
}
init(id: String, name: String = "", price: Double = 0, isNewItem: Bool = false, imageId: String? = nil, box: VNDetectedObjectObservation? = nil) {
self.id = id
self.name = name
self.price = price
self.isNewItem = isNewItem
self.imageId = imageId
self.box = box
}
}
struct PairProductPriceCodable: Identifiable, Equatable, Codable {
var id: String = ""
var name: String = ""
var price: Double = 0
var chosenBy: [UUID] = []
}
struct IdentifiedImage: Identifiable {
init(id: String, image: UIImage? = nil) {
self.id = id
self.image = image
}
var id: String
var image: UIImage?
func boxes(listOfProductsAndPrices: [PairProductPrice]) -> [VNDetectedObjectObservation] {
return listOfProductsAndPrices.compactMap({ pair -> VNDetectedObjectObservation? in
if pair.imageId==id && !(pair.box == nil){
return pair.box!
}
return nil
})
}
}
extension StringProtocol {
func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...].range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
class TextData: ObservableObject {
@Published var items = [TextModel]()
}
| 25.257426 | 150 | 0.589181 |
3a5ee9c21575f9204d5d252459e2dea82f4e80ba | 66,409 | import Foundation
import UIKit
import AsyncDisplayKit
import Display
import SwiftSignalKit
import Postbox
import TelegramCore
import SyncCore
import TelegramPresentationData
import TextFormat
import AccountContext
import StickerResources
import ContextUI
import Markdown
import ShimmerEffect
private let nameFont = Font.medium(14.0)
private let inlineBotPrefixFont = Font.regular(14.0)
private let inlineBotNameFont = nameFont
class ChatMessageStickerItemNode: ChatMessageItemView {
private let contextSourceNode: ContextExtractedContentContainingNode
private let containerNode: ContextControllerSourceNode
let imageNode: TransformImageNode
private var placeholderNode: StickerShimmerEffectNode
var textNode: TextNode?
private var swipeToReplyNode: ChatMessageSwipeToReplyNode?
private var swipeToReplyFeedback: HapticFeedback?
private var selectionNode: ChatMessageSelectionNode?
private var deliveryFailedNode: ChatMessageDeliveryFailedNode?
private var shareButtonNode: ChatMessageShareButton?
var telegramFile: TelegramMediaFile?
private let fetchDisposable = MetaDisposable()
private var viaBotNode: TextNode?
private let dateAndStatusNode: ChatMessageDateAndStatusNode
private var replyInfoNode: ChatMessageReplyInfoNode?
private var replyBackgroundNode: ASImageNode?
private var actionButtonsNode: ChatMessageActionButtonsNode?
private let messageAccessibilityArea: AccessibilityAreaNode
private var highlightedState: Bool = false
private var currentSwipeToReplyTranslation: CGFloat = 0.0
private var currentSwipeAction: ChatControllerInteractionSwipeAction?
required init() {
self.contextSourceNode = ContextExtractedContentContainingNode()
self.containerNode = ContextControllerSourceNode()
self.imageNode = TransformImageNode()
self.placeholderNode = StickerShimmerEffectNode()
self.placeholderNode.isUserInteractionEnabled = false
self.dateAndStatusNode = ChatMessageDateAndStatusNode()
self.messageAccessibilityArea = AccessibilityAreaNode()
super.init(layerBacked: false)
var firstTime = true
self.imageNode.imageUpdated = { [weak self] image in
guard let strongSelf = self else {
return
}
if image != nil {
if firstTime && !strongSelf.placeholderNode.isEmpty {
strongSelf.imageNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2, completion: { [weak self] _ in
self?.removePlaceholder(animated: false)
})
} else {
strongSelf.removePlaceholder(animated: true)
}
firstTime = false
}
}
self.containerNode.shouldBegin = { [weak self] location in
guard let strongSelf = self else {
return false
}
if !strongSelf.imageNode.frame.contains(location) {
return false
}
if let action = strongSelf.gestureRecognized(gesture: .tap, location: location, recognizer: nil) {
if case .action = action {
return false
}
}
if let action = strongSelf.gestureRecognized(gesture: .longTap, location: location, recognizer: nil) {
switch action {
case .action, .optionalAction:
return false
case .openContextMenu:
return true
}
}
return true
}
self.containerNode.activated = { [weak self] gesture, location in
guard let strongSelf = self, let item = strongSelf.item else {
return
}
if let action = strongSelf.gestureRecognized(gesture: .longTap, location: location, recognizer: nil) {
switch action {
case .action, .optionalAction:
break
case let .openContextMenu(tapMessage, selectAll, subFrame):
item.controllerInteraction.openMessageContextMenu(tapMessage, selectAll, strongSelf, subFrame, gesture)
}
}
}
self.imageNode.displaysAsynchronously = false
self.containerNode.addSubnode(self.contextSourceNode)
self.containerNode.targetNodeForActivationProgress = self.contextSourceNode.contentNode
self.addSubnode(self.containerNode)
self.contextSourceNode.contentNode.addSubnode(self.placeholderNode)
self.contextSourceNode.contentNode.addSubnode(self.imageNode)
self.contextSourceNode.contentNode.addSubnode(self.dateAndStatusNode)
self.addSubnode(self.messageAccessibilityArea)
self.messageAccessibilityArea.focused = { [weak self] in
self?.accessibilityElementDidBecomeFocused()
}
self.dateAndStatusNode.openReactions = { [weak self] in
guard let strongSelf = self, let item = strongSelf.item else {
return
}
item.controllerInteraction.openMessageReactions(item.message.id)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.fetchDisposable.dispose()
}
private func removePlaceholder(animated: Bool) {
if !animated {
self.placeholderNode.removeFromSupernode()
} else {
self.placeholderNode.alpha = 0.0
self.placeholderNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, completion: { [weak self] _ in
self?.placeholderNode.removeFromSupernode()
})
}
}
override func didLoad() {
super.didLoad()
let recognizer = TapLongTapOrDoubleTapGestureRecognizer(target: self, action: #selector(self.tapLongTapOrDoubleTapGesture(_:)))
recognizer.tapActionAtPoint = { [weak self] point in
if let strongSelf = self {
if let shareButtonNode = strongSelf.shareButtonNode, shareButtonNode.frame.contains(point) {
return .fail
}
if let item = strongSelf.item, item.presentationData.largeEmoji && messageIsElligibleForLargeEmoji(item.message) {
if strongSelf.imageNode.frame.contains(point) {
return .waitForDoubleTap
}
}
}
return .waitForSingleTap
}
recognizer.longTap = { [weak self] point, recognizer in
guard let strongSelf = self else {
return
}
//strongSelf.reactionRecognizer?.cancel()
if let action = strongSelf.gestureRecognized(gesture: .longTap, location: point, recognizer: recognizer) {
switch action {
case let .action(f):
f()
recognizer.cancel()
case let .optionalAction(f):
f()
recognizer.cancel()
case .openContextMenu:
break
}
}
}
self.view.addGestureRecognizer(recognizer)
let replyRecognizer = ChatSwipeToReplyRecognizer(target: self, action: #selector(self.swipeToReplyGesture(_:)))
replyRecognizer.shouldBegin = { [weak self] in
if let strongSelf = self, let item = strongSelf.item {
if strongSelf.selectionNode != nil {
return false
}
let action = item.controllerInteraction.canSetupReply(item.message)
strongSelf.currentSwipeAction = action
if case .none = action {
return false
} else {
return true
}
}
return false
}
self.view.addGestureRecognizer(replyRecognizer)
}
override func setupItem(_ item: ChatMessageItem) {
super.setupItem(item)
for media in item.message.media {
if let telegramFile = media as? TelegramMediaFile {
if self.telegramFile != telegramFile {
let signal = chatMessageSticker(account: item.context.account, file: telegramFile, small: false, onlyFullSize: self.telegramFile != nil)
self.telegramFile = telegramFile
self.imageNode.setSignal(signal)
self.fetchDisposable.set(freeMediaFileInteractiveFetched(account: item.context.account, fileReference: .message(message: MessageReference(item.message), media: telegramFile)).start())
}
break
}
}
if self.telegramFile == nil && item.presentationData.largeEmoji && messageIsElligibleForLargeEmoji(item.message) {
self.imageNode.setSignal(largeEmoji(postbox: item.context.account.postbox, emoji: item.message.text))
}
}
private var absoluteRect: (CGRect, CGSize)?
override func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) {
self.absoluteRect = (rect, containerSize)
if !self.contextSourceNode.isExtractedToContextPreview {
var rect = rect
rect.origin.y = containerSize.height - rect.maxY + self.insets.top
self.placeholderNode.updateAbsoluteRect(CGRect(origin: CGPoint(x: rect.minX + placeholderNode.frame.minX, y: rect.minY + placeholderNode.frame.minY), size: placeholderNode.frame.size), within: containerSize)
}
}
override func updateAccessibilityData(_ accessibilityData: ChatMessageAccessibilityData) {
super.updateAccessibilityData(accessibilityData)
self.messageAccessibilityArea.accessibilityLabel = accessibilityData.label
self.messageAccessibilityArea.accessibilityValue = accessibilityData.value
self.messageAccessibilityArea.accessibilityHint = accessibilityData.hint
self.messageAccessibilityArea.accessibilityTraits = accessibilityData.traits
if let customActions = accessibilityData.customActions {
self.messageAccessibilityArea.accessibilityCustomActions = customActions.map({ action -> UIAccessibilityCustomAction in
return ChatMessageAccessibilityCustomAction(name: action.name, target: self, selector: #selector(self.performLocalAccessibilityCustomAction(_:)), action: action.action)
})
} else {
self.messageAccessibilityArea.accessibilityCustomActions = nil
}
}
@objc private func performLocalAccessibilityCustomAction(_ action: UIAccessibilityCustomAction) {
if let action = action as? ChatMessageAccessibilityCustomAction {
switch action.action {
case .reply:
if let item = self.item {
item.controllerInteraction.setupReply(item.message.id)
}
case .options:
if let item = self.item {
item.controllerInteraction.openMessageContextMenu(item.message, false, self, self.imageNode.frame, nil)
}
}
}
}
override func asyncLayout() -> (_ item: ChatMessageItem, _ params: ListViewItemLayoutParams, _ mergedTop: ChatMessageMerge, _ mergedBottom: ChatMessageMerge, _ dateHeaderAtBottom: Bool) -> (ListViewItemNodeLayout, (ListViewItemUpdateAnimation, Bool) -> Void) {
let displaySize = CGSize(width: 184.0, height: 184.0)
let telegramFile = self.telegramFile
let layoutConstants = self.layoutConstants
let imageLayout = self.imageNode.asyncLayout()
let makeDateAndStatusLayout = self.dateAndStatusNode.asyncLayout()
let actionButtonsLayout = ChatMessageActionButtonsNode.asyncLayout(self.actionButtonsNode)
let textLayout = TextNode.asyncLayout(self.textNode)
let viaBotLayout = TextNode.asyncLayout(self.viaBotNode)
let makeReplyInfoLayout = ChatMessageReplyInfoNode.asyncLayout(self.replyInfoNode)
let currentReplyBackgroundNode = self.replyBackgroundNode
let currentShareButtonNode = self.shareButtonNode
let currentItem = self.item
return { item, params, mergedTop, mergedBottom, dateHeaderAtBottom in
let accessibilityData = ChatMessageAccessibilityData(item: item, isSelected: nil)
let layoutConstants = chatMessageItemLayoutConstants(layoutConstants, params: params, presentationData: item.presentationData)
let incoming = item.message.effectivelyIncoming(item.context.account.peerId)
var imageSize: CGSize = CGSize(width: 100.0, height: 100.0)
if let telegramFile = telegramFile {
if let dimensions = telegramFile.dimensions {
imageSize = dimensions.cgSize.aspectFitted(displaySize)
} else if let thumbnailSize = telegramFile.previewRepresentations.first?.dimensions {
imageSize = thumbnailSize.cgSize.aspectFitted(displaySize)
}
}
var textLayoutAndApply: (TextNodeLayout, () -> TextNode)?
var isEmoji = false
if item.presentationData.largeEmoji && messageIsElligibleForLargeEmoji(item.message) {
let attributedText = NSAttributedString(string: item.message.text, font: item.presentationData.messageEmojiFont, textColor: .black)
textLayoutAndApply = textLayout(TextNodeLayoutArguments(attributedString: attributedText, backgroundColor: nil, maximumNumberOfLines: 0, truncationType: .end, constrainedSize: CGSize(width: 180.0, height: 90.0), alignment: .natural))
imageSize = CGSize(width: textLayoutAndApply!.0.size.width, height: textLayoutAndApply!.0.size.height)
isEmoji = true
}
let avatarInset: CGFloat
var hasAvatar = false
switch item.chatLocation {
case let .peer(peerId):
if !peerId.isRepliesOrSavedMessages(accountPeerId: item.context.account.peerId) {
if peerId.isGroupOrChannel && item.message.author != nil {
var isBroadcastChannel = false
if let peer = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = peer.info {
isBroadcastChannel = true
}
if !isBroadcastChannel {
hasAvatar = true
}
}
} else if incoming {
hasAvatar = true
}
case let .replyThread(replyThreadMessage):
if replyThreadMessage.messageId.peerId != item.context.account.peerId {
if replyThreadMessage.messageId.peerId.isGroupOrChannel && item.message.author != nil {
var isBroadcastChannel = false
if let peer = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = peer.info {
isBroadcastChannel = true
}
if replyThreadMessage.isChannelPost, replyThreadMessage.effectiveTopId == item.message.id {
isBroadcastChannel = true
}
if !isBroadcastChannel {
hasAvatar = true
}
}
} else if incoming {
hasAvatar = true
}
}
if hasAvatar {
avatarInset = layoutConstants.avatarDiameter
} else {
avatarInset = 0.0
}
let isFailed = item.content.firstMessage.effectivelyFailed(timestamp: item.context.account.network.getApproximateRemoteTimestamp())
var needShareButton = false
if case .pinnedMessages = item.associatedData.subject {
needShareButton = true
} else if isFailed || Namespaces.Message.allScheduled.contains(item.message.id.namespace) {
needShareButton = false
} else if item.message.id.peerId == item.context.account.peerId {
for attribute in item.content.firstMessage.attributes {
if let _ = attribute as? SourceReferenceMessageAttribute {
needShareButton = true
break
}
}
} else if item.message.effectivelyIncoming(item.context.account.peerId) {
if let peer = item.message.peers[item.message.id.peerId] {
if let channel = peer as? TelegramChannel {
if case .broadcast = channel.info {
needShareButton = true
}
}
}
if !needShareButton, let author = item.message.author as? TelegramUser, let _ = author.botInfo, !item.message.media.isEmpty {
needShareButton = true
}
if !needShareButton {
loop: for media in item.message.media {
if media is TelegramMediaGame || media is TelegramMediaInvoice {
needShareButton = true
break loop
} else if let media = media as? TelegramMediaWebpage, case .Loaded = media.content {
needShareButton = true
break loop
}
}
} else {
loop: for media in item.message.media {
if media is TelegramMediaAction {
needShareButton = false
break loop
}
}
}
}
var layoutInsets = UIEdgeInsets(top: mergedTop.merged ? layoutConstants.bubble.mergedSpacing : layoutConstants.bubble.defaultSpacing, left: 0.0, bottom: mergedBottom.merged ? layoutConstants.bubble.mergedSpacing : layoutConstants.bubble.defaultSpacing, right: 0.0)
if dateHeaderAtBottom {
layoutInsets.top += layoutConstants.timestampHeaderHeight
}
var deliveryFailedInset: CGFloat = 0.0
if isFailed {
deliveryFailedInset += 24.0
}
let displayLeftInset = params.leftInset + layoutConstants.bubble.edgeInset + avatarInset
let innerImageInset: CGFloat = 10.0
let innerImageSize = CGSize(width: imageSize.width + innerImageInset * 2.0, height: imageSize.height + innerImageInset * 2.0)
let imageFrame = CGRect(origin: CGPoint(x: 0.0 + (incoming ? (params.leftInset + layoutConstants.bubble.edgeInset + avatarInset + layoutConstants.bubble.contentInsets.left) : (params.width - params.rightInset - innerImageSize.width - layoutConstants.bubble.edgeInset - layoutConstants.bubble.contentInsets.left - deliveryFailedInset)), y: -innerImageInset), size: innerImageSize)
let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: imageSize, boundingSize: imageSize, intrinsicInsets: UIEdgeInsets(top: innerImageInset, left: innerImageInset, bottom: innerImageInset, right: innerImageInset))
let imageApply = imageLayout(arguments)
let statusType: ChatMessageDateAndStatusType
if item.message.effectivelyIncoming(item.context.account.peerId) {
statusType = .FreeIncoming
} else {
if isFailed {
statusType = .FreeOutgoing(.Failed)
} else if item.message.flags.isSending && !item.message.isSentOrAcknowledged {
statusType = .FreeOutgoing(.Sending)
} else {
statusType = .FreeOutgoing(.Sent(read: item.read))
}
}
var edited = false
var viewCount: Int? = nil
var dateReplies = 0
for attribute in item.message.attributes {
if let _ = attribute as? EditedMessageAttribute, isEmoji {
edited = true
} else if let attribute = attribute as? ViewCountMessageAttribute {
viewCount = attribute.count
} else if let attribute = attribute as? ReplyThreadMessageAttribute, case .peer = item.chatLocation {
if let channel = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .group = channel.info {
dateReplies = Int(attribute.count)
}
}
}
var dateReactions: [MessageReaction] = []
var dateReactionCount = 0
if let reactionsAttribute = mergedMessageReactions(attributes: item.message.attributes), !reactionsAttribute.reactions.isEmpty {
for reaction in reactionsAttribute.reactions {
if reaction.isSelected {
dateReactions.insert(reaction, at: 0)
} else {
dateReactions.append(reaction)
}
dateReactionCount += Int(reaction.count)
}
}
let dateText = stringForMessageTimestampStatus(accountPeerId: item.context.account.peerId, message: item.message, dateTimeFormat: item.presentationData.dateTimeFormat, nameDisplayOrder: item.presentationData.nameDisplayOrder, strings: item.presentationData.strings, format: .regular, reactionCount: dateReactionCount)
var isReplyThread = false
if case .replyThread = item.chatLocation {
isReplyThread = true
}
let (dateAndStatusSize, dateAndStatusApply) = makeDateAndStatusLayout(item.context, item.presentationData, edited, viewCount, dateText, statusType, CGSize(width: params.width, height: CGFloat.greatestFiniteMagnitude), dateReactions, dateReplies, item.message.tags.contains(.pinned) && !item.associatedData.isInPinnedListMode && !isReplyThread, item.message.isSelfExpiring)
var viaBotApply: (TextNodeLayout, () -> TextNode)?
var replyInfoApply: (CGSize, () -> ChatMessageReplyInfoNode)?
var updatedReplyBackgroundNode: ASImageNode?
var replyBackgroundImage: UIImage?
var replyMarkup: ReplyMarkupMessageAttribute?
var availableWidth = max(60.0, params.width - params.leftInset - params.rightInset - max(imageSize.width, 160.0) - 20.0 - layoutConstants.bubble.edgeInset * 2.0 - avatarInset - layoutConstants.bubble.contentInsets.left)
if isEmoji {
availableWidth -= 24.0
}
for attribute in item.message.attributes {
if let attribute = attribute as? InlineBotMessageAttribute {
var inlineBotNameString: String?
if let peerId = attribute.peerId, let bot = item.message.peers[peerId] as? TelegramUser {
inlineBotNameString = bot.username
} else {
inlineBotNameString = attribute.title
}
if let inlineBotNameString = inlineBotNameString {
let inlineBotNameColor = serviceMessageColorComponents(theme: item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper).primaryText
let bodyAttributes = MarkdownAttributeSet(font: nameFont, textColor: inlineBotNameColor)
let boldAttributes = MarkdownAttributeSet(font: inlineBotPrefixFont, textColor: inlineBotNameColor)
let botString = addAttributesToStringWithRanges(item.presentationData.strings.Conversation_MessageViaUser("@\(inlineBotNameString)"), body: bodyAttributes, argumentAttributes: [0: boldAttributes])
viaBotApply = viaBotLayout(TextNodeLayoutArguments(attributedString: botString, backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: max(0, availableWidth), height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets()))
}
}
if let replyAttribute = attribute as? ReplyMessageAttribute, let replyMessage = item.message.associatedMessages[replyAttribute.messageId] {
if case let .replyThread(replyThreadMessage) = item.chatLocation, replyThreadMessage.messageId == replyAttribute.messageId {
} else {
replyInfoApply = makeReplyInfoLayout(item.presentationData, item.presentationData.strings, item.context, .standalone, replyMessage, CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude))
}
} else if let attribute = attribute as? ReplyMarkupMessageAttribute, attribute.flags.contains(.inline), !attribute.rows.isEmpty {
replyMarkup = attribute
}
}
if item.message.id.peerId != item.context.account.peerId && !item.message.id.peerId.isReplies {
for attribute in item.message.attributes {
if let attribute = attribute as? SourceReferenceMessageAttribute {
if let sourcePeer = item.message.peers[attribute.messageId.peerId] {
let inlineBotNameColor = serviceMessageColorComponents(theme: item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper).primaryText
let nameString = NSAttributedString(string: sourcePeer.displayTitle(strings: item.presentationData.strings, displayOrder: item.presentationData.nameDisplayOrder), font: inlineBotPrefixFont, textColor: inlineBotNameColor)
viaBotApply = viaBotLayout(TextNodeLayoutArguments(attributedString: nameString, backgroundColor: nil, maximumNumberOfLines: 1, truncationType: .end, constrainedSize: CGSize(width: max(0, availableWidth), height: CGFloat.greatestFiniteMagnitude), alignment: .natural, cutout: nil, insets: UIEdgeInsets()))
}
}
}
}
if replyInfoApply != nil || viaBotApply != nil {
if let currentReplyBackgroundNode = currentReplyBackgroundNode {
updatedReplyBackgroundNode = currentReplyBackgroundNode
} else {
updatedReplyBackgroundNode = ASImageNode()
}
let graphics = PresentationResourcesChat.additionalGraphics(item.presentationData.theme.theme, wallpaper: item.presentationData.theme.wallpaper, bubbleCorners: item.presentationData.chatBubbleCorners)
replyBackgroundImage = graphics.chatFreeformContentAdditionalInfoBackgroundImage
}
var updatedShareButtonNode: ChatMessageShareButton?
if needShareButton {
if let currentShareButtonNode = currentShareButtonNode {
updatedShareButtonNode = currentShareButtonNode
} else {
let buttonNode = ChatMessageShareButton()
updatedShareButtonNode = buttonNode
}
}
let contentHeight = max(imageSize.height, layoutConstants.image.minDimensions.height)
var maxContentWidth = imageSize.width
var actionButtonsFinalize: ((CGFloat) -> (CGSize, (_ animated: Bool) -> ChatMessageActionButtonsNode))?
if let replyMarkup = replyMarkup {
let (minWidth, buttonsLayout) = actionButtonsLayout(item.context, item.presentationData.theme, item.presentationData.chatBubbleCorners, item.presentationData.strings, replyMarkup, item.message, maxContentWidth)
maxContentWidth = max(maxContentWidth, minWidth)
actionButtonsFinalize = buttonsLayout
}
var actionButtonsSizeAndApply: (CGSize, (Bool) -> ChatMessageActionButtonsNode)?
if let actionButtonsFinalize = actionButtonsFinalize {
actionButtonsSizeAndApply = actionButtonsFinalize(maxContentWidth)
}
var layoutSize = CGSize(width: params.width, height: contentHeight)
if isEmoji && !incoming {
layoutSize.height += dateAndStatusSize.height
}
if let actionButtonsSizeAndApply = actionButtonsSizeAndApply {
layoutSize.height += actionButtonsSizeAndApply.0.height
}
var updatedImageFrame = imageFrame.offsetBy(dx: 0.0, dy: floor((contentHeight - imageSize.height) / 2.0))
var dateOffset = CGPoint(x: dateAndStatusSize.width + 4.0, y: dateAndStatusSize.height + 16.0)
if isEmoji {
if incoming {
dateOffset.x = 12.0
} else {
dateOffset.y = 12.0
}
}
var dateAndStatusFrame = CGRect(origin: CGPoint(x: min(layoutSize.width - dateAndStatusSize.width - 14.0, max(displayLeftInset, updatedImageFrame.maxX - dateOffset.x)), y: updatedImageFrame.maxY - dateOffset.y), size: dateAndStatusSize)
let baseShareButtonSize = CGSize(width: 30.0, height: 60.0)
var baseShareButtonFrame = CGRect(origin: CGPoint(x: updatedImageFrame.maxX + 6.0, y: updatedImageFrame.maxY - 10.0 - baseShareButtonSize.height - 4.0), size: baseShareButtonSize)
if isEmoji && incoming {
baseShareButtonFrame.origin.x = dateAndStatusFrame.maxX + 8.0
}
var viaBotFrame: CGRect?
if let (viaBotLayout, _) = viaBotApply {
viaBotFrame = CGRect(origin: CGPoint(x: (!incoming ? (params.leftInset + layoutConstants.bubble.edgeInset + 15.0) : (params.width - params.rightInset - viaBotLayout.size.width - layoutConstants.bubble.edgeInset - 14.0)), y: 8.0), size: viaBotLayout.size)
}
var replyInfoFrame: CGRect?
if let (replyInfoSize, _) = replyInfoApply {
var viaBotSize = CGSize()
if let viaBotFrame = viaBotFrame {
viaBotSize = viaBotFrame.size
}
let replyInfoFrameValue = CGRect(origin: CGPoint(x: (!incoming ? (params.leftInset + layoutConstants.bubble.edgeInset + 10.0) : (params.width - params.rightInset - max(replyInfoSize.width, viaBotSize.width) - layoutConstants.bubble.edgeInset - 10.0)), y: 8.0 + viaBotSize.height), size: replyInfoSize)
replyInfoFrame = replyInfoFrameValue
if let viaBotFrameValue = viaBotFrame {
if replyInfoFrameValue.minX < replyInfoFrameValue.minX {
viaBotFrame = viaBotFrameValue.offsetBy(dx: replyInfoFrameValue.minX - viaBotFrameValue.minX, dy: 0.0)
}
}
}
var replyBackgroundFrame: CGRect?
if let replyInfoFrame = replyInfoFrame {
var viaBotSize = CGSize()
if let viaBotFrame = viaBotFrame {
viaBotSize = viaBotFrame.size
}
replyBackgroundFrame = CGRect(origin: CGPoint(x: replyInfoFrame.minX - 4.0, y: replyInfoFrame.minY - viaBotSize.height - 2.0), size: CGSize(width: max(replyInfoFrame.size.width, viaBotSize.width) + 8.0, height: replyInfoFrame.size.height + viaBotSize.height + 5.0))
}
if let replyBackgroundFrameValue = replyBackgroundFrame {
if replyBackgroundFrameValue.insetBy(dx: -2.0, dy: -2.0).intersects(baseShareButtonFrame) {
let offset: CGFloat = 25.0
layoutSize.height += offset
updatedImageFrame.origin.y += offset
dateAndStatusFrame.origin.y += offset
baseShareButtonFrame.origin.y += offset
}
}
return (ListViewItemNodeLayout(contentSize: layoutSize, insets: layoutInsets), { [weak self] animation, _ in
if let strongSelf = self {
var transition: ContainedViewLayoutTransition = .immediate
if case let .System(duration) = animation {
transition = .animated(duration: duration, curve: .spring)
}
strongSelf.updateAccessibilityData(accessibilityData)
transition.updateFrame(node: strongSelf.imageNode, frame: updatedImageFrame)
imageApply()
if let immediateThumbnailData = telegramFile?.immediateThumbnailData {
let foregroundColor = bubbleVariableColor(variableColor: item.presentationData.theme.theme.chat.message.stickerPlaceholderColor, wallpaper: item.presentationData.theme.wallpaper)
let shimmeringColor = bubbleVariableColor(variableColor: item.presentationData.theme.theme.chat.message.stickerPlaceholderShimmerColor, wallpaper: item.presentationData.theme.wallpaper)
let placeholderFrame = updatedImageFrame.insetBy(dx: innerImageInset, dy: innerImageInset)
strongSelf.placeholderNode.update(backgroundColor: nil, foregroundColor: foregroundColor, shimmeringColor: shimmeringColor, data: immediateThumbnailData, size: placeholderFrame.size)
strongSelf.placeholderNode.frame = placeholderFrame
}
strongSelf.messageAccessibilityArea.frame = CGRect(origin: CGPoint(), size: layoutSize)
strongSelf.containerNode.frame = CGRect(origin: CGPoint(), size: layoutSize)
strongSelf.contextSourceNode.frame = CGRect(origin: CGPoint(), size: layoutSize)
strongSelf.contextSourceNode.contentNode.frame = CGRect(origin: CGPoint(), size: layoutSize)
strongSelf.contextSourceNode.contentRect = strongSelf.imageNode.frame
strongSelf.containerNode.targetNodeForActivationProgressContentRect = strongSelf.contextSourceNode.contentRect
dateAndStatusApply(false)
transition.updateFrame(node: strongSelf.dateAndStatusNode, frame: dateAndStatusFrame)
if let updatedShareButtonNode = updatedShareButtonNode {
if updatedShareButtonNode !== strongSelf.shareButtonNode {
if let shareButtonNode = strongSelf.shareButtonNode {
shareButtonNode.removeFromSupernode()
}
strongSelf.shareButtonNode = updatedShareButtonNode
strongSelf.addSubnode(updatedShareButtonNode)
updatedShareButtonNode.addTarget(strongSelf, action: #selector(strongSelf.shareButtonPressed), forControlEvents: .touchUpInside)
}
let buttonSize = updatedShareButtonNode.update(presentationData: item.presentationData, chatLocation: item.chatLocation, subject: item.associatedData.subject, message: item.message, account: item.context.account)
let shareButtonFrame = CGRect(origin: CGPoint(x: baseShareButtonFrame.minX, y: baseShareButtonFrame.maxY - buttonSize.height), size: buttonSize)
transition.updateFrame(node: updatedShareButtonNode, frame: shareButtonFrame)
} else if let shareButtonNode = strongSelf.shareButtonNode {
shareButtonNode.removeFromSupernode()
strongSelf.shareButtonNode = nil
}
if let updatedReplyBackgroundNode = updatedReplyBackgroundNode {
if strongSelf.replyBackgroundNode == nil {
strongSelf.replyBackgroundNode = updatedReplyBackgroundNode
strongSelf.addSubnode(updatedReplyBackgroundNode)
updatedReplyBackgroundNode.image = replyBackgroundImage
} else {
strongSelf.replyBackgroundNode?.image = replyBackgroundImage
}
} else if let replyBackgroundNode = strongSelf.replyBackgroundNode {
replyBackgroundNode.removeFromSupernode()
strongSelf.replyBackgroundNode = nil
}
if let (_, viaBotApply) = viaBotApply, let viaBotFrame = viaBotFrame {
let viaBotNode = viaBotApply()
if strongSelf.viaBotNode == nil {
strongSelf.viaBotNode = viaBotNode
strongSelf.addSubnode(viaBotNode)
}
viaBotNode.frame = viaBotFrame
strongSelf.replyBackgroundNode?.frame = CGRect(origin: CGPoint(x: viaBotFrame.minX - 6.0, y: viaBotFrame.minY - 2.0 - UIScreenPixel), size: CGSize(width: viaBotFrame.size.width + 11.0, height: viaBotFrame.size.height + 5.0))
} else if let viaBotNode = strongSelf.viaBotNode {
viaBotNode.removeFromSupernode()
strongSelf.viaBotNode = nil
}
if let (_, replyInfoApply) = replyInfoApply, let replyInfoFrame = replyInfoFrame {
let replyInfoNode = replyInfoApply()
if strongSelf.replyInfoNode == nil {
strongSelf.replyInfoNode = replyInfoNode
strongSelf.addSubnode(replyInfoNode)
}
replyInfoNode.frame = replyInfoFrame
strongSelf.replyBackgroundNode?.frame = replyBackgroundFrame ?? CGRect()
if isEmoji && !incoming {
if let _ = item.controllerInteraction.selectionState {
replyInfoNode.alpha = 0.0
strongSelf.replyBackgroundNode?.alpha = 0.0
} else {
replyInfoNode.alpha = 1.0
strongSelf.replyBackgroundNode?.alpha = 1.0
}
}
} else if let replyInfoNode = strongSelf.replyInfoNode {
replyInfoNode.removeFromSupernode()
strongSelf.replyInfoNode = nil
}
if isFailed {
let deliveryFailedNode: ChatMessageDeliveryFailedNode
var isAppearing = false
if let current = strongSelf.deliveryFailedNode {
deliveryFailedNode = current
} else {
isAppearing = true
deliveryFailedNode = ChatMessageDeliveryFailedNode(tapped: {
if let item = self?.item {
item.controllerInteraction.requestRedeliveryOfFailedMessages(item.content.firstMessage.id)
}
})
strongSelf.deliveryFailedNode = deliveryFailedNode
strongSelf.addSubnode(deliveryFailedNode)
}
let deliveryFailedSize = deliveryFailedNode.updateLayout(theme: item.presentationData.theme.theme)
let deliveryFailedFrame = CGRect(origin: CGPoint(x: imageFrame.maxX + deliveryFailedInset - deliveryFailedSize.width, y: imageFrame.maxY - deliveryFailedSize.height - innerImageInset), size: deliveryFailedSize)
if isAppearing {
deliveryFailedNode.frame = deliveryFailedFrame
transition.animatePositionAdditive(node: deliveryFailedNode, offset: CGPoint(x: deliveryFailedInset, y: 0.0))
} else {
transition.updateFrame(node: deliveryFailedNode, frame: deliveryFailedFrame)
}
} else if let deliveryFailedNode = strongSelf.deliveryFailedNode {
strongSelf.deliveryFailedNode = nil
transition.updateAlpha(node: deliveryFailedNode, alpha: 0.0)
transition.updateFrame(node: deliveryFailedNode, frame: deliveryFailedNode.frame.offsetBy(dx: 24.0, dy: 0.0), completion: { [weak deliveryFailedNode] _ in
deliveryFailedNode?.removeFromSupernode()
})
}
if let actionButtonsSizeAndApply = actionButtonsSizeAndApply {
var animated = false
if let _ = strongSelf.actionButtonsNode {
if case .System = animation {
animated = true
}
}
let actionButtonsNode = actionButtonsSizeAndApply.1(animated)
let previousFrame = actionButtonsNode.frame
let actionButtonsFrame = CGRect(origin: CGPoint(x: imageFrame.minX, y: imageFrame.maxY - 10.0), size: actionButtonsSizeAndApply.0)
actionButtonsNode.frame = actionButtonsFrame
if actionButtonsNode !== strongSelf.actionButtonsNode {
strongSelf.actionButtonsNode = actionButtonsNode
actionButtonsNode.buttonPressed = { button in
if let strongSelf = self {
strongSelf.performMessageButtonAction(button: button)
}
}
actionButtonsNode.buttonLongTapped = { button in
if let strongSelf = self {
strongSelf.presentMessageButtonContextMenu(button: button)
}
}
strongSelf.addSubnode(actionButtonsNode)
} else {
if case let .System(duration) = animation {
actionButtonsNode.layer.animateFrame(from: previousFrame, to: actionButtonsFrame, duration: duration, timingFunction: kCAMediaTimingFunctionSpring)
}
}
} else if let actionButtonsNode = strongSelf.actionButtonsNode {
actionButtonsNode.removeFromSupernode()
strongSelf.actionButtonsNode = nil
}
if let forwardInfo = item.message.forwardInfo, forwardInfo.flags.contains(.isImported) {
strongSelf.dateAndStatusNode.pressed = {
guard let strongSelf = self else {
return
}
item.controllerInteraction.displayImportedMessageTooltip(strongSelf.dateAndStatusNode)
}
} else {
strongSelf.dateAndStatusNode.pressed = nil
}
}
})
}
}
@objc func tapLongTapOrDoubleTapGesture(_ recognizer: TapLongTapOrDoubleTapGestureRecognizer) {
switch recognizer.state {
case .ended:
if let (gesture, location) = recognizer.lastRecognizedGestureAndLocation {
if case .doubleTap = gesture {
self.containerNode.cancelGesture()
}
if let action = self.gestureRecognized(gesture: gesture, location: location, recognizer: nil) {
if case .doubleTap = gesture {
self.containerNode.cancelGesture()
}
switch action {
case let .action(f):
f()
case let .optionalAction(f):
f()
case let .openContextMenu(tapMessage, selectAll, subFrame):
self.item?.controllerInteraction.openMessageContextMenu(tapMessage, selectAll, self, subFrame, nil)
}
} else if case .tap = gesture {
self.item?.controllerInteraction.clickThroughMessage()
}
}
default:
break
}
}
private func gestureRecognized(gesture: TapLongTapOrDoubleTapGesture, location: CGPoint, recognizer: TapLongTapOrDoubleTapGestureRecognizer?) -> InternalBubbleTapAction? {
switch gesture {
case .tap:
if let avatarNode = self.accessoryItemNode as? ChatMessageAvatarAccessoryItemNode, avatarNode.frame.contains(location) {
if let item = self.item, let author = item.content.firstMessage.author {
return .optionalAction({
var openPeerId = item.effectiveAuthorId ?? author.id
var navigate: ChatControllerInteractionNavigateToPeer
if item.content.firstMessage.id.peerId == item.context.account.peerId {
navigate = .chat(textInputState: nil, subject: nil, peekData: nil)
} else {
navigate = .info
}
for attribute in item.content.firstMessage.attributes {
if let attribute = attribute as? SourceReferenceMessageAttribute {
openPeerId = attribute.messageId.peerId
navigate = .chat(textInputState: nil, subject: .message(id: attribute.messageId, highlight: true), peekData: nil)
}
}
if item.effectiveAuthorId?.namespace == Namespaces.Peer.Empty {
item.controllerInteraction.displayMessageTooltip(item.content.firstMessage.id, item.presentationData.strings.Conversation_ForwardAuthorHiddenTooltip, self, avatarNode.frame)
} else if let forwardInfo = item.content.firstMessage.forwardInfo, forwardInfo.flags.contains(.isImported), forwardInfo.author == nil {
item.controllerInteraction.displayImportedMessageTooltip(avatarNode)
} else {
if !item.message.id.peerId.isReplies, let channel = item.content.firstMessage.forwardInfo?.author as? TelegramChannel, channel.username == nil {
if case .member = channel.participationStatus {
} else {
item.controllerInteraction.displayMessageTooltip(item.message.id, item.presentationData.strings.Conversation_PrivateChannelTooltip, self, avatarNode.frame)
}
}
item.controllerInteraction.openPeer(openPeerId, navigate, item.message)
}
})
}
}
if let viaBotNode = self.viaBotNode, viaBotNode.frame.contains(location) {
if let item = self.item {
for attribute in item.message.attributes {
if let attribute = attribute as? InlineBotMessageAttribute {
var botAddressName: String?
if let peerId = attribute.peerId, let botPeer = item.message.peers[peerId], let addressName = botPeer.addressName {
botAddressName = addressName
} else {
botAddressName = attribute.title
}
if let botAddressName = botAddressName {
return .optionalAction({
item.controllerInteraction.updateInputState { textInputState in
return ChatTextInputState(inputText: NSAttributedString(string: "@" + botAddressName + " "))
}
item.controllerInteraction.updateInputMode { _ in
return .text
}
})
}
}
}
}
}
if let replyInfoNode = self.replyInfoNode, replyInfoNode.frame.contains(location) {
if let item = self.item {
for attribute in item.message.attributes {
if let attribute = attribute as? ReplyMessageAttribute {
return .optionalAction({
item.controllerInteraction.navigateToMessage(item.message.id, attribute.messageId)
})
}
}
}
}
if let item = self.item, self.imageNode.frame.contains(location) {
return .optionalAction({
let _ = item.controllerInteraction.openMessage(item.message, .default)
})
}
return nil
case .longTap, .doubleTap:
if let item = self.item, self.imageNode.frame.contains(location) {
return .openContextMenu(tapMessage: item.message, selectAll: false, subFrame: self.imageNode.frame)
}
case .hold:
break
}
return nil
}
@objc func shareButtonPressed() {
if let item = self.item {
if case .pinnedMessages = item.associatedData.subject {
item.controllerInteraction.navigateToMessageStandalone(item.content.firstMessage.id)
return
}
if let channel = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = channel.info {
for attribute in item.message.attributes {
if let _ = attribute as? ReplyThreadMessageAttribute {
item.controllerInteraction.openMessageReplies(item.message.id, true, false)
return
}
}
}
if item.content.firstMessage.id.peerId.isReplies {
item.controllerInteraction.openReplyThreadOriginalMessage(item.content.firstMessage)
} else if item.content.firstMessage.id.peerId.isRepliesOrSavedMessages(accountPeerId: item.context.account.peerId) {
for attribute in item.content.firstMessage.attributes {
if let attribute = attribute as? SourceReferenceMessageAttribute {
item.controllerInteraction.navigateToMessage(item.content.firstMessage.id, attribute.messageId)
break
}
}
} else {
item.controllerInteraction.openMessageShareMenu(item.message.id)
}
}
}
@objc func swipeToReplyGesture(_ recognizer: ChatSwipeToReplyRecognizer) {
switch recognizer.state {
case .began:
self.currentSwipeToReplyTranslation = 0.0
if self.swipeToReplyFeedback == nil {
self.swipeToReplyFeedback = HapticFeedback()
self.swipeToReplyFeedback?.prepareImpact()
}
(self.view.window as? WindowHost)?.cancelInteractiveKeyboardGestures()
case .changed:
var translation = recognizer.translation(in: self.view)
translation.x = max(-80.0, min(0.0, translation.x))
var animateReplyNodeIn = false
if (translation.x < -45.0) != (self.currentSwipeToReplyTranslation < -45.0) {
if translation.x < -45.0, self.swipeToReplyNode == nil, let item = self.item {
self.swipeToReplyFeedback?.impact()
let swipeToReplyNode = ChatMessageSwipeToReplyNode(fillColor: bubbleVariableColor(variableColor: item.presentationData.theme.theme.chat.message.shareButtonFillColor, wallpaper: item.presentationData.theme.wallpaper), strokeColor: bubbleVariableColor(variableColor: item.presentationData.theme.theme.chat.message.shareButtonStrokeColor, wallpaper: item.presentationData.theme.wallpaper), foregroundColor: bubbleVariableColor(variableColor: item.presentationData.theme.theme.chat.message.shareButtonForegroundColor, wallpaper: item.presentationData.theme.wallpaper), action: ChatMessageSwipeToReplyNode.Action(self.currentSwipeAction))
self.swipeToReplyNode = swipeToReplyNode
self.addSubnode(swipeToReplyNode)
animateReplyNodeIn = true
}
}
self.currentSwipeToReplyTranslation = translation.x
var bounds = self.bounds
bounds.origin.x = -translation.x
self.bounds = bounds
if let swipeToReplyNode = self.swipeToReplyNode {
swipeToReplyNode.frame = CGRect(origin: CGPoint(x: bounds.size.width, y: floor((self.contentSize.height - 33.0) / 2.0)), size: CGSize(width: 33.0, height: 33.0))
if animateReplyNodeIn {
swipeToReplyNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.12)
swipeToReplyNode.layer.animateSpring(from: 0.1 as NSNumber, to: 1.0 as NSNumber, keyPath: "transform.scale", duration: 0.4)
} else {
swipeToReplyNode.alpha = min(1.0, abs(translation.x / 45.0))
}
}
case .cancelled, .ended:
self.swipeToReplyFeedback = nil
let translation = recognizer.translation(in: self.view)
if case .ended = recognizer.state, translation.x < -45.0 {
if let item = self.item {
if let currentSwipeAction = currentSwipeAction {
switch currentSwipeAction {
case .none:
break
case .reply:
item.controllerInteraction.setupReply(item.message.id)
case .like:
item.controllerInteraction.updateMessageLike(item.message.id, true)
case .unlike:
item.controllerInteraction.updateMessageLike(item.message.id, true)
}
}
}
}
var bounds = self.bounds
let previousBounds = bounds
bounds.origin.x = 0.0
self.bounds = bounds
self.layer.animateBounds(from: previousBounds, to: bounds, duration: 0.3, timingFunction: kCAMediaTimingFunctionSpring)
if let swipeToReplyNode = self.swipeToReplyNode {
self.swipeToReplyNode = nil
swipeToReplyNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3, removeOnCompletion: false, completion: { [weak swipeToReplyNode] _ in
swipeToReplyNode?.removeFromSupernode()
})
swipeToReplyNode.layer.animateScale(from: 1.0, to: 0.2, duration: 0.3, timingFunction: kCAMediaTimingFunctionSpring, removeOnCompletion: false)
}
default:
break
}
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let shareButtonNode = self.shareButtonNode, shareButtonNode.frame.contains(point) {
return shareButtonNode.view
}
return super.hitTest(point, with: event)
}
override func updateSelectionState(animated: Bool) {
guard let item = self.item else {
return
}
if case let .replyThread(replyThreadMessage) = item.chatLocation, replyThreadMessage.effectiveTopId == item.message.id {
return
}
let incoming = item.message.effectivelyIncoming(item.context.account.peerId)
var isEmoji = false
if let item = self.item, item.presentationData.largeEmoji && messageIsElligibleForLargeEmoji(item.message) {
isEmoji = true
}
if let selectionState = item.controllerInteraction.selectionState {
let selected = selectionState.selectedIds.contains(item.message.id)
let offset: CGFloat = incoming ? 42.0 : 0.0
if let selectionNode = self.selectionNode {
let selectionFrame = CGRect(origin: CGPoint(x: -offset, y: 0.0), size: CGSize(width: self.contentBounds.size.width, height: self.contentBounds.size.height))
selectionNode.frame = selectionFrame
selectionNode.updateLayout(size: selectionFrame.size, leftInset: self.safeInsets.left)
selectionNode.updateSelected(selected, animated: animated)
self.subnodeTransform = CATransform3DMakeTranslation(offset, 0.0, 0.0);
} else {
let selectionNode = ChatMessageSelectionNode(wallpaper: item.presentationData.theme.wallpaper, theme: item.presentationData.theme.theme, toggle: { [weak self] value in
if let strongSelf = self, let item = strongSelf.item {
item.controllerInteraction.toggleMessagesSelection([item.message.id], value)
}
})
let selectionFrame = CGRect(origin: CGPoint(x: -offset, y: 0.0), size: CGSize(width: self.contentBounds.size.width, height: self.contentBounds.size.height))
selectionNode.frame = selectionFrame
selectionNode.updateLayout(size: selectionFrame.size, leftInset: self.safeInsets.left)
self.addSubnode(selectionNode)
self.selectionNode = selectionNode
selectionNode.updateSelected(selected, animated: false)
let previousSubnodeTransform = self.subnodeTransform
self.subnodeTransform = CATransform3DMakeTranslation(offset, 0.0, 0.0);
if animated {
selectionNode.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2)
self.layer.animate(from: NSValue(caTransform3D: previousSubnodeTransform), to: NSValue(caTransform3D: self.subnodeTransform), keyPath: "sublayerTransform", timingFunction: CAMediaTimingFunctionName.easeOut.rawValue, duration: 0.2)
if !incoming {
let position = selectionNode.layer.position
selectionNode.layer.animatePosition(from: CGPoint(x: position.x - 42.0, y: position.y), to: position, duration: 0.2, timingFunction: CAMediaTimingFunctionName.easeOut.rawValue)
}
}
}
if let replyInfoNode = self.replyInfoNode, isEmoji && !incoming {
let alpha: CGFloat = 0.0
let previousAlpha = replyInfoNode.alpha
replyInfoNode.alpha = alpha
self.replyBackgroundNode?.alpha = alpha
if animated {
replyInfoNode.layer.animateAlpha(from: previousAlpha, to: alpha, duration: 0.3)
self.replyBackgroundNode?.layer.animateAlpha(from: previousAlpha, to: alpha, duration: 0.3)
}
}
} else {
if let selectionNode = self.selectionNode {
self.selectionNode = nil
let previousSubnodeTransform = self.subnodeTransform
self.subnodeTransform = CATransform3DIdentity
if animated {
self.layer.animate(from: NSValue(caTransform3D: previousSubnodeTransform), to: NSValue(caTransform3D: self.subnodeTransform), keyPath: "sublayerTransform", timingFunction: CAMediaTimingFunctionName.easeOut.rawValue, duration: 0.2, completion: { [weak selectionNode]_ in
selectionNode?.removeFromSupernode()
})
selectionNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false)
if CGFloat(0.0).isLessThanOrEqualTo(selectionNode.frame.origin.x) {
let position = selectionNode.layer.position
selectionNode.layer.animatePosition(from: position, to: CGPoint(x: position.x - 42.0, y: position.y), duration: 0.2, timingFunction: CAMediaTimingFunctionName.easeOut.rawValue, removeOnCompletion: false)
}
} else {
selectionNode.removeFromSupernode()
}
}
if let replyInfoNode = self.replyInfoNode, isEmoji && !incoming {
let alpha: CGFloat = 1.0
let previousAlpha = replyInfoNode.alpha
replyInfoNode.alpha = alpha
self.replyBackgroundNode?.alpha = alpha
if animated {
replyInfoNode.layer.animateAlpha(from: previousAlpha, to: alpha, duration: 0.3)
self.replyBackgroundNode?.layer.animateAlpha(from: previousAlpha, to: alpha, duration: 0.3)
}
}
}
}
override func updateHighlightedState(animated: Bool) {
super.updateHighlightedState(animated: animated)
if let item = self.item {
var highlighted = false
if let highlightedState = item.controllerInteraction.highlightedState {
if highlightedState.messageStableId == item.message.stableId {
highlighted = true
}
}
if self.highlightedState != highlighted {
self.highlightedState = highlighted
if highlighted {
self.imageNode.setOverlayColor(item.presentationData.theme.theme.chat.message.mediaHighlightOverlayColor, animated: false)
} else {
self.imageNode.setOverlayColor(nil, animated: animated)
}
}
}
}
override func animateInsertion(_ currentTimestamp: Double, duration: Double, short: Bool) {
super.animateInsertion(currentTimestamp, duration: duration, short: short)
self.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2)
}
override func animateRemoved(_ currentTimestamp: Double, duration: Double) {
super.animateRemoved(currentTimestamp, duration: duration)
self.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.2, removeOnCompletion: false)
}
override func animateAdded(_ currentTimestamp: Double, duration: Double) {
super.animateAdded(currentTimestamp, duration: duration)
self.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.2)
}
override func getMessageContextSourceNode(stableId: UInt32?) -> ContextExtractedContentContainingNode? {
return self.contextSourceNode
}
override func addAccessoryItemNode(_ accessoryItemNode: ListViewAccessoryItemNode) {
self.contextSourceNode.contentNode.addSubnode(accessoryItemNode)
}
}
| 55.805882 | 657 | 0.5717 |
0322e9feee5d40727f9aa6aa9a30822b2dddec1c | 6,799 | //: [Previous](@previous)
import PlaygroundSupport
import Foundation
import ParseSwift
import SwiftUI
PlaygroundPage.current.needsIndefiniteExecution = true
initializeParse()
//: Create your own value typed ParseObject.
struct GameScore: ParseObject {
//: These are required for any Object.
var objectId: String?
var createdAt: Date?
var updatedAt: Date?
var ACL: ParseACL?
//: Your own properties.
var score: Int = 0
var location: ParseGeoPoint?
var name: String?
//: Custom initializer.
init(name: String, score: Int) {
self.name = name
self.score = score
}
}
//: Create a delegate for LiveQuery errors
class LiveQueryDelegate: ParseLiveQueryDelegate {
func received(_ error: Error) {
print(error)
}
func closedSocket(_ code: URLSessionWebSocketTask.CloseCode?, reason: Data?) {
print("Socket closed with \(String(describing: code)) and \(String(describing: reason))")
}
}
//: Be sure you have LiveQuery enabled on your server.
//: Set the delegate.
let delegate = LiveQueryDelegate()
if let socket = ParseLiveQuery.getDefault() {
socket.receiveDelegate = delegate
}
//: Create a query just as you normally would.
var query = GameScore.query("score" < 11)
//: This is how you subscribe to your created query using callbacks.
let subscription = query.subscribeCallback!
//: This is how you receive notifications about the success
//: of your subscription.
subscription.handleSubscribe { subscribedQuery, isNew in
//: You can check this subscription is for this query
if isNew {
print("Successfully subscribed to new query \(subscribedQuery)")
} else {
print("Successfully updated subscription to new query \(subscribedQuery)")
}
}
//: This is how you register to receive notifications of events related to your LiveQuery.
subscription.handleEvent { _, event in
switch event {
case .entered(let object):
print("Entered: \(object)")
case .left(let object):
print("Left: \(object)")
case .created(let object):
print("Created: \(object)")
case .updated(let object):
print("Updated: \(object)")
case .deleted(let object):
print("Deleted: \(object)")
}
}
//: Ping the LiveQuery server
ParseLiveQuery.client?.sendPing { error in
if let error = error {
print("Error pinging LiveQuery server: \(error)")
} else {
print("Successfully pinged server!")
}
}
//: Now go to your dashboard, go to the GameScore table and add, update or remove rows.
//: You should receive notifications for each.
//: This is how you register to receive notifications about being unsubscribed.
subscription.handleUnsubscribe { query in
print("Unsubscribed from \(query)")
}
//: To unsubscribe from your query.
do {
try query.unsubscribe()
} catch {
print(error)
}
//: If you look at your server log, you will notice the client and server disconnnected.
//: This is because there is no more LiveQuery subscriptions.
//: Ping the LiveQuery server. This should produce an error
//: because LiveQuery is disconnected.
ParseLiveQuery.client?.sendPing { error in
if let error = error {
print("Error pinging LiveQuery server: \(error)")
} else {
print("Successfully pinged server!")
}
}
//: Create a new query.
var query2 = GameScore.query("score" > 50)
//: Select the fields you are interested in receiving.
query2.fields("score")
//: Subscribe to your new query.
let subscription2 = query2.subscribeCallback!
//: As before, setup your subscription, event, and unsubscribe handlers.
subscription2.handleSubscribe { subscribedQuery, isNew in
//: You can check this subscription is for this query.
if isNew {
print("Successfully subscribed to new query \(subscribedQuery)")
} else {
print("Successfully updated subscription to new query \(subscribedQuery)")
}
}
subscription2.handleEvent { _, event in
switch event {
case .entered(let object):
print("Entered: \(object)")
case .left(let object):
print("Left: \(object)")
case .created(let object):
print("Created: \(object)")
case .updated(let object):
print("Updated: \(object)")
case .deleted(let object):
print("Deleted: \(object)")
}
}
subscription2.handleUnsubscribe { query in
print("Unsubscribed from \(query)")
}
//: To close the current LiveQuery connection.
ParseLiveQuery.client?.close()
//: To close all LiveQuery connections use:
//ParseLiveQuery.client?.closeAll()
//: Ping the LiveQuery server. This should produce an error
//: because LiveQuery is disconnected.
ParseLiveQuery.client?.sendPing { error in
if let error = error {
print("Error pinging LiveQuery server: \(error)")
} else {
print("Successfully pinged server!")
}
}
//: Resubscribe to your previous query.
//: Since we never unsubscribed you can use your previous handlers.
let subscription3 = query2.subscribeCallback!
//: Resubscribe to another previous query.
//: This one needs new handlers.
let subscription4 = query.subscribeCallback!
//: Need a new handler because we previously unsubscribed.
subscription4.handleSubscribe { subscribedQuery, isNew in
//: You can check this subscription is for this query
if isNew {
print("Successfully subscribed to new query \(subscribedQuery)")
} else {
print("Successfully updated subscription to new query \(subscribedQuery)")
}
}
//: Need a new event handler because we previously unsubscribed.
subscription4.handleEvent { _, event in
switch event {
case .entered(let object):
print("Entered: \(object)")
case .left(let object):
print("Left: \(object)")
case .created(let object):
print("Created: \(object)")
case .updated(let object):
print("Updated: \(object)")
case .deleted(let object):
print("Deleted: \(object)")
}
}
//: Need a new unsubscribe handler because we previously unsubscribed.
subscription4.handleUnsubscribe { query in
print("Unsubscribed from \(query)")
}
//: To unsubscribe from your query.
do {
try query2.unsubscribe()
} catch {
print(error)
}
//: Ping the LiveQuery server
ParseLiveQuery.client?.sendPing { error in
if let error = error {
print("Error pinging LiveQuery server: \(error)")
} else {
print("Successfully pinged server!")
}
}
//: To unsubscribe from your your last query.
do {
try query.unsubscribe()
} catch {
print(error)
}
//: If you look at your server log, you will notice the client and server disconnnected.
//: This is because there is no more LiveQuery subscriptions.
PlaygroundPage.current.finishExecution()
//: [Next](@next)
| 27.305221 | 97 | 0.683042 |
e0a0d2e26f012fc791434b972272519aedb98e14 | 428 | import UIKit
extension String {
func size(withSystemFontSize pointSize: CGFloat) -> CGSize {
return (self as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: pointSize)])
}
}
extension CGPoint {
func adding(x: CGFloat) -> CGPoint { return CGPoint(x: self.x + x, y: self.y) }
func adding(y: CGFloat) -> CGPoint { return CGPoint(x: self.x, y: self.y + y) }
}
| 32.923077 | 122 | 0.668224 |
48e29f93936d5e385a3b2ff9e197c86bddaad494 | 1,391 | //
// DecodeStringTests.swift
// CodingChallengesTests
//
// Created by William Boles on 15/12/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import XCTest
@testable import CodingChallenges
class DecodeStringTests: XCTestCase {
// MARK: - Tests
func test_A() {
let s = "3[a]2[bc]"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "aaabcbc")
}
func test_B() {
let s = "3[a2[c]]"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "accaccacc")
}
func test_C() {
let s = "2[abc]3[cd]ef"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "abcabccdcdcdef")
}
func test_D() {
let s = "abc3[cd]xyz"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "abccdcdcdxyz")
}
func test_E() {
let s = "10[leetcode]"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode")
}
func test_F() {
let s = "12[e]"
let decoded = DecodeString.decodeString(s)
XCTAssertEqual(decoded, "eeeeeeeeeeee")
}
}
| 21.4 | 115 | 0.565061 |
163cadef3b5f7203f61412d97c75fd089255534c | 1,070 | //
// UIImage+MADExtension.swift
// OstrichBlockChain
//
// Created by 梁宪松 on 2018/10/31.
// Copyright © 2018 ipzoe. All rights reserved.
//
import UIKit
extension UIImage {
static func mad_getImage(color: UIColor, size:CGSize, cornerRadius: CGFloat) -> UIImage? {
let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale);
let context = UIGraphicsGetCurrentContext();
context!.setFillColor(color.cgColor);
context!.fill(rect);
var image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale);
UIBezierPath.init(roundedRect: rect, cornerRadius: cornerRadius).addClip();
image?.draw(in: rect);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
}
| 29.722222 | 94 | 0.652336 |
221e1d5b09e643fd280da2570dbd8329eb225675 | 1,470 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// ClusterVersions is the azure Service Fabric Resource Provider API Client
import Foundation
import azureSwiftRuntime
extension Commands {
public struct ClusterVersions {
public static func Get(location: String, subscriptionId: String, clusterVersion: String) -> ClusterVersionsGet {
return GetCommand(location: location, subscriptionId: subscriptionId, clusterVersion: clusterVersion)
}
public static func GetByEnvironment(location: String, environment: GetByEnvironmentEnvironmentEnum, subscriptionId: String, clusterVersion: String) -> ClusterVersionsGetByEnvironment {
return GetByEnvironmentCommand(location: location, environment: environment, subscriptionId: subscriptionId, clusterVersion: clusterVersion)
}
public static func List(location: String, subscriptionId: String) -> ClusterVersionsList {
return ListCommand(location: location, subscriptionId: subscriptionId)
}
public static func ListByEnvironment(location: String, environment: ListByEnvironmentEnvironmentEnum, subscriptionId: String) -> ClusterVersionsListByEnvironment {
return ListByEnvironmentCommand(location: location, environment: environment, subscriptionId: subscriptionId)
}
}
}
| 58.8 | 189 | 0.780952 |
d9fabd527aa400179ee780defb92865ada90b5a7 | 979 | //
// TestDriveTests.swift
// TestDriveTests
//
// Created by Jorge Cruz on 12/7/15.
// Copyright © 2015 Jorge Cruz. All rights reserved.
//
import XCTest
@testable import TestDrive
class TestDriveTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.459459 | 111 | 0.635342 |
d7813515a7e622a35285d16b87a88cae06664429 | 3,703 | //
// FeedbackViewController.swift
// iMast
//
// Created by rinsuki on 2018/10/10.
//
// ------------------------------------------------------------------------
//
// Copyright 2017-2019 rinsuki and other 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.
//
import UIKit
import Eureka
import Alamofire
class FeedbackViewController: FormViewController {
let versionString = (Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)+"(\((Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String)))"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let footerText = "GitHub アカウントをお持ちの場合、公開できる内容のバグ報告は GitHub 上でしてくれるとうれしいです\nhttps://github.com/cinderella-project/iMast"
self.form.append {
Section(footer: footerText) {
TextAreaRow("body") { row in
row.placeholder = "Feedbackの内容をお書きください"
row.textAreaHeight = TextAreaHeight.dynamic(initialTextViewHeight: 90)
}
}
Section(header: "Feedbackを送信すると、以下の情報も一緒に送信され、iMastの改善に役立てられます。") {
LabelRow {
$0.title = "iMastのバージョン"
$0.value = versionString
}
LabelRow {
$0.title = "iOSのバージョン"
$0.value = UIDevice.current.systemVersion
}
LabelRow {
$0.title = "端末名"
$0.value = UIDevice.current.platform
}
}
Section {
ButtonRow {
$0.title = "送信"
$0.onCellSelection { [weak self] cell, row in
self?.sendFeedback()
}
}
}
}
title = "Feedback"
}
func sendFeedback() {
let values = form.values()
guard let body = values["body"] as? String, body.count > 0 else {
alert(title: "エラー", message: "Feedbackの内容を入力してください")
return
}
let postBody = [
"body": body,
"app_version": versionString,
"ios_version": UIDevice.current.systemVersion,
"device_name": UIDevice.current.platform,
]
Alamofire.request("https://imast-backend.rinsuki.net/old-api/feedback", method: .post, parameters: postBody).responseJSON { request in
if (request.response?.statusCode ?? 0) >= 400 {
self.alert(title: "通信エラー", message: "通信に失敗しました。(HTTP-\((request.response?.statusCode ?? 599)))\nしばらく待ってから、もう一度送信してみてください。\nFeedbackは@[email protected]へのリプライでも受け付けています。")
}
if request.error != nil {
self.alert(title: "通信エラー", message: "通信に失敗しました。\nしばらく待ってから、もう一度送信してみてください。\nFeedbackは@[email protected]へのリプライでも受け付けています。")
return
}
self.navigationController?.popViewController(animated: true)
self.alert(title: "送信しました!", message: "Feedbackありがとうございました。")
}
}
}
| 38.978947 | 195 | 0.571159 |
69e8b4609ccadc86cf35cc666d333120b2a4eed6 | 4,253 | //
// AddTokenWindowController.swift
//
// Copyright © 2020 Steamclock Software.
//
// 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 Cocoa
import SwiftyUserDefaults
import Valet
protocol AddTokenDelegate: AnyObject {
func addTokenWindowControllerDidEnterToken(_ addTokenWindowController: AddTokenWindowController)
}
class AddTokenWindowController: NSWindowController {
private var sourceViewController: AddTokenSourceViewController?
private var authViewController: AddTokenAuthViewController?
weak var delegate: AddTokenDelegate?
var isFirstUse = false {
didSet {
sourceViewController?.isFirstUse = isFirstUse
}
}
override func windowDidLoad() {
super.windowDidLoad()
sourceViewController = AddTokenSourceViewController(nibName: NSNib.Name("AddTokenSourceViewController"), bundle: nil)
sourceViewController?.delegate = self
authViewController = AddTokenAuthViewController(nibName: NSNib.Name("AddTokenAuthViewController"), bundle: nil)
authViewController?.delegate = self
window?.contentViewController = sourceViewController
sourceViewController?.isFirstUse = isFirstUse
}
func reset() {
// We don't want this to run if the window hasn't loaded yet
guard let authView = authViewController else { return }
authView.reset()
window?.contentViewController = sourceViewController
}
}
extension AddTokenWindowController: AddTokenSourceDelegate {
func addTokenSourceSelected(_ addTokenSourceViewController: AddTokenSourceViewController, source: Source) {
authViewController?.source = source
window?.contentViewController = authViewController
}
}
extension AddTokenWindowController: AddTokenAuthDelegate {
func addTokenAuthDidComplete(_ addTokenAuthViewController: AddTokenAuthViewController) {
delegate?.addTokenWindowControllerDidEnterToken(self)
}
func addTokenAuthDidCancel(_ addTokenAuthViewController: AddTokenAuthViewController) {
addTokenAuthViewController.source = nil
window?.contentViewController = sourceViewController
}
func addTokenAuthDidError(_ addTokenAuthViewController: AddTokenAuthViewController, error: String) {
showAlert(message: error)
}
func addTokenAuthDidFailToken(_ addTokenAuthViewController: AddTokenAuthViewController, error: String, token: Token, key: String) {
let alert = NSAlert()
alert.messageText = "We couldn't retrieve any issues for that token, you may not have given the token the 'repo' scope. Did you mean to do this?"
alert.alertStyle = .warning
alert.addButton(withTitle: "Keep using this token")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!) { response in
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
// Keep this token pressed
DefaultsKeys.add(token: token)
try? Valet.shared.setString(key, forKey: token.key)
AnalyticsModel.shared.tokenAdded(source: token.source)
self.close()
}
}
}
}
| 39.747664 | 153 | 0.728897 |
03923d27581f0a7c570328133f0401caffafb8a1 | 404 | import NetService
import class XCTest.XCTestCase
class BrowserTests: XCTestCase {
static var allTests: [(String, (BrowserTests) -> () throws -> Void)] {
return [
("testBrowse", testBrowse)
]
}
func testBrowse() {
let browser = NetServiceBrowser()
browser.searchForServices(ofType: "_ssh._tcp.", inDomain: "local.")
browser.stop()
}
}
| 23.764706 | 75 | 0.60396 |
8fe244e632e15c7495d39b3e70c36d9ad7b7ec80 | 2,085 |
import Foundation
struct Day08: Day {
static func run(input: String) {
let picture = Picture(width: 25, height: 6, input: input)
print("Checksum for Day 8-1 is \(picture.checksum)")
picture.print()
}
struct Picture {
let width: Int
let height: Int
let layers: [[Int]]
init(width: Int, height: Int, input: String) {
self.width = width
self.height = height
let size = width * height
let pixels = input.compactMap { Int(String($0)) }
assert(pixels.count % size == 0)
self.layers = stride(from: 0, to: pixels.count, by: size).map { Array(pixels[$0 ..< min($0 + size, pixels.count)]) }
}
var layerWithMin0: [Int] {
let index = layers.enumerated().map({ (offset, element) -> (Int, Int) in
return (offset, element.filter({ $0 == 0 }).count)
}).min(by: { $0.1 < $1.1 })!.0
return layers[index]
}
var checksum: Int {
let layer = layerWithMin0
let (ones, twos) = layer.reduce((0,0)) { initial, element in
return (
initial.0 + (element == 1 ? 1 : 0),
initial.1 + (element == 2 ? 1 : 0)
)
}
return ones * twos
}
var decode: [Int] {
var image = [Int]()
let size = width*height
for index in 0..<size {
var offset = 0
var pixel: Int
repeat {
pixel = layers[offset][index]
offset += 1
} while pixel == 2
image.append(pixel)
}
return image
}
func print() {
for (index, pixel) in decode.enumerated() {
Swift.print(pixel == 1 ? "X" : " ", terminator: "")
if index % width == width - 1 {
Swift.print("") // Will go to the line
}
}
}
}
}
| 30.661765 | 128 | 0.441247 |
1d03e97353d57c814164cd700c0d5e1c91f5fd2f | 1,784 | // 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: "hummingbird-redis",
platforms: [.iOS(.v12), .tvOS(.v12)],
products: [
.library(name: "HummingbirdRedis", targets: ["HummingbirdRedis"]),
.library(name: "HummingbirdJobsRedis", targets: ["HummingbirdJobsRedis"]),
],
dependencies: [
.package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "0.14.0"),
.package(url: "https://gitlab.com/mordil/RediStack.git", from: "1.1.0"),
],
targets: [
.target(name: "HummingbirdRedis", dependencies: [
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "RediStack", package: "RediStack"),
]),
.target(name: "HummingbirdJobsRedis", dependencies: [
.byName(name: "HummingbirdRedis"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdJobs", package: "hummingbird"),
.product(name: "RediStack", package: "RediStack"),
]),
.testTarget(name: "HummingbirdRedisTests", dependencies: [
.byName(name: "HummingbirdRedis"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdXCT", package: "hummingbird"),
]),
.testTarget(name: "HummingbirdJobsRedisTests", dependencies: [
.byName(name: "HummingbirdJobsRedis"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdJobs", package: "hummingbird"),
.product(name: "HummingbirdXCT", package: "hummingbird"),
]),
]
)
| 43.512195 | 96 | 0.613229 |
f4a51de77b2084169b6f6634a07e6ca4cf153143 | 882 | //
// GroupChannelViewController+Freeze.swift
// FreezeUnFreezeGroupChannel
//
// Created by Yogesh Veeraraj on 08.04.22.
// Copyright © 2022 Sendbird. All rights reserved.
//
import UIKit
extension GroupChannelViewController {
func freezeChannel() {
channel.freeze { [weak self] error in
guard let sbError = error else {
self?.presentAlert(title: "Freeze Channel", message: "Success", closeHandler: nil)
return
}
self?.presentAlert(error: sbError)
}
}
func unFreezeChannel() {
channel.unfreeze { [weak self] error in
guard let sbError = error else {
self?.presentAlert(title: "UnFreeze Channel", message: "Success", closeHandler: nil)
return
}
self?.presentAlert(error: sbError)
}
}
}
| 26.727273 | 100 | 0.585034 |
eddf5c0b4134c7f8ba2994c3e403ce0dd4163413 | 549 |
/*
* Test the waiton and waitonall annotations for for loops
*/
import assert;
import math;
main {
int n = 20;
int j;
@waiton=j @waiton=i
for (int i = 0, j = 1; i < n; i = i + 1, j = j * 2) {
// Hopefully these both turned into local
trace(i+i);
trace(j+1);
}
int k;
@waitonall
for (int i = 0, k = 1; i < n; i = i + 1, k = k * 2) {
// Hopefully these both turned into local
trace(i+i);
trace(k+1);
assertEqual(k, toInt(2**i), "2^" + fromint(i));
}
}
| 18.931034 | 58 | 0.48816 |
4bc11cd898d49ecb6880615028a2337ada997065 | 3,540 | //
// Copyright © 2018 Square, 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 UIKit
class RandomImageCenteringView: UIView {
private var image: UIImage
private var imageViews = [UIImageView]()
init(image: UIImage) {
self.image = image
super.init(frame: .zero)
addImageView(centerRelativeMultiplierX: 1, centerRelativeMultiplierY: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
public func addImageView() {
let insetPercentage: CGFloat = UIDevice.current.isPhone ? 0.5 : 0.3
let randomXMultiplier = generateRandomNumber(min: insetPercentage, max: 2 - insetPercentage)
let randomYMultiplier = generateRandomNumber(min: insetPercentage, max: 2 - insetPercentage)
let randomScale = generateRandomNumber(min: 0.5, max: 1.0, granularity: 0.1)
addImageView(centerRelativeMultiplierX: randomXMultiplier,
centerRelativeMultiplierY: randomYMultiplier,
scale: randomScale)
}
public func removeLastImageView() {
guard let imageView = imageViews.last, imageViews.count > 1 else { return }
imageView.removeConstraints(imageView.constraints)
imageView.removeFromSuperview()
imageViews.removeLast()
}
public func removeAllAddedImageViews() {
for _ in 0..<imageViews.count {
removeLastImageView()
}
}
// MARK: - Private
private func addImageView(centerRelativeMultiplierX: CGFloat,
centerRelativeMultiplierY: CGFloat,
scale: CGFloat = 1) {
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.transform = CGAffineTransform(scaleX: scale, y: scale)
addSubview(imageView)
NSLayoutConstraint.activate([
NSLayoutConstraint(item: imageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: centerRelativeMultiplierX,
constant: 0),
NSLayoutConstraint(item: imageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: centerRelativeMultiplierY,
constant: 0)
])
imageViews.append(imageView)
}
private func generateRandomNumber(min: CGFloat, max: CGFloat, granularity: CGFloat = 0.01) -> CGFloat {
return CGFloat(arc4random_uniform(UInt32(CGFloat(max) / granularity))) * granularity + CGFloat(min)
}
}
| 38.901099 | 107 | 0.598023 |
29e012a1964e369c97fa9a245d2576c1542cf156 | 2,528 | //
// XArchiver.swift
// XFoundation
//
// Created by FITZ on 2022/4/24.
//
import Foundation
public struct XArchiver<T : Any> {
/// 获取本地归档数据
/// - Parameter key: 最后路径
/// - Returns: 对象
public static func unarchiverSaveDatasWithKey(key: String) -> T? {
let array = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let fileName = array.first?.appending("/" + key)
let url = URL(fileURLWithPath: fileName ?? "")
let data = try? Data(contentsOf: url)
guard let realData = data else { return nil }
let unarchiver: NSKeyedUnarchiver?
if #available(iOS 11.0, *) {
unarchiver = try? NSKeyedUnarchiver(forReadingFrom: realData)
} else {
unarchiver = NSKeyedUnarchiver(forReadingWith: realData)
}
guard let realUnarchiver = unarchiver else { return nil }
let datas:T? = realUnarchiver.decodeObject(forKey: key) as? T
unarchiver?.finishDecoding()
return datas
}
/// 归档数据
/// - Parameters:
/// - key: 最后的路径
/// - content: 对象
/// - Returns: 是否成功
public static func archiverDataWithKey(key: String, content: T) -> Bool {
let data: NSMutableData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
let content = content as AnyObject
if !content.conforms(to: NSCoding.self) {
return false
}
archiver.encode(content, forKey: key)
archiver.finishEncoding()
let array = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let fileName = array.first?.appending("/" + key)
guard let realFileName = fileName else { return false }
if data.write(toFile: realFileName, atomically: true) {
return true
}
return false
}
/// 删除指定路径的文件
/// - Parameter fileName: 路径名
/// - Returns: 是否成功
public static func deleteFileWithFileName(fileName: String) -> Bool {
let fileManager = FileManager.default
let filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let uniquePath = filePath?.appending("/" + fileName)
guard let realUniquePath = uniquePath else { return false }
if fileManager.fileExists(atPath: realUniquePath) {
try? fileManager.removeItem(atPath: realUniquePath)
return true
}
return false
}
}
| 34.630137 | 107 | 0.623813 |
16ab0a4cf8997a967419fb94b29785713c5ef916 | 16,803 | //
// SocketIOClient.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 11/23/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable {
public let socketURL: String
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public var connectParams: [String: AnyObject]?
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
self.options = options
if socketURL["https://"].matches().count != 0 {
self.options.insertIgnore(.Secure(true))
}
self.socketURL = socketURL["https?://"] ~= ""
for option in options {
switch option {
case let .ConnectParams(params):
connectParams = params
case let .Reconnects(reconnects):
self.reconnects = reconnects
case let .ReconnectAttempts(attempts):
reconnectAttempts = attempts
case let .ReconnectWait(wait):
reconnectWait = abs(wait)
case let .Nsp(nsp):
self.nsp = nsp
case let .Log(log):
DefaultSocketLogger.Logger.log = log
case let .Logger(logger):
DefaultSocketLogger.Logger = logger
case let .HandleQueue(queue):
handleQueue = queue
case let .ForceNew(force):
forceNew = force
default:
continue
}
}
self.options.insertIgnore(.Path("/socket.io"))
super.init()
}
/**
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
*/
public convenience init(socketURL: String, options: NSDictionary?) {
self.init(socketURL: socketURL,
options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
engine?.close()
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
engine = SocketEngine(client: self, url: socketURL, options: options)
return engine!
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
reconnects = false
didDisconnect("Closed")
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter: Int,
withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
type: logType)
return
}
status = .Connecting
if engine == nil || forceNew {
addEngine().open(connectParams)
} else {
engine?.open(connectParams)
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close()
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
currentAck += 1
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, this.handleQueue) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: [], isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close()
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason: AnyObject) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect() {
close()
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else {return}
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack, items: data)
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool,
withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
}
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(data, withAck: ack, withSocket: self)
}
}
}
/**
Leaves nsp and goes back to /
*/
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
nsp = "/"
}
}
/**
Joins namespace
*/
public func joinNamespace(namespace: String) {
nsp = namespace
if nsp != "/" {
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
engine?.send("0\(nsp)", withData: [])
}
}
/**
Removes handler(s)
*/
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else {return}
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
public func open() {
connect()
}
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message", type: "SocketIOClient")
dispatch_async(parseQueue) {
self.parseSocketMessage(msg)
}
}
public func parseEngineBinaryData(data: NSData) {
dispatch_async(parseQueue) {
self.parseBinaryData(data)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt += 1
connect()
}
}
// Test extensions
extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
}
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
}
}
| 32.313462 | 118 | 0.574362 |
79dab48bdbf629c2b2d16c6dc9c4004fda216835 | 2,690 | //
// LoggedOutViewController.swift
// TicTacToe
//
// Created by 정연문 on 2022/01/11.
// Copyright © 2022 Uber. All rights reserved.
//
import RIBs
import RxSwift
import UIKit
import SnapKit
protocol LoggedOutPresentableListener: AnyObject {
// TODO: Declare properties and methods that the view controller can invoke to perform
// business logic, such as signIn(). This protocol is implemented by the corresponding
// interactor class.
func login(player1Name: String?, player2Name: String?)
}
final class LoggedOutViewController: UIViewController, LoggedOutPresentable, LoggedOutViewControllable {
// MARK: - Properties
weak var listener: LoggedOutPresentableListener?
let player1Field: UITextField = {
let textField = UITextField()
textField.layer.borderWidth = 1
textField.layer.borderColor = UIColor.orange.cgColor
textField.placeholder = " Player 1 Name"
return textField
}()
let player2Field: UITextField = {
let textField = UITextField()
textField.layer.borderWidth = 1
textField.layer.borderColor = UIColor.orange.cgColor
textField.placeholder = " Player 2 Name"
return textField
}()
let loginButton: UIButton = {
let button = UIButton()
button.setTitle("로그인", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 14, weight: .bold)
button.setTitleColor(UIColor.white, for: .normal)
button.setTitleColor(UIColor.white.withAlphaComponent(0.3), for: .highlighted)
button.layer.cornerRadius = 4
button.backgroundColor = UIColor.orange
button.addTarget(self, action: #selector(didTapLoginButton), for: .touchUpInside)
return button
}()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
}
// MARK: - Configure UI
extension LoggedOutViewController {
func configureUI() {
view.backgroundColor = UIColor.white
view.addSubview(player1Field)
player1Field.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(100)
make.leading.trailing.equalToSuperview().inset(40)
make.height.equalTo(40)
}
view.addSubview(player2Field)
player2Field.snp.makeConstraints { (make) in
make.top.equalTo(player1Field.snp.bottom).offset(20)
make.leading.trailing.height.equalTo(player1Field)
}
view.addSubview(loginButton)
loginButton.snp.makeConstraints { (make) in
make.top.equalTo(player2Field.snp.bottom).offset(20)
make.leading.trailing.height.equalTo(player1Field)
}
}
@objc private func didTapLoginButton() {
listener?.login(player1Name: player1Field.text, player2Name: player2Field.text)
}
}
| 29.23913 | 104 | 0.715242 |
fed8e4a937922bb1464a50ea84a8f8093c5ed357 | 1,427 | //
// TipCalcUITests.swift
// TipCalcUITests
//
// Created by Shazia Ajmal on 12/21/19.
// Copyright © 2019 codepath. All rights reserved.
//
import XCTest
class TipCalcUITests: 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
// 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() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.431818 | 182 | 0.652418 |
9050ce5460389fc1e364b3b4a5ef99c7a6d2e850 | 11,726 | //
// Observable+Time.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: throttle
extension ObservableType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func throttle(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func debounce(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: sample
extension ObservableType {
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html)
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sample<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true)
}
}
extension Observable where Element : SignedIntegerType {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func interval(period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
}
// MARK: timer
extension Observable where Element: SignedIntegerType {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func timer(dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType)
-> Observable<E> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
// MARK: take
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func take(duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: skip
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func skip(duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: ignoreElements
extension ObservableType {
/**
Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false.
- seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html)
- returns: An observable sequence that skips all elements of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func ignoreElements()
-> Observable<E> {
return filter { _ -> Bool in
return false
}
}
}
// MARK: delaySubscription
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func delaySubscription(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: buffer
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html)
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func buffer(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[E]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: window
extension ObservableType {
/**
Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed.
- seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html)
- parameter timeSpan: Maximum time length of a window.
- parameter count: Maximum element count of a window.
- parameter scheduler: Scheduler to run windowing timers on.
- returns: An observable sequence of windows (instances of `Observable`).
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func window(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<Observable<E>> {
return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: timeout
extension ObservableType {
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a TimeoutError in case of a timeout.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timeout(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.Timeout), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timeout<O: ObservableConvertibleType where E == O.E>(dueTime: RxTimeInterval, other: O, scheduler: SchedulerType)
-> Observable<E> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler)
}
}
| 42.64 | 316 | 0.715845 |
7a405ac79d5cd94052f2b3362d81451972649cf4 | 14,141 | //
// Operation.swift
// Spine
//
// Created by Ward van Teijlingen on 05-04-15.
// Copyright (c) 2015 Ward van Teijlingen. All rights reserved.
//
import Foundation
fileprivate func statusCodeIsSuccess(_ statusCode: Int?) -> Bool {
return statusCode != nil && 200 ... 299 ~= statusCode!
}
fileprivate extension Error {
/// Promotes the rror to a SpineError.
/// Errors that cannot be represented as a SpineError will be returned as SpineError.unknownError
var asSpineError: SpineError {
switch self {
case is SpineError:
return self as! SpineError
case is SerializerError:
return .serializerError(self as! SerializerError)
default:
return .unknownError
}
}
}
// MARK: - Base operation
/**
The ConcurrentOperation class is an abstract class for all Spine operations.
You must not create instances of this class directly, but instead create
an instance of one of its concrete subclasses.
Subclassing
===========
To support generic subclasses, Operation adds an `execute` method.
Override this method to provide the implementation for a concurrent subclass.
Concurrent state
================
ConcurrentOperation is concurrent by default. To update the state of the operation,
update the `state` instance variable. This will fire off the needed KVO notifications.
Operating against a Spine
=========================
The `Spine` instance variable references the Spine against which to operate.
*/
class ConcurrentOperation: Operation {
enum State: String {
case ready = "isReady"
case executing = "isExecuting"
case finished = "isFinished"
}
/// The current state of the operation
var state: State = .ready {
willSet {
willChangeValue(forKey: newValue.rawValue)
willChangeValue(forKey: state.rawValue)
}
didSet {
didChangeValue(forKey: oldValue.rawValue)
didChangeValue(forKey: state.rawValue)
}
}
override var isReady: Bool {
return super.isReady && state == .ready
}
override var isExecuting: Bool {
return state == .executing
}
override var isFinished: Bool {
return state == .finished
}
override var isAsynchronous: Bool {
return true
}
/// The Spine instance to operate against.
var spine: Spine!
/// Convenience variables that proxy to their spine counterpart
var router: Router {
return spine.router
}
var networkClient: NetworkClient {
return spine.networkClient
}
var serializer: Serializer {
return spine.serializer
}
override init() {}
final override func start() {
if isCancelled {
state = .finished
} else {
state = .executing
main()
}
}
final override func main() {
execute()
}
func execute() {}
}
// MARK: - Main operations
/// FetchOperation fetches a JSONAPI document from a Spine, using a given Query.
class FetchOperation<T: Resource>: ConcurrentOperation {
/// The query describing which resources to fetch.
let query: Query<T>
/// Existing resources onto which to map the fetched resources.
var mappingTargets = [Resource]()
/// The result of the operation. You can safely force unwrap this in the completionBlock.
var result: Failable<JSONAPIDocument, SpineError>?
init(query: Query<T>, spine: Spine) {
self.query = query
super.init()
self.spine = spine
}
override func execute() {
let url = spine.router.urlForQuery(query)
Spine.logInfo(.spine, "Fetching document using URL: \(url)")
networkClient.request(method: "GET", url: url) { statusCode, responseData, networkError in
defer { self.state = .finished }
guard networkError == nil else {
self.result = .failure(.networkError(networkError!))
return
}
if let data = responseData , data.count > 0 {
do {
let document = try self.serializer.deserializeData(data, mappingTargets: self.mappingTargets)
if statusCodeIsSuccess(statusCode) {
self.result = .success(document)
} else {
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: document.errors))
}
} catch let error {
self.result = .failure(error.asSpineError)
}
} else {
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: nil))
}
}
}
}
/// DeleteOperation deletes a resource from a Spine.
class DeleteOperation: ConcurrentOperation {
/// The resource to delete.
let resource: Resource
/// The result of the operation. You can safely force unwrap this in the completionBlock.
var result: Failable<Void, SpineError>?
init(resource: Resource, spine: Spine) {
self.resource = resource
super.init()
self.spine = spine
}
override func execute() {
let URL = spine.router.urlForQuery(Query(resource: resource))
Spine.logInfo(.spine, "Deleting resource \(resource) using URL: \(URL)")
networkClient.request(method: "DELETE", url: URL) { statusCode, responseData, networkError in
defer { self.state = .finished }
guard networkError == nil else {
self.result = .failure(.networkError(networkError!))
return
}
if statusCodeIsSuccess(statusCode) {
self.result = .success(())
} else if let data = responseData , data.count > 0 {
do {
let document = try self.serializer.deserializeData(data)
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: document.errors))
} catch let error {
self.result = .failure(error.asSpineError)
}
} else {
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: nil))
}
}
}
}
/// A SaveOperation updates or adds a resource in a Spine.
class SaveOperation: ConcurrentOperation {
/// The resource to save.
let resource: Resource
/// The result of the operation. You can safely force unwrap this in the completionBlock.
var result: Failable<Void, SpineError>?
/// Whether the resource is a new resource, or an existing resource.
fileprivate let isNewResource: Bool
fileprivate let relationshipOperationQueue = OperationQueue()
init(resource: Resource, spine: Spine) {
self.resource = resource
self.isNewResource = (resource.id == nil)
super.init()
self.spine = spine
self.relationshipOperationQueue.maxConcurrentOperationCount = 1
self.relationshipOperationQueue.addObserver(self, forKeyPath: "operations", context: nil)
}
deinit {
self.relationshipOperationQueue.removeObserver(self, forKeyPath: "operations")
}
override func execute() {
// First update relationships if this is an existing resource. Otherwise the local relationships
// are overwritten with data that is returned from saving the resource.
if isNewResource {
updateResource()
} else {
updateRelationships()
}
}
fileprivate func updateResource() {
let url: URL
let method: String
let options: SerializationOptions
if isNewResource {
url = router.urlForResourceType(resource.resourceType)
method = "POST"
if let idGenerator = spine.idGenerator {
resource.id = idGenerator(resource)
options = [.IncludeToOne, .IncludeToMany, .IncludeID]
} else {
options = [.IncludeToOne, .IncludeToMany]
}
} else {
url = router.urlForQuery(Query(resource: resource))
method = "PATCH"
options = [.IncludeID]
}
let payload: Data
do {
payload = try serializer.serializeResources([resource], options: options)
} catch let error {
result = .failure(error.asSpineError)
state = .finished
return
}
Spine.logInfo(.spine, "Saving resource \(resource) using URL: \(url)")
networkClient.request(method: method, url: url, payload: payload) { statusCode, responseData, networkError in
defer { self.state = .finished }
if let error = networkError {
self.result = .failure(.networkError(error))
return
}
let success = statusCodeIsSuccess(statusCode)
let document: JSONAPIDocument?
if let data = responseData , data.count > 0 {
do {
// Don't map onto the resources if the response is not in the success range.
let mappingTargets: [Resource]? = success ? [self.resource] : nil
document = try self.serializer.deserializeData(data, mappingTargets: mappingTargets)
} catch let error {
self.result = .failure(error.asSpineError)
return
}
} else {
document = nil
}
if success {
self.result = .success(())
} else {
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: document?.errors))
}
}
}
/// Serializes `resource` into NSData using `options`. Any error that occurs is rethrown as a SpineError.
fileprivate func serializePayload(_ resource: Resource, options: SerializationOptions) throws -> Data {
do {
let payload = try serializer.serializeResources([resource], options: options)
return payload
} catch let error {
throw error.asSpineError
}
}
fileprivate func updateRelationships() {
let relationships = resource.fields.filter { field in
return field is Relationship && !field.isReadOnly
}
guard !relationships.isEmpty else {
updateResource()
return
}
let completionHandler: (_ result: Failable<Void, SpineError>?) -> Void = { result in
if let error = result?.error {
self.relationshipOperationQueue.cancelAllOperations()
self.result = .failure(error)
self.state = .finished
}
}
for relationship in relationships {
switch relationship {
case let toOne as ToOneRelationship:
let operation = RelationshipReplaceOperation(resource: resource, relationship: toOne, spine: spine)
operation.completionBlock = { [unowned operation] in completionHandler(operation.result) }
relationshipOperationQueue.addOperation(operation)
case let toMany as ToManyRelationship:
let addOperation = RelationshipMutateOperation(resource: resource, relationship: toMany, mutation: .add, spine: spine)
addOperation.completionBlock = { [unowned addOperation] in completionHandler(addOperation.result) }
relationshipOperationQueue.addOperation(addOperation)
let removeOperation = RelationshipMutateOperation(resource: resource, relationship: toMany, mutation: .remove, spine: spine)
removeOperation.completionBlock = { [unowned removeOperation] in completionHandler(removeOperation.result) }
relationshipOperationQueue.addOperation(removeOperation)
default: ()
}
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let path = keyPath, let queue = object as? OperationQueue , path == "operations" && queue == relationshipOperationQueue else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if queue.operationCount == 0 {
// At this point, we know all relationships are updated
updateResource()
}
}
}
private class RelationshipOperation: ConcurrentOperation {
var result: Failable<Void, SpineError>?
func handleNetworkResponse(_ statusCode: Int?, responseData: Data?, networkError: NSError?) {
defer { self.state = .finished }
guard networkError == nil else {
self.result = .failure(.networkError(networkError!))
return
}
if statusCodeIsSuccess(statusCode) {
self.result = .success(())
} else if let data = responseData, data.count > 0 {
do {
let document = try serializer.deserializeData(data)
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: document.errors))
} catch let error {
self.result = .failure(error.asSpineError)
}
} else {
self.result = .failure(.serverError(statusCode: statusCode!, apiErrors: nil))
}
}
}
/// A RelationshipReplaceOperation replaces the entire contents of a relationship.
private class RelationshipReplaceOperation: RelationshipOperation {
let resource: Resource
let relationship: Relationship
init(resource: Resource, relationship: Relationship, spine: Spine) {
self.resource = resource
self.relationship = relationship
super.init()
self.spine = spine
}
override func execute() {
let url = router.urlForRelationship(relationship, ofResource: resource)
let payload: Data
switch relationship {
case is ToOneRelationship:
payload = try! serializer.serializeLinkData(resource.value(forField: relationship.name) as? Resource)
case is ToManyRelationship:
let relatedResources = (resource.value(forField: relationship.name) as? ResourceCollection)?.resources ?? []
payload = try! serializer.serializeLinkData(relatedResources)
default:
assertionFailure("Cannot only replace relationship contents for ToOneRelationship and ToManyRelationship")
return
}
Spine.logInfo(.spine, "Replacing relationship \(relationship) using URL: \(url)")
networkClient.request(method: "PATCH", url: url, payload: payload, callback: handleNetworkResponse)
}
}
/// A RelationshipMutateOperation mutates a to-many relationship by adding or removing linked resources.
private class RelationshipMutateOperation: RelationshipOperation {
enum Mutation {
case add, remove
}
let resource: Resource
let relationship: ToManyRelationship
let mutation: Mutation
init(resource: Resource, relationship: ToManyRelationship, mutation: Mutation, spine: Spine) {
self.resource = resource
self.relationship = relationship
self.mutation = mutation
super.init()
self.spine = spine
}
override func execute() {
let resourceCollection = resource.value(forField: relationship.name) as! LinkedResourceCollection
let httpMethod: String
let relatedResources: [Resource]
switch mutation {
case .add:
httpMethod = "POST"
relatedResources = resourceCollection.addedResources
case .remove:
httpMethod = "DELETE"
relatedResources = resourceCollection.removedResources
}
guard !relatedResources.isEmpty else {
result = .success(())
state = .finished
return
}
let url = router.urlForRelationship(relationship, ofResource: resource)
let payload = try! serializer.serializeLinkData(relatedResources)
Spine.logInfo(.spine, "Mutating relationship \(relationship) using URL: \(url)")
networkClient.request(method: httpMethod, url: url, payload: payload, callback: handleNetworkResponse)
}
}
| 29.959746 | 148 | 0.719822 |
0ef0ecefb04cb6af5ec102a632c1aadeada6168a | 3,921 | //
// APIClient.swift
// ChatBot
//
// Created by iOS dev on 13/10/2019.
// Copyright © 2019 kvantsoft All rights reserved.
//
import Foundation
import Alamofire
import RxAlamofire
import RxSwift
import RxCocoa
protocol RawValue: Codable {
var someBaseEncodedString: Data { get set }
}
enum AppError: Error {
case noInternet
case networkError(Error?)
case serverResponseError(Int, String)
case unexpectedError(Error?)
}
public protocol APIClientProtocol: AlamofireManager {
func process<Model: Decodable>(_ networkRequest: APIRequest) -> Observable<ApiResult<ApiErrorMessage, Model>>
}
public class APIClient: APIClientProtocol {
private let scheduler: ConcurrentDispatchQueueScheduler = ConcurrentDispatchQueueScheduler(qos: DispatchQoS(qosClass: .userInteractive, relativePriority: 1))
}
extension APIClient {
public func process<Model: Decodable>(_ request: APIRequest) -> Observable<ApiResult<ApiErrorMessage, Model>> {
cancelAllRequests()
let method = request.method
let url = request.url
//let parameters = request.parameters
let headers = request.headers
var r = URLRequest(url: URL(string: url)!)
r.httpMethod = method.rawValue
r.allHTTPHeaderFields = headers
r.httpBody = request.parametersData != nil ? request.parametersData : request.data
let observable = RxAlamofire.requestData(r)
.debug()
//.observeOn(scheduler)
.observeOn(MainScheduler.instance)
.asObservable()
.share(replay: 1)
.expectingObject(ofType: Model.self)
return observable
}
}
public struct ApiErrorMessage: Decodable {
let code: Int?
let message: String?
init(code: Int, message: String) {
self.code = code
self.message = message
}
public init(from decoder: Decoder) throws {
let container = try? decoder.container(keyedBy: ApiErrorMessageKeys.self)
.nestedContainer(keyedBy: ErrorMessageKeys.self, forKey: .error)
self.code = try? container?.decode(Int.self, forKey: .code)
self.message = try? container?.decode(String.self, forKey: .message)
}
enum ApiErrorMessageKeys: String, CodingKey {
case error
}
enum ErrorMessageKeys: String, CodingKey {
case code
case message
}
}
public enum ApiResult<Error, Value: Decodable> {
case success(Value)
case failure(Error)
init(value: Value) {
self = .success(value)
}
init(error: Error) {
self = .failure(error)
}
}
extension Observable where Element == (HTTPURLResponse, Data) {
fileprivate func expectingObject<T: Decodable>(ofType type: T.Type) -> Observable<ApiResult<ApiErrorMessage, T>> {
return self.map { (httpURLResponse, data) -> ApiResult<ApiErrorMessage, T> in
switch httpURLResponse.statusCode {
case 200...299:
if type is RawValue.Type {
guard let object = VoiceModel(someBaseEncodedString: data) as? T else {
return .failure(ApiErrorMessage(code: -1, message: "Ошибка. Повторите позже"))
}
return .success(object)
} else {
let object = try JSONDecoder().decode(type, from: data)
return .success(object)
}
default:
// otherwise try
let apiErrorMessage: ApiErrorMessage
do {
apiErrorMessage = try JSONDecoder().decode(ApiErrorMessage.self, from: data)
} catch _ {
apiErrorMessage = ApiErrorMessage(code: -1, message: "Ошибка. Повторите позже")
}
return .failure(apiErrorMessage)
}
}
}
}
| 30.161538 | 161 | 0.615914 |
e9720c1b6c76f38aa23d15692d140d60f284bcbc | 1,349 | //
// File.swift
//
//
// Created by Tibor Bodecs on 2020. 08. 21..
//
import Foundation
import AWSS3
extension S3.Bucket: ExpressibleByStringLiteral {
/// Create a Bucket object using a String literal
public init(stringLiteral value: String) {
self = .init(name: value)
}
}
extension S3.Bucket {
///
/// Simple bucket name validator
///
/// Rules based on [Bucket restrictions and limitations](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html)
///
/// - Note:
/// This method does not account for the rule disallowing IP Addresses, nor does it check uniqueness or other special cases
///
public func hasValidName() -> Bool {
let validStartEnd = CharacterSet.lowercaseLetters.union(.decimalDigits)
let valid = validStartEnd.union(CharacterSet(charactersIn: ".-"))
guard
let name = self.name,
name.count >= 3,
name.count <= 63,
name.unicodeScalars.allSatisfy({ valid.contains($0) }),
let first = name.first,
first.unicodeScalars.allSatisfy({ validStartEnd.contains($0) }),
let last = name.last,
last.unicodeScalars.allSatisfy({ validStartEnd.contains($0) })
else {
return false
}
return true
}
}
| 27.530612 | 133 | 0.612305 |
dbd69397c7fad493c8e52ecf84477eacb4bfab55 | 2,045 | import Foundation
import ObjectMapper
import Alamofire
open class CallerInfo: Mappable {
// Phone number of a party. Usually it is a plain number including country and area code like 18661234567. But sometimes it could be returned from database with some formatting applied, for example (866)123-4567. This property is filled in all cases where parties communicate by means of global phone numbers, for example when calling to direct numbers or sending/receiving SMS
open var `phoneNumber`: String?
// Extension short number (usually 3 or 4 digits). This property is filled when parties communicate by means of short internal numbers, for example when calling to other extension or sending/receiving Company Pager message
open var `extensionNumber`: String?
// Contains party location (city, state) if one can be determined from phoneNumber. This property is filled only when phoneNumber is not empty and server can calculate location information from it (for example, this information is unavailable for US toll-free numbers)
open var `location`: String?
// Symbolic name associated with a party. If the phone does not belong to the known extension, only the location is returned, the name is not determined then
open var `name`: String?
public init() {
}
convenience public init(phoneNumber: String? = nil, extensionNumber: String? = nil, location: String? = nil, name: String? = nil) {
self.init()
self.phoneNumber = `phoneNumber`
self.extensionNumber = `extensionNumber`
self.location = `location`
self.name = `name`
}
required public init?(map: Map) {
}
open func mapping(map: Map) {
`phoneNumber` <- map["phoneNumber"]
`extensionNumber` <- map["extensionNumber"]
`location` <- map["location"]
`name` <- map["name"]
}
open func toParameters() -> Parameters {
var result = [String: String]()
result["json-string"] = self.toJSONString(prettyPrint: false)!
return result
}
}
| 56.805556 | 381 | 0.707579 |
4a6101a50c0d96687e0efcae1946a7367c9e2516 | 376 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// swiftlint:disable all
import Amplify
import Foundation
public struct Team1: Model {
public let id: String
public var name: String
public init(id: String = UUID().uuidString,
name: String) {
self.id = id
self.name = name
}
}
| 17.090909 | 47 | 0.664894 |
d982bc326094f543f65c410f8c7c1968b4b16909 | 2,316 | //
// Persistence.swift
// HotProspects
//
// Created by Tiger Yang on 10/2/21.
//
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "HotProspects")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
| 41.357143 | 199 | 0.631261 |
e6929a353a77631362334f922df59ffef1010926 | 1,581 | //
// RequestMetadata.swift
// ForecastIO
//
// Created by Satyam Ghodasara on 10/2/16.
//
//
import Foundation
/// Metadata about the consumption of the Dark Sky API.
public struct RequestMetadata {
/// `Cache-Control` HTTP header for responses from the Dark Sky API.
public let cacheControl: String?
/// Number of API requests made by the current API key for today.
public let apiRequestsCount: Int?
/// Server-side response time of the current request in milliseconds.
public let responseTime: Float?
/// Creates a new `RequestMetadata` from a `Dictionary` of Dark Sky API response header fields.
///
/// - parameter headerFields: A `Dictionary` containing Dark Sky API response header fields.
///
/// - returns: A new `RequestMetadata` filled with data from the given Dark Sky API response header fields `Dictionary`.
public init(fromHTTPHeaderFields headerFields: [AnyHashable: Any]) {
cacheControl = headerFields["Cache-Control"] as? String
if let forecastAPICallsHeader = headerFields["x-forecast-api-calls"] as? String {
apiRequestsCount = Int(forecastAPICallsHeader)
} else {
apiRequestsCount = nil
}
if var responseTimeHeader = headerFields["x-response-time"] as? String {
// Remove "ms" units from the string
responseTimeHeader = responseTimeHeader.trimmingCharacters(in: CharacterSet.letters)
responseTime = Float(responseTimeHeader)
} else {
responseTime = nil
}
}
}
| 35.931818 | 124 | 0.669197 |
679a4e4bcb0cd017bb122d057f20539b3f3a3e26 | 2,179 | //
// AppDelegate.swift
// Example
//
// Created by Wojciech Lukaszuk on 27/08/14.
// Copyright (c) 2014 Wojtek Lukaszuk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.361702 | 285 | 0.74346 |
fbff92ff0c773535d4348cde715506b577e73e4b | 7,765 | //
// MPEGXingHeader.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public struct MPEGXingHeader {
// MARK: Type Properties
static let dataMarkerCBR: [UInt8] = [73, 110, 102, 111]
static let dataMarkerVBR: [UInt8] = [88, 105, 110, 103]
static let minDataLength: Int = 8
// MARK: Instance Properties
public var bitRateMode: MPEGBitRateMode
public var framesCount: UInt32?
public var bytesCount: UInt32?
public var tableOfContent: [UInt8]?
public var quality: UInt32?
// MARK:
public var isValid: Bool {
if let framesCount = self.framesCount {
if let bytesCount = self.bytesCount {
if framesCount > bytesCount {
return false
}
}
if framesCount == 0 {
return false
}
}
if let bytesCount = self.bytesCount {
if bytesCount == 0 {
return false
}
}
if let tableOfContent = self.tableOfContent {
if tableOfContent.count != 100 {
return false
}
}
switch self.bitRateMode {
case MPEGBitRateMode.variable:
return true
case MPEGBitRateMode.constant:
if self.framesCount != nil {
return true
}
if self.bytesCount != nil {
return true
}
if self.tableOfContent != nil {
return true
}
if self.tableOfContent != nil {
return true
}
return false
}
}
// MARK: Initializers
public init() {
self.bitRateMode = MPEGBitRateMode.constant
}
public init?(fromData data: [UInt8]) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
var range = Range<UInt64>(0..<UInt64(data.count))
self.init(fromStream: stream, range: &range)
}
public init?(fromStream stream: Stream, range: inout Range<UInt64>) {
assert(stream.isOpen && stream.isReadable && (stream.length >= range.upperBound), "Invalid stream")
guard range.lowerBound < range.upperBound else {
return nil
}
let maxDataLength = UInt64(range.count)
guard UInt64(MPEGXingHeader.minDataLength) <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.lowerBound) else {
return nil
}
let data = stream.read(maxLength: MPEGXingHeader.minDataLength)
guard data.count == MPEGXingHeader.minDataLength else {
return nil
}
if data.starts(with: MPEGXingHeader.dataMarkerVBR) {
self.bitRateMode = MPEGBitRateMode.variable
} else {
guard data.starts(with: MPEGXingHeader.dataMarkerCBR) else {
return nil
}
self.bitRateMode = MPEGBitRateMode.constant
}
if (data[7] & 1) != 0 {
guard range.upperBound - stream.offset >= UInt64(4) else {
return nil
}
let nextData = stream.read(maxLength: 4)
guard nextData.count == 4 else {
return nil
}
var framesCount = UInt32(nextData[3])
framesCount |= UInt32(nextData[2]) << 8
framesCount |= UInt32(nextData[1]) << 16
framesCount |= UInt32(nextData[0]) << 24
self.framesCount = framesCount
}
if (data[7] & 2) != 0 {
guard range.upperBound - stream.offset >= UInt64(4) else {
return nil
}
let nextData = stream.read(maxLength: 4)
guard nextData.count == 4 else {
return nil
}
var bytesCount = UInt32(nextData[3])
bytesCount |= UInt32(nextData[2]) << 8
bytesCount |= UInt32(nextData[1]) << 16
bytesCount |= UInt32(nextData[0]) << 24
self.bytesCount = bytesCount
}
if (data[7] & 4) != 0 {
guard range.upperBound - stream.offset >= UInt64(100) else {
return nil
}
let nextData = stream.read(maxLength: 100)
guard nextData.count == 100 else {
return nil
}
self.tableOfContent = nextData
}
if (data[7] & 8) != 0 {
guard range.upperBound - stream.offset >= UInt64(4) else {
return nil
}
let nextData = stream.read(maxLength: 4)
guard nextData.count == 4 else {
return nil
}
var quality = UInt32(nextData[3])
quality |= UInt32(nextData[2]) << 8
quality |= UInt32(nextData[1]) << 16
quality |= UInt32(nextData[0]) << 24
self.quality = quality
}
range = range.lowerBound..<stream.offset
}
// MARK: Instance Methods
public func toData() -> [UInt8]? {
guard self.isValid else {
return nil
}
var data: [UInt8]
switch self.bitRateMode {
case MPEGBitRateMode.variable:
data = MPEGXingHeader.dataMarkerVBR
case MPEGBitRateMode.constant:
data = MPEGXingHeader.dataMarkerCBR
}
data.append(contentsOf: [0, 0, 0, 0])
if let framesCount = self.framesCount {
data.append(contentsOf: [UInt8((framesCount >> 24) & 255),
UInt8((framesCount >> 16) & 255),
UInt8((framesCount >> 8) & 255),
UInt8((framesCount) & 255)])
data[7] |= 1
}
if let bytesCount = self.bytesCount {
data.append(contentsOf: [UInt8((bytesCount >> 24) & 255),
UInt8((bytesCount >> 16) & 255),
UInt8((bytesCount >> 8) & 255),
UInt8((bytesCount) & 255)])
data[7] |= 2
}
if let tableOfContent = self.tableOfContent {
data.append(contentsOf: tableOfContent)
data[7] |= 4
}
if let quality = self.quality {
data.append(contentsOf: [UInt8((quality >> 24) & 255),
UInt8((quality >> 16) & 255),
UInt8((quality >> 8) & 255),
UInt8((quality) & 255)])
data[7] |= 8
}
return data
}
}
| 27.438163 | 107 | 0.538699 |
08bb4eb4436d51a9854ca4d7b9febfc5bedc1a74 | 2,263 | // Mark: - Calculation Operators
infix operator +: AdditionPrecedence
public func +<N1: IntValue, N2: IntValue>(num1: N1, num2: N2) -> Int
{
return num1.int + num2.int
}
infix operator -: AdditionPrecedence
public func -<N1: IntValue, N2: IntValue>(num1: N1, num2: N2) -> Int
{
return num1.int - num2.int
}
infix operator *: MultiplicationPrecedence
public func *<N1: IntValue, N2: IntValue>(num1: N1, num2: N2) -> Int
{
return num1.int * num2.int
}
infix operator /: MultiplicationPrecedence
public func /<N1: IntValue, N2: IntValue>(num1: N1, num2: N2) -> Int
{
return num1.int / num2.int
}
// Mark: - Assignment Operators
infix operator +=: AssignmentPrecedence
public func +=<N1: IntValue, N2: IntValue>(num1: inout N1, num2: N2)
{
num1.int = num1.int + num2.int
}
public func +=<N1: IntVar, N2: IntValue>(num1: N1, num2: N2)
{
num1.int = num1.int + num2.int
}
infix operator -=: AssignmentPrecedence
public func -=<N1: IntValue, N2: IntValue>(num1: inout N1, num2: N2)
{
num1.int = num1.int - num2.int
}
public func -=<N1: IntVar, N2: IntValue>(num1: N1, num2: N2)
{
num1.int = num1.int - num2.int
}
infix operator *=: AssignmentPrecedence
public func *=<N1: IntValue, N2: IntValue>(num1: inout N1, num2: N2)
{
num1.int = num1.int * num2.int
}
public func *=<N1: IntVar, N2: IntValue>(num1: N1, num2: N2)
{
num1.int = num1.int * num2.int
}
infix operator /=: AssignmentPrecedence
public func /=<N1: IntValue, N2: IntValue>(num1: inout N1, num2: N2)
{
num1.int = num1.int / num2.int
}
public func /=<N1: IntVar, N2: IntValue>(num1: N1, num2: N2)
{
num1.int = num1.int / num2.int
}
// Mark: - Extensions
extension Var: IntVar, IntValue where Value: IntValue
{
public var int: Int
{
get { return value.int }
set { value.int = newValue }
}
}
public protocol IntVar: AnyObject
{
var int: Int { get set }
}
extension Int: IntValue
{
public var int: Int
{
get { return self }
set { self = newValue }
}
}
extension Optional: IntValue where Wrapped: IntValue
{
public var int: Int
{
get { return self?.int ?? 0 }
set { self?.int = newValue }
}
}
public protocol IntValue
{
var int: Int { get set }
}
| 19.016807 | 68 | 0.635882 |
cc23a965623600c5c6be86427f9fcc5e703709a9 | 2,194 | //
// ContentView.swift
// CoolGifList
//
// Created by Giordano Scalzo on 12/10/2021.
//
import SwiftUI
import NukeUI
struct Gif: Identifiable, Codable, Equatable {
static func == (lhs: Gif, rhs: Gif) -> Bool {
lhs.id == rhs.id
}
let id: String
let title: String
var url: String {
images.downsized.url
}
let images: Images
}
struct Images: Codable {
let downsized: Image
}
struct Image: Codable {
let url: String
}
struct Response: Codable {
let data: [Gif]
}
struct Service {
private let apiKey = <INSERT YOUR KEY>
private let pageSize = 10
private let query = "cat"
private let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
func fetchGifs(page: Int) async -> [Gif] {
let offset = page * pageSize
guard let url = URL(string:
"https://api.giphy.com/v1/gifs/search?api_key=\(apiKey)&q=\(query)&limit=\(pageSize)&offset=\(offset)")
else {
return []
}
do {
let (data, _) = try await URLSession
.shared
.data(from: url)
let response = try decoder.decode(Response.self, from: data)
return response.data
} catch {
print(error)
return []
}
}
}
struct ContentView: View {
let service = Service()
@State var gifs: [Gif] = []
@State var page = 0
var body: some View {
List(gifs) { gif in
VStack {
LazyImage(source: gif.url)
.aspectRatio(contentMode: .fit)
Text(gif.title)
}
.task {
if gif == gifs.last {
page += 1
gifs += await service.fetchGifs(page: page)
}
}
}
.listStyle(.plain)
.task {
gifs = await service.fetchGifs(page: page)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22.387755 | 135 | 0.517776 |
3a2a0fc24527304e5f65219c9933d99c46e5d6e9 | 2,702 | import SwiftUI
/// An erased path builder that erases the underlying Content to AnyView
public struct AnyPathBuilder: PathBuilder {
private let buildPathElement: (NavigationPathElement) -> AnyView?
/// Erases the passed PathBuilder's Content to AnyView, if it builds the passed PathElement
public init<Erased: PathBuilder>(erasing: Erased) {
buildPathElement = { pathElement in
erasing
.build(pathElement: pathElement)
.flatMap(AnyView.init)
}
}
public func build(pathElement: NavigationPathElement) -> AnyView? {
buildPathElement(pathElement)
}
}
extension PathBuilder {
/// Erases circular navigation paths
///
/// NavigationTrees define a `PathBuilder<Content: View>` via their builder computed variable.
/// The `Screen` PathBuilder adds `NavigationNode<ScreenView, Successor>`s to the NavigationTree.
///
/// One the one hand, this makes sure that all valid navigation paths are known at build time.
/// On the other hand, this leads to problems if the NavigationTree contains a circular path.
///
/// The following NavigationTree leads to a circular path:
///
/// ```swift
/// struct HomeScreen {
/// let presentationStyle = ScreenPresentationStyle.push
///
/// struct Builder: NavigationTree {
/// var builder: _PathBuilder<
/// NavigationNode<HomeView,
/// NavigationNode<HomeView, ...> // <- Circular Type
/// >
/// > {
/// Screen(
/// HomeScreen.self,
/// content: HomeView.init,
/// nesting: {
/// HomeScreen.Builder()
/// }
/// )
/// }
/// }
/// }
/// ```
///
/// Whenever a `Screen` Builder is contained multiple times in a navigation tree,
/// the `Screen` and its successors are contained recursively in the NavigationTrees content type.
///
/// Unfortunately, the compiler is not able to resolve recursive, generic types.
/// To solve this, we can erase PathBuilders that lead to circular paths.
///
/// ```swift
/// struct HomeScreen {
/// let presentationStyle = ScreenPresentationStyle.push
///
/// struct Builder: NavigationTree {
/// var builder: _PathBuilder<
/// NavigationNode<HomeView, AnyView> // <- No longer circular
/// > {
/// Screen(
/// HomeScreen.self,
/// content: HomeView.init,
/// nesting: {
/// HomeScreen
/// .Builder()
/// .eraseCircularNavigationPath()
/// }
/// )
/// }
/// }
/// }
/// ```
public func eraseCircularNavigationPath() -> AnyPathBuilder {
AnyPathBuilder(erasing: self)
}
}
| 31.788235 | 100 | 0.612139 |
9b3d3eae9a306bfdcb0004bb6175f3a8db6eaf2b | 60 | //
// File.swift
// RnUpdateExample
//
import Foundation
| 8.571429 | 19 | 0.666667 |
fe1018200b2c55b81750a93bc82ce48e4780a8f2 | 417 | //
// Collection+Average.swift
// Timekeeper
//
// Created by Andreas Pfurtscheller on 15.10.21.
//
import Foundation
extension Collection where Element: BinaryInteger {
var average: Double {
Double(reduce(.zero, +)) / Double(count)
}
}
extension Collection where Element: BinaryFloatingPoint {
var average: Double {
Double(reduce(.zero, +)) / Double(count)
}
}
| 16.038462 | 57 | 0.635492 |
d5bb683f269ec0078996afb69ed0faab6d668b3d | 305 | // RestrictFieldDelegate.swift
// TextFields
//
// Created by DavidKevinChen on 3/28/20.
// Copyright © 2020 Udacity. All rights reserved.
import Foundation;
import UIKit;
class RestrictFieldDelegate: NSObject, UITextFieldDelegate {
// MARK: - Accessories
// MARK: - Core method
}
| 19.0625 | 60 | 0.695082 |
1d4a985db0f154ab80990ea0cb8fc666319260e0 | 435 | import Foundation
@objcMembers public class USReverseGeoResponse: NSObject, Codable {
public var results:[USReverseGeoResult]?
public init(dictionary: NSDictionary) {
if let result = dictionary["results"] {
self.results?.append(USReverseGeoResult(dictionary: result as! NSDictionary))
} else {
self.results?.append(USReverseGeoResult(dictionary: NSDictionary()))
}
}
}
| 31.071429 | 89 | 0.673563 |
20a9bc8b3d9aef879edaf4414b7226b3c0bf7514 | 4,728 | // *******************************************
// File Name: UIView+BQExtension.swift
// Author: MrBai
// Created Date: 2019/8/15 2:18 PM
//
// Copyright © 2019 baiqiang
// All rights reserved
// *******************************************
import UIKit
public extension UIView {
var origin: CGPoint {
get { return frame.origin }
set { frame.origin = newValue }
}
@discardableResult
func origin(_ origin: CGPoint) -> Self {
self.origin = origin
return self
}
var top: CGFloat {
get { return frame.origin.y }
set { frame.origin = CGPoint(x: frame.origin.x, y: newValue) }
}
@discardableResult
func top(_ top: CGFloat) -> Self {
self.top = top
return self
}
var left: CGFloat {
get { return frame.origin.x }
set { frame.origin = CGPoint(x: newValue, y: frame.origin.y) }
}
@discardableResult
func left(_ left: CGFloat) -> Self {
self.left = left
return self
}
var bottom: CGFloat {
get { return frame.origin.y + frame.height }
set { top = newValue - frame.height }
}
@discardableResult
func bottom(_ bottom: CGFloat) -> Self {
self.bottom = bottom
return self
}
var right: CGFloat {
get { return frame.origin.x + frame.width }
set { left = newValue - frame.width }
}
@discardableResult
func right(_ right: CGFloat) -> Self {
self.right = right
return self
}
var size: CGSize {
get { return bounds.size }
set { bounds.size = newValue }
}
@discardableResult
func size(_ size: CGSize) -> Self {
self.size = size
return self
}
var sizeW: CGFloat {
get { return frame.width }
set { frame.size = CGSize(width: newValue, height: frame.height) }
}
@discardableResult
func sizeW(_ sizeW: CGFloat) -> Self {
self.sizeW = sizeW
return self
}
var sizeH: CGFloat {
get { return frame.height }
set { frame.size = CGSize(width: frame.width, height: newValue) }
}
@discardableResult
func sizeH(_ sizeH: CGFloat) -> Self {
self.sizeH = sizeH
return self
}
func cneter(_ point: CGPoint) -> Self {
center = point
return self
}
@discardableResult
func toRound() -> Self {
return corner(frame.height * 0.5)
}
@discardableResult
func corner(_ readius: CGFloat) -> Self {
layer.allowsEdgeAntialiasing = true
layer.cornerRadius = readius
clipsToBounds = true
return self
}
@discardableResult
func backgroundColor(_ color: UIColor) -> Self {
backgroundColor = color
return self
}
@discardableResult
func setBordColor(color: UIColor, width: CGFloat = 1.0) -> Self {
layer.borderColor = color.cgColor
layer.borderWidth = width
return self
}
static func xibView(name: String? = nil) -> Self? {
var clsName = ""
if let cn = name {
clsName = cn
} else {
clsName = className()
}
return Bundle.main.loadNibNamed(clsName, owner: nil, options: nil)?.last as? Self
}
func snapshoot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
let opImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return opImg
}
return nil
}
@discardableResult
func addTapGes(action: @escaping (_ view: UIView) -> Void) -> Self {
let gesture = UITapGestureRecognizer(target: self, action: #selector(myTapGestureAction))
isUserInteractionEnabled = true
self.action = action
addGestureRecognizer(gesture)
return self
}
// MARK: - ***** Private tapGesture *****
typealias addBlock = (_ view: UIView) -> Void
private enum AssociatedKeys {
static var actionKey: Void?
}
private var action: addBlock? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.actionKey) as? addBlock
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.actionKey, newValue!, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
@objc private func myTapGestureAction(sender: UITapGestureRecognizer) {
guard let actionBlock = action else {
return
}
if sender.state == .ended {
actionBlock(self)
}
}
}
| 25.015873 | 114 | 0.569162 |
9c389cc908fb36a2d40d611846f2963beefda09e | 3,380 | //
// LeeCotentModel.swift
// GiftShow
//
// Created by admin on 16/8/10.
// Copyright © 2016年 Mr_LeeKi. All rights reserved.
// 这是精选模型
import UIKit
class LeeCotentModel: LeeBaseModel {
var ad_monitors:[String]?
//字典类型
var author:[String:NSObject]?{
didSet{
guard let authors = author else {return }
myAuthor = LeeAuthor(dict:authors)
}
}
//字典类型
var column:[String:NSObject]?{
didSet{
guard let column = column else {return }
myColumn = LeeColumn(dict:column)
}
}
var introduction:String? {
didSet{
if let ins = introduction {
let textY:CGFloat = 310
//文本的高度
let maxSize = CGSize(width: UIScreen.main.bounds.width - 20,height: CGFloat(MAXFLOAT))
let textString = ins as NSString
let textH = textString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 13)], context: nil).size.height
guard textH == 0.0 else { cellHeight = textH + textY + 30
return }
cellHeight = textH + textY - 20
}
}
}
var myColumn:LeeColumn? //分类
var myAuthor:LeeAuthor? //作者
var cellHeight:CGFloat = 0.0
var content_type:NSNumber?
var content_url:String?
var cover_webp_url:String?
var cover_image_url:String?{
didSet{
if let url = cover_image_url {
cover_image_URL = URL(string: url)
}
}
}
var created_at:NSNumber?
var likes_count:NSNumber?
var share_msg:String?
var title:String?
var url:String?
var cover_image_URL:URL?
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
// if "author" == key {
//
// author = LeeAuthor(dict:value as! [String:AnyObject])
// return
// }
//
// if "column" == key {
//
// if value != nil{
// column = LeeColumn(dict:value as! [String:AnyObject])
// return
// }
// }
super.setValue(value, forKey: key)
}
// static func loadBanner(finished:(modals:[LeeCotentModel]?,error:NSError?)->()){
// let dit = ["ad":"2","gender":"2","generation":"2","limit":"20","offset":"0"]
// LeeGiftNetworkTool.shareInstance().GET("v2/channels/104/items_v2", parameters: dit, success: { (_, JSON) in
//
// var dd = JSON["data"]! as! [String:AnyObject]
// let array = dd["items"] as! [[String : AnyObject]]
//
//
// let arrs = Json2Modal(array)
// finished(modals: arrs,error:nil)
//
//
// }) { (_, error) in
// finished(modals: nil,error:error)
// }
//
//
// }
// //转换成模型数组
//
// class func Json2Modal(lists:[[String:AnyObject]]) -> [LeeCotentModel]{
// var arr = [LeeCotentModel]() //初始化一个数组
// for dict in lists{
// arr .append(LeeCotentModel(dict: dict))
// }
// return arr
// }
}
| 28.888889 | 193 | 0.516864 |
61f5267871b1e547bed2a79bbd1af23dd8bced5f | 29,436 | // RUN: %target-swift-frontend -parse-stdlib -emit-sil %s | FileCheck %s
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s -check-prefix=SILGEN
import Swift
struct A {
var base: UnsafeMutablePointer<Int32> = nil
subscript(index: Int32) -> Int32 {
unsafeAddress {
return UnsafePointer(base)
}
unsafeMutableAddress {
return base
}
}
}
// CHECK-LABEL: sil hidden @_TFV10addressors1Alu9subscriptFVs5Int32S1_ : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A):
// CHECK: [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base
// CHECK: [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer)
// CHECK: return [[T1]] : $UnsafePointer<Int32>
// CHECK-LABEL: sil hidden @_TFV10addressors1Aau9subscriptFVs5Int32S1_ : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32>
// CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A):
// CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*A, #A.base
// CHECK: [[BASE:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32>
// CHECK: return [[BASE]] : $UnsafeMutablePointer<Int32>
// CHECK-LABEL: sil hidden @_TF10addressors5test0FT_T_ : $@convention(thin) () -> () {
func test0() {
// CHECK: [[A:%.*]] = alloc_stack $A
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1AC
// CHECK: [[T1:%.*]] = metatype $@thin A.Type
// CHECK: [[AVAL:%.*]] = apply [[T0]]([[T1]])
// CHECK: store [[AVAL]] to [[A]]#1
var a = A()
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Alu9subscriptFVs5Int32S1_ :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: [[Z:%.*]] = load [[T3]] : $*Int32
let z = a[10]
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Aau9subscriptFVs5Int32S1_ :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[A]]#1)
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: load
// CHECK: sadd_with_overflow_Int{{32|64}}
// CHECK: store {{%.*}} to [[T3]]
a[5] += z
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Aau9subscriptFVs5Int32S1_ :
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[A]]#1)
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: store {{%.*}} to [[T3]]
a[3] = 6
}
// CHECK-LABEL: sil hidden @_TF10addressors5test1FT_Vs5Int32 : $@convention(thin) () -> Int32
func test1() -> Int32 {
// CHECK: [[CTOR:%.*]] = function_ref @_TFV10addressors1AC
// CHECK: [[T0:%.*]] = metatype $@thin A.Type
// CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(thin) (@thin A.Type) -> A
// CHECK: [[ACCESSOR:%.*]] = function_ref @_TFV10addressors1Alu9subscriptFVs5Int32S1_ : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
// CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = load [[T1]] : $*Int32
// CHECK: return [[T2]] : $Int32
return A()[0]
}
let uninitAddr = UnsafeMutablePointer<Int32>.alloc(1)
var global: Int32 {
unsafeAddress {
return UnsafePointer(uninitAddr)
}
// CHECK: sil hidden @_TF10addressorslu6globalVs5Int32 : $@convention(thin) () -> UnsafePointer<Int32> {
// CHECK: [[T0:%.*]] = global_addr @_Tv10addressors10uninitAddrGSpVs5Int32_ : $*UnsafeMutablePointer<Int32>
// CHECK: [[T1:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32>
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = struct $UnsafePointer<Int32> ([[T2]] : $Builtin.RawPointer)
// CHECK: return [[T3]] : $UnsafePointer<Int32>
}
func test_global() -> Int32 {
return global
}
// CHECK: sil hidden @_TF10addressors11test_globalFT_Vs5Int32 : $@convention(thin) () -> Int32 {
// CHECK: [[T0:%.*]] = function_ref @_TF10addressorslu6globalVs5Int32 : $@convention(thin) () -> UnsafePointer<Int32>
// CHECK: [[T1:%.*]] = apply [[T0]]() : $@convention(thin) () -> UnsafePointer<Int32>
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T4:%.*]] = load [[T3]] : $*Int32
// CHECK: return [[T4]] : $Int32
// Test that having generated trivial accessors for something because
// of protocol conformance doesn't force us down inefficient access paths.
protocol Subscriptable {
subscript(i: Int32) -> Int32 { get set }
}
struct B : Subscriptable {
subscript(i: Int32) -> Int32 {
unsafeAddress { return nil }
unsafeMutableAddress { return nil }
}
}
// CHECK: sil hidden @_TF10addressors6test_BFRVS_1BT_ : $@convention(thin) (@inout B) -> () {
// CHECK: bb0([[B:%.*]] : $*B):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 0
// CHECK: [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[RHS:%.*]] = integer_literal $Builtin.Int32, 7
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Bau9subscriptFVs5Int32S1_
// CHECK: [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[B]])
// CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// Accept either of struct_extract+load or load+struct_element_addr.
// CHECK: load
// CHECK: [[T1:%.*]] = builtin "or_Int32"
// CHECK: [[T2:%.*]] = struct $Int32 ([[T1]] : $Builtin.Int32)
// CHECK: store [[T2]] to [[ADDR]] : $*Int32
func test_B(inout b: B) {
b[0] |= 7
}
// Test that we handle abstraction difference.
struct CArray<T> {
var storage: UnsafeMutablePointer<T> = nil
subscript(index: Int) -> T {
unsafeAddress { return UnsafePointer(storage) + index }
unsafeMutableAddress { return storage + index }
}
}
func id_int(i: Int32) -> Int32 { return i }
// CHECK-LABEL: sil hidden @_TF10addressors11test_carrayFRGVS_6CArrayFVs5Int32S1__S1_ : $@convention(thin) (@inout CArray<Int32 -> Int32>) -> Int32 {
// CHECK: bb0([[ARRAY:%.*]] : $*CArray<Int32 -> Int32>):
func test_carray(inout array: CArray<Int32 -> Int32>) -> Int32 {
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors6CArrayau9subscriptFSix :
// CHECK: [[T1:%.*]] = apply [[T0]]<Int32 -> Int32>({{%.*}}, [[ARRAY]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32 -> Int32>, #UnsafeMutablePointer._rawValue
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*@callee_owned (@out Int32, @in Int32) -> ()
// CHECK: store {{%.*}} to [[T3]] :
array[0] = id_int
// CHECK: [[T0:%.*]] = load [[ARRAY]]
// CHECK: [[T1:%.*]] = function_ref @_TFV10addressors6CArraylu9subscriptFSix :
// CHECK: [[T2:%.*]] = apply [[T1]]<Int32 -> Int32>({{%.*}}, [[T0]])
// CHECK: [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<Int32 -> Int32>, #UnsafePointer._rawValue
// CHECK: [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to $*@callee_owned (@out Int32, @in Int32) -> ()
// CHECK: [[T5:%.*]] = load [[T4]]
return array[1](5)
}
// rdar://17270560, redux
struct D : Subscriptable {
subscript(i: Int32) -> Int32 {
get { return i }
unsafeMutableAddress { return nil }
}
}
// Setter.
// SILGEN-LABEL: sil hidden [transparent] @_TFV10addressors1Ds9subscriptFVs5Int32S1_
// SILGEN: bb0([[VALUE:%.*]] : $Int32, [[I:%.*]] : $Int32, [[SELF:%.*]] : $*D):
// SILGEN: debug_value [[VALUE]] : $Int32
// SILGEN: debug_value [[I]] : $Int32
// SILGEN: [[BOX:%.*]] = alloc_box $D
// SILGEN: copy_addr [[SELF]] to [initialization] [[BOX]]#1 : $*D // id: %6
// SILGEN: [[T0:%.*]] = function_ref @_TFV10addressors1Dau9subscriptFVs5Int32S1_{{.*}}
// SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[BOX]]#1)
// SILGEN: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// SILGEN: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// SILGEN: assign [[VALUE]] to [[ADDR]] : $*Int32
// materializeForSet.
// SILGEN: sil hidden [transparent] @_TFV10addressors1Dm9subscriptFVs5Int32S1_
// SILGEN: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[I:%.*]] : $Int32, [[SELF:%.*]] : $*D):
// SILGEN: debug_value [[BUFFER]]
// SILGEN: debug_value [[I]]
// SILGEN: [[BOX:%.*]] = alloc_box $D
// SILGEN: copy_addr [[SELF]] to [initialization] [[BOX]]#1 : $*D
// SILGEN: [[T0:%.*]] = function_ref @_TFV10addressors1Dau9subscriptFVs5Int32S1_
// SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[BOX]]#1)
// SILGEN: [[ADDR:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
// SILGEN: [[INIT:%.*]] = function_ref @_TFSqC
// SILGEN: [[META:%.*]] = metatype $@thin Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout D, @thick D.Type) -> ()>.Type
// SILGEN: [[T0:%.*]] = alloc_stack $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout D, @thick D.Type) -> ()>
// SILGEN: [[OPT:%.*]] = apply [[INIT]]<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout D, @thick D.Type) -> ()>([[T0]]#1, [[META]])
// SILGEN: [[T1:%.*]] = load [[T0]]#1
// SILGEN: [[T2:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[T1]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout D, @thick D.Type) -> ()>)
// SILGEN: dealloc_stack [[T0]]#0
// SILGEN: copy_addr [[BOX]]#1 to [[SELF]]
// SILGEN: strong_release [[BOX]]#0
// SILGEN: return [[T2]] :
func make_int() -> Int32 { return 0 }
func take_int_inout(inout value: Int32) {}
// CHECK-LABEL: sil hidden @_TF10addressors6test_dFRVS_1DVs5Int32 : $@convention(thin) (@inout D) -> Int32
// CHECK: bb0([[ARRAY:%.*]] : $*D):
func test_d(inout array: D) -> Int32 {
// CHECK: [[T0:%.*]] = function_ref @_TF10addressors8make_intFT_Vs5Int32
// CHECK: [[V:%.*]] = apply [[T0]]()
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Dau9subscriptFVs5Int32S1_
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[ARRAY]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: store [[V]] to [[ADDR]] : $*Int32
array[0] = make_int()
// CHECK: [[FN:%.*]] = function_ref @_TF10addressors14take_int_inoutFRVs5Int32T_
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Dau9subscriptFVs5Int32S1_
// CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[ARRAY]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
// CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to $*Int32
// CHECK: apply [[FN]]([[ADDR]])
take_int_inout(&array[1])
// CHECK: [[T0:%.*]] = load [[ARRAY]]
// CHECK: [[T1:%.*]] = function_ref @_TFV10addressors1Dg9subscriptFVs5Int32S1_
// CHECK: [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]])
// CHECK: return [[T2]]
return array[2]
}
struct E {
var value: Int32 {
unsafeAddress { return nil }
nonmutating unsafeMutableAddress { return nil }
}
}
// CHECK-LABEL: sil hidden @_TF10addressors6test_eFVS_1ET_
// CHECK: bb0([[E:%.*]] : $E):
// CHECK: [[T0:%.*]] = function_ref @_TFV10addressors1Eau5valueVs5Int32
// CHECK: [[T1:%.*]] = apply [[T0]]([[E]])
// CHECK: [[T2:%.*]] = struct_extract [[T1]]
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]]
// CHECK: store {{%.*}} to [[T3]] : $*Int32
func test_e(e: E) {
e.value = 0
}
class F {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(100)
final var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
// CHECK: sil hidden @_TFC10addressors1Flo5valueVs5Int32 : $@convention(method) (@guaranteed F) -> @owned (UnsafePointer<Int32>, Builtin.NativeObject) {
// CHECK: sil hidden @_TFC10addressors1Fao5valueVs5Int32 : $@convention(method) (@guaranteed F) -> @owned (UnsafeMutablePointer<Int32>, Builtin.NativeObject) {
func test_f0(f: F) -> Int32 {
return f.value
}
// CHECK: sil hidden @_TF10addressors7test_f0FCS_1FVs5Int32 : $@convention(thin) (@owned F) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $F):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Flo5valueVs5Int32 : $@convention(method) (@guaranteed F) -> @owned (UnsafePointer<Int32>, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: strong_release [[SELF]] : $F
// CHECK: return [[VALUE]] : $Int32
func test_f1(f: F) {
f.value = 14
}
// CHECK: sil hidden @_TF10addressors7test_f1FCS_1FT_ : $@convention(thin) (@owned F) -> () {
// CHECK: bb0([[SELF:%0]] : $F):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14
// CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Fao5valueVs5Int32 : $@convention(method) (@guaranteed F) -> @owned (UnsafeMutablePointer<Int32>, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: store [[VALUE]] to [[T2]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: strong_release [[SELF]] : $F
class G {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(100)
var value: Int32 {
addressWithNativeOwner {
return (UnsafePointer(data), Builtin.castToNativeObject(self))
}
mutableAddressWithNativeOwner {
return (data, Builtin.castToNativeObject(self))
}
}
}
// CHECK: sil hidden [transparent] @_TFC10addressors1Gg5valueVs5Int32 : $@convention(method) (@guaranteed G) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $G):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Glo5valueVs5Int32 : $@convention(method) (@guaranteed G) -> @owned (UnsafePointer<Int32>, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: return [[VALUE]] : $Int32
// CHECK: sil hidden [transparent] @_TFC10addressors1Gs5valueVs5Int32 : $@convention(method) (Int32, @guaranteed G) -> () {
// CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $G):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Gao5valueVs5Int32 : $@convention(method) (@guaranteed G) -> @owned (UnsafeMutablePointer<Int32>, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject
// CHECK: store [[VALUE]] to [[T2]] : $*Int32
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// materializeForSet for G.value
// CHECK-LABEL: sil hidden [transparent] @_TFC10addressors1Gm5valueVs5Int32 : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed G) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout G, @thick G.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $G):
// Call the addressor.
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Gao5valueVs5Int32 : $@convention(method) (@guaranteed G) -> @owned (UnsafeMutablePointer<Int32>, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[TUPLE:%.*]] = tuple ([[T1]] : $UnsafeMutablePointer<Int32>, [[T2]] : $Builtin.NativeObject)
// Initialize the callback storage with the owner.
// CHECK: [[T0:%.*]] = alloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]]
// CHECK: [[T2:%.*]] = pointer_to_address [[T1]]
// CHECK: [[T3:%.*]] = tuple_extract [[TUPLE]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: store [[T3]] to [[T2]] : $*Builtin.NativeObject
// Pull out the address.
// CHECK: [[T0:%.*]] = tuple_extract [[TUPLE]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0
// CHECK: [[ADDR_OWNER:%.*]] = tuple_extract [[TUPLE]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1
// CHECK: [[PTR:%.*]] = struct_extract [[T0]] :
// Set up the callback.
// CHECK: [[T1:%.*]] = function_ref @_TFFC10addressors1Gm5valueVs5Int32U_FTBpRBBRS0_MS0__T_ :
// CHECK: [[CALLBACK:%.*]] = enum $Optional<{{.*}}>, #Optional.Some!enumelt.1, [[T1]]
// Epilogue.
// CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout G, @thick G.Type) -> ()>)
// CHECK: return [[RESULT]]
// materializeForSet callback for G.value
// CHECK-LABEL: sil @_TFFC10addressors1Gm5valueVs5Int32U_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout G, @thick G.Type) -> () {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*G, [[SELFTYPE:%3]] : $@thick G.Type):
// CHECK: [[T0:%.*]] = project_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]]
// CHECK: [[T2:%.*]] = pointer_to_address [[T1]]
// CHECK: [[OWNER:%.*]] = load [[T2]]
// CHECK: strong_release [[OWNER]] : $Builtin.NativeObject
// CHECK: dealloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
class H {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(100)
final var value: Int32 {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
// CHECK-LABEL: sil hidden @_TFC10addressors1Hlp5valueVs5Int32 : $@convention(method) (@guaranteed H) -> @owned (UnsafePointer<Int32>, Optional<Builtin.NativeObject>) {
// CHECK-LABEL: sil hidden @_TFC10addressors1Hap5valueVs5Int32 : $@convention(method) (@guaranteed H) -> @owned (UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>) {
func test_h0(f: H) -> Int32 {
return f.value
}
// CHECK-LABEL: sil hidden @_TF10addressors7test_h0FCS_1HVs5Int32 : $@convention(thin) (@owned H) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $H):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Hlp5valueVs5Int32 : $@convention(method) (@guaranteed H) -> @owned (UnsafePointer<Int32>, Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: strong_release [[SELF]] : $H
// CHECK: return [[VALUE]] : $Int32
func test_h1(f: H) {
f.value = 14
}
// CHECK: sil hidden @_TF10addressors7test_h1FCS_1HT_ : $@convention(thin) (@owned H) -> () {
// CHECK: bb0([[SELF:%0]] : $H):
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14
// CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Hap5valueVs5Int32 : $@convention(method) (@guaranteed H) -> @owned (UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: store [[VALUE]] to [[T2]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: strong_release [[SELF]] : $H
class I {
var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(100)
var value: Int32 {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
// CHECK-LABEL: sil hidden [transparent] @_TFC10addressors1Ig5valueVs5Int32 : $@convention(method) (@guaranteed I) -> Int32 {
// CHECK: bb0([[SELF:%0]] : $I):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Ilp5valueVs5Int32 : $@convention(method) (@guaranteed I) -> @owned (UnsafePointer<Int32>, Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: return [[VALUE]] : $Int32
// CHECK-LABEL: sil hidden [transparent] @_TFC10addressors1Is5valueVs5Int32 : $@convention(method) (Int32, @guaranteed I) -> () {
// CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $I):
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Iap5valueVs5Int32 : $@convention(method) (@guaranteed I) -> @owned (UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[T0:%.*]] = struct_extract [[PTR]]
// CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Int32
// CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: store [[VALUE]] to [[T2]] : $*Int32
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-LABEL: sil hidden [transparent] @_TFC10addressors1Im5valueVs5Int32 : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed I) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout I, @thick I.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $I):
// Call the addressor.
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_TFC10addressors1Iap5valueVs5Int32 : $@convention(method) (@guaranteed I) -> @owned (UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>)
// CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: [[TUPLE:%.*]] = tuple ([[T1]] : $UnsafeMutablePointer<Int32>, [[T2]] : $Optional<Builtin.NativeObject>)
// Initialize the callback storage with the owner.
// CHECK: [[T0:%.*]] = alloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]]
// CHECK: [[T2:%.*]] = pointer_to_address [[T1]]
// CHECK: [[T3:%.*]] = tuple_extract [[TUPLE]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1
// CHECK: store [[T3]] to [[T2]] : $*Optional<Builtin.NativeObject>
// Pull out the address.
// CHECK: [[T0:%.*]] = tuple_extract [[TUPLE]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0
// CHECK: [[PTR:%.*]] = struct_extract [[T0]] :
// Set up the callback.
// CHECK: [[T1:%.*]] = function_ref @_TFFC10addressors1Im5valueVs5Int32U_FTBpRBBRS0_MS0__T_ :
// CHECK: [[CALLBACK:%.*]] = enum $Optional<{{.*}}>, #Optional.Some!enumelt.1, [[T1]]
// Epilogue.
// CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout I, @thick I.Type) -> ()>)
// CHECK: return [[RESULT]]
// materializeForSet callback for I.value
// CHECK-LABEL: sil @_TFFC10addressors1Im5valueVs5Int32U_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout I, @thick I.Type) -> () {
// CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*I, [[SELFTYPE:%3]] : $@thick I.Type):
// CHECK: [[T0:%.*]] = project_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]]
// CHECK: [[T2:%.*]] = pointer_to_address [[T1]]
// CHECK: [[OWNER:%.*]] = load [[T2]]
// CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK: dealloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
struct RecInner {
subscript(i: Int32) -> Int32 {
mutating get { return i }
}
}
struct RecMiddle {
var inner: RecInner
}
class RecOuter {
var data: UnsafeMutablePointer<RecMiddle> = UnsafeMutablePointer.alloc(100)
final var middle: RecMiddle {
addressWithPinnedNativeOwner {
return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self)))
}
mutableAddressWithPinnedNativeOwner {
return (data, Builtin.tryPin(Builtin.castToNativeObject(self)))
}
}
}
func test_rec(outer: RecOuter) -> Int32 {
return outer.middle.inner[0]
}
// This uses the mutable addressor.
// CHECK-LABEL: sil hidden @_TF10addressors8test_recFCS_8RecOuterVs5Int32 : $@convention(thin) (@owned RecOuter) -> Int32 {
// CHECK: function_ref @_TFC10addressors8RecOuterap6middleVS_9RecMiddle
// CHECK: struct_element_addr {{.*}} : $*RecMiddle, #RecMiddle.inner
// CHECK: function_ref @_TFV10addressors8RecInnerg9subscriptFVs5Int32S1_
| 55.961977 | 307 | 0.640338 |
69fa0182b5dd6e6b21565e78b6fe81e2a982d4b1 | 1,497 | import XCTest
class MGLSourceTests: MGLMapViewIntegrationTest {
// See testForRaisingExceptionsOnStaleStyleObjects for Obj-C sibling.
func testForRaisingExceptionsOnStaleStyleObjectsOnRemoveFromMapView() {
guard
let configURL = URL(string: "mapbox://examples.2uf7qges") else {
XCTFail()
return
}
let source = MGLVectorTileSource(identifier: "trees", configurationURL: configURL)
mapView.style?.addSource(source)
let bundle = Bundle(for: type(of: self))
guard let styleURL = bundle.url(forResource: "one-liner", withExtension: "json") else {
XCTFail()
return
}
styleLoadingExpectation = nil;
mapView.centerCoordinate = CLLocationCoordinate2D(latitude : 38.897, longitude : -77.039)
mapView.zoomLevel = 10.5
mapView.styleURL = styleURL
waitForMapViewToFinishLoadingStyle(withTimeout: 10.0)
let expect = expectation(description: "Remove source should error")
do {
try mapView.style?.removeSource(source, error: ())
}
catch let error as NSError {
XCTAssertEqual(error.domain, MGLErrorDomain)
XCTAssertEqual(error.code, MGLErrorCode.sourceCannotBeRemovedFromStyle.rawValue)
expect.fulfill()
}
wait(for: [expect], timeout: 0.1)
}
}
| 32.543478 | 97 | 0.600534 |
189a8c46ada706735c3b552c0d7a53f14236d986 | 1,207 | //
// GroupedObservable.swift
// RxSwift
//
// Created by Tomi Koskinen on 01/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an observable sequence of elements that have a common key.
public struct GroupedObservable<Key, Element> : ObservableType {
/// Gets the common key.
public let key: Key
private let source: Observable<Element>
/// Initializes grouped observable sequence with key and source observable sequence.
///
/// - parameter key: Grouped observable sequence key
/// - parameter source: Observable sequence that represents sequence of elements for the key
/// - returns: Grouped observable sequence of elements for the specific key
public init(key: Key, source: Observable<Element>) {
self.key = key
self.source = source
}
/// Subscribes `observer` to receive events for this sequence.
public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self.source.subscribe(observer)
}
/// Converts `self` to `Observable` sequence.
public func asObservable() -> Observable<Element> {
self.source
}
}
| 33.527778 | 121 | 0.690969 |
768d1bb29a0102d7ff1da68077c005c1f50fad41 | 741 | //
// StorageMocks.swift
// BTMeshTests
//
// Created by Marcos on 01/07/2018.
// Copyright © 2018 Marcos Borges. All rights reserved.
//
import Foundation
import RxSwift
@testable import BTMesh
// MARK: - Mocks
class StorageMock: BTStorageProtocol {
// MARK: - Public properties
public var currentUser: BTUser?
public var users = BehaviorSubject<Array<BTUser>>(value: [])
// MARK: - Public methods
public func addUser(user: BTUser) {
var users = (try? self.users.value()) ?? []
users.append(user)
self.users.onNext(users)
}
public func removeUser(user: BTUser) {}
// MARK: - Test methods
func fireVisibleItemsChange() {
}
}
| 19.5 | 64 | 0.609987 |
7ad50332fa70096cc33e53c4d164dd992af21e92 | 5,255 | // From https://github.com/securing/SimpleXPCApp/
import Foundation
import os.log
class ConnectionVerifier {
private static func prepareCodeReferencesFromAuditToken(connection: NSXPCConnection, secCodeOptional: inout SecCode?, secStaticCodeOptional: inout SecStaticCode?) -> Bool {
let auditTokenData = AuditTokenHack.getAuditTokenData(from: connection)
let attributesDictrionary = [
kSecGuestAttributeAudit : auditTokenData
]
if SecCodeCopyGuestWithAttributes(nil, attributesDictrionary as CFDictionary, SecCSFlags(rawValue: 0), &secCodeOptional) != errSecSuccess {
Logger.connectionVerifier.error("Couldn't get SecCode with the audit token")
return false
}
guard let secCode = secCodeOptional else {
Logger.connectionVerifier.error("Couldn't unwrap the secCode")
return false
}
SecCodeCopyStaticCode(secCode, SecCSFlags(rawValue: 0), &secStaticCodeOptional)
guard let _ = secStaticCodeOptional else {
Logger.connectionVerifier.error("Couldn't unwrap the secStaticCode")
return false
}
return true
}
private static func verifyHardenedRuntimeAndProblematicEntitlements(secStaticCode: SecStaticCode) -> Bool {
var signingInformationOptional: CFDictionary? = nil
if SecCodeCopySigningInformation(secStaticCode, SecCSFlags(rawValue: kSecCSDynamicInformation), &signingInformationOptional) != errSecSuccess {
Logger.connectionVerifier.error("Couldn't obtain signing information")
return false
}
guard let signingInformation = signingInformationOptional else {
return false
}
let signingInformationDict = signingInformation as NSDictionary
let signingFlagsOptional = signingInformationDict.object(forKey: "flags") as? UInt32
if let signingFlags = signingFlagsOptional {
let hardenedRuntimeFlag: UInt32 = 0x10000
if (signingFlags & hardenedRuntimeFlag) != hardenedRuntimeFlag {
Logger.connectionVerifier.error("Hardened runtime is not set for the sender")
return false
}
} else {
return false
}
let entitlementsOptional = signingInformationDict.object(forKey: "entitlements-dict") as? NSDictionary
guard let entitlements = entitlementsOptional else {
return false
}
Logger.connectionVerifier.info("Entitlements are \(entitlements)")
let problematicEntitlements = [
"com.apple.security.get-task-allow",
"com.apple.security.cs.disable-library-validation",
"com.apple.security.cs.allow-dyld-environment-variables"
]
// Skip this check for debug builds because they'll have the get-task-allow entitlement
#if !DEBUG
for problematicEntitlement in problematicEntitlements {
if let presentEntitlement = entitlements.object(forKey: problematicEntitlement) {
if presentEntitlement as! Int == 1 {
Logger.connectionVerifier.error("The sender has \(problematicEntitlement) entitlement set to true")
return false
}
}
}
#endif
return true
}
private static func verifyWithRequirementString(secCode: SecCode) -> Bool {
// Code Signing Requirement Language
// https://developer.apple.com/library/archive/documentation/Security/Conceptual/CodeSigningGuide/RequirementLang/RequirementLang.html#//apple_ref/doc/uid/TP40005929-CH5-SW1
let requirementString = "identifier \"\(clientBundleID)\" and info [CFBundleShortVersionString] >= \"1.0.0\" and anchor apple generic and certificate leaf[subject.OU] = \"\(subjectOrganizationalUnit)\"" as NSString
var secRequirement: SecRequirement? = nil
if SecRequirementCreateWithString(requirementString as CFString, SecCSFlags(rawValue: 0), &secRequirement) != errSecSuccess {
Logger.connectionVerifier.error("Couldn't create the requirement string")
return false
}
if SecCodeCheckValidity(secCode, SecCSFlags(rawValue: 0), secRequirement) != errSecSuccess {
Logger.connectionVerifier.error("NSXPC client does not meet the requirements")
return false
}
return true
}
public static func isValid(connection: NSXPCConnection) -> Bool {
var secCodeOptional: SecCode? = nil
var secStaticCodeOptional: SecStaticCode? = nil
if !prepareCodeReferencesFromAuditToken(connection: connection, secCodeOptional: &secCodeOptional, secStaticCodeOptional: &secStaticCodeOptional) {
return false
}
if !verifyHardenedRuntimeAndProblematicEntitlements(secStaticCode: secStaticCodeOptional!) {
return false
}
if !verifyWithRequirementString(secCode: secCodeOptional!) {
return false
}
return true
}
}
| 42.04 | 222 | 0.655186 |
fb1e5279a0b22b2fbffabe78f159d253db422af3 | 13,548 | //
// ElderMainViewController.swift
// SaveElderProject
//
// Created by Demian on 2020/01/15.
// Copyright © 2020 Demian. All rights reserved.
//
import UIKit
import MapKit
import Firebase
import UserNotifications
class ElderMainViewController: UIViewController {
let locationManager = CLLocationManager()
let mapView = MKMapView()
var ref: DatabaseReference!
var interval: TimeInterval = 60 //노티 보낼 간격
let bgView = UIView()
let bgBottomView = UIView()
let elderNameLabel = UILabel()
let elderLabel1 = UILabel()
let elderLabel2 = UILabel()
let helperView = UIView()
let helperTitleLabel = UILabel()
let helperNameLabel = UILabel()
let helperPhoneNumberLabel = UILabel()
var helperCallBtn = UIButton()
var helperMessageBtn = UIButton()
var emergencyCallBtn = UIButton()
var myName = ""
var helperName = ""
var helperNumber = ""
var tempPhoneNumber = ""
var helperNumberInLabel = ""
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
checkAuthorizationStatus()
locationManager.delegate = self
notificationShoot()
setInfoAndSetupUI()
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(checkAuthorizationStatus), userInfo: nil, repeats: true)
}
func setInfoAndSetupUI() {
guard let elderCode = UserDefaults.standard.string(forKey: "elderCode") else {return}
Database.database().reference().child("users").child(elderCode).observeSingleEvent(of: .value) { snapshop in
let datas = snapshop.value as? [String:Any] ?? ["fail":"fail"]
guard let myName = datas["ElderName"] as? String else { return }
guard let helperName = datas["HelperName"] as? String else {return}
guard let helperPhonNumber = datas["HelperPhoneNumber"] as? String else { return }
self.myName = myName
self.helperName = helperName
self.helperNumber = helperPhonNumber
self.tempPhoneNumber = helperPhonNumber
self.chageShapePhoneNumber()
self.setupUI()
}
}
private func chageShapePhoneNumber() {
var count = 0
for i in tempPhoneNumber {
count += 1
if count == 4 || count == 8 {
helperNumberInLabel.append("-")
helperNumberInLabel.append(i)
print(helperNumberInLabel)
} else {
helperNumberInLabel.append(i)
print(helperNumberInLabel)
}
}
}
private func notificationShoot() {
print("노티가 예약되었습니다.")
let content = UNMutableNotificationContent()
content.title = "Save Elder"
content.body = "알림을 눌러 보호자를 안심시켜주세요."
content.badge = 1
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print(error)
} else {
print("Success")
}
}
}
private func setupUI() {
bgView.shadow()
bgView.backgroundColor = .white
helperView.shadow()
helperView.backgroundColor = .white
helperView.layer.cornerRadius = 4
// elderLabel.numberOfLines = 0
elderNameLabel.text = myName
elderNameLabel.font = .systemFont(ofSize: 28, weight: .bold)
elderNameLabel.textColor = #colorLiteral(red: 0.2605174184, green: 0.2605243921, blue: 0.260520637, alpha: 1)
elderLabel1.text = "님"
elderLabel1.font = .systemFont(ofSize: 28)
elderLabel1.textColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)
elderLabel2.text = "안녕하세요?"
elderLabel2.font = .systemFont(ofSize: 28)
elderLabel2.textColor = #colorLiteral(red: 0.4756349325, green: 0.4756467342, blue: 0.4756404161, alpha: 1)
helperTitleLabel.text = "보호자 정보"
helperTitleLabel.font = .systemFont(ofSize: 18, weight: .bold)
helperTitleLabel.textColor = .lightGray
helperNameLabel.text = helperName
helperNameLabel.font = .systemFont(ofSize: 28)
helperNameLabel.textColor = .darkGray
helperPhoneNumberLabel.text = helperNumberInLabel
helperPhoneNumberLabel.font = .systemFont(ofSize: 28)
helperPhoneNumberLabel.textColor = .darkGray
helperCallBtn = self.btnStyle(title: "전화 하기")
helperCallBtn.shadow()
helperCallBtn.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
helperCallBtn.addTarget(self, action: #selector(helperCallAction(_:)), for: .touchUpInside)
helperMessageBtn = self.btnStyle(title: "문자 보내기")
helperMessageBtn.shadow()
helperMessageBtn.backgroundColor = #colorLiteral(red: 0.1877941191, green: 0.4580045938, blue: 0.9603970647, alpha: 1)
helperMessageBtn.addTarget(self, action: #selector(helperMessageAction(_:)), for: .touchUpInside)
emergencyCallBtn = self.btnStyle(title: "긴급전화 하기")
emergencyCallBtn.shadow()
emergencyCallBtn.backgroundColor = #colorLiteral(red: 0.9768529534, green: 0.3592768908, blue: 0.3947588801, alpha: 1)
emergencyCallBtn.addTarget(self, action: #selector(emergencyCallAction(_:)), for: .touchUpInside)
bgBottomView.alpha = 0
bgBottomView.backgroundColor = .black
[bgView, helperView, elderNameLabel, elderLabel1, elderLabel2, helperTitleLabel, helperNameLabel, helperPhoneNumberLabel, helperCallBtn, helperMessageBtn, emergencyCallBtn, bgBottomView].forEach {
view.addSubview($0)
}
setupConstraint()
}
private func setupConstraint() {
let guide = self.view.safeAreaLayoutGuide
bgView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bgView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
bgView.widthAnchor.constraint(equalTo: guide.widthAnchor, multiplier: 1),
bgView.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 0.9)
])
bgBottomView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bgBottomView.topAnchor.constraint(equalTo: bgView.bottomAnchor, constant: 0),
bgBottomView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
bgBottomView.widthAnchor.constraint(equalTo: guide.widthAnchor, multiplier: 1)
])
elderNameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
elderNameLabel.topAnchor.constraint(equalTo: guide.topAnchor, constant: 40),
elderNameLabel.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 26)
])
elderLabel1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
elderLabel1.topAnchor.constraint(equalTo: guide.topAnchor, constant: 40),
elderLabel1.leadingAnchor.constraint(equalTo: elderNameLabel.trailingAnchor, constant: 3)
])
elderLabel2.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
elderLabel2.topAnchor.constraint(equalTo: elderNameLabel.bottomAnchor),
elderLabel2.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 26)
])
helperView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 140),
helperView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 20),
helperView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -20),
helperView.heightAnchor.constraint(equalTo: bgView.heightAnchor, multiplier: 0.4)
])
helperTitleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperTitleLabel.topAnchor.constraint(equalTo: helperView.topAnchor, constant: 20),
helperTitleLabel.centerXAnchor.constraint(equalTo: helperView.centerXAnchor)
])
helperNameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperNameLabel.leadingAnchor.constraint(equalTo: helperView.leadingAnchor, constant: 20),
helperNameLabel.centerYAnchor.constraint(equalTo: helperView.centerYAnchor, constant: -20)
])
helperPhoneNumberLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperPhoneNumberLabel.leadingAnchor.constraint(equalTo: helperView.leadingAnchor, constant: 20),
helperPhoneNumberLabel.centerYAnchor.constraint(equalTo: helperView.centerYAnchor, constant: 40)
])
helperCallBtn.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperCallBtn.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 20),
helperCallBtn.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -20),
helperCallBtn.heightAnchor.constraint(equalTo: helperView.heightAnchor, multiplier: 0.28),
helperCallBtn.topAnchor.constraint(equalTo: helperView.bottomAnchor, constant: 20)
])
helperMessageBtn.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
helperMessageBtn.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 20),
helperMessageBtn.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -20),
helperMessageBtn.heightAnchor.constraint(equalTo: helperView.heightAnchor, multiplier: 0.28),
helperMessageBtn.topAnchor.constraint(equalTo: helperCallBtn.bottomAnchor, constant: 20)
])
emergencyCallBtn.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
emergencyCallBtn.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 20),
emergencyCallBtn.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -20),
emergencyCallBtn.heightAnchor.constraint(equalTo: helperView.heightAnchor, multiplier: 0.28),
emergencyCallBtn.centerYAnchor.constraint(equalTo: bgBottomView.centerYAnchor)
])
}
@objc private func helperCallAction(_ sender: UIButton) {
print("\n---------- [ helperCall ] ----------\n")
let url = URL(string: "tel:\(helperNumber)")!
print(url)
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url)
}
@objc private func helperMessageAction(_ sender: UIButton) {
print("\n---------- [ openMessage ] ----------\n")
let url = URL(string: "sms:\(helperNumber)&body=hello")!
print(url)
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url)
}
@objc private func emergencyCallAction(_ sender: UIButton) {
print("\n---------- [ emergencyCallCall ] ----------\n")
let url = URL(string: "tel:119")!
print(url)
guard UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url)
}
@objc private func checkAuthorizationStatus() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted, .denied: break
case .authorizedWhenInUse:
fallthrough
case .authorizedAlways:
startUpdatingLocation()
@unknown default: break
}
}
func startUpdatingLocation() {
let status = CLLocationManager.authorizationStatus()
guard status == .authorizedWhenInUse || status == .authorizedAlways else { return }
guard CLLocationManager.locationServicesEnabled() else { return }
locationManager.startUpdatingLocation() //위치 업데이트 실행하도록 하는 매소드
}
private func btnStyle(title: String) -> UIButton { // 버튼 스타일 함수
let button = UIButton()
button.setTitle(title, for: .normal)
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 4
button.titleLabel?.font = .systemFont(ofSize: 22, weight: .bold)
return button
}
}
extension ElderMainViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse, .authorizedAlways:
print("Authorized")
default:
print("Unauthorized")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let current = locations.last!
let elderLocation = current.coordinate
ref = Database.database().reference()
guard let elderCode = UserDefaults.standard.string(forKey: "elderCode") else {return}
let values = ["latitude": String(elderLocation.latitude),
"longitude": String(elderLocation.longitude)]
self.ref.child("users").child(elderCode).child("elderLocation").setValue(values) { (error, ref) in
if error == nil {
Timer.cancelPreviousPerformRequests(withTarget: self.checkAuthorizationStatus())
print("success")
} else {
print("fail")
fatalError(error!.localizedDescription)
}
}
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMddHH"
let stringDate = dateFormatter.string(from: date)
// print(stringDate)
let timeInfo = ["lastUpdatingTime": stringDate]
self.ref.child("users").child(elderCode).child("lastTime").setValue(timeInfo) { (error, ref) in
if error == nil {
print("timeUpdating Success")
} else {
print("timeUpdating fail")
fatalError()
}
}
}
}
| 42.603774 | 200 | 0.722542 |
f918fcffcc0c6848eb04af56803568b75d99a9b1 | 1,852 | //
// CornersView.swift
// SwiftRebuildOC
//
// Created by Benjamin on 2021/6/29.
// Copyright © 2021 com.Personal.Benjamin. All rights reserved.
//
import UIKit
/*** UIBezierPath(贝塞尔曲线)绘图 ***/
class CornersView: UIView {
var circleOfCenter: CGPoint! // 绘制的圆心
var radius: CGFloat! // 半径
var startAngle: CGFloat! // 开始角度(弧度制)
var endAngle: CGFloat! // 结束角度(弧度制)
var lineWidth: CGFloat! // 绘制宽度
var lineColor: UIColor! // 绘制颜色
// MARK: 自定义初始化方法
init(frame: CGRect, circleOfCenter: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, lineWidth: CGFloat, lineColor: UIColor) {
super.init(frame: frame)
// 初始化赋值
self.circleOfCenter = circleOfCenter
self.radius = radius
self.startAngle = startAngle
self.endAngle = endAngle
self.lineWidth = lineWidth
self.lineColor = lineColor
// setNeedsDisplay异步执行的,它会自动调用drawRect方法
self.setNeedsDisplay()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: 画图
override func draw(_ rect: CGRect) {
super.draw(rect)
// 调用
self.createCorners()
}
// Bezier(贝塞尔曲线绘制:角球区域)
func createCorners() {
let path: UIBezierPath! = UIBezierPath.init()
// Bezier画圆(弧)
path.addArc(withCenter: self.circleOfCenter, radius: self.radius, startAngle: self.startAngle, endAngle: self.endAngle, clockwise: true)
path.lineWidth = self.lineWidth
path.lineCapStyle = .round
UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0).setStroke()
// 返回绘制后的图像
path.stroke()
}
}
| 28.060606 | 147 | 0.584233 |
261369ada918b90a31b1b899d60a85626a66690f | 891 | //
// MDAppDelegate.swift
// MyDictionary_App_Swift
//
// Created by Dmytro Chumakov on 03.06.2021.
//
import UIKit
protocol MDAppDelegateProtocol {
var rootWindow: UIWindow! { get }
var dependencies: MDAppDependenciesProtocol! { get }
}
@main
final class MDAppDelegate: UIResponder,
UIApplicationDelegate,
MDAppDelegateProtocol {
var rootWindow: UIWindow!
var dependencies: MDAppDependenciesProtocol!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.dependencies = MDAppDependencies.init()
self.rootWindow = RootWindow.window(isLoggedIn: self.dependencies.appSettings.isLoggedIn)
self.dependencies.rootWindow = self.rootWindow
return true
}
}
| 27 | 145 | 0.676768 |
38d9ea0f42bba205aee09e6dd84100de8537efd3 | 66,549 | //
// BluepeerObject.swift
//
// Created by Tim Carr on 7/7/16.
// Copyright © 2016 Tim Carr Photo. All rights reserved.
//
import Foundation
import CoreBluetooth
import CFNetwork
import CocoaAsyncSocket // NOTE: requires pod CocoaAsyncSocket
import HHServices
import dnssd
import xaphodObjCUtils
import DataCompression
// "Any" means can be both a client and a server. If accepting a new connection from another peer, that peer is deemed a client. If found an advertising .any peer, that peer is considered a server.
@objc public enum RoleType: Int, CustomStringConvertible {
case unknown = 0
case server = 1
case client = 2
case any = 3
public var description: String {
switch self {
case .server: return "Server"
case .client: return "Client"
case .unknown: return "Unknown"
case .any: return "Any"
}
}
public static func roleFromString(_ roleStr: String?) -> RoleType {
guard let roleStr = roleStr else {
assert(false, "ERROR")
return .unknown
}
switch roleStr {
case "Server": return .server
case "Client": return .client
case "Unknown": return .unknown
case "Any": return .any
default: return .unknown
}
}
}
@objc public enum BluetoothState: Int {
case unknown = 0
case poweredOff = 1
case poweredOn = 2
case other = 3
}
@objc public enum BluepeerInterfaces: Int {
case any = 0
case infrastructureModeWifiOnly
case notWifi
}
@objc public enum BPPeerState: Int, CustomStringConvertible {
case notConnected = 0
case connecting = 1
case awaitingAuth = 2
case authenticated = 3
public var description: String {
switch self {
case .notConnected: return "NotConnected"
case .connecting: return "Connecting"
case .awaitingAuth: return "AwaitingAuth"
case .authenticated: return "Authenticated"
}
}
}
@objc open class BPPeer: NSObject {
@objc open var displayName: String = "" // is same as HHService.name !
@objc open var displayShortName: String { // doesn't have the "-0923" numbers at the end
if displayName.count <= 5 {
return displayName
}
let index = displayName.index(displayName.endIndex, offsetBy: -5)
return String(displayName.prefix(upTo: index))
}
@objc open var role: RoleType = .unknown
@objc open var state: BPPeerState = .notConnected
@objc open var canConnect: Bool {
return self.candidateAddresses.count > 0
}
@objc open var keepaliveTimer: Timer?
@objc open var lastDataRead: Date = Date.init(timeIntervalSince1970: 0) // includes keepalives
@objc open var lastDataKeepAliveWritten: Date = Date.init(timeIntervalSince1970: 0) // only keepalives
@objc open var lastDataNonKeepAliveWritten: Date = Date.init(timeIntervalSince1970: 0) // no keepalives
public typealias ConnectBlock = ()->Bool
@objc open var connect: (ConnectBlock)? // false if no connection attempt will happen
@objc open func disconnect() {
socket?.disconnect()
}
@objc open var customData = [String:AnyHashable]() // store your own data here. When a browser finds an advertiser and creates a peer for it, this will be filled out with the advertiser's customData *even before any connection occurs*. Note that while you can store values that are AnyHashable, only Strings are used as values for advertiser->browser connections.
weak var owner: BluepeerObject?
var connectCount=0, disconnectCount=0, connectAttemptFailCount=0, connectAttemptFailAuthRejectCount=0, dataRecvCount=0, dataSendCount=0
override open var description: String {
var socketDesc = "nil"
if let socket = self.socket {
if let host = socket.connectedHost {
socketDesc = host
} else {
socketDesc = "NOT connected"
}
}
let lastDataWritten = max(self.lastDataNonKeepAliveWritten, self.lastDataKeepAliveWritten) // the most recent
return "\n[\(displayName) is \(state) as \(role) on \(lastInterfaceName ?? "nil") with \(customData.count) customData keys. C:\(connectCount) D:\(disconnectCount) cFail:\(connectAttemptFailCount) cFailAuth:\(connectAttemptFailAuthRejectCount), Data In#:\(dataRecvCount) LastRecv: \(lastDataRead), LastWrite: \(lastDataWritten), Out#:\(dataSendCount). Socket: \(socketDesc), services#: \(services.count) (\(resolvedServices().count) resolved)]"
}
@objc open var isConnectedViaWifi: Bool {
guard let interface = self.lastInterfaceName else {
return false
}
return interface == BluepeerObject.iOS_wifi_interface
}
// fileprivates
fileprivate var socket: GCDAsyncSocket?
fileprivate var services = [HHService]()
fileprivate func resolvedServices() -> [HHService] {
return services.filter { $0.resolved == true }
}
fileprivate func pickedResolvedService() -> HHService? {
// this function determines which of the resolved services is used
return resolvedServices().last
}
fileprivate func destroyServices() {
for service in services {
service.delegate = nil
service.endResolve()
}
services = [HHService]()
}
fileprivate var candidateAddresses: [HHAddressInfo] {
guard let hhaddresses2 = self.pickedResolvedService()?.resolvedAddressInfo, hhaddresses2.count > 0 else {
return []
}
var interfaces: BluepeerInterfaces = .any
if let owner = self.owner {
interfaces = owner.bluepeerInterfaces
}
return hhaddresses2.filter({ $0.isCandidateAddress(excludeWifi: interfaces == .notWifi, onlyWifi: interfaces == .infrastructureModeWifiOnly) })
}
fileprivate var lastInterfaceName: String?
fileprivate var clientReceivedBytes: Int = 0
}
@objc public protocol BluepeerMembershipRosterDelegate {
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, peerDidConnect peerRole: RoleType, peer: BPPeer)
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, peerDidDisconnect peerRole: RoleType, peer: BPPeer, canConnectNow: Bool) // canConnectNow: true if this peer is still announce-able, ie. can now call connect() on it. Note, it is highly recommended to have a ~2 sec delay before calling connect() to avoid 100% CPU loops
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, peerConnectionAttemptFailed peerRole: RoleType, peer: BPPeer?, isAuthRejection: Bool, canConnectNow: Bool) // canConnectNow: true if this peer is still announce-able, ie. can now call connect() on it. Note, it is highly recommended to have a ~2 sec delay before calling connect() to avoid 100% CPU loops
}
@objc public protocol BluepeerMembershipAdminDelegate {
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, peerConnectionRequest peer: BPPeer, invitationHandler: @escaping (Bool) -> Void) // Someone's trying to connect to you. Earlier this was named: sessionConnectionRequest
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, browserFindingPeer isNew: Bool) // There's someone out there with the same serviceType, which is now being queried for more details. This can occur as much as 2 seconds before browserFoundPeer(), so it's used to give you an early heads-up. If this peer has not been seen before, isNew is true.
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, browserFindingPeerFailed unused: Bool) // balances the previous call. Use to cancel UI like progress indicator etc.
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, browserFoundPeer role: RoleType, peer: BPPeer) // You found someone to connect to. The peer has connect() that can be executed, and your .customData too. This can be called more than once for the same peer.
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, browserLostPeer role: RoleType, peer: BPPeer)
}
@objc public protocol BluepeerDataDelegate {
@objc optional func bluepeer(_ bluepeerObject: BluepeerObject, receivingData bytesReceived: Int, totalBytes: Int, peer: BPPeer) // the values of 0 and 100% are guaranteed prior to didReceiveData
@objc func bluepeer(_ bluepeerObject: BluepeerObject, didReceiveData data: Data, peer: BPPeer)
}
@objc public protocol BluepeerLoggingDelegate {
@objc func logString(_ message: String)
}
/* ADD TO POD FILE
post_install do |installer_representation|
installer_representation.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.name != 'Release'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'DEBUG=1']
config.build_settings['OTHER_SWIFT_FLAGS'] = ['$(inherited)', '-DDEBUG']
end
end
end
end
*/
@objc open class BluepeerObject: NSObject {
static let kDNSServiceInterfaceIndexP2PSwift = UInt32.max-2
static let iOS_wifi_interface = "en0"
@objc var delegateQueue: DispatchQueue?
@objc var serverSocket: GCDAsyncSocket?
@objc var publisher: HHServicePublisher?
@objc var browser: HHServiceBrowser?
fileprivate var bluepeerInterfaces: BluepeerInterfaces = .any
open var advertisingRole: RoleType?
@objc var advertisingCustomData = [String:String]()
@objc open var browsing: Bool = false
var onLastBackground: (advertising: RoleType?, browsing: Bool) = (nil, false)
@objc open var serviceType: String = ""
@objc var serverPort: UInt16 = 0
@objc var versionString: String = "unknown"
@objc open var displayNameSanitized: String = ""
@objc var appIsInBackground = false
@objc weak open var membershipAdminDelegate: BluepeerMembershipAdminDelegate?
@objc weak open var membershipRosterDelegate: BluepeerMembershipRosterDelegate?
@objc weak open var dataDelegate: BluepeerDataDelegate?
@objc weak open var logDelegate: BluepeerLoggingDelegate? {
didSet {
fileLogDelegate = logDelegate
}
}
@objc open var peers = [BPPeer]() // does not include self
@objc open var bluetoothState : BluetoothState = .unknown
@objc var bluetoothPeripheralManager: CBPeripheralManager!
@objc open var bluetoothBlock: ((_ bluetoothState: BluetoothState) -> Void)?
@objc open var disconnectOnBackground: Bool = false
let headerTerminator: Data = "\r\n\r\n".data(using: String.Encoding.utf8)! // same as HTTP. But header content here is just a number, representing the byte count of the incoming nsdata.
let keepAliveHeader: Data = "0 ! 0 ! 0 ! 0 ! 0 ! 0 ! 0 ! ".data(using: String.Encoding.utf8)! // A special header kept to avoid timeouts
let socketQueue = DispatchQueue(label: "xaphod.bluepeer.socketQueue", attributes: [])
@objc var browsingWorkaroundRestarts = 0
/// nil : no compression
/// ZLIB : Fast with a very solid compression rate. There is a reason it is used everywhere.
/// LZFSE : Apples proprietary compression algorithm. Claims to compress as good as ZLIB but 2 to 3 times faster.
/// LZMA : Horribly slow. Compression as well as decompression. Normally you will regret choosing LZMA.
/// LZ4 : Fast, but depending on the data the compression rate can be really bad. Which is often the case.
open var compressionAlgorithm: Data.CompressionAlgorithm? = .lzfse
@objc open func turnOffCompression() { self.compressionAlgorithm = nil }
enum DataTag: Int {
case tag_HEADER = -1
// case tag_BODY = -2 -- no longer used: negative tag values are conventional, positive tag values indicate number of bytes expected to read
case tag_WRITING = -3
case tag_AUTH = -4
case tag_NAME = -5
case tag_WRITINGKEEPALIVE = -6 // new in 1.4.0
}
enum Timeouts: Double {
case header = 40
case body = 90
case keepAlive = 16
}
fileprivate var fileLogDelegate: BluepeerLoggingDelegate?
func dlog(_ items: CustomStringConvertible...) {
var willLog = false
#if DEBUG
willLog = true
#endif
if let _ = fileLogDelegate {
willLog = true
}
guard willLog else { return }
var str = ""
for item in items {
str += item.description
}
let serviceType = self.serviceType.replacingOccurrences(of: "_xd-", with: "").replacingOccurrences(of: "._tcp", with: "")
if let del = fileLogDelegate {
del.logString("Bluepeer \(serviceType) " + str)
} else {
let formatter = DateFormatter.init()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
let out = formatter.string(from: Date.init()) + " - Bluepeer \(serviceType) - " + str
print(out)
}
}
// if queue isn't given, main queue is used
@objc public init?(serviceType: String, displayName:String?, queue:DispatchQueue?, serverPort: UInt16, interfaces: BluepeerInterfaces, logDelegate: BluepeerLoggingDelegate? = nil, bluetoothBlock: ((_ bluetoothState: BluetoothState)->Void)?) {
super.init()
fileLogDelegate = logDelegate
// serviceType must be 1-15 chars, only a-z0-9 and hyphen, eg "xd-blueprint"
if serviceType.count > 15 {
assert(false, "ERROR: service name is too long")
return nil
}
self.serviceType = "_" + self.sanitizeCharsToDNSChars(str: serviceType) + "._tcp"
self.serverPort = serverPort
self.delegateQueue = queue
self.bluepeerInterfaces = interfaces
var name = UIDevice.current.name
if let displayName = displayName {
name = displayName
}
self.displayNameSanitized = self.sanitizeStringAsDNSName(str: name)
if let bundleVersionString = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
versionString = bundleVersionString
}
self.bluetoothBlock = bluetoothBlock
self.bluetoothPeripheralManager = CBPeripheralManager.init(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey:0])
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
if #available(iOS 8.2, *) {
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: NSNotification.Name.NSExtensionHostDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: NSNotification.Name.NSExtensionHostWillEnterForeground, object: nil)
}
dlog("Initialized. Name: \(self.displayNameSanitized)")
}
deinit {
NotificationCenter.default.removeObserver(self)
self.killAllKeepaliveTimers() // probably moot: won't start deiniting until all timers are dead, because they have a strong ref to self
self.disconnectSession()
self.stopBrowsing()
self.stopAdvertising()
dlog("DEINIT FINISH")
}
override open var description: String {
let formatter = DateFormatter.init()
formatter.dateStyle = .none
formatter.timeStyle = .medium
var retval = ""
for peer in self.peers {
retval += peer.description + "\n"
}
return retval
}
// Note: if I disconnect, then my delegate is expected to reconnect if needed.
@objc func didEnterBackground() {
self.appIsInBackground = true
self.onLastBackground = (self.advertisingRole, self.browsing)
stopBrowsing()
stopAdvertising()
if disconnectOnBackground {
disconnectSession()
dlog("didEnterBackground - stopped browsing & advertising, and disconnected session")
} else {
dlog("didEnterBackground - stopped browsing & advertising")
}
}
@objc func willEnterForeground() {
dlog("willEnterForeground")
self.appIsInBackground = false
if let role = self.onLastBackground.advertising {
dlog("willEnterForeground, startAdvertising")
startAdvertising(role, customData: self.advertisingCustomData)
}
if self.onLastBackground.browsing {
dlog("willEnterForeground, startBrowsing")
startBrowsing()
}
}
func sanitizeCharsToDNSChars(str: String) -> String {
let acceptableChars = CharacterSet.init(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-")
return String(str.filter({ $0 != "'"}).map { (char: Character) in
if acceptableChars.containsCharacter(char) == false {
return "-"
} else {
return char
}
})
}
// per DNSServiceRegister called by HHServices, the String must be at most 63 bytes of UTF8 data. But, Bluepeer sends 32-byte name strings as part of its connection buildup, so limit this to max 32 bytes. The name is used to uniquely identify devices, and devices might have the same name (ie. "iPhone"), so append some random numbers to the end
// returns: the given string with an identifier appended on the end, guaranteed to be max 32 bytes
func sanitizeStringAsDNSName(str: String) -> String {
// first sanitize name by getting rid of invalid chars
var retval = self.sanitizeCharsToDNSChars(str: str)
// we need to append "-NNNN" to the end, which is 5 bytes in UTF8. So, the name part can be max 32-5 bytes = 27 bytes
// characters take up different amounts of bytes in UTF8, so let's be careful to count them
var strData = Data.init(capacity: 32)
// make 27-byte UTF-8 name
for c in retval {
if let thisData = String.init(c).data(using: String.Encoding.utf8) {
if thisData.count + (strData.count) <= 27 {
strData.append(thisData)
} else {
break
}
} else {
assert(false, "ERROR: non-UTF8 chars found")
}
}
strData.append(String.init("-").data(using: String.Encoding.utf8)!)
for _ in 1...4 {
strData.append(String.init(arc4random_uniform(10)).data(using: String.Encoding.utf8)!)
}
retval = String.init(data: strData, encoding: String.Encoding.utf8)!
dlog("sanitized \(str) to \(retval)")
return retval
}
@objc open func disconnectSession() {
// don't close serverSocket: expectation is that only stopAdvertising does this
// loop through peers, disconenct all sockets
for peer in self.peers {
dlog(" disconnectSession: disconnecting \(peer.displayName)")
peer.socket?.synchronouslySetDelegate(nil) // we don't want to run our disconnection logic below
peer.socket?.disconnect()
peer.socket = nil
peer.destroyServices()
peer.state = .notConnected
peer.keepaliveTimer?.invalidate()
peer.keepaliveTimer = nil
}
self.peers = [] // remove all peers!
}
@objc open func connectedPeers(_ role: RoleType) -> [BPPeer] {
return self.peers.filter({ $0.role == role && $0.state == .authenticated })
}
@objc open func connectedPeers() -> [BPPeer] {
return self.peers.filter({ $0.state == .authenticated })
}
// specify customData if this is needed for browser to decide whether to connect or not. Each key and value should be less than 255 bytes, and the total should be less than 1300 bytes.
@objc open func startAdvertising(_ role: RoleType, customData: [String:String]) {
if let _ = self.advertisingRole {
dlog("Already advertising (no-op)")
return
}
dlog("starting advertising using port \(serverPort)")
// type must be like: _myexampleservice._tcp (no trailing .)
// txtData, from http://www.zeroconf.org/rendezvous/txtrecords.html: Using TXT records larger than 1300 bytes is NOT RECOMMENDED at this time. The format of the data within a DNS TXT record is zero or more strings, packed together in memory without any intervening gaps or padding bytes for word alignment. The format of each constituent string within the DNS TXT record is a single length byte, followed by 0-255 bytes of text data.
// Could use the NSNetService version of this (TXTDATA maker), it'd be easier :)
var swiftdict: [String:String] = ["role":role.description, "comp":"1"] // 1.3.0: added compression flag to advertising/browsing, to make sure old clients cannot connect to new ones due to differing compression algorithms
self.advertisingCustomData = customData
swiftdict.merge(with: customData)
let cfdata: Unmanaged<CFData>? = CFNetServiceCreateTXTDataWithDictionary(kCFAllocatorDefault, swiftdict as CFDictionary)
guard let txtdata = cfdata?.takeUnretainedValue() else {
dlog("ERROR could not create TXTDATA")
return
}
self.publisher = HHServicePublisher.init(name: self.displayNameSanitized, type: self.serviceType, domain: "local.", txtData: txtdata as Data, port: UInt(serverPort))
self.publisher?.mainDispatchQueue = socketQueue
guard let publisher = self.publisher else {
dlog("could not create publisher")
return
}
publisher.delegate = self
var starting: Bool
switch self.bluepeerInterfaces {
case .any:
starting = publisher.beginPublish()
break
case .notWifi:
starting = publisher.beginPublishOverBluetoothOnly()
break
case .infrastructureModeWifiOnly:
starting = publisher.beginPublish(UInt32(kDNSServiceInterfaceIndexAny), includeP2P: false)
break
}
if !starting {
dlog(" ERROR: could not start advertising")
assert(false, "ERROR could not start advertising")
self.publisher = nil
self.advertisingRole = nil
return
}
// serverSocket is created in didPublish delegate (from HHServicePublisherDelegate) below
self.advertisingRole = role
}
@objc open func stopAdvertising(leaveServerSocketAlone: Bool = false) {
if let _ = self.advertisingRole {
if let publisher = self.publisher {
publisher.endPublish()
} else {
dlog("WARNING: publisher is MIA while advertising set true!")
}
dlog("advertising stopped")
} else {
dlog("no advertising to stop (no-op)")
}
self.publisher = nil
self.advertisingRole = nil
if leaveServerSocketAlone == false {
self.destroyServerSocket()
}
}
fileprivate func createServerSocket() -> Bool {
self.serverSocket = GCDAsyncSocket.init(delegate: self, delegateQueue: socketQueue)
self.serverSocket?.isIPv4PreferredOverIPv6 = false
guard let serverSocket = self.serverSocket else {
dlog("ERROR - Could not create serverSocket")
return false
}
do {
try serverSocket.accept(onPort: serverPort)
} catch {
dlog("ERROR accepting on serverSocket")
return false
}
dlog("Created serverSocket, is accepting on \(serverPort)")
return true
}
fileprivate func destroyServerSocket() {
if let socket = self.serverSocket {
socket.synchronouslySetDelegate(nil)
socket.disconnect()
self.serverSocket = nil
dlog("Destroyed serverSocket")
}
}
@objc open func startBrowsing() {
if self.browsing == true {
dlog("Already browsing (no-op)")
return
}
self.browser = HHServiceBrowser.init(type: self.serviceType, domain: "local.")
self.browser?.mainDispatchQueue = socketQueue
guard let browser = self.browser else {
dlog("ERROR, could not create browser")
return
}
browser.delegate = self
switch self.bluepeerInterfaces {
case .any:
self.browsing = browser.beginBrowse()
break
case .notWifi:
self.browsing = browser.beginBrowseOverBluetoothOnly()
break
case .infrastructureModeWifiOnly:
self.browsing = browser.beginBrowse(UInt32(kDNSServiceInterfaceIndexAny), includeP2P: false)
break
}
dlog("now browsing")
}
@objc open func stopBrowsing() {
if (self.browsing) {
if self.browser == nil {
dlog("WARNING, browser is MIA while browsing set true! ")
} else {
self.browser!.endBrowse()
dlog("browsing stopped")
}
} else {
dlog("no browsing to stop")
}
self.browser = nil
self.browsing = false
for peer in self.peers {
peer.destroyServices()
}
}
@objc open func sendData(_ datas: [Data], toPeers:[BPPeer]) throws {
for data in datas {
for peer in toPeers {
self.sendDataInternal(peer, data: data)
}
}
}
@objc open func sendData(_ datas: [Data], toRole: RoleType) throws {
let targetPeers: [BPPeer] = peers.filter({
if toRole != .any {
return $0.role == toRole && $0.state == .authenticated
} else {
return $0.state == .authenticated
}
})
for data in datas {
if data.count == 0 {
continue
}
for peer in targetPeers {
self.sendDataInternal(peer, data: data)
}
}
}
func sendDataInternal(_ peer: BPPeer, data: Data) {
// send header first. Then separator. Then send body.
// length: send as 4-byte, then 4 bytes of unused 0s for now. assumes endianness doesn't change between platforms, ie 23 00 00 00 not 00 00 00 23
// compress that data
var dataToSend: Data
var ratio: Double = 100.0
var timeToCompress: Double = 0.0
if let algorithm = self.compressionAlgorithm {
let compressionStart = Date.init()
guard let compressedData = data.compress(withAlgorithm: algorithm) else {
assert(false)
return
}
timeToCompress = abs(compressionStart.timeIntervalSinceNow)
ratio = Double(compressedData.count) / Double(data.count) * 100.0
dataToSend = compressedData
} else {
dataToSend = data
}
var length: UInt = UInt(dataToSend.count)
let senddata = NSMutableData.init(bytes: &length, length: 4)
let unused4bytesdata = NSMutableData.init(length: 4)!
senddata.append(unused4bytesdata as Data)
senddata.append(self.headerTerminator)
senddata.append(dataToSend)
dlog("sending \(senddata.length) bytes to \(peer.displayName): \(data.count) bytes compressed to \(dataToSend.count) bytes (\(ratio)%) in \(timeToCompress)s")
// DLog("sendDataInternal writes: \((senddata as Data).hex), payload part: \(data.hex)")
peer.dataSendCount += 1
peer.socket?.write(senddata as Data, withTimeout: Timeouts.body.rawValue, tag: DataTag.tag_WRITING.rawValue)
}
func scheduleNextKeepaliveTimer(_ peer: BPPeer) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if peer.state != .authenticated || peer.socket == nil {
return
}
peer.dataRecvCount += 1
if peer.dataRecvCount + 1 == Int.max {
peer.dataRecvCount = 0
}
if peer.keepaliveTimer?.isValid == true {
return
}
let delay: TimeInterval = Timeouts.keepAlive.rawValue - 5 - (Double(arc4random_uniform(5000)) / Double(1000)) // keepAlive.rawValue - 5 - (up to 5)
self.dlog("keepalive INITIAL SCHEDULING for \(peer.displayName) in \(delay)s")
peer.keepaliveTimer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(self.keepAliveTimerFired), userInfo: ["peer":peer], repeats: true)
}
}
@objc func keepAliveTimerFired(_ timer: Timer) {
guard let ui = timer.userInfo as? Dictionary<String, AnyObject> else {
assert(false, "ERROR")
timer.invalidate()
return
}
guard let peer = ui["peer"] as? BPPeer else {
dlog("keepAlive timer didn't find a peer, invalidating timer")
timer.invalidate()
return
}
if peer.state != .authenticated || peer.socket == nil {
dlog("keepAlive timer finds peer isn't authenticated(connected), invalidating timer")
timer.invalidate()
peer.keepaliveTimer = nil
return
}
// New in 1.4.0: send keepalives OR real data sends, not both at same time
let timeKeepAlives = abs(peer.lastDataKeepAliveWritten.timeIntervalSinceNow)
let timeNotKeepAlives = abs(peer.lastDataNonKeepAliveWritten.timeIntervalSinceNow)
assert(Thread.current.isMainThread)
guard timeNotKeepAlives > Timeouts.keepAlive.rawValue / 2.0 else {
dlog("keepAlive timer no-op as data was recently sent: timeKeepAlive=\(timeKeepAlives), timeNotKeepAlive=\(timeNotKeepAlives)")
return
}
var senddata = NSData.init(data: self.keepAliveHeader) as Data
senddata.append(self.headerTerminator)
dlog("writeKeepAlive to \(peer.displayName)")
peer.socket?.write(senddata, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_WRITINGKEEPALIVE.rawValue)
}
func killAllKeepaliveTimers() {
for peer in self.peers {
peer.keepaliveTimer?.invalidate()
peer.keepaliveTimer = nil
}
}
func dispatch_on_delegate_queue(_ block: @escaping ()->()) {
if let queue = self.delegateQueue {
queue.async(execute: block)
} else {
DispatchQueue.main.async(execute: block)
}
}
@objc open func getBrowser(_ completionBlock: @escaping (Bool) -> ()) -> UIViewController? {
let initialVC = self.getStoryboard()?.instantiateInitialViewController()
var browserVC = initialVC
if let nav = browserVC as? UINavigationController {
browserVC = nav.topViewController
}
guard let browser = browserVC as? BluepeerBrowserViewController else {
assert(false, "ERROR - storyboard layout changed")
return nil
}
browser.bluepeerObject = self
browser.browserCompletionBlock = completionBlock
return initialVC
}
func getStoryboard() -> UIStoryboard? {
guard let bundlePath = Bundle.init(for: BluepeerObject.self).path(forResource: "Bluepeer", ofType: "bundle") else {
assert(false, "ERROR: could not load bundle")
return nil
}
return UIStoryboard.init(name: "Bluepeer", bundle: Bundle.init(path: bundlePath))
}
}
extension GCDAsyncSocket {
var peer: BPPeer? {
guard let bo = self.delegate as? BluepeerObject else {
return nil
}
guard let peer = bo.peers.filter({ $0.socket == self }).first else {
return nil
}
return peer
}
}
extension BluepeerObject : HHServicePublisherDelegate {
public func serviceDidPublish(_ servicePublisher: HHServicePublisher) {
// create serverSocket
if let socket = self.serverSocket {
dlog("serviceDidPublish: USING EXISTING SERVERSOCKET \(socket)")
} else {
if self.createServerSocket() == false {
return
}
}
dlog("now advertising for service \(serviceType)")
}
public func serviceDidNotPublish(_ servicePublisher: HHServicePublisher) {
self.advertisingRole = nil
dlog("ERROR: serviceDidNotPublish")
}
}
extension BluepeerObject : HHServiceBrowserDelegate {
public func serviceBrowser(_ serviceBrowser: HHServiceBrowser, didFind service: HHService, moreComing: Bool) {
if self.browsing == false {
return
}
if self.displayNameSanitized == service.name { // names are made unique by having random numbers appended
dlog("found my own published service, ignoring...")
return
}
if service.type == self.serviceType {
dlog("didFindService \(service.name), moreComing: \(moreComing)")
service.delegate = self
// if this peer exists, then add this as another address(es), otherwise add now
var peer = self.peers.filter({ $0.displayName == service.name }).first
if let peer = peer {
dlog("didFind: added new unresolved service to peer \(peer.displayName)")
peer.services.append(service)
self.dispatch_on_delegate_queue({
self.membershipAdminDelegate?.bluepeer?(self, browserFindingPeer: false)
})
} else {
peer = BPPeer.init()
guard let peer = peer else { return }
peer.owner = self
peer.displayName = service.name
peer.services.append(service)
self.peers.append(peer)
dlog("didFind: created new peer \(peer.displayName). Peers(n=\(self.peers.count)) after adding")
self.dispatch_on_delegate_queue({
self.membershipAdminDelegate?.bluepeer?(self, browserFindingPeer: true)
})
}
let prots = UInt32(kDNSServiceProtocol_IPv4) | UInt32(kDNSServiceProtocol_IPv6)
switch self.bluepeerInterfaces {
case .any:
service.beginResolve(UInt32(kDNSServiceInterfaceIndexAny), includeP2P: true, addressLookupProtocols: prots)
break
case .notWifi:
service.beginResolve(BluepeerObject.kDNSServiceInterfaceIndexP2PSwift, includeP2P: true, addressLookupProtocols: prots)
break
case .infrastructureModeWifiOnly:
service.beginResolve(UInt32(kDNSServiceInterfaceIndexAny), includeP2P: false, addressLookupProtocols: prots)
break
}
}
}
public func serviceBrowser(_ serviceBrowser: HHServiceBrowser, didRemove service: HHService, moreComing: Bool) {
let matchingPeers = self.peers.filter({ $0.displayName == service.name })
if matchingPeers.count == 0 {
dlog("didRemoveService for service.name \(service.name) -- IGNORING because no peer found")
return
}
for peer in matchingPeers {
// if found exact service, then nil it out to prevent more connection attempts
if let serviceIndex = peer.services.firstIndex(of: service) {
let previousResolvedServiceCount = peer.resolvedServices().count
dlog("didRemoveService - REMOVING SERVICE from \(peer.displayName)")
peer.services.remove(at: serviceIndex)
if peer.resolvedServices().count == 0 && previousResolvedServiceCount > 0 {
dlog("didRemoveService - that was the LAST resolved service so calling browserLostPeer for \(peer.displayName)")
self.dispatch_on_delegate_queue({
self.membershipAdminDelegate?.bluepeer?(self, browserLostPeer: peer.role, peer: peer)
})
}
} else {
dlog("didRemoveService - \(peer.displayName) has no matching service (no-op)")
}
}
}
}
extension BluepeerObject : HHServiceDelegate {
public func serviceDidResolve(_ service: HHService, moreComing: Bool) {
func cleanup() {
self.dispatch_on_delegate_queue({
self.membershipAdminDelegate?.bluepeer?(self, browserFindingPeerFailed: false)
})
}
if self.browsing == false {
return
}
guard let txtdata = service.txtData else {
dlog("serviceDidResolve IGNORING service because no txtData found")
cleanup()
return
}
guard let hhaddresses: [HHAddressInfo] = service.resolvedAddressInfo, hhaddresses.count > 0 else {
dlog("serviceDidResolve IGNORING service because could not get resolvedAddressInfo")
cleanup()
return
}
let cfdict: Unmanaged<CFDictionary>? = CFNetServiceCreateDictionaryWithTXTData(kCFAllocatorDefault, txtdata as CFData)
guard let _ = cfdict else {
dlog("serviceDidResolve IGNORING service because txtData was invalid")
cleanup()
return
}
let dict: NSDictionary = cfdict!.takeUnretainedValue()
guard let rD = dict["role"] as? Data,
let roleStr = String.init(data: rD, encoding: String.Encoding.utf8) else {
dlog("serviceDidResolve IGNORING service because role was missing")
cleanup()
return
}
let role = RoleType.roleFromString(roleStr)
switch role {
case .unknown:
assert(false, "Expecting a role that isn't unknown here")
cleanup()
return
default:
break
}
// load custom data
var customData = [String:String]()
for (k, v) in dict {
guard let k = k as? String,
let vd = v as? Data,
let v = String.init(data: vd, encoding: String.Encoding.utf8) else {
assert(false, "Expecting [String:Data] dict")
continue
}
if k == "role" {
continue
} else {
customData[k] = v
}
}
let matchingPeers = self.peers.filter({ $0.displayName == service.name })
if matchingPeers.count != 1 {
dlog("serviceDidResolve FAILED, expected 1 peer but found \(matchingPeers.count)")
assert(false)
cleanup()
return
}
let peer = matchingPeers.first!
peer.role = role
peer.customData = customData
dlog("serviceDidResolve for \(peer.displayName) - addresses \(hhaddresses.count), peer.role: \(role), peer.state: \(peer.state), #customData:\(customData.count)")
// if has insufficient version, don't announce it
guard let compStr = customData["comp"], compStr == "1" else {
dlog("serviceDidResolve: IGNORING THIS PEER, IT IS TOO OLD - DOES NOT SUPPORT CORRECT COMPRESSION ALGORITHM")
cleanup()
return
}
let candidates = hhaddresses.filter({ $0.isCandidateAddress(excludeWifi: self.bluepeerInterfaces == .notWifi, onlyWifi: self.bluepeerInterfaces == .infrastructureModeWifiOnly) })
if peer.state != .notConnected {
dlog("... has state!=notConnected, so no-op")
return
} else if candidates.count == 0 {
dlog("... no candidates out of \(hhaddresses.count) addresses. moreComing = \(moreComing)")
if hhaddresses.count > 1 && !moreComing && self.bluepeerInterfaces == .notWifi {
if (self.browsingWorkaroundRestarts >= 3) {
dlog(" *** workarounds exhausted! falling back to not bluetoothOnly")
self.browsingWorkaroundRestarts = 0
self.bluepeerInterfaces = .any
let secondaryCandidates = hhaddresses.filter({ $0.isCandidateAddress(excludeWifi: self.bluepeerInterfaces == .notWifi, onlyWifi: self.bluepeerInterfaces == .infrastructureModeWifiOnly) })
if (secondaryCandidates.count <= 0) {
dlog("... STILL no candidates. Bummer.")
return
}
} else {
self.browsingWorkaroundRestarts += 1
dlog(" *** workaround for BT radio connection delay: restarting browsing, \(self.browsingWorkaroundRestarts) of 3")
self.stopBrowsing()
if let indexOfPeer = self.peers.firstIndex(of: peer) {
self.peers.remove(at: indexOfPeer)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.startBrowsing()
}
return
}
} else {
return
}
}
peer.connect = { [weak self] in
guard let self = self else { return false }
do {
// pick the address to connect to INSIDE the block, because more addresses may have been added between announcement and inviteBlock being executed
let candidateAddresses = peer.candidateAddresses
guard candidateAddresses.count > 0 else {
self.dlog("connect: \(peer.displayName) has no candidates, BAILING")
return false
}
// We have N candidateAddresses from 1 resolved service, which should we pick?
// if we tried to connect to one recently and failed, and there's another one, pick the other one
var interimAddress: HHAddressInfo?
if let lastInterfaceName = peer.lastInterfaceName, candidateAddresses.count > 1 {
let otherAddresses = candidateAddresses.filter { $0.interfaceName != lastInterfaceName }
if otherAddresses.count > 0 {
interimAddress = otherAddresses.first!
self.dlog("connect: \(peer.displayName) trying a different interface than last attempt. Now trying: \(interimAddress!.interfaceName)")
}
}
var chosenAddress = candidateAddresses.first!
if let interimAddress = interimAddress {
// first priority is not always trying to reconnect on the same interface when >1 is available
chosenAddress = interimAddress
} else {
// second priority is if we can use wifi, then do so
if self.bluepeerInterfaces != .notWifi && !chosenAddress.isWifiInterface() {
let wifiCandidates = candidateAddresses.filter({ $0.isWifiInterface() })
if wifiCandidates.count > 0 {
chosenAddress = wifiCandidates.first!
}
}
}
peer.lastInterfaceName = chosenAddress.interfaceName
self.dlog("connect: \(peer.displayName) has \(peer.services.count) svcs (\(peer.resolvedServices().count) resolved); chose \(chosenAddress.addressAndPortString) on interface \(chosenAddress.interfaceName)")
let sockdata = chosenAddress.socketAsData()
if let oldSocket = peer.socket {
self.dlog("**** connect: PEER ALREADY HAD SOCKET, DESTROYING...")
oldSocket.synchronouslySetDelegate(nil)
oldSocket.disconnect()
peer.socket = nil
}
peer.socket = GCDAsyncSocket.init(delegate: self, delegateQueue: self.socketQueue)
peer.socket?.isIPv4PreferredOverIPv6 = false
peer.state = .connecting
try peer.socket?.connect(toAddress: sockdata, withTimeout: 10.0)
// try peer.socket?.connect(toAddress: sockdata, viaInterface: chosenAddress.interfaceName, withTimeout: 10.0)
return true
} catch {
self.dlog("could not connect, ERROR: \(error)")
peer.state = .notConnected
return false
}
}
guard let delegate = self.membershipAdminDelegate else {
dlog("announcePeer: WARNING, no-op because membershipAdminDelegate is not set")
return
}
if self.appIsInBackground == false {
dlog("announcePeer: announcing now with browserFoundPeer - call peer.connect() to connect")
self.dispatch_on_delegate_queue({
delegate.bluepeer?(self, browserFoundPeer: peer.role, peer: peer)
})
} else {
dlog("announcePeer: app is in BACKGROUND, no-op!")
}
}
public func serviceDidNotResolve(_ service: HHService) {
dlog("****** ERROR, service did not resolve: \(service.name) *******")
self.dispatch_on_delegate_queue({
self.membershipAdminDelegate?.bluepeer?(self, browserFindingPeerFailed: false)
})
}
}
extension HHAddressInfo {
func isIPV6() -> Bool {
let socketAddrData = Data.init(bytes: self.address, count: MemoryLayout<sockaddr>.size)
var storage = sockaddr_storage()
(socketAddrData as NSData).getBytes(&storage, length: MemoryLayout<sockaddr_storage>.size)
if Int32(storage.ss_family) == AF_INET6 {
return true
} else {
return false
}
}
func isWifiInterface() -> Bool {
return self.interfaceName == BluepeerObject.iOS_wifi_interface
}
func socketAsData() -> Data {
var socketAddrData = Data.init(bytes: self.address, count: MemoryLayout<sockaddr>.size)
var storage = sockaddr_storage()
(socketAddrData as NSData).getBytes(&storage, length: MemoryLayout<sockaddr_storage>.size)
if Int32(storage.ss_family) == AF_INET6 {
socketAddrData = Data.init(bytes: self.address, count: MemoryLayout<sockaddr_in6>.size)
}
return socketAddrData
}
func isCandidateAddress(excludeWifi: Bool, onlyWifi: Bool) -> Bool {
if excludeWifi && self.isWifiInterface() {
return false
}
if onlyWifi && !self.isWifiInterface() {
return false
}
if ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 10, minorVersion: 0, patchVersion: 0)) {
// iOS 10: *require* IPv6 address!
return self.isIPV6()
} else {
return true
}
}
func IP() -> String? {
let ipAndPort = self.addressAndPortString
guard let lastColonIndex = ipAndPort.range(of: ":", options: .backwards)?.lowerBound else {
assert(false, "error")
return nil
}
let ip = String(ipAndPort[..<lastColonIndex])
if ipAndPort.components(separatedBy: ":").count-1 > 1 {
// ipv6 - looks like [00:22:22.....]:port
let start = ip.index(ip.startIndex, offsetBy: 1)
let end = ip.index(ip.endIndex, offsetBy: -1)
return String(ip[start ..< end])
}
return ip
}
}
extension BluepeerObject : GCDAsyncSocketDelegate {
public func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
if self.membershipAdminDelegate != nil {
guard let connectedHost = newSocket.connectedHost, let localhost = newSocket.localHost else {
dlog("ERROR, accepted newSocket has no connectedHost (no-op)")
return
}
newSocket.delegate = self
let newPeer = BPPeer.init()
newPeer.owner = self
newPeer.state = .awaitingAuth
newPeer.role = .client
newPeer.socket = newSocket
newPeer.lastInterfaceName = XaphodUtils.interfaceName(ofLocalIpAddress: localhost)
self.peers.append(newPeer) // always add as a new peer, even if it already exists. This might result in a dupe if we are browsing and advertising for same service. The original will get removed on receiving the name of other device, if it matches
dlog("accepting new connection from \(connectedHost) on \(String(describing: newPeer.lastInterfaceName)). Peers(n=\(self.peers.count)) after adding")
// CONVENTION: CLIENT sends SERVER 32 bytes of its name -- UTF-8 string
newSocket.readData(toLength: 32, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_NAME.rawValue)
} else {
dlog("WARNING, ignoring connection attempt because I don't have a membershipAdminDelegate assigned")
}
}
public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
guard let peer = sock.peer else {
dlog("WARNING, did not find peer in didConnectToHost, doing nothing")
return
}
peer.state = .awaitingAuth
dlog("got to state = awaitingAuth with \(String(describing: sock.connectedHost)), sending name then awaiting ACK ('0')")
let strData = self.displayNameSanitized.data(using: String.Encoding.utf8)! as NSData
// Other side is expecting to receive EXACTLY 32 bytes so pad to 32 bytes!
let paddedStrData: NSMutableData = (" ".data(using: String.Encoding.utf8) as NSData?)?.mutableCopy() as! NSMutableData // that's 32 spaces :)
paddedStrData.replaceBytes(in: NSMakeRange(0, strData.length), withBytes: strData.bytes)
dlog("didConnect to \(String(describing: sock.connectedHost)), writing name: \((paddedStrData as Data).hex)")
sock.write(paddedStrData as Data, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_WRITING.rawValue)
// now await auth
dlog("waiting to read Auth from \(String(describing: sock.connectedHost))...")
sock.readData(toLength: 1, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_AUTH.rawValue)
}
public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
let matchingPeers = self.peers.filter({ $0.socket == sock})
if matchingPeers.count != 1 {
dlog(" socketDidDisconnect: WARNING expected to find 1 peer with this socket but found \(matchingPeers.count), calling peerConnectionAttemptFailed.")
sock.synchronouslySetDelegate(nil)
self.dispatch_on_delegate_queue({
self.membershipRosterDelegate?.bluepeer?(self, peerConnectionAttemptFailed: .unknown, peer: nil, isAuthRejection: false, canConnectNow: false)
})
return
}
let peer = matchingPeers.first!
dlog(" socketDidDisconnect: \(peer.displayName) disconnected. Peers(n=\(self.peers.count))")
let oldState = peer.state
peer.state = .notConnected
peer.keepaliveTimer?.invalidate()
peer.keepaliveTimer = nil
peer.socket = nil
sock.synchronouslySetDelegate(nil)
switch oldState {
case .authenticated:
peer.disconnectCount += 1
self.dispatch_on_delegate_queue({
self.membershipRosterDelegate?.bluepeer?(self, peerDidDisconnect: peer.role, peer: peer, canConnectNow: peer.canConnect)
})
break
case .notConnected:
break
case .connecting, .awaitingAuth:
peer.connectAttemptFailCount += 1
if oldState == .awaitingAuth {
peer.connectAttemptFailAuthRejectCount += 1
}
self.dispatch_on_delegate_queue({
self.membershipRosterDelegate?.bluepeer?(self, peerConnectionAttemptFailed: peer.role, peer: peer, isAuthRejection: oldState == .awaitingAuth, canConnectNow: peer.canConnect)
})
break
}
}
fileprivate func disconnectSocket(socket: GCDAsyncSocket?, peer: BPPeer) {
peer.state = .notConnected
socket?.synchronouslySetDelegate(nil)
socket?.disconnect()
peer.socket = nil
}
public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
guard let peer = sock.peer else {
dlog("WARNING, did not find peer in didReadData, doing nothing")
return
}
self.scheduleNextKeepaliveTimer(peer)
DispatchQueue.main.async {
peer.lastDataRead = Date.init()
}
if tag == DataTag.tag_AUTH.rawValue {
if data.count != 1 {
assert(false, "ERROR: not right length of bytes")
self.disconnectSocket(socket: sock, peer: peer)
return
}
var ack: UInt8 = 1
(data as NSData).getBytes(&ack, length: 1)
if (ack != 0 || peer.state != .awaitingAuth) {
assert(false, "ERROR: not the right ACK, or state was not .awaitingAuth as expected")
self.disconnectSocket(socket: sock, peer: peer)
return
}
peer.state = .authenticated // CLIENT becomes authenticated
peer.connectCount += 1
self.dispatch_on_delegate_queue({
self.membershipRosterDelegate?.bluepeer?(self, peerDidConnect: peer.role, peer: peer)
})
dlog("\(peer.displayName).state=connected (auth OK), readHeaderTerminator1")
sock.readData(to: self.headerTerminator, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_HEADER.rawValue)
} else if tag == DataTag.tag_HEADER.rawValue {
// first, strip the trailing headerTerminator
let range = 0..<data.count-self.headerTerminator.count
let dataWithoutTerminator = data.subdata(in: range)
if dataWithoutTerminator == self.keepAliveHeader {
dlog("readKeepAlive from \(peer.displayName)")
sock.readData(to: self.headerTerminator, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_HEADER.rawValue)
} else {
// take the first 4 bytes and use them as UInt of length of data. read the next 4 bytes and discard for now, might use them for versioning/feature-supported in future, where clients are allowed to connect but have different feature abilities (as opposed to limiting what services you can see)
var length: UInt = 0
(dataWithoutTerminator as NSData).getBytes(&length, length: 4)
// ignore bytes 4-8 for now
dlog("got header, reading \(length) bytes from \(peer.displayName)...")
peer.clientReceivedBytes = 0
self.dispatch_on_delegate_queue({
self.dataDelegate?.bluepeer?(self, receivingData: 0, totalBytes: Int(length), peer: peer)
})
sock.readData(toLength: length, withTimeout: Timeouts.body.rawValue, tag: Int(length))
}
} else if tag == DataTag.tag_NAME.rawValue {
var name = String.init(data: data, encoding: String.Encoding.utf8)
if name == nil {
name = "Unknown"
}
name = name!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) // sender pads with spaces to 32 bytes
peer.displayName = self.sanitizeCharsToDNSChars(str: name!) // probably unnecessary but need to be safe
// we're the server. If we are advertising and browsing for the same serviceType, there might be a duplicate peer situation to take care of -- one created by browsing, one when socket was accepted. Remedy: kill old one, keep this one
for existingPeer in self.peers.filter({ $0.displayName == peer.displayName && $0 != peer }) {
let indexOfPeer = self.peers.firstIndex(of: existingPeer)!
dlog("about to remove dupe peer \(existingPeer.displayName) from index \(indexOfPeer), had socket: \(existingPeer.socket != nil ? "ACTIVE" : "nil"). Peers(n=\(self.peers.count)) before removal")
peer.connectAttemptFailCount += existingPeer.connectAttemptFailCount
peer.connectAttemptFailAuthRejectCount += existingPeer.connectAttemptFailAuthRejectCount
peer.connectCount += existingPeer.connectCount
peer.disconnectCount += existingPeer.disconnectCount
peer.dataRecvCount += existingPeer.dataRecvCount
peer.dataSendCount += existingPeer.dataSendCount
// existingPeer.destroyServices()
if existingPeer.customData.count > 0 {
var newCustomData = peer.customData
if newCustomData.count > 0 {
newCustomData.merge(with: existingPeer.customData)
} else {
peer.customData = existingPeer.customData
}
}
peer.services.append(contentsOf: existingPeer.services)
existingPeer.keepaliveTimer?.invalidate()
existingPeer.keepaliveTimer = nil
self.disconnectSocket(socket: existingPeer.socket, peer: existingPeer)
self.peers.remove(at: indexOfPeer)
dlog("... removed")
}
if let delegate = self.membershipAdminDelegate {
self.dispatch_on_delegate_queue({
delegate.bluepeer?(self, peerConnectionRequest: peer, invitationHandler: { [weak self] (inviteAccepted) in
guard let self = self else { return }
if peer.state != .awaitingAuth || sock.isConnected != true {
self.dlog("inviteHandlerBlock: not connected/wrong state, so cannot accept!")
if (sock.isConnected) {
self.disconnectSocket(socket: sock, peer: peer)
}
} else if inviteAccepted {
peer.state = .authenticated // SERVER-local-peer becomes connected
peer.connectCount += 1
// CONVENTION: SERVER sends CLIENT a single 0 to show connection has been accepted, since it isn't possible to send a header for a payload of size zero except here.
sock.write(Data.init(count: 1), withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_WRITING.rawValue)
self.dlog("inviteHandlerBlock: accepted \(peer.displayName) (by my delegate), reading header...")
self.dispatch_on_delegate_queue({
self.membershipRosterDelegate?.bluepeer?(self, peerDidConnect: .client, peer: peer)
})
self.scheduleNextKeepaliveTimer(peer) // NEW in 1.1: if the two sides open up a connection but no one says anything, make sure it stays open
sock.readData(to: self.headerTerminator, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_HEADER.rawValue)
} else {
self.dlog("inviteHandlerBlock: auth-rejected \(peer.displayName) (by my delegate)")
self.disconnectSocket(socket: sock, peer: peer)
}
})
})
}
} else { // BODY/data case
var data = data
if let algorithm = self.compressionAlgorithm {
guard let uncompressedData = data.decompress(withAlgorithm: algorithm) else {
assert(false, "Could not decompress data")
return
}
data = uncompressedData
}
peer.clientReceivedBytes = 0
self.dispatch_on_delegate_queue({
self.dataDelegate?.bluepeer?(self, receivingData: tag, totalBytes: tag, peer: peer)
self.dataDelegate?.bluepeer(self, didReceiveData: data, peer: peer)
})
sock.readData(to: self.headerTerminator, withTimeout: Timeouts.header.rawValue, tag: DataTag.tag_HEADER.rawValue)
}
}
public func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
guard let peer = sock.peer else { return }
self.scheduleNextKeepaliveTimer(peer)
DispatchQueue.main.async {
peer.lastDataRead = Date.init()
}
guard partialLength > 0 else { return }
peer.clientReceivedBytes += Int(partialLength)
self.dispatch_on_delegate_queue({
self.dataDelegate?.bluepeer?(self, receivingData: peer.clientReceivedBytes, totalBytes: tag, peer: peer)
})
}
private func updateKeepAlivesOnSend(peer: BPPeer, tag: Int) {
DispatchQueue.main.async {
if tag == DataTag.tag_WRITINGKEEPALIVE.rawValue {
peer.lastDataKeepAliveWritten = Date.init()
} else {
peer.lastDataNonKeepAliveWritten = Date.init()
}
}
}
// New in 1.4.0: avoid sending keepalives while sending data
public func socket(_ sock: GCDAsyncSocket, didWritePartialDataOfLength partialLength: UInt, tag: Int) {
guard let peer = sock.peer else { return }
updateKeepAlivesOnSend(peer: peer, tag: tag)
}
// New in 1.4.0: avoid sending keepalives while sending data
public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
guard let peer = sock.peer else { return }
updateKeepAlivesOnSend(peer: peer, tag: tag)
}
public func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
return self.calcTimeExtension(sock, tag: tag)
}
public func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
return self.calcTimeExtension(sock, tag: tag)
}
public func calcTimeExtension(_ sock: GCDAsyncSocket, tag: Int) -> TimeInterval {
guard let peer = sock.peer else {
return 0
}
assert(!Thread.current.isMainThread)
// it can happen that while sending lots of data, we don't receive keepalives that the other side is sending.
// so if we are sending real data succesfully, don't time out
var timeSinceLastDataRead: Double?
var timeSinceLastDataWrittenWithoutKeepAlives: Double?
DispatchQueue.main.sync {
timeSinceLastDataRead = abs(peer.lastDataRead.timeIntervalSinceNow)
timeSinceLastDataWrittenWithoutKeepAlives = abs(peer.lastDataNonKeepAliveWritten.timeIntervalSinceNow)
}
guard let timeSinceRead = timeSinceLastDataRead, let timeSinceWrite = timeSinceLastDataWrittenWithoutKeepAlives else {
assert(false)
return Timeouts.keepAlive.rawValue
}
let timeSince = min(timeSinceRead, timeSinceWrite)
if timeSince > (2.0 * Timeouts.keepAlive.rawValue) {
// timeout!
dlog("keepalive: socket timed out waiting for read/write. timeSinceRead: \(timeSinceRead), timeSinceWrite: \(timeSinceWrite). Tag: \(tag). Disconnecting.")
sock.disconnect()
return 0
}
// extend
dlog("keepalive: extending socket timeout by \(Timeouts.keepAlive.rawValue)s bc I saw data \(timeSince)s ago")
return Timeouts.keepAlive.rawValue
}
}
extension BluepeerObject: CBPeripheralManagerDelegate {
public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
guard self.bluetoothPeripheralManager != nil else {
dlog("!!!!!! BluepeerObject bluetooth state change with no bluetoothPeripheralManager !!!!!")
return
}
dlog("Bluetooth status: ")
switch (self.bluetoothPeripheralManager.state) {
case .unknown:
dlog("Unknown")
self.bluetoothState = .unknown
case .resetting:
dlog("Resetting")
self.bluetoothState = .other
case .unsupported:
dlog("Unsupported")
self.bluetoothState = .other
case .unauthorized:
dlog("Unauthorized")
self.bluetoothState = .other
case .poweredOff:
dlog("PoweredOff")
self.bluetoothState = .poweredOff
case .poweredOn:
dlog("PoweredOn")
self.bluetoothState = .poweredOn
@unknown default:
dlog("WARNING: unknown Bluetooth state")
break
}
self.bluetoothBlock?(self.bluetoothState)
}
}
extension CharacterSet {
func containsCharacter(_ c:Character) -> Bool {
let s = String(c)
let result = s.rangeOfCharacter(from: self)
return result != nil
}
}
extension Data {
var hex: String {
return self.map { b in String(format: "%02X", b) }.joined()
}
}
extension Dictionary {
mutating func merge(with a: Dictionary) {
for (k,v) in a {
self[k] = v
}
}
}
| 45.612748 | 451 | 0.61738 |
3a1c3ad14b6b615e814649c9bdc1f83aaee17e01 | 2,070 | //
// Copyright © 2017 Gondek. All rights reserved.
//
public class Event: NSObject, Decodable {
public var id: Int = 0
public var title: String = ""
public var link: String = ""
public var type: String = ""
public var poster: String = ""
public var status: String = ""
public var rsvpTotal: Int = 0
public var saleEnabled: Bool = false
public var eventDescription: String = ""
public var rsvp: [User] = []
public var date: [EventDate] = []
public var customTickets: [CustomTicket] = []
public var planner: Planner?
public var venue: Venue?
enum CodingKeys: String, CodingKey {
case eventDescription = "description"
case id
case title
case link
case type
case poster
case status
case rsvpTotal
case saleEnabled
case rsvp
case date
case customTickets
case planner
case venue
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = container.decodeKey(.id, ofType: Int.self)
saleEnabled = container.decodeKey(.saleEnabled, ofType: Bool.self)
rsvpTotal = container.decodeKey(.rsvpTotal, ofType: Int.self)
eventDescription = container.decodeKey(.eventDescription, ofType: String.self)
title = container.decodeKey(.title, ofType: String.self)
link = container.decodeKey(.link, ofType: String.self)
type = container.decodeKey(.type, ofType: String.self)
poster = container.decodeKey(.poster, ofType: String.self)
status = container.decodeKey(.status, ofType: String.self)
customTickets = container.decodeKey(.customTickets, ofType: [CustomTicket].self)
rsvp = container.decodeKey(.rsvp, ofType: [User].self)
date = container.decodeKey(.date, ofType: [EventDate].self)
planner = container.safeDecodeKey(.planner, to: Planner.self)
venue = container.safeDecodeKey(.venue, to: Venue.self)
}
}
| 35.689655 | 88 | 0.644444 |
38642d1d94d87a23de244d22b3f672ab64a3feda | 5,724 | //
// File.swift
//
//
// Created by Eric Rabil on 7/31/21.
//
import Foundation
public extension Collection {
/// Creates a dictionary whose key is represented by the keypath and whose value is that of this collection
@inlinable
func dictionary<Key: Hashable>(keyedBy key: KeyPath<Element, Key>) -> [Key: Element] {
dictionary(keyedBy: key, valuedBy: \Element.self)
}
/// Creates a dictionary whose key is represented by the keypath and whose value is all of the elements who have a non-nill value for said keypath
@inlinable
func dictionary<Key: Hashable>(keyedBy key: KeyPath<Element, Optional<Key>>) -> [Key: Element] {
dictionary(keyedBy: key, valuedBy: \Element.self)
}
/// Creates a dictionary whose key is represented by the first keypath and whose value is represented by the second keypath
@inlinable
func dictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Key>, valuedBy value: KeyPath<Element, Value>) -> [Key: Value] {
reduce(into: [Key: Value]()) { dict, entry in
dict[entry[keyPath: key]] = entry[keyPath: value]
}
}
/// Creates a dictionary whose key is represented by the first keypath and whose value is represented by the second keypath, for every element with a non-nill value for the first keypath
@inlinable
func dictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Optional<Key>>, valuedBy value: KeyPath<Element, Value>) -> [Key: Value] {
reduce(into: [Key: Value]()) { dict, entry in
guard let key = entry[keyPath: key] else { return }
dict[key] = entry[keyPath: value]
}
}
@inlinable
func collectedDictionary<Key: Hashable>(keyedBy key: KeyPath<Element, Key>) -> [Key: [Element]] {
collectedDictionary(keyedBy: key, valuedBy: \Element.self)
}
@inlinable
func collectedDictionary<Key: Hashable>(keyedBy key: KeyPath<Element, Optional<Key>>) -> [Key: [Element]] {
collectedDictionary(keyedBy: key, valuedBy: \Element.self)
}
/// Creates a dictionary whose key is represented by the first keypath and whose value is an array of element[value] where element[key] matches
@inlinable
func collectedDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Key>, valuedBy value: KeyPath<Element, Value>) -> [Key: [Value]] {
reduce(into: [Key: [Value]]()) { dict, entry in
let key = entry[keyPath: key]
if dict[key] == nil { dict[key] = [] }
dict[key]!.append(entry[keyPath: value])
}
}
@inlinable
func collectedDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Optional<Key>>, valuedBy value: KeyPath<Element, Value>) -> [Key: [Value]] {
reduce(into: [Key: [Value]]()) { dict, entry in
guard let key = entry[keyPath: key] else { return }
if dict[key] == nil { dict[key] = [] }
dict[key]!.append(entry[keyPath: value])
}
}
@inlinable
func collectedDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Key>, valuedBy value: KeyPath<Element, Optional<Value>>) -> [Key: [Value]] {
reduce(into: [Key: [Value]]()) { dict, entry in
guard let value = entry[keyPath: value] else { return }
let key = entry[keyPath: key]
if dict[key] == nil { dict[key] = [value] }
else { dict[key]!.append(value) }
}
}
@inlinable
func collectedDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Optional<Key>>, valuedBy value: KeyPath<Element, Optional<Value>>) -> [Key: [Value]] {
reduce(into: [Key: [Value]]()) { dict, entry in
guard let key = entry[keyPath: key], let value = entry[keyPath: value] else { return }
if dict[key] == nil { dict[key] = [value] }
else { dict[key]!.append(value) }
}
}
@inlinable
func compactDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Key>, valuedBy value: KeyPath<Element, Optional<Value>>) -> [Key: Value] {
reduce(into: [Key: Value]()) { dict, entry in
guard let value = entry[keyPath: value] else { return }
dict[entry[keyPath: key]] = value
}
}
@inlinable
func compactDictionary<Key: Hashable, Value>(keyedBy key: KeyPath<Element, Optional<Key>>, valuedBy value: KeyPath<Element, Optional<Value>>) -> [Key: Value] {
reduce(into: [Key: Value]()) { dict, entry in
guard let key = entry[keyPath: key], let value = entry[keyPath: value] else { return }
dict[key] = value
}
}
@inlinable
// used as such: arr.sorted(usingKey: \.date, by: >)
func sorted<Value: Comparable>(usingKey key: KeyPath<Element, Value>, by areInIncreasingOrder: (Value, Value) throws -> Bool) rethrows -> [Element] {
try self.sorted(by: { a, b in
try areInIncreasingOrder(a[keyPath: key], b[keyPath: key])
})
}
@inlinable
// used as such: arr.sorted(usingKey: \.chat?.lastMessage, withdefaultValue: 0, by: >)
func sorted<Value: Comparable>(usingKey key: KeyPath<Element, Optional<Value>>, withDefaultValue defaultValue: @autoclosure () -> Value, by areInIncreasingOrder: (Value, Value) throws -> Bool) rethrows -> [Element] {
try self.sorted(by: { a, b in
try areInIncreasingOrder(a[keyPath: key] ?? defaultValue(), b[keyPath: key] ?? defaultValue())
})
}
}
public extension Collection where Element: Collection {
@inlinable
func flatten() -> [Element.Element] {
flatMap {
$0
}
}
}
| 44.372093 | 220 | 0.621593 |
099e47d30328c446b01a046daf9c09b7c5916021 | 3,528 | //
// main.swift
// Day 21
//
// Copyright © 2021 peter bohac. All rights reserved.
//
// MARK: - Part 1
print("Day 21:")
enum Part1 {
static var dice = Array(1...100)
static var board = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
static func run(player1Start: Int, player2Start: Int) {
var p1 = player1Start
var p2 = player2Start
var p1Score = 0
var p2Score = 0
var rollCount = -1
while true {
rollCount += 1
var move = Self.dice[rollCount % 100]
rollCount += 1
move += Self.dice[rollCount % 100]
rollCount += 1
move += Self.dice[rollCount % 100]
p1 += move
p1Score += Self.board[p1 % 10]
if p1Score >= 1000 {
break
}
rollCount += 1
move = Self.dice[rollCount % 100]
rollCount += 1
move += Self.dice[rollCount % 100]
rollCount += 1
move += Self.dice[rollCount % 100]
p2 += move
p2Score += Self.board[p2 % 10]
if p2Score >= 1000 {
break
}
}
let answer = min(p1Score, p2Score) * (rollCount + 1)
print("Part 1 start from \(player1Start), \(player2Start): losing score: \(min(p1Score, p2Score)), dice rolls: \(rollCount + 1), result: \(answer)")
}
}
Part1.run(player1Start: 4, player2Start: 8)
Part1.run(player1Start: 6, player2Start: 7)
// MARK: - Part 2
print("")
enum Part2 {
static var board = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
static func run(player1Start: Int, player2Start: Int) {
var cache: [String: (Int, Int)] = [:]
func turn(position: (p1: Int, p2: Int), score: (p1: Int, p2: Int), player1Turn: Bool) -> (p1: Int, p2: Int) {
if score.p1 >= 21 {
return (1, 0)
}
if score.p2 >= 21 {
return (0, 1)
}
let key = "\(position),\(score),\(player1Turn)"
if let cached = cache[key] {
return cached
}
var wins: (p1: Int, p2: Int) = (0, 0)
for roll1 in 1...3 {
for roll2 in 1...3 {
for roll3 in 1...3 {
let sum = [roll1, roll2, roll3].reduce(0, +)
let newPosition: (p1: Int, p2: Int)
var newScore = score
if player1Turn {
newPosition = ((position.p1 + sum) % 10, position.p2)
newScore.p1 += Self.board[newPosition.p1]
} else {
newPosition = (position.p1, (position.p2 + sum) % 10)
newScore.p2 += Self.board[newPosition.p2]
}
let newWins = turn(position: newPosition, score: newScore, player1Turn: !player1Turn)
wins.p1 += newWins.p1
wins.p2 += newWins.p2
}
}
}
cache[key] = wins
return wins
}
let wins = turn(position: (player1Start, player2Start), score: (0, 0), player1Turn: true)
print("Part 2 start from \(player1Start), \(player2Start): player 1 wins: \(wins.p1), player 2 wins: \(wins.p2), max: \(max(wins.p1, wins.p2))")
}
}
Part2.run(player1Start: 4, player2Start: 8)
Part2.run(player1Start: 6, player2Start: 7)
| 31.221239 | 156 | 0.467971 |
8f8b792f54b0843eb0c7af3234c4151175c40b3f | 3,783 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// BottomNavigationBar is a component responsible to display a bottom navigation bar layout.
/// It works by displaying tabs that can change a context when clicked.
public struct BottomNavigationBar: Widget, Decodable {
/// Defines yours tabs title and icon.
public let items: [BottomNavigationBarItem]
/// Defines the expression that is observed to change the current tab selected.
public let currentTab: Expression<Int>?
/// Defines a list of action that will be executed when a tab is selected.
public let onTabSelection: [Action]?
public let barTintColor: Expression<String>?
public let tintColor: Expression<String>?
public var widgetProperties: WidgetProperties
public init(
items: [BottomNavigationBarItem],
currentTab: Expression<Int>? = nil,
onTabSelection: [Action]? = nil,
barTintColor: Expression<String>? = nil,
tintColor: Expression<String>? = nil,
widgetProperties: WidgetProperties = WidgetProperties()
) {
self.items = items
self.currentTab = currentTab
self.onTabSelection = onTabSelection
self.barTintColor = barTintColor
self.tintColor = tintColor
self.widgetProperties = widgetProperties
}
enum CodingKeys: String, CodingKey {
case items
case currentTab
case onTabSelection
case barTintColor
case tintColor
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
items = try container.decode([BottomNavigationBarItem].self, forKey: .items)
currentTab = try container.decodeIfPresent(Expression<Int>.self, forKey: .currentTab)
onTabSelection = try container.decodeIfPresent(forKey: .onTabSelection)
barTintColor = try container.decode(Expression<String>.self, forKey: .barTintColor)
tintColor = try container.decode(Expression<String>.self, forKey: .tintColor)
widgetProperties = try WidgetProperties(from: decoder)
}
}
/// Defines the view item in the tab view
public struct BottomNavigationBarItem: Decodable {
public let selectedIconPath: Expression<String>
public let unselectedIconPath: Expression<String>
public let title: String?
public init(
selectedIconPath: Expression<String>,
unselectedIconPath: Expression<String>,
title: String? = nil
) {
self.selectedIconPath = selectedIconPath
self.unselectedIconPath = unselectedIconPath
self.title = title
}
enum CodingKeys: String, CodingKey {
case selectedIconPath
case unselectedIconPath
case title
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
selectedIconPath = try container.decode(Expression<String>.self, forKey: .selectedIconPath)
unselectedIconPath = try container.decode(Expression<String>.self, forKey: .unselectedIconPath)
title = try container.decodeIfPresent(String.self, forKey: .title)
}
}
| 36.375 | 103 | 0.696801 |
ebaa5955cae107b295726f8ce02560395aa55c0d | 6,869 | //
// JDFindRecViewModel.swift
// MyFFM
//
// Created by BaoLuniOS-3 on 2017/3/2.
// Copyright © 2017年 BaoLuniOS-3. All rights reserved.
//
import UIKit
import SwiftyJSON
import HandyJSON
class JDFindRecViewModel: NSObject {
// MARK:- 网络请求Model属性
// 小编推荐
var editorRecAlbum: JDFindEditorRecommendAlbum!
// 轮播图
var focusImgs: JDFindFocusImages!
// 精品听单
var special: JDFindSpecialColumn!
// 分类
var discoveryColumns: JDFindDiscoveryColumns!
// 猜你喜欢
var guess: JDFindGuess!
// 听北京
var cityColumn: JDFindCityColumn!
// 热门推荐
var hotRecommends: JDFindHotRecommends!
// 现场直播
var liveList: [JDFindLive?] = []
// MARK:- 对数据处理的属性
/// 轮播图URL数组
var focusImgsPics: [String] = [String]()
/// 分类
var headerCategorys: [JDFindDiscoveryColumnsList] = [JDFindDiscoveryColumnsList]()
// MARK:- 数据更新回调
typealias AddBlock = ()->Void;
var updateBlock = AddBlock?()
}
// MARK:- 加载数据
extension JDFindRecViewModel {
func refreshDataSource() {
// 加载 RecommendAPI
JDFindAPI.requestRecommends { [unowned self] (result, error) in
if error != nil {
JDLog(error)
return;
}
guard let result = result else { return }
let json = JSON(result)
// 小编推荐
let editorRecAlbum = JSONDeserializer<JDFindEditorRecommendAlbum>.deserializeFrom(json: json["editorRecommendAlbums"].description)
// 轮播图
let focusImgs = JSONDeserializer<JDFindFocusImages>.deserializeFrom(json: json["focusImages"].description)
// 精品听单
let special = JSONDeserializer<JDFindSpecialColumn>.deserializeFrom(json: json["specialColumn"].description)
self.editorRecAlbum = editorRecAlbum
self.focusImgs = focusImgs
self.special = special
/* =============================== 处理数据 ============================= */
/// 遍历取出轮播图
if let focusImgsList = focusImgs?.list {
for item in focusImgsList {
self.focusImgsPics.append(item.pic ?? "")
}
}
// 更新tableView数据
self.updateBlock?()
}
// 加载 HotAndGuessAPI
JDFindAPI.requestHotAndGuess { [unowned self] (result, error) in
if error != nil {
JDLog(error)
return
}
guard let result = result else { return }
let json = JSON(result)
// 分类
let discoveryColumns = JSONDeserializer<JDFindDiscoveryColumns>.deserializeFrom(json: json["discoveryColumns"].description)
// 猜你喜欢
let guess = JSONDeserializer<JDFindGuess>.deserializeFrom(json: json["guess"].description)
// 听北京
let cityColumn = JSONDeserializer<JDFindCityColumn>.deserializeFrom(json: json["cityColumn"].description)
// 热门推荐
let hotRecommends = JSONDeserializer<JDFindHotRecommends>.deserializeFrom(json: json["hotRecommends"].description)
self.discoveryColumns = discoveryColumns
self.guess = guess
self.cityColumn = cityColumn
self.hotRecommends = hotRecommends
/* =============================== 处理数据 ============================= */
/// 分类
if let discoveryColumnsList = discoveryColumns?.list {
self.headerCategorys = discoveryColumnsList
}
// 更新tableView数据
self.updateBlock?()
}
JDFindAPI.requestLiveRecommend { [unowned self] (result, error) in
if error != nil {
JDLog(error)
return
}
guard let result = result else { return }
let json = JSON(result)
// 现场直播
if let liveArray = JSONDeserializer<JDFindLive>.deserializeModelArrayFrom(json: json["data"].description) {
self.liveList = liveArray
}
// 更新tableView数据
self.updateBlock?()
}
}
}
// MARK:- 各section的高度
let kSectionHeight: CGFloat = 230.0
let kSectionLiveHeight: CGFloat = 227.0
let kSectionSpecialHeight: CGFloat = 219.0
let kSectionMoreHeight: CGFloat = 60.0
// MARK:- tableView的数据
extension JDFindRecViewModel {
func numberOfSections() -> NSInteger {
return 8
}
func numberOfItemInSection(_ section: NSInteger) -> NSInteger {
// 各值定义在 JDFindRecommendController 下
switch section {
case kFindSectionEditCommen: // 小编推荐
return 1
case kFindSectionLive: // 现场直播
return liveList.count == 0 ? 0 : 1
case kFindSectionGuess: // 猜你喜欢
guard (guess != nil) else { return 0 }
return guess.list?.count == 0 ? 0 : 1
case kFindSectionCityColumn: // 城市歌单
guard (cityColumn != nil) else { return 0 }
return cityColumn.list?.count == 0 ? 0 : 1
case kFindSectionSpecial: // 精品听单
guard (special != nil) else { return 0 }
return special.list?.count == 0 ? 0 : 1
case kFindSectionAdvertise: // 推广
return 0 // 暂时未找到接口
case kFindSectionHotCommends: // 热门推荐
guard (hotRecommends != nil) else { return 0 }
return (hotRecommends.list?.count)!
case kFindSectionMore: // 更多分类
return 1
default:
return 0
}
}
func heightForRow(at indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case kFindSectionEditCommen: // 小编推荐
return kSectionHeight
case kFindSectionLive: // 现场直播
return liveList.count == 0 ? 0 : kSectionLiveHeight
case kFindSectionGuess: // 猜你喜欢
guard (guess != nil) else { return 0 }
return guess.list?.count == 0 ? 0 : kSectionHeight
case kFindSectionCityColumn: // 城市歌单
guard (cityColumn != nil) else { return 0 }
return cityColumn.list?.count == 0 ? 0 : kSectionHeight
case kFindSectionSpecial: // 精品听单
guard (special != nil) else { return 0 }
return special.list?.count == 0 ? 0 : kSectionSpecialHeight
case kFindSectionAdvertise: // 推广
return 0 // 暂时未找到接口
case kFindSectionHotCommends: // 热门推荐
return kSectionHeight
case kFindSectionMore: // 更多分类
return kSectionMoreHeight
default:
return 0
}
}
}
| 34.174129 | 142 | 0.547678 |
71138e8bd667cbeea552ec4d56bda904bbf71c43 | 6,657 | //
// ImageCache.swift
// AsyncTaskQueueTests
//
// Created by SuXinDe on 2021/3/14.
// Copyright © 2021 Skyprayer Studio. All rights reserved.
//
import Foundation
import UIKit
import AsyncTaskQueue
/// A simple example of an image cache built around AsyncTaskQueue. It coalesces
/// multiple requests for the same image to a single task, ensuring that work is
/// only performed once per image url. The same image result will be distributed
/// to all concurrent requests.
class ImageCache {
// MARK: Typealiases
typealias ImageTaskQueue = AsyncTaskQueue<URL, UIImage?>
typealias RequestToken = ImageTaskQueue.RequestToken
// MARK: Enums
enum CallbackMode {
case sync
case async(RequestToken)
}
// MARK: Private Properties
private let directory: URL
private let queue = ImageTaskQueue()
private let memoryCache = MemoryCache<URL, UIImage>()
// MARK: Init
init(directory: URL) {
self.directory = directory
}
// MARK: Public Methods
func getImage(url: URL,
preferredPriority: Operation.QueuePriority = .normal,
completion: @escaping (UIImage?) -> Void) -> CallbackMode {
assert(Thread.current.isMainThread)
// Check if the image exists in the in-memory cache.
if let image = memoryCache.value(for: url) {
completion(image)
return .sync
}
// It wasn't in the memory cache already, so spawn a new task and add
// it to the task queue. Note that if there's an existing task for this
// image url, the user's request will be appended to the active requests
// for the existing task. AsyncTaskQueue handles that logic automatically.
var asyncToken: ImageTaskQueue.RequestToken!
// The operation queue and the task internals will be passed into the
// task and cancellation blocks below. If those blocks are ignored (as
// they will be for subsequent concurrent requests for the same image),
// the duplicate operation queue and internals will be unused.
var operationQueue: OperationQueue? = nil
let internals = ImageTaskInternals(url: url,
directory: directory)
// Again, please note that if there's already an existing task operation
// for this image url, the `task` and `cancellation` block arguments
// below will be quietly ignored. This is by design; that work should
// only be performed once.
queue.enqueue(
task: { (finish) in
// This block will only be executed once, regardless of the
// number of concurrent requests for the image at `url`.
let check = CheckForCachedFileOperation(internals: internals)
let download = DownloadOperation(internals: internals)
let crop = CropOperation(internals: internals)
download.addDependency(check)
crop.addDependency(download)
let ops = [check, download, crop]
operationQueue = OperationQueue()
operationQueue!.addOperations(ops)
},
taskId: url,
cancellation: {
operationQueue?.cancelAllOperations()
},
preferredPriority: preferredPriority,
tokenHandler: { token in
asyncToken = token
},
resultHandler: { [weak self] (image) in
// The result handlers for all the requests will be invoked using
// the same `image` result, even though the image was only
// downloaded and cropped once.
if let image = image {
self?.memoryCache.set(image, for: url)
}
completion(image)
}
)
return .async(asyncToken)
}
func cancelRequest(with token: RequestToken) {
queue.cancelRequest(with: token)
}
func adjustPriorityForRequest(with token: RequestToken,
preferredPriority: Operation.QueuePriority) {
queue.adjustPriorityForRequest(
with: token,
preferredPriority: preferredPriority
)
}
}
///-----------------------------------------------------------------------------
/// Stubbed Implementation Details
///-----------------------------------------------------------------------------
/// Stub wrapper around an NSCache-like creature.
private class MemoryCache<Key: Hashable, Value> {
func value(for key: Key) -> Value? {
// todo
return nil
}
func set(_ value: Value?,
for key: Key) {
// todo
}
}
/// Reference type for internal values shared among the various steps of the
/// image cache task procedure (checking local directory, downloading, cropping).
private class ImageTaskInternals {
let url: URL
let directory: URL
var fileUrl: URL?
var image: UIImage?
init(url: URL, directory: URL) {
self.url = url
self.directory = directory
}
}
/// Checks the local directory for an existing cached image file. If present,
/// it sets that file URL as the value of `internals.fileUrl` and finishes.
private class CheckForCachedFileOperation: AsyncOperation {
let internals: ImageTaskInternals
init(internals: ImageTaskInternals) {
self.internals = internals
}
}
/// Checks that `internals.fileUrl` is nil and, if so, downloads the original
/// image, moving the downloaded file to the local directory, setting the
/// value of `internals.fileUrl` to the resulting file url.
///
/// If `internals.fileUrl` is already non-nil, this operation bails out early
/// since there's no need to download anything.
private class DownloadOperation: AsyncOperation {
let internals: ImageTaskInternals
init(internals: ImageTaskInternals) {
self.internals = internals
}
}
/// Reads the image data from the file at `internals.fileUrl`, converts it to a
/// UIImage, decompresses and crops it, and saves the result to `internals.image`.
private class CropOperation: AsyncOperation {
let internals: ImageTaskInternals
init(internals: ImageTaskInternals) {
self.internals = internals
}
}
private extension OperationQueue {
func addOperations(_ ops: [Operation]) {
addOperations(ops, waitUntilFinished: false)
}
}
| 32.793103 | 82 | 0.608833 |
08c2dfda11fe809fa40d95897314eeebd69e304d | 944 | //
// BalletTests.swift
// BalletTests
//
// Created by Koray Koska on 17.12.17.
// Copyright © 2017 Boilertalk. All rights reserved.
//
import XCTest
@testable import Ballet
class BalletTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.513514 | 111 | 0.644068 |
3adc6ef2a748bbc8e35959d74ac1b071f1a861ee | 8,087 | import AppKit
import SwiftUI
struct RectHelper {
public static func getCenter(rect: NSRect) -> NSPoint {
return NSPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y - rect.height / 2)
}
public static func getRectWithRotation(rect: NSRect, rotation: Double) -> NSRect {
var sinValue = CGFloat(sin(rotation / 180 * .pi))
var cosValue = CGFloat(cos(rotation / 180 * .pi))
if sinValue < 0 {
sinValue *= -1
}
if cosValue < 0 {
cosValue *= -1
}
let height = rect.height
let width = rect.width
let actualWidth = (height * sinValue) + (width * cosValue)
let actualHeight = (height * cosValue) + (width * sinValue)
let actualLeft = rect.origin.x - ((actualWidth - width) / 2)
let actualTop = rect.origin.y + ((actualHeight - height) / 2)
return NSRect(x: actualLeft, y: actualTop, width: actualWidth, height: actualHeight)
}
}
extension String {
func measureString(fontName: String, fontSize: CGFloat, strokeWidth: CGFloat = 0) -> NSSize {
let tempStrokeWidth = strokeWidth > 0 ? (strokeWidth * -1) : 0
let tempFontSize = fontSize + strokeWidth
var font: NSFont
let fromFont = NSFont(name: fontName, size: tempFontSize)
if fromFont == nil {
font = NSFont.boldSystemFont(ofSize: tempFontSize)
} else {
font = fromFont!
}
let textFontAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.strokeWidth: tempStrokeWidth,
] as [NSAttributedString.Key: Any]
let size = self.size(withAttributes: textFontAttributes as [NSAttributedString.Key: Any])
return size
}
}
extension NSImage {
var pngData: Data? {
guard let tiffRepresentation = tiffRepresentation, let bitmapImage = NSBitmapImageRep(data: tiffRepresentation) else { return nil }
return bitmapImage.representation(using: .jpeg2000, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: 1])
}
func saveAsPNG(to url: URL, options: Data.WritingOptions = .atomic) -> Bool {
do {
try self.pngData?.write(to: url, options: options)
return true
} catch {
print(error)
return false
}
}
static func drawEmptyImage(width: CGFloat, height: CGFloat, background: Color) -> NSImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil }
context.interpolationQuality = .high
if let cgcolor = background.cgColor {
context.setFillColor(cgcolor)
} else {
context.setFillColor(CGColor.white)
}
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else { return nil }
let data = NSMutableData()
if let imageDestination = CGImageDestinationCreateWithData(data, kUTTypePNG, 1, nil) {
CGImageDestinationAddImage(imageDestination, image, nil)
CGImageDestinationFinalize(imageDestination)
}
let nsImage = NSImage(cgImage: image, size: NSSize(width: width, height: height))
return nsImage
}
func drawText(text: String, x: Double = 0, y: Double = 0, fontName: String = ".AppleSDGothicNeoI-Bold", fontSize: CGFloat = 14, foregroundColor: CGColor? = CGColor.black, strokeColor: CGColor? = CGColor.black, strokeWidth: CGFloat = 0) -> NSImage? {
let tempStrokeWidth = strokeWidth > 0 ? (strokeWidth * -1) : 0
let tempFontSize = fontSize + strokeWidth
var font: NSFont
let fromFont = NSFont(name: fontName, size: tempFontSize)
if fromFont == nil {
font = NSFont.boldSystemFont(ofSize: tempFontSize)
} else {
font = fromFont!
}
guard let textStyle = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle else { return self }
let textFontAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.paragraphStyle: textStyle,
NSAttributedString.Key.strokeColor: strokeColor ?? CGColor.black,
NSAttributedString.Key.strokeWidth: tempStrokeWidth,
NSAttributedString.Key.foregroundColor: foregroundColor ?? CGColor.black,
] as [NSAttributedString.Key: Any]
self.lockFocus()
text.draw(at: NSPoint(x: CGFloat(x), y: CGFloat(y)), withAttributes: textFontAttributes)
self.unlockFocus()
return self
}
func drawImage(imgPath: String, x: Int = 0, y: Int = 0, scale: Int = 1, rotate: Int = 90, opacity: CGFloat = 1) -> NSImage? {
guard let newImage = NSImage(contentsOf: URL(fileURLWithPath: imgPath)) else { return self }
let bounds = CGRect(x: 0, y: 0, width: Int(newImage.size.width) * scale, height: Int(newImage.size.height) * scale)
let imageRect = CGRect(x: x, y: y, width: Int(bounds.width), height: Int(bounds.height))
self.lockFocus()
let transf: NSAffineTransform = .init()
transf.rotate(byDegrees: CGFloat(rotate))
transf.concat()
newImage.draw(in: imageRect, from: .zero, operation: .sourceOver, fraction: opacity)
self.unlockFocus()
return self
}
func drawImage(imgPath: String, inRect: NSRect, fromRect: NSRect) -> NSImage? {
guard let newImage = NSImage(contentsOf: URL(fileURLWithPath: imgPath)) else { return self }
self.lockFocus()
newImage.draw(in: inRect, from: fromRect, operation: .sourceOver, fraction: 1)
self.unlockFocus()
return self
}
func drawImage(img: NSImage, inRect: NSRect, fromRect: NSRect) -> NSImage? {
self.lockFocus()
img.draw(in: inRect, from: fromRect, operation: .sourceOver, fraction: 1)
self.unlockFocus()
return self
}
func drawImage(sourceImg: NSImage, inRect: NSRect, fromRect: NSRect, opacity: Double = 1) -> NSImage? {
self.lockFocus()
sourceImg.draw(in: inRect, from: fromRect, operation: .sourceOver, fraction: CGFloat(opacity))
self.unlockFocus()
return self
}
func rotate(degrees: CGFloat) -> NSImage {
let sinDegrees = abs(sin(degrees * CGFloat.pi / 180.0))
let cosDegrees = abs(cos(degrees * CGFloat.pi / 180.0))
let newSize = CGSize(width: size.height * sinDegrees + size.width * cosDegrees,
height: size.width * sinDegrees + size.height * cosDegrees)
let imageBounds = NSRect(x: (newSize.width - size.width) / 2,
y: (newSize.height - size.height) / 2,
width: size.width, height: size.height)
let otherTransform = NSAffineTransform()
otherTransform.translateX(by: newSize.width / 2, yBy: newSize.height / 2)
otherTransform.rotate(byDegrees: degrees)
otherTransform.translateX(by: -newSize.width / 2, yBy: -newSize.height / 2)
let rotatedImage = NSImage(size: newSize)
rotatedImage.lockFocus()
otherTransform.concat()
draw(in: imageBounds, from: CGRect.zero, operation: NSCompositingOperation.copy, fraction: 1.0)
rotatedImage.unlockFocus()
return rotatedImage
}
func fillRectangle(inRect: NSRect, fillColor: Color = Color.white) -> NSImage? {
self.lockFocus()
let ctx = NSGraphicsContext.current
ctx?.cgContext.setFillColor(CGColor.white)
if let cgcolor = fillColor.cgColor {
ctx?.cgContext.setFillColor(cgcolor)
} else {
ctx?.cgContext.setFillColor(CGColor.white)
}
ctx?.cgContext.fill(inRect)
self.unlockFocus()
return self
}
}
| 39.642157 | 253 | 0.630271 |
c156fcd1c6e0808514edf28da0e84725ddf68d1d | 10,265 | //
// EasyPopover.swift
// EasyPopover
//
// Created by 程巍巍 on 3/21/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import UIKit
final class EasyPopover: UIView {
private let arrowSize: CGFloat = 12.0
private let cornerRadius: CGFloat = 8.0
private let borderSize: CGFloat = 8.0
private var scrollView: UIScrollView = UIScrollView()
private weak var contentView: UIView?
private var arrowPosition = (from: CGPointZero, pass: CGPointZero, to: CGPointZero)
/**
* 初始化 popover
* contentView 需设置期望显示的大小
*/
init(contentView view: UIView, tintColor: UIColor = UIColor.clearColor()){
super.init(frame: CGRectZero)
self.backgroundColor = tintColor
self.tintColor = view.backgroundColor
self.clipsToBounds = true
self.contentView = view
self.scrollView.addSubview(view)
self.scrollView.contentSize = view.bounds.size
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.clipsToBounds = true
self.scrollView.layer.cornerRadius = cornerRadius
self.scrollView.backgroundColor = view.backgroundColor
self.addSubview(self.scrollView)
}
/**
*
*/
func popFromRect(rect: CGRect, inView view: UIView, animated: Bool = true){
self.frame = view.bounds
positionFitToRect(rect, inView: view)
if contentView!.isKindOfClass(UIScrollView.self) {
contentView!.frame = scrollView.frame
}
view.addSubview(self)
view.addObserver(self, forKeyPath: "frame", options: .Old, context: nil)
if !animated {return}
// 动画
let center = self.center
let frame = self.frame
self.transform = CGAffineTransformMakeScale(0.01, 0.001)
self.center = arrowPosition.pass
UIView.animateWithDuration(0.175, animations: { () -> Void in
self.center = center
self.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
func dismiss(animated: Bool = true){
self.superview?.removeObserver(self, forKeyPath: "frame", context: nil)
if !animated { self.removeFromSuperview(); return}
UIView.animateWithDuration(0.175, animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(0.01, 0.01)
self.center = self.arrowPosition.pass
}) { (complete: Bool) -> Void in
self.scrollView.removeFromSuperview()
self.removeFromSuperview()
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension EasyPopover {
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
dismiss(animated: true)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
dismiss(animated: false)
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
var context = UIGraphicsGetCurrentContext()
CGContextClearRect(context, rect)
CGContextBeginPath(context)
CGContextMoveToPoint(context, arrowPosition.from.x, arrowPosition.from.y)
CGContextAddLineToPoint(context, arrowPosition.pass.x, arrowPosition.pass.y)
CGContextAddLineToPoint(context, arrowPosition.to.x, arrowPosition.to.y)
CGContextClosePath(context)
CGContextSetFillColorWithColor(context, self.tintColor.CGColor)
CGContextFillPath(context)
}
}
extension EasyPopover {
private func positionFitToRect(rect: CGRect, inView view: UIView){
// 分为上下左右四个位置,优先级: 右 <- 左 <- 下 <- 上
var size = scrollView.contentSize
let spaceRight = CGRectMake((rect.origin.x + rect.size.width), 0, view.frame.width - (rect.origin.x + rect.size.width), view.frame.height)
let spaceLeft = CGRectMake(0, 0, rect.origin.x, view.frame.height)
let spaceBottom = CGRectMake(0, (rect.origin.y + rect.size.height), view.frame.width, view.frame.height - (rect.origin.y + rect.size.height))
let spaceTop = CGRectMake(0, 0, view.frame.width, rect.origin.y)
// 上、下,左、右空间较大者
let spaceHor = spaceRight.size.width >= spaceLeft.size.width ? spaceRight : spaceLeft
let spaceVer = spaceBottom.size.height > spaceTop.size.height ? spaceBottom : spaceTop
var space: CGRect? = nil
if spaceHor.size.width >= size.width + arrowSize + borderSize && spaceVer.size.height >= size.height + arrowSize + borderSize {
// 左右空间、上下空间,都能放下,则考虑形状的影响
let promotionDifHor = spaceHor.width / size.width - spaceHor.height / size.height
let promotionDifVer = spaceVer.width / size.width - spaceVer.height / size.height
space = abs(promotionDifHor) <= abs(promotionDifVer) ? spaceHor : spaceVer
}else if spaceHor.size.width >= size.width + arrowSize + borderSize && spaceVer.size.height <= size.height + arrowSize + borderSize {
// 左右空间可以放下,优先左右
space = spaceHor
}else if spaceHor.size.width <= size.width + arrowSize + borderSize && spaceVer.size.height >= size.height + arrowSize + borderSize {
space = spaceVer
}
if space == nil {
// 如查上下、左右都放不下,则放中间, 没有 arrow
size.width = min(size.width, view.frame.width - borderSize * 2)
size.height = min(size.height, view.frame.height - borderSize * 2)
scrollView.frame.size = size
scrollView.center = CGPointMake(view.frame.width / 2, view.frame.height / 2)
arrowPosition.pass = scrollView.center
}else{
// 确定 arrow 方向
var dx: CGFloat = 0, dy: CGFloat = 0
if space!.origin.y == 0 && space!.size.height == view.frame.height{
size.width = min(size.width, space!.width - arrowSize - borderSize)
size.height = min(size.height, space!.height - borderSize * 2)
scrollView.frame.size = size
if space!.origin.x >= rect.origin.x {
// arrowdirection left
arrowPosition.pass = CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height / 2)
arrowPosition.from = CGPointMake(arrowPosition.pass.x + arrowSize, arrowPosition.pass.y - arrowSize * 0.579)
arrowPosition.to = CGPointMake(arrowPosition.pass.x + arrowSize, arrowPosition.pass.y + arrowSize * 0.579)
scrollView.center.x = space!.origin.x + arrowSize + scrollView.frame.width / 2
dx = cornerRadius
}else{
// arrowdirection right
arrowPosition.pass = CGPointMake(rect.origin.x, rect.origin.y + rect.size.height / 2)
arrowPosition.from = CGPointMake(arrowPosition.pass.x - arrowSize, arrowPosition.pass.y - arrowSize * 0.579)
arrowPosition.to = CGPointMake(arrowPosition.pass.x - arrowSize, arrowPosition.pass.y + arrowSize * 0.579)
scrollView.center.x = space!.width - arrowSize - scrollView.frame.width / 2
dx = -cornerRadius + scrollView.frame.width
}
scrollView.center.y = arrowPosition.pass.y + (view.frame.height / 2 - arrowPosition.pass.y) / view.frame.height * (size.height + borderSize * 2)
if arrowPosition.from.y < scrollView.frame.origin.y + cornerRadius {
arrowPosition.from = CGPointMake(scrollView.frame.origin.x + dx, scrollView.frame.origin.y)
};if arrowPosition.to.y > scrollView.frame.origin.y + scrollView.frame.height - cornerRadius{
arrowPosition.to = CGPointMake(scrollView.frame.origin.x + dx, scrollView.frame.origin.y + scrollView.frame.height)
}
}else
if space!.origin.x == 0 && space!.size.width == view.frame.width{
size.width = min(size.width, space!.width - borderSize * 2)
size.height = min(size.height, space!.height - arrowSize - borderSize)
scrollView.frame.size = size
if space!.origin.y >= rect.origin.y {
// arrowdirection up
arrowPosition.pass = CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height)
arrowPosition.from = CGPointMake(arrowPosition.pass.x - arrowSize * 0.579, arrowPosition.pass.y + arrowSize)
arrowPosition.to = CGPointMake(arrowPosition.pass.x + arrowSize * 0.579, arrowPosition.pass.y + arrowSize)
scrollView.center.y = space!.origin.y + arrowSize + scrollView.frame.height / 2
dy = cornerRadius
}else{
// arrowdirection down
arrowPosition.pass = CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y)
arrowPosition.from = CGPointMake(arrowPosition.pass.x - arrowSize * 0.579, arrowPosition.pass.y - arrowSize)
arrowPosition.to = CGPointMake(arrowPosition.pass.x + arrowSize * 0.579, arrowPosition.pass.y - arrowSize)
scrollView.center.y = space!.height - arrowSize - scrollView.frame.height / 2
dy = -cornerRadius + scrollView.frame.height
}
scrollView.center.x = arrowPosition.pass.x + (view.frame.width / 2 - arrowPosition.pass.x) / view.frame.width * (size.width + borderSize * 2)
if arrowPosition.from.x < scrollView.frame.origin.x + cornerRadius {
arrowPosition.from = CGPointMake(scrollView.frame.origin.x, scrollView.frame.origin.y + dy)
};if arrowPosition.to.x > scrollView.frame.origin.x + scrollView.frame.width - cornerRadius{
arrowPosition.to = CGPointMake(scrollView.frame.origin.x + scrollView.frame.width , scrollView.frame.origin.y + dy)
}
}
}
}
}
| 51.325 | 160 | 0.620848 |
e4ee614e52a566e1f9095dff3887fedb64a9747b | 344 | //
// ViewController+ARSCNViewDelegate.swift
// FocusNode+Example
//
// Created by Max Cobb on 12/23/18.
// Copyright © 2018 Max Cobb. All rights reserved.
//
import ARKit
extension ViewController: ARSCNViewDelegate {
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
self.focusNode.updateFocusNode()
}
}
| 21.5 | 79 | 0.747093 |
9c955d746a29545fb9539ecade3c73c0d87f56c1 | 1,042 | import Foundation
class StructNodeFactory: TypeNodeFactoryProtocol {
let parser: TypeParser
init(parser: TypeParser) {
self.parser = parser
}
func buildNode(from json: JSON, typeName: String, mediator: TypeRegistering) throws -> Node? {
guard let children = parser.parse(json: json) else {
return nil
}
let childrenNodes: [NameNode] = try children.map { child in
guard let nameAndValueType = child.arrayValue,
nameAndValueType.count == 2,
let name = nameAndValueType.first?.stringValue,
let value = nameAndValueType.last,
let valueTypeName = value.stringValue else {
throw TypeNodeFactoryError.unexpectedParsingResult(typeName: typeName)
}
let node = mediator.register(typeName: valueTypeName, json: value)
return NameNode(name: name, node: node)
}
return StructNode(typeName: typeName, typeMapping: childrenNodes)
}
}
| 32.5625 | 98 | 0.621881 |
56e2e1ec98210235a6cb562795db90d4fea01cb1 | 527 | //
// UIStackView+beforeSpacing.swift
// iOS11ProgrammingAuthors
//
// Created by Yusuke Kawanabe on 8/27/17.
// Copyright © 2017 Yusuke Kawanabe. All rights reserved.
//
import UIKit
extension UIStackView {
func setCustomSpacing(_ spacing: CGFloat, before arrangedSubview: UIView) {
let index = self.subviews.index(of: arrangedSubview)
if let index = index,
index > 1 {
let view = self.subviews[index - 1]
self.setCustomSpacing(12, after: view)
}
}
}
| 23.954545 | 79 | 0.641366 |
fedf9f6aedbcc2d23bea4dd16e59de37310ebd2a | 6,466 | //
// SignUpView.swift
// UHShield
//
// Created by weirong he on 10/28/20.
//
import SwiftUI
struct SignUpView: View {
@State var email: String = ""
@State var password: String = ""
@State var error: String = ""
@State var rePassword: String = ""
@State var isVisiable = false
@State var showAlert = false
@EnvironmentObject var session: SessionStore
@StateObject var profileViewModel = ProfileViewModel()
var TextColor = Color("bg1")
var body: some View {
ZStack {
VStack {
// title of the View
HStack {
Spacer()
VStack(alignment: .trailing) {
Text("Create Account")
.fontWeight(.heavy)
.font(.largeTitle)
.foregroundColor(TextColor)
Text("Sign Up to get started")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.gray)
}
}.padding(.bottom, 20)
// information entering field
VStack {
VStack{
VStack(alignment: .leading) {
// email text filed
Text("Email")
.fontWeight(.semibold)
.font(.title)
.foregroundColor(TextColor)
TextField("Email address", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
.modifier(TextFieldModifier())
}
VStack(alignment: .leading) {
// Password text filed
Text("Password")
.fontWeight(.semibold)
.font(.title)
.foregroundColor(TextColor)
HStack {
if isVisiable {
TextField("Enter Your Password", text: $password)
.frame(height: 20)
.modifier(TextFieldModifier())
} else {
SecureField("Enter Your Password", text: $password)
.frame(height: 20)
.modifier(TextFieldModifier())
}
// change visiable password button
Button(action: {
self.isVisiable.toggle()
}, label: {
Image(systemName: "eye.fill").foregroundColor(.gray)
}).buttonStyle(SmallButtonStyle())
} // end of HStack containing password and eye button
}
// Re-enter password field
if isVisiable {
TextField("Re-Enter Password", text: $rePassword)
.frame(height: 20)
.modifier(TextFieldModifier())
} else {
SecureField("Re-Enter Password", text: $rePassword)
.frame(height: 20)
.modifier(TextFieldModifier())
}
}.padding()
// sign up button
Button(action: signUp){
Text("Sign Up").fontWeight(.semibold)
.font(.title3)
.foregroundColor(Color(#colorLiteral(red: 0.8864660859, green: 0.8863860965, blue: 0.9189570546, alpha: 1)))
}.padding().buttonStyle(LongButtonStyle())
}
.background(
RoundedRectangle(cornerRadius: 25).foregroundColor(Color(#colorLiteral(red: 0.8864660859, green: 0.8863860965, blue: 0.9189570546, alpha: 1)))
.shadow(color: Color.black.opacity(0.2), radius: 5, x: 4, y: 5)
.shadow(color: Color.white.opacity(0.4), radius: 5, x: -5, y: -5)
)
Spacer()
// Whole View Background
}.padding(.horizontal, 32)
.padding(.vertical, 50)
.background(Color(#colorLiteral(red: 0.8864660859, green: 0.8863860965, blue: 0.9189570546, alpha: 1)))
.edgesIgnoringSafeArea(.all)
.onAppear {
profileViewModel.fetchData()
}
// if error occured show the alert popup View
if showAlert {
AlertView(showAlert: $showAlert, alertMessage: $error, alertTitle: "ERROR").transition(.slide)
}
}
}
func signUp(){
if rePassword != password {
error = "Your passwords don't match"
showAlert = true
} else {
session.signUp(email: email, password: password) { (result, error) in
if let error = error {
self.error = error.localizedDescription
showAlert = true
} else {
profileViewModel.addProfile(profile: Profile(id: email ,email: email, firstName: "User", lastName: "", role: "sponsor", building: ""))
self.email = ""
self.password = ""
}
}
}
}
}
struct SignUpView_Previews: PreviewProvider {
static var previews: some View {
SignUpView()
}
}
| 39.91358 | 162 | 0.389422 |
f71128267f93b6cedec62520975f1605614798e3 | 5,570 | // automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
import FlatBuffers
public struct HelloReply: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
public static func getRootAsHelloReply(bb: ByteBuffer) -> HelloReply { return HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
enum VTOFFSET: VOffset {
case message = 4
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) }
public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) }
public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(message: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createHelloReply(_ fbb: inout FlatBufferBuilder,
offsetOfMessage message: Offset<String> = Offset()) -> Offset<UOffset> {
let __start = HelloReply.startHelloReply(&fbb)
HelloReply.add(message: message, &fbb)
return HelloReply.endHelloReply(&fbb, start: __start)
}
}
public struct HelloRequest: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
public static func getRootAsHelloRequest(bb: ByteBuffer) -> HelloRequest { return HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
enum VTOFFSET: VOffset {
case name = 4
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createHelloRequest(_ fbb: inout FlatBufferBuilder,
offsetOfName name: Offset<String> = Offset()) -> Offset<UOffset> {
let __start = HelloRequest.startHelloRequest(&fbb)
HelloRequest.add(name: name, &fbb)
return HelloRequest.endHelloRequest(&fbb, start: __start)
}
}
public struct ManyHellosRequest: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
public static func getRootAsManyHellosRequest(bb: ByteBuffer) -> ManyHellosRequest { return ManyHellosRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
enum VTOFFSET: VOffset {
case name = 4
case numGreetings = 6
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
public var numGreetings: Int32 { let o = _accessor.offset(VTOFFSET.numGreetings.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) }
public static func startManyHellosRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
public static func add(numGreetings: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numGreetings, def: 0, at: VTOFFSET.numGreetings.p) }
public static func endManyHellosRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createManyHellosRequest(_ fbb: inout FlatBufferBuilder,
offsetOfName name: Offset<String> = Offset(),
numGreetings: Int32 = 0) -> Offset<UOffset> {
let __start = ManyHellosRequest.startManyHellosRequest(&fbb)
ManyHellosRequest.add(name: name, &fbb)
ManyHellosRequest.add(numGreetings: numGreetings, &fbb)
return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start)
}
}
| 55.148515 | 215 | 0.704129 |
67ff8506cf654d9d2a9ca1502205e972f03ca3f1 | 329 | //
// ViewController.swift
// JFWindguruTVOS
//
// Created by fox on 10/07/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 15.666667 | 58 | 0.662614 |
b921fe3f8456e1af0708a83b2215b00f2104f203 | 3,851 | // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
import Foundation
// === xdr source ============================================================
// struct ContractEntry
// {
// uint64 contractID;
//
// AccountID contractor;
// AccountID customer;
// AccountID escrow;
//
// uint64 startTime;
// uint64 endTime;
// uint64 invoiceRequestsIDs<>;
// longstring initialDetails;
//
// uint32 state;
// longstring customerDetails;
//
// union switch (LedgerVersion v)
// {
// case EMPTY_VERSION:
// void;
// }
// ext;
// };
// ===========================================================================
public struct ContractEntry: XDRCodable {
public var contractID: Uint64
public var contractor: AccountID
public var customer: AccountID
public var escrow: AccountID
public var startTime: Uint64
public var endTime: Uint64
public var invoiceRequestsIDs: [Uint64]
public var initialDetails: Longstring
public var state: Uint32
public var customerDetails: Longstring
public var ext: ContractEntryExt
public init(
contractID: Uint64,
contractor: AccountID,
customer: AccountID,
escrow: AccountID,
startTime: Uint64,
endTime: Uint64,
invoiceRequestsIDs: [Uint64],
initialDetails: Longstring,
state: Uint32,
customerDetails: Longstring,
ext: ContractEntryExt) {
self.contractID = contractID
self.contractor = contractor
self.customer = customer
self.escrow = escrow
self.startTime = startTime
self.endTime = endTime
self.invoiceRequestsIDs = invoiceRequestsIDs
self.initialDetails = initialDetails
self.state = state
self.customerDetails = customerDetails
self.ext = ext
}
public func toXDR() -> Data {
var xdr = Data()
xdr.append(self.contractID.toXDR())
xdr.append(self.contractor.toXDR())
xdr.append(self.customer.toXDR())
xdr.append(self.escrow.toXDR())
xdr.append(self.startTime.toXDR())
xdr.append(self.endTime.toXDR())
xdr.append(self.invoiceRequestsIDs.toXDR())
xdr.append(self.initialDetails.toXDR())
xdr.append(self.state.toXDR())
xdr.append(self.customerDetails.toXDR())
xdr.append(self.ext.toXDR())
return xdr
}
public init(xdrData: inout Data) throws {
self.contractID = try Uint64(xdrData: &xdrData)
self.contractor = try AccountID(xdrData: &xdrData)
self.customer = try AccountID(xdrData: &xdrData)
self.escrow = try AccountID(xdrData: &xdrData)
self.startTime = try Uint64(xdrData: &xdrData)
self.endTime = try Uint64(xdrData: &xdrData)
let lengthinvoiceRequestsIDs = try Int32(xdrData: &xdrData)
self.invoiceRequestsIDs = [Uint64]()
for _ in 1...lengthinvoiceRequestsIDs {
self.invoiceRequestsIDs.append(try Uint64(xdrData: &xdrData))
}
self.initialDetails = try Longstring(xdrData: &xdrData)
self.state = try Uint32(xdrData: &xdrData)
self.customerDetails = try Longstring(xdrData: &xdrData)
self.ext = try ContractEntryExt(xdrData: &xdrData)
}
public enum ContractEntryExt: XDRDiscriminatedUnion {
case emptyVersion
public var discriminant: Int32 {
switch self {
case .emptyVersion: return LedgerVersion.emptyVersion.rawValue
}
}
public func toXDR() -> Data {
var xdr = Data()
xdr.append(self.discriminant.toXDR())
switch self {
case .emptyVersion: xdr.append(Data())
}
return xdr
}
public init(xdrData: inout Data) throws {
let discriminant = try Int32(xdrData: &xdrData)
switch discriminant {
case LedgerVersion.emptyVersion.rawValue: self = .emptyVersion
default:
throw XDRErrors.unknownEnumCase
}
}
}
}
| 27.312057 | 79 | 0.645806 |
6460af80f1b155cdf008bd994de6d42522659116 | 2,787 | //
// Database.swift
// SQL
//
// Created by Michael Arrington on 3/30/19.
// Copyright © 2019 Duct Ape Productions. All rights reserved.
//
import Foundation
enum DatabaseError: Error {
case internalInconsistency
}
/// A type-safe wrapper around the SQLite3 database framework.
///
/// - Note: A `Database` is not thread-safe, and its methods should only be called from a single thread. It is advised that consumers of this framework create a wrapper around a `Database` instance rather than consuming it directly. The wrapper should guarantee that the `Database` methods are accessed on a single thread. Note that this does not mean one thread at a time, it means one thread ever, as long as the `Database` instance exists. Failure to do so could cause unexpected behavior.
public class Database {
let connection: Connection
public var dir: URL {
connection.config.directory
}
public var filename: String {
connection.config.filename
}
/// /// Opens a connection to a new database at the given directory, with the given filename.
///
/// If a database does not exist at the given location a new database will be created.
///
/// - Parameters:
/// - dir: the full URL to a directory. Default is /ApplicationSupport/CodableData/
/// - filename: the name of the database file. Default is "Data"
/// - Throws: Potentially any ConnectionError
public convenience init(
dir: URL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask).first!.appendingPathComponent("CodableData"),
filename: String = "Data") throws {
let config = Configuration(directory: dir, filename: filename, isReadOnly: false)
try self.init(connection: Connection(config))
}
internal init(connection: Connection) throws {
self.connection = connection
try self.connection.connect()
}
@discardableResult
func execute(_ query: String) -> Status {
do {
var s = Statement(query)
try s.prepare(in: connection.db)
defer {
s.finalize()
}
return s.step()
} catch {
fatalError(String(reflecting: error))
}
}
public func deleteTheWholeDangDatabase() throws {
try connection.deleteEverything()
}
/// Multi-threading with SQLite can be tricky. Save yourself a headache and get
/// a unique connection for reading asynchronously from the database
public func getReadOnly() throws -> ReadOnlyConnection {
let config = Configuration(
directory: connection.config.directory,
filename: connection.config.filename,
isReadOnly: true)
let db = try Database(connection: Connection(config))
return ReadOnlyConnection(db: db)
}
}
| 32.406977 | 492 | 0.687119 |
71d82e9f8980e2dc0d2a15be71d8a9939d6a591c | 987 |
import Foundation
public class StringUtils {
static public func isBlank(input: String?) -> Bool {
return input == nil || input!.trimmingCharacters(in: .whitespaces).count == 0
}
static public func isEmpty(input: String?) -> Bool {
return input == nil || input!.count == 0
}
static public func getLength(input: String?) -> Int {
if isEmpty(input: input) {
return 0
}
return input!.count
}
static public func getCount(input: String?, char: Character?) -> Int {
if isEmpty(input: input) || char == nil {
return 0
}
var count = 0
for ch in input! {
if char == ch {
count = count + 1
}
}
return count
}
static public func getTitleCase(input: String) -> String {
if isBlank(input: input) {
return input
}
return input.capitalized
}
}
| 24.073171 | 85 | 0.514691 |
eb0777b2043ca2e35b19504e3bd31c5e933b561a | 1,535 | //
// Response+Argo.swift
// RxMoyaExample
//
// Created by Benjamin Emdon on 2017-01-15.
// Copyright © 2017 Benjamin Emdon. All rights reserved.
//
import Moya
import Argo
public extension Response {
public func mapObject<T:Decodable>() throws -> T where T == T.DecodedType {
guard let jsonDictionary = try mapJSON() as? NSDictionary, let object: T = decode(jsonDictionary) else {
throw MoyaError.jsonMapping(self)
}
return object
}
public func mapObject<T: Decodable>(withKeyPath keyPath: String?) throws -> T where T == T.DecodedType {
guard let keyPath = keyPath else { return try mapObject() }
guard let jsonDictionary = try mapJSON() as? NSDictionary,
let objectDictionary = jsonDictionary.value(forKeyPath: keyPath) as? NSDictionary,
let object: T = decode(objectDictionary) else {
throw MoyaError.jsonMapping(self)
}
return object
}
public func mapArray<T: Decodable>() throws -> [T] where T == T.DecodedType {
guard let jsonArray = try mapJSON() as? NSArray, let object: [T] = decode(jsonArray) else {
throw MoyaError.jsonMapping(self)
}
return object
}
public func mapArray<T: Decodable>(withKeyPath keyPath: String?) throws -> [T] where T == T.DecodedType {
guard let keyPath = keyPath else { return try mapArray() }
guard let jsonDictionary = try mapJSON() as? NSDictionary,
let objectArray = jsonDictionary.value(forKeyPath:keyPath) as? NSArray,
let object: [T] = decode(objectArray) else {
throw MoyaError.jsonMapping(self)
}
return object
}
}
| 29.519231 | 106 | 0.712052 |
03bdaa39b758203cab3428b81abaace181a349f1 | 1,859 | //
// GraphBarView.swift
// FitnessApp
//
// Created by Luan Nguyen on 24/12/2020.
//
import SwiftUI
struct GraphBarView: View {
// MARK: - PROPERTIES
@ObservedObject var manager = DataManager()
// MARK: - BODY
var body: some View {
VStack {
HStack {
Image(systemName: "calendar.badge.clock")
Text("Average")
.bold()
Spacer()
} //: HSTACK
.foregroundColor(ColorConstants.textCircleSecendary)
HStack(alignment: .bottom, spacing: 14) {
ForEach(manager.bpmsValue) { bpm in
GraphCell(bpm: bpm, barHeight: getRealtiveHeight(value: bpm.value))
.onTapGesture {
withAnimation {
manager.selectData(bpm: bpm)
}
}
}
HStack {
Text("AVERAGE BPM: ")
.foregroundColor(ColorConstants.textCircleSecendary)
Text("Hours")
.bold()
.foregroundColor(.white)
} //: HSTACK
.font(.system(size: 12))
.fixedSize()
.frame(width: 20, height: 180)
.rotationEffect(Angle.degrees(-90))
} //; HSTACK
} //: VSTACK
}
// MARK: - GET REALTIVe HEIGHT
func getRealtiveHeight(value: CGFloat) -> CGFloat {
var rHeight: CGFloat
let availableHeight: CGFloat = 120
let maxValue = bpms.map { $0.value }.max()!
rHeight = (value/maxValue) * availableHeight
return rHeight
}
}
| 29.046875 | 87 | 0.439484 |
764cd6dadaad88ea871e0acd76fe7016bef5ceba | 2,006 | //
// ActivityCell.swift
// SwiftUI_Jike
//
// Created by alexyang on 2019/6/5.
// Copyright © 2019 alexyang. All rights reserved.
//
import SwiftUI
struct ActivityCell : View {
var nickName:String
var timeStamp:String
var content:String
var imgName:String
var body: some View {
VStack(alignment: .leading){
HStack(){
VStack{
CircleImage(imgName: "pokemon")
.padding(.leading, 20)
.padding(.top, 10)
Spacer()
}
VStack(alignment: .leading){
HStack{
Text(nickName)
.padding(.top, 5)
.padding(.bottom, 2)
Spacer()
}
Text(timeStamp)
.font(Font.system(size: 12))
.color(Color.gray)
.padding(.bottom, 2)
Text(content)
.frame(minHeight:50, maxHeight: 300, alignment: .top)
.font(Font.system(size: 15))
.lineLimit(-1)
Image(imgName)
.padding(.bottom, 20)
.padding(.trailing, 10)
}
}
HStack{
Spacer()
Image("dianzan")
Spacer()
Image("pinglun")
Spacer()
Image("share")
Spacer()
Image("shenglue")
}
}
.lineSpacing(0)
.frame(minHeight: 300)
}
}
#if DEBUG
struct ActivityCell_Previews : PreviewProvider {
static var previews: some View {
ActivityCell(nickName: "皮卡丘", timeStamp: "2小时前",content: "发明一种新吃法#一人食灌蛋手抓饼夹小油条泡菜香肠,挤上番茄酱甜面酱巨好吃呀😘!!灌蛋是灵魂,不能偷懒!!", imgName: "sucai"
)
}
}
#endif
| 27.861111 | 137 | 0.420239 |
ab37901e001576dd849361aef587679453a14593 | 1,619 | //
// LogFormat.swift
// LingoLog
//
// Created by Chun on 2019/1/10.
// Copyright © 2019 LLS iOS Team. All rights reserved.
//
import Foundation
import LingoLogPrivate
protocol LogFormattable {
func format(logInfo: LogInfo, message: String) -> String
}
class LogFormatter: LogFormattable {
func format(logInfo: LogInfo, message: String) -> String {
var formatMessage = "[\(getLevelDisplay(logInfo.level))][\(getTimeDisplay(logInfo.timeval))][\(getThreadMessageDisplay(logInfo))]"
if let tag = logInfo.tag {
formatMessage += "[\(tag)]"
}
formatMessage += "["
formatMessage += "\(logInfo.filename), "
formatMessage += "\(logInfo.funcname), "
formatMessage += "\(logInfo.line)] \(message)"
return formatMessage
}
private func getThreadMessageDisplay(_ logInfo: LogInfo) -> String {
var threadMessage = "\(logInfo.tid)"
if LingoLogHelper.mainThreadId() == logInfo.tid {
threadMessage += "*"
}
return threadMessage
}
private func getTimeDisplay(_ timeval: timeval) -> String {
let usecDisplay = String(format: "%.3d", timeval.tv_usec / 1000)
var sec = timeval.tv_sec
let tm: tm! = localtime(&sec)?.pointee
return "\(1900 + tm.tm_year)-\(1 + tm.tm_mon)-\(tm.tm_mday) \(tm.tm_hour):\(tm.tm_min):\(tm.tm_sec).\(usecDisplay)"
}
private func getLevelDisplay(_ level: LogLevel) -> String {
switch level {
case .verbose:
return "Verbose"
case .debug:
return "Debug"
case .info:
return "Info"
case .warning:
return "Warning"
case .error:
return "Error"
}
}
}
| 26.540984 | 134 | 0.641137 |
d5b53a6b7257a88d376e3c7ddc361eda84cf64f4 | 13,320 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
base.image = placeholder
guard let resource = resource else {
completionHandler?(nil, nil, .none, nil)
return .empty
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
var options = options ?? KingfisherEmptyOptionsInfo
if shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.downloadTask?.cancel()
}
func shouldPreloadAllGIF() -> Bool {
return true
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
newIndicator.view.frame = base.frame
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set {
var holder = kf
holder.indicatorType = newValue
}
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set {
var holder = kf
holder.indicator = newValue
}
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.shouldPreloadAllGIF")
func shouldPreloadAllGIF() -> Bool { return kf.shouldPreloadAllGIF() }
}
| 45.460751 | 173 | 0.604805 |
2fac3637619d4761c35ba458186f7a0f92037162 | 16,831 | import Foundation
import UserNotifications
enum LocalNotificationError: LocalizedError {
case contentNoId
case contentNoTitle
case contentNoBody
case triggerConstructionFailed
case triggerRepeatIntervalTooShort
case attachmentNoId
case attachmentNoUrl
case attachmentFileNotFound(path: String)
case attachmentUnableToCreate(String)
var errorDescription: String? {
switch self {
case .attachmentFileNotFound(path: let path):
return "Unable to find file \(path) for attachment"
default:
return ""
}
}
}
/**
* Implement three common modal types: alert, confirm, and prompt
*/
@objc(CAPLocalNotificationsPlugin)
public class CAPLocalNotificationsPlugin : CAPPlugin {
/**
* Schedule a notification.
*/
@objc func schedule(_ call: CAPPluginCall) {
guard let notifications = call.getArray("notifications", [String:Any].self) else {
call.error("Must provide notifications array as notifications option")
return
}
self.bridge.notificationsDelegate.requestPermissions()
var ids = [String]()
for notification in notifications {
guard let identifier = notification["id"] as? Int else {
call.error("Notification missing identifier")
return
}
// let extra = notification["options"] as? JSObject ?? [:]
var content: UNNotificationContent
do {
content = try makeNotificationContent(notification)
} catch {
CAPLog.print(error.localizedDescription)
call.error("Unable to make notification", error)
return
}
var trigger: UNNotificationTrigger?
do {
if let schedule = notification["schedule"] as? [String:Any] {
try trigger = handleScheduledNotification(call, schedule)
}
} catch {
call.error("Unable to create notification, trigger failed", error)
return
}
// Schedule the request.
let request = UNNotificationRequest(identifier: "\(identifier)", content: content, trigger: trigger)
self.bridge.notificationsDelegate.notificationRequestLookup[request.identifier] = notification
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
CAPLog.print(theError.localizedDescription)
call.error(theError.localizedDescription)
}
}
ids.append(request.identifier)
}
call.success([
"ids": ids
])
}
/**
* Cancel notifications by id
*/
@objc func cancel(_ call: CAPPluginCall) {
guard let notifications = call.getArray("notifications", JSObject.self, []), notifications.count > 0 else {
call.error("Must supply notifications to cancel")
return
}
let ids = notifications.map { $0["id"] as? String ?? "" }
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ids)
call.success()
}
/**
* Get all pending notifications.
*/
@objc func getPending(_ call: CAPPluginCall) {
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notifications) in
CAPLog.print("num of pending notifications \(notifications.count)")
CAPLog.print(notifications)
let ret = notifications.map({ (notification) -> [String:Any] in
return self.bridge.notificationsDelegate.makePendingNotificationRequestJSObject(notification)
})
call.success([
"notifications": ret
])
})
}
/**
* Register allowed action types that a notification may present.
*/
@objc func registerActionTypes(_ call: CAPPluginCall) {
guard let types = call.getArray("types", Any.self) as? JSArray else {
return
}
makeActionTypes(types)
call.success()
}
/**
* Check if Local Notifications are authorized and enabled
*/
@objc func areEnabled(_ call: CAPPluginCall) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
let authorized = settings.authorizationStatus == UNAuthorizationStatus.authorized
let enabled = settings.notificationCenterSetting == UNNotificationSetting.enabled
call.success([
"value": enabled && authorized
])
}
}
/**
* Build the content for a notification.
*/
func makeNotificationContent(_ notification: JSObject) throws -> UNNotificationContent {
guard let title = notification["title"] as? String else {
throw LocalNotificationError.contentNoTitle
}
guard let body = notification["body"] as? String else {
throw LocalNotificationError.contentNoBody
}
let actionTypeId = notification["actionTypeId"] as? String
let sound = notification["sound"] as? String
let attachments = notification["attachments"] as? JSArray
let extra = notification["extra"] as? JSObject ?? [:]
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: body,
arguments: nil)
content.userInfo = extra
if actionTypeId != nil {
content.categoryIdentifier = actionTypeId!
}
if sound != nil {
content.sound = UNNotificationSound(named: UNNotificationSoundName(sound!))
}
if attachments != nil {
content.attachments = try makeAttachments(attachments!)
}
return content
}
/**
* Build a notification trigger, such as triggering each N seconds, or
* on a certain date "shape" (such as every first of the month)
*/
func handleScheduledNotification(_ call: CAPPluginCall, _ schedule: [String:Any]) throws -> UNNotificationTrigger? {
let at = schedule["at"] as? Date
let every = schedule["every"] as? String
let on = schedule["on"] as? [String:Int]
let repeats = schedule["repeats"] as? Bool ?? false
// If there's a specific date for this notificiation
if at != nil {
let dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: at!)
if dateInfo.date! < Date() {
call.error("Scheduled time must be *after* current time")
return nil
}
var dateInterval = DateInterval(start: Date(), end: dateInfo.date!)
// Notifications that repeat have to be at least a minute between each other
if repeats && dateInterval.duration < 60 {
throw LocalNotificationError.triggerRepeatIntervalTooShort
}
return UNTimeIntervalNotificationTrigger(timeInterval: dateInterval.duration, repeats: repeats)
}
// If this notification should repeat every day/month/week/etc. or on a certain
// matching set of date components
if on != nil {
let dateComponents = getDateComponents(on!)
return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
}
if every != nil {
if let repeatDateInterval = getRepeatDateInterval(every!) {
return UNTimeIntervalNotificationTrigger(timeInterval: repeatDateInterval.duration, repeats: true)
}
}
return nil
}
/**
* Given our schedule format, return a DateComponents object
* that only contains the components passed in.
*/
func getDateComponents(_ at: [String:Int]) -> DateComponents {
//var dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
//dateInfo.calendar = Calendar.current
var dateInfo = DateComponents()
if let year = at["year"] {
dateInfo.year = year
}
if let month = at["month"] {
dateInfo.month = month
}
if let day = at["day"] {
dateInfo.day = day
}
if let hour = at["hour"] {
dateInfo.hour = hour
}
if let minute = at["minute"] {
dateInfo.minute = minute
}
if let second = at["second"] {
dateInfo.second = second
}
return dateInfo
}
/**
* Compute the difference between the string representation of a date
* interval and today. For example, if every is "month", then we
* return the interval between today and a month from today.
*/
func getRepeatDateInterval(_ every: String) -> DateInterval? {
let cal = Calendar.current
let now = Date()
switch every {
case "year":
let newDate = cal.date(byAdding: .year, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "month":
let newDate = cal.date(byAdding: .month, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "two-weeks":
let newDate = cal.date(byAdding: .weekOfYear, value: 2, to: now)!
return DateInterval(start: now, end: newDate)
case "week":
let newDate = cal.date(byAdding: .weekOfYear, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "day":
let newDate = cal.date(byAdding: .day, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "hour":
let newDate = cal.date(byAdding: .hour, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "minute":
let newDate = cal.date(byAdding: .minute, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
case "second":
let newDate = cal.date(byAdding: .second, value: 1, to: now)!
return DateInterval(start: now, end: newDate)
default:
return nil
}
}
/**
* Make required UNNotificationCategory entries for action types
*/
func makeActionTypes(_ actionTypes: JSArray) {
var createdCategories = [UNNotificationCategory]()
let generalCategory = UNNotificationCategory(identifier: "GENERAL",
actions: [],
intentIdentifiers: [],
options: .customDismissAction)
createdCategories.append(generalCategory)
for type in actionTypes {
guard let id = type["id"] as? String else {
bridge.modulePrint(self, "Action type must have an id field")
continue
}
let hiddenBodyPlaceholder = type["iosHiddenPreviewsBodyPlaceholder"] as? String ?? ""
let actions = type["actions"] as? JSArray ?? []
let newActions = makeActions(actions)
// Create the custom actions for the TIMER_EXPIRED category.
var newCategory: UNNotificationCategory?
newCategory = UNNotificationCategory(identifier: id,
actions: newActions,
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: hiddenBodyPlaceholder,
options: makeCategoryOptions(type))
createdCategories.append(newCategory!)
}
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(Set(createdCategories))
}
/**
* Build the required UNNotificationAction objects for each action type registered.
*/
func makeActions(_ actions: JSArray) -> [UNNotificationAction] {
var createdActions = [UNNotificationAction]()
for action in actions {
guard let id = action["id"] as? String else {
bridge.modulePrint(self, "Action must have an id field")
continue
}
let title = action["title"] as? String ?? ""
let input = action["input"] as? Bool ?? false
var newAction: UNNotificationAction
if input {
let inputButtonTitle = action["inputButtonTitle"] as? String
let inputPlaceholder = action["inputPlaceholder"] as? String ?? ""
if inputButtonTitle != nil {
newAction = UNTextInputNotificationAction(identifier: id,
title: title,
options: makeActionOptions(action),
textInputButtonTitle: inputButtonTitle!,
textInputPlaceholder: inputPlaceholder)
} else {
newAction = UNTextInputNotificationAction(identifier: id, title: title, options: makeActionOptions(action))
}
} else {
// Create the custom actions for the TIMER_EXPIRED category.
newAction = UNNotificationAction(identifier: id,
title: title,
options: makeActionOptions(action))
}
createdActions.append(newAction)
}
return createdActions
}
/**
* Make options for UNNotificationActions
*/
func makeActionOptions(_ action: [String:Any]) -> UNNotificationActionOptions {
let foreground = action["foreground"] as? Bool ?? false
let destructive = action["destructive"] as? Bool ?? false
let requiresAuthentication = action["requiresAuthentication"] as? Bool ?? false
if foreground {
return .foreground
}
if destructive {
return .destructive
}
if requiresAuthentication {
return .authenticationRequired
}
return UNNotificationActionOptions(rawValue: 0)
}
/**
* Make options for UNNotificationCategoryActions
*/
func makeCategoryOptions(_ type: JSObject) -> UNNotificationCategoryOptions {
let customDismiss = type["iosCustomDismissAction"] as? Bool ?? false
let carPlay = type["iosAllowInCarPlay"] as? Bool ?? false
let hiddenPreviewsShowTitle = type["iosHiddenPreviewsShowTitle"] as? Bool ?? false
let hiddenPreviewsShowSubtitle = type["iosHiddenPreviewsShowSubtitle"] as? Bool ?? false
if customDismiss {
return .customDismissAction
}
if carPlay {
return .allowInCarPlay
}
if hiddenPreviewsShowTitle {
return .hiddenPreviewsShowTitle
}
if hiddenPreviewsShowSubtitle {
return .hiddenPreviewsShowSubtitle
}
return UNNotificationCategoryOptions(rawValue: 0)
}
/**
* Build the UNNotificationAttachment object for each attachment supplied.
*/
func makeAttachments(_ attachments: JSArray) throws -> [UNNotificationAttachment] {
var createdAttachments = [UNNotificationAttachment]()
for a in attachments {
guard let id = a["id"] as? String else {
throw LocalNotificationError.attachmentNoId
}
guard let url = a["url"] as? String else {
throw LocalNotificationError.attachmentNoUrl
}
guard let urlObject = makeAttachmentUrl(url) else {
throw LocalNotificationError.attachmentFileNotFound(path: url)
}
let options = a["options"] as? JSObject ?? [:]
do {
let newAttachment = try UNNotificationAttachment(identifier: id, url: urlObject, options: makeAttachmentOptions(options))
createdAttachments.append(newAttachment)
} catch {
throw LocalNotificationError.attachmentUnableToCreate(error.localizedDescription)
}
}
return createdAttachments
}
/**
* Get the internal URL for the attachment URL
*/
func makeAttachmentUrl(_ path: String) -> URL? {
let file = CAPFileManager.get(path: path)
return file?.url
}
/**
* Build the options for the attachment, if any. (For example: the clipping rectangle to use
* for image attachments)
*/
func makeAttachmentOptions(_ options: JSObject) -> [AnyHashable:Any] {
var opts = [AnyHashable:Any]()
if let iosUNNotificationAttachmentOptionsTypeHintKey = options["iosUNNotificationAttachmentOptionsTypeHintKey"] as? String {
opts[UNNotificationAttachmentOptionsTypeHintKey] = iosUNNotificationAttachmentOptionsTypeHintKey
}
if let iosUNNotificationAttachmentOptionsThumbnailHiddenKey = options["iosUNNotificationAttachmentOptionsThumbnailHiddenKey"] as? String {
opts[UNNotificationAttachmentOptionsThumbnailHiddenKey] = iosUNNotificationAttachmentOptionsThumbnailHiddenKey
}
if let iosUNNotificationAttachmentOptionsThumbnailClippingRectKey = options["iosUNNotificationAttachmentOptionsThumbnailClippingRectKey"] as? String {
opts[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = iosUNNotificationAttachmentOptionsThumbnailClippingRectKey
}
if let iosUNNotificationAttachmentOptionsThumbnailTimeKey = options["iosUNNotificationAttachmentOptionsThumbnailTimeKey"] as? String {
opts[UNNotificationAttachmentOptionsThumbnailTimeKey] = iosUNNotificationAttachmentOptionsThumbnailTimeKey
}
return opts
}
}
| 34.34898 | 154 | 0.651061 |
906d6e12f7d96a434d7a08aca03bc42bd7694774 | 768 | //
// Copyright © 2016 Baris Sencan. All rights reserved.
//
import Foundation
import XCTest
import JSONHelper
class DeserializableTests: XCTestCase {
struct Item: Deserializable {
static let nameKey = "name"
var name = ""
init(dictionary: [String : AnyObject]) {
name <-- dictionary[Item.nameKey]
}
init() {}
}
let itemDictionary = [Item.nameKey : "a"]
let itemString = "{ \"name\": \"a\" }"
var item = Item()
override func setUp() {
item = Item()
}
func testDictionaryDeserialization() {
item <-- itemDictionary
XCTAssertEqual(item.name, itemDictionary[Item.nameKey])
}
func testStringDeserialization() {
item <-- itemString
XCTAssertEqual(item.name, itemDictionary[Item.nameKey])
}
}
| 18.285714 | 59 | 0.64974 |
1f061d624d5550a9c2f82b8fd82a97d5b9bda578 | 11,625 | //
// MasterViewController.swift
// TasskySidebar
//
// Created by towry on 27/02/2017.
// Copyright © 2017 towry. All rights reserved.
//
import UIKit
let kMenubarWidth: CGFloat = 80.0
class MasterViewController: UIViewController {
var scrollView: UIScrollView?
var contentView: UIView?
var detailViewCtl: DetailViewController?
var isMenuShow = false
var menuContainerView: UIView?
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
self.scrollView = UIScrollView()
self.scrollView?.bounces = false
self.scrollView?.translatesAutoresizingMaskIntoConstraints = false
if let scrollView = self.scrollView {
self.view.addSubview(scrollView)
scrollView.showsHorizontalScrollIndicator = false
scrollView.backgroundColor = .white
scrollView.clipsToBounds = true
scrollView.delegate = self
// Add constraints to scroll view upon it's superview.
self.addConstraintsToScrollView()
// Add scrollview's contents.
self.addScrollViewSubViews()
}
self.automaticallyAdjustsScrollViewInsets = false
}
func addConstraintsToScrollView() {
let view = self.scrollView!
self.view.addConstraints([
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: self.bottomLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0)
])
}
func addScrollViewSubViews() {
let sv = self.scrollView!
// Add a view to manage the contents.
self.contentView = UIView(frame: CGRect(x: 0, y:0, width: 600 + kMenubarWidth, height: 600))
contentView?.backgroundColor = .black
contentView?.frame = sv.bounds
contentView?.translatesAutoresizingMaskIntoConstraints = false
sv.addSubview(self.contentView!)
self.addConstraintsToContentView()
// Add a menu container view
let menuContainerView = UIView(frame: CGRect(x: 0, y: 0, width: kMenubarWidth, height: 600))
menuContainerView.translatesAutoresizingMaskIntoConstraints = false
// Add a detail container view
let detailContainerView = UIView(frame: CGRect(x: kMenubarWidth, y: 0, width: 600, height: 600))
detailContainerView.translatesAutoresizingMaskIntoConstraints = false
detailContainerView.backgroundColor = .blue
contentView?.addSubview(menuContainerView)
contentView?.addSubview(detailContainerView)
// - add constraints for menuContainerView and detailContainerView
contentView?.addConstraints([
NSLayoutConstraint(item: menuContainerView, attribute: .top, relatedBy: .equal, toItem: contentView!, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: menuContainerView, attribute: .bottom, relatedBy: .equal, toItem: contentView!, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: menuContainerView, attribute: .leading, relatedBy: .equal, toItem: contentView!, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: menuContainerView, attribute: .trailing, relatedBy: .equal, toItem: detailContainerView, attribute: .leading, multiplier: 1.0, constant: 0),
])
menuContainerView.addConstraint(NSLayoutConstraint(item: menuContainerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: kMenubarWidth))
contentView?.addConstraints([
NSLayoutConstraint(item: detailContainerView, attribute: .top, relatedBy: .equal, toItem: contentView!, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: detailContainerView, attribute: .bottom, relatedBy: .equal, toItem: contentView!, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: detailContainerView, attribute: .trailing, relatedBy: .equal, toItem: contentView!, attribute: .trailing, multiplier: 1.0, constant: 0)
])
self.menuContainerView = menuContainerView
// - end
let menubarViewCtl = MenubarViewController()
menubarViewCtl.delegate = self
let detailViewCtl = DetailViewController()
self.detailViewCtl = detailViewCtl
self.detailViewCtl?.delegate = self
let leftNav = UINavigationController(rootViewController: menubarViewCtl)
let rightNav = UINavigationController(rootViewController: detailViewCtl)
// - menu
self.addChildViewController(leftNav)
menuContainerView.addSubview(leftNav.view)
leftNav.view.frame = menuContainerView.bounds
leftNav.view.autoresizesSubviews = true
leftNav.view.translatesAutoresizingMaskIntoConstraints = true
// constraint for leftnav's root view
menuContainerView.addConstraints([
NSLayoutConstraint(item: leftNav.view, attribute: .top, relatedBy: .equal, toItem: menuContainerView, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: leftNav.view, attribute: .bottom, relatedBy: .equal, toItem: menuContainerView, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: leftNav.view, attribute: .leading, relatedBy: .equal, toItem: menuContainerView, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: leftNav.view, attribute: .trailing, relatedBy: .equal, toItem: menuContainerView, attribute: .trailing, multiplier: 1.0, constant: 0),
])
leftNav.didMove(toParentViewController: self)
// - end
// - detail
self.addChildViewController(rightNav)
detailContainerView.addSubview(rightNav.view)
rightNav.view.frame = detailContainerView.bounds
rightNav.view.translatesAutoresizingMaskIntoConstraints = true
// constraint for right nav's root view
detailContainerView.addConstraints([
NSLayoutConstraint(item: rightNav.view, attribute: .top, relatedBy: .equal, toItem: detailContainerView, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: rightNav.view, attribute: .bottom, relatedBy: .equal, toItem: detailContainerView, attribute: .bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: rightNav.view, attribute: .leading, relatedBy: .equal, toItem: detailContainerView, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: rightNav.view, attribute: .trailing, relatedBy: .equal, toItem: detailContainerView, attribute: .trailing, multiplier: 1.0, constant: 0),
])
rightNav.didMove(toParentViewController: self)
// -end
leftNav.navigationBar.isTranslucent = false
rightNav.navigationBar.isTranslucent = false
}
func addConstraintsToContentView() {
let view = self.contentView!
let sv = self.scrollView!
// Add constraints to content view between the scrollview
sv.addConstraints([
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: sv, attribute: .top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: sv, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: sv, attribute: .trailing, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: sv, attribute: .bottom, multiplier: 1.0, constant: 0),
])
// Add height and width constraints to content view between the superview of scrollview.
// because the superview of scrollview(self.view) has a fixed width and height.
// and scrollview can scroll, the it's width and height is not same as superview's.
self.view.addConstraints([
// width constraint
// the constant is 80, because we want to the content view wider than the superview of scrollview,
// so it can accommodate the menu view.
NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: kMenubarWidth),
// height constraint
NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0)
])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.menuContainerView?.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)
self.showOrHide(self.isMenuShow, animated: false)
}
}
extension MasterViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let multiplier = 1.0 / (self.menuContainerView?.bounds.width)!
let offset = (self.scrollView?.contentOffset.x)! * multiplier
let fraction = 1.0 - offset
// Begin layer 3d transform
self.menuContainerView?.layer.transform = self.get3dTransform(fraction)
self.menuContainerView?.alpha = fraction
if let detailViewCtl = self.detailViewCtl {
if let menuButton = detailViewCtl.menuButton {
menuButton.rotate(fraction)
}
}
self.scrollView?.isPagingEnabled = scrollView.contentOffset.x < (scrollView.contentSize.width - scrollView.frame.width)
let menuOffset = self.menuContainerView?.bounds.width
self.isMenuShow = !CGPoint(x: menuOffset!, y: 0).equalTo((self.scrollView?.contentOffset)!)
}
func get3dTransform(_ fraction: CGFloat) -> CATransform3D {
var identity = CATransform3DIdentity
identity.m34 = -1.0 / 1000.0
let angle = CGFloat(1.0 - fraction) * -CGFloat(M_PI_2)
let xOffset = (self.menuContainerView?.bounds.width)! / 2
let rotateTransform = CATransform3DRotate(identity, angle, 0.0, 1.0, 0.0)
let translateTransform = CATransform3DMakeTranslation(xOffset, 0, 0)
return CATransform3DConcat(rotateTransform, translateTransform)
}
}
extension MasterViewController: SidebarAnimationDelegate {
func showOrHide(_ show: Bool, animated: Bool) {
let xOffset = self.menuContainerView!.bounds.width
let point = show ? CGPoint.zero : CGPoint(x: xOffset, y: 0)
self.scrollView?.setContentOffset(point, animated: animated)
self.isMenuShow = show
}
func didSelect(_ item: MenuItemType) {
self.showOrHide(false, animated: true)
self.detailViewCtl?.presentDetail(item)
}
}
| 50.324675 | 205 | 0.680688 |
503d7fbcb7b556a81ff51c0cf743b2cacb14057c | 670 | // 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class i<m>: j {
f l: m init(l: m) {
k{
}
class k {
func m<l:m
}
structunc> (l, l -> l) -> l {
f k f.i = {
}
{
l)}
n e {
}
class f: e{ class func i {}
func h<j>() {
l c h(l: Int = m) {
}
func j<d>() -> (d, d -> d) -> d {
b l b.k , l : b l l.j == l> (j: l) {
}
enum S<T> : P {
| 21.612903 | 78 | 0.60597 |
8f406da3825ed01816bb02e6864d3a036f84a887 | 8,908 | //
// FolioReaderContainer.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 15/04/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import FontBlaster
/// Reader container
open class FolioReaderContainer: UIViewController {
var shouldHideStatusBar = true
var shouldRemoveEpub = true
// Mark those property as public so they can accessed from other classes/subclasses.
public var epubPath: String
public var unzipPath: String?
public var book: FRBook
public var centerNavigationController: UINavigationController?
public var centerViewController: FolioReaderCenter?
public var audioPlayer: FolioReaderAudioPlayer?
public var readerConfig: FolioReaderConfig
public var folioReader: FolioReader
fileprivate var errorOnLoad = false
// MARK: - Init
/// Init a Folio Reader Container
///
/// - Parameters:
/// - config: Current Folio Reader configuration
/// - folioReader: Current instance of the FolioReader kit.
/// - path: The ePub path on system. Must not be nil nor empty string.
/// - unzipPath: Path to unzip the compressed epub.
/// - removeEpub: Should delete the original file after unzip? Default to `true` so the ePub will be unziped only once.
public init(withConfig config: FolioReaderConfig, folioReader: FolioReader, epubPath path: String, unzipPath: String? = nil, removeEpub: Bool = true) {
self.readerConfig = config
self.folioReader = folioReader
self.epubPath = path
self.unzipPath = unzipPath
self.shouldRemoveEpub = removeEpub
self.book = FRBook()
super.init(nibName: nil, bundle: Bundle.frameworkBundle())
// Configure the folio reader.
self.folioReader.readerContainer = self
// Initialize the default reader options.
if self.epubPath != "" {
self.initialization()
}
}
required public init?(coder aDecoder: NSCoder) {
// When a FolioReaderContainer object is instantiated from the storyboard this function is called before.
// At this moment, we need to initialize all non-optional objects with default values.
// The function `setupConfig(config:epubPath:removeEpub:)` MUST be called afterward.
// See the ExampleFolioReaderContainer.swift for more information?
self.readerConfig = FolioReaderConfig()
self.folioReader = FolioReader()
self.epubPath = ""
self.shouldRemoveEpub = false
self.book = FRBook()
super.init(coder: aDecoder)
// Configure the folio reader.
self.folioReader.readerContainer = self
}
/// Common Initialization
fileprivate func initialization() {
// Register custom fonts
FontBlaster.debugEnabled = true
FontBlaster.blast(bundle: Bundle.frameworkBundle()) { (fonts) in
print(fonts) // fonts is an array of Strings containing font names
}
// Register initial defaults
self.folioReader.register(defaults: [
kCurrentFontFamily: FolioReaderFont.andada.rawValue,
kNightMode: false,
kCurrentFontSize: 2,
kCurrentFontColor: self.readerConfig.fontTextColor,
kCurrentLineHeight: 2,
kCurrentAudioRate: 1,
kCurrentHighlightStyle: 0,
kCurrentTOCMenu: 0,
kCurrentMediaOverlayStyle: MediaOverlayStyle.default.rawValue,
kCurrentScrollDirection: FolioReaderScrollDirection.defaultVertical.rawValue
])
}
/// Set the `FolioReaderConfig` and epubPath.
///
/// - Parameters:
/// - config: Current Folio Reader configuration
/// - path: The ePub path on system. Must not be nil nor empty string.
/// - unzipPath: Path to unzip the compressed epub.
/// - removeEpub: Should delete the original file after unzip? Default to `true` so the ePub will be unziped only once.
open func setupConfig(_ config: FolioReaderConfig, epubPath path: String, unzipPath: String? = nil, removeEpub: Bool = true) {
self.readerConfig = config
self.folioReader = FolioReader()
self.folioReader.readerContainer = self
self.epubPath = path
self.unzipPath = unzipPath
self.shouldRemoveEpub = removeEpub
}
// MARK: - View life cicle
override open func viewDidLoad() {
super.viewDidLoad()
let canChangeScrollDirection = self.readerConfig.canChangeScrollDirection
self.readerConfig.canChangeScrollDirection = self.readerConfig.isDirection(canChangeScrollDirection, canChangeScrollDirection, false)
// If user can change scroll direction use the last saved
if self.readerConfig.canChangeScrollDirection == true {
var scrollDirection = FolioReaderScrollDirection(rawValue: self.folioReader.currentScrollDirection) ?? .vertical
if (scrollDirection == .defaultVertical && self.readerConfig.scrollDirection != .defaultVertical) {
scrollDirection = self.readerConfig.scrollDirection
}
self.readerConfig.scrollDirection = scrollDirection
}
let hideBars = readerConfig.hideBars
self.readerConfig.shouldHideNavigationOnTap = ((hideBars == true) ? true : self.readerConfig.shouldHideNavigationOnTap)
self.centerViewController = FolioReaderCenter(withContainer: self)
if let rootViewController = self.centerViewController {
self.centerNavigationController = UINavigationController(rootViewController: rootViewController)
}
self.centerNavigationController?.setNavigationBarHidden(self.readerConfig.shouldHideNavigationOnTap, animated: false)
if let _centerNavigationController = self.centerNavigationController {
self.view.addSubview(_centerNavigationController.view)
self.addChild(_centerNavigationController)
}
self.centerNavigationController?.didMove(toParent: self)
if (self.readerConfig.hideBars == true) {
self.readerConfig.shouldHideNavigationOnTap = false
self.navigationController?.navigationBar.isHidden = true
self.centerViewController?.pageIndicatorHeight = 0
}
// Read async book
guard (self.epubPath.isEmpty == false) else {
print("Epub path is nil.")
self.errorOnLoad = true
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
let parsedBook = try FREpubParser().readEpub(epubPath: self.epubPath, removeEpub: self.shouldRemoveEpub, unzipPath: self.unzipPath)
self.book = parsedBook
self.folioReader.isReaderOpen = true
// Reload data
DispatchQueue.main.async {
// Add audio player if needed
if self.book.hasAudio || self.readerConfig.enableTTS {
self.addAudioPlayer()
}
self.centerViewController?.reloadData()
self.folioReader.isReaderReady = true
self.folioReader.delegate?.folioReader?(self.folioReader, didFinishedLoading: self.book)
}
} catch {
self.errorOnLoad = true
self.alert(message: error.localizedDescription)
}
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (self.errorOnLoad == true) {
self.dismiss()
}
}
/**
Initialize the media player
*/
func addAudioPlayer() {
self.audioPlayer = FolioReaderAudioPlayer(withFolioReader: self.folioReader, book: self.book)
self.folioReader.readerAudioPlayer = audioPlayer
}
// MARK: - Status Bar
override open var prefersStatusBarHidden: Bool {
return (self.readerConfig.shouldHideNavigationOnTap == false ? false : self.shouldHideStatusBar)
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return UIStatusBarAnimation.slide
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return self.folioReader.isNight(.lightContent, .default)
}
}
extension FolioReaderContainer {
func alert(message: String) {
let alertController = UIAlertController(
title: "Error",
message: message,
preferredStyle: UIAlertController.Style.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel) { [weak self]
(result : UIAlertAction) -> Void in
self?.dismiss()
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
| 38.23176 | 155 | 0.659856 |
762a45d3b8638f20ab97e9d651c65bbb07cf0245 | 4,833 | import XCTest
@testable import Quick
import Nimble
class FunctionalTests_ItSpec: QuickSpec {
override func spec() {
var exampleMetadata: ExampleMetadata?
beforeEach { metadata in exampleMetadata = metadata }
it("") {
expect(exampleMetadata!.example.name).to(equal(""))
}
it("has a description with セレクター名に使えない文字が入っている 👊💥") {
let name = "has a description with セレクター名に使えない文字が入っている 👊💥"
expect(exampleMetadata!.example.name).to(equal(name))
}
#if canImport(Darwin)
describe("when an example has a unique name") {
it("has a unique name") {}
it("doesn't add multiple selectors for it") {
let allSelectors = [String](
FunctionalTests_ItSpec.allSelectors()
.filter { $0.hasPrefix("when_an_example_has_a_unique_name__") })
.sorted(by: <)
expect(allSelectors) == [
"when_an_example_has_a_unique_name__doesn_t_add_multiple_selectors_for_it",
"when_an_example_has_a_unique_name__has_a_unique_name"
]
}
}
describe("when two examples have the exact name") {
it("has exactly the same name") {}
it("has exactly the same name") {}
it("makes a unique name for each of the above") {
let allSelectors = [String](
FunctionalTests_ItSpec.allSelectors()
.filter { $0.hasPrefix("when_two_examples_have_the_exact_name__") })
.sorted(by: <)
expect(allSelectors) == [
"when_two_examples_have_the_exact_name__has_exactly_the_same_name",
"when_two_examples_have_the_exact_name__has_exactly_the_same_name_2",
"when_two_examples_have_the_exact_name__makes_a_unique_name_for_each_of_the_above"
]
}
}
#if !SWIFT_PACKAGE
describe("error handling when misusing ordering") {
it("an it") {
expect {
it("will throw an error when it is nested in another it") { }
}.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal(NSExceptionName.internalInconsistencyException))
expect(exception.reason).to(equal("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'. "))
})
}
describe("behavior with an 'it' inside a 'beforeEach'") {
var exception: NSException?
beforeEach {
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
it("a rogue 'it' inside a 'beforeEach'") { }
return
}
}
it("should have thrown an exception with the correct error message") {
expect(exception).toNot(beNil())
expect(exception!.reason).to(equal("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'. "))
}
}
describe("behavior with an 'it' inside an 'afterEach'") {
var exception: NSException?
afterEach {
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
expect(exception).toNot(beNil())
expect(exception!.reason).to(equal("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'. "))
}), finally: nil)
capture.tryBlock {
it("a rogue 'it' inside an 'afterEach'") { }
return
}
}
it("should throw an exception with the correct message after this 'it' block executes") { }
}
}
#endif
#endif
}
}
final class ItTests: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (ItTests) -> () throws -> Void)] {
return [
("testAllExamplesAreExecuted", testAllExamplesAreExecuted)
]
}
func testAllExamplesAreExecuted() {
let result = qck_runSpec(FunctionalTests_ItSpec.self)
#if canImport(Darwin)
#if SWIFT_PACKAGE
XCTAssertEqual(result?.executionCount, 7)
#else
XCTAssertEqual(result?.executionCount, 10)
#endif
#else
XCTAssertEqual(result?.executionCount, 2)
#endif
}
}
| 37.176923 | 157 | 0.534244 |
bbfdd2a163f3cdff0b4b6c3fff0b1b6b30a9e0c0 | 7,505 | import Ably
import CoreLocation
import AblyAssetTrackingCore
import AblyAssetTrackingInternal
class DefaultAblyPublisherService: AblyPublisherService {
private let client: ARTRealtime
private let presenceData: PresenceData
private var channels: [Trackable: ARTRealtimeChannel]
weak var delegate: AblyPublisherServiceDelegate?
init(configuration: ConnectionConfiguration) {
self.client = ARTRealtime(options: configuration.getClientOptions())
self.presenceData = PresenceData(type: .publisher)
self.channels = [:]
setup()
}
private func setup() {
client.connection.on { [weak self] stateChange in
guard let self = self else {
return
}
let receivedConnectionState = stateChange.current.toConnectionState()
logger.debug("Connection to Ably changed. New state: \(receivedConnectionState.description)", source: String(describing: Self.self))
self.delegate?.publisherService(
sender: self,
didChangeConnectionState: receivedConnectionState
)
}
}
// MARK: Main interface
func track(trackable: Trackable, completion: ResultHandler<Void>?) {
// Force cast intentional here. It's a fatal error if we are unable to create presenceData JSON
let data = try! presenceData.toJSONString()
let channel = client.channels.getChannelFor(trackingId: trackable.id)
channel.presence.subscribe { [weak self] message in
guard let self = self,
let json = message.data as? String,
let data: PresenceData = try? PresenceData.fromJSONString(json),
let clientId = message.clientId
else { return }
self.delegate?.publisherService(sender: self,
didReceivePresenceUpdate: message.action.toPresence(),
forTrackable: trackable,
presenceData: data,
clientId: clientId)
}
channel.presence.enter(data) { error in
guard let error = error else {
logger.debug("Entered to presence successfully", source: String(describing: Self.self))
self.channels[trackable] = channel
completion?(.success)
return
}
logger.error("Error during joining to channel presence: \(String(describing: error))", source: "AblyPublisherService")
completion?(.failure(error.toErrorInformation()))
}
channel.on { [weak self] stateChange in
guard let self = self else {
return
}
let receivedConnectionState = stateChange.current.toConnectionState()
logger.debug("Channel state for trackable \(trackable.id) changed. New state: \(receivedConnectionState.description)", source: String(describing: Self.self))
self.delegate?.publisherService(sender: self, didChangeChannelConnectionState: receivedConnectionState, forTrackable: trackable)
}
}
func sendEnhancedAssetLocationUpdate(locationUpdate: EnhancedLocationUpdate, forTrackable trackable: Trackable, completion: ResultHandler<Void>?) {
guard let channel = channels[trackable] else {
let errorInformation = ErrorInformation(type: .publisherError(errorMessage: "Attempt to send location while not tracked channel"))
completion?(.failure(errorInformation))
return
}
let message: ARTMessage
do {
message = try createARTMessage(for: locationUpdate)
} catch {
let errorInformation = ErrorInformation(
type: .publisherError(errorMessage: "Cannot create location update message. Underlying error: \(error)")
)
delegate?.publisherService(sender: self, didFailWithError: errorInformation)
return
}
channel.publish([message]) { [weak self] error in
guard let self = self else {
return
}
if let error = error {
self.delegate?.publisherService(sender: self, didFailWithError: error.toErrorInformation())
return
}
self.delegate?.publisherService(sender: self, didChangeChannelConnectionState: .online, forTrackable: trackable)
completion?(.success)
}
}
private func createARTMessage(for locationUpdate: EnhancedLocationUpdate) throws -> ARTMessage {
let geoJson = try EnhancedLocationUpdateMessage(locationUpdate: locationUpdate)
let data = try geoJson.toJSONString()
return ARTMessage(name: EventName.enhanced.rawValue, data: data)
}
func close(completion: @escaping ResultHandler<Void>) {
closeAllChannels { _ in
self.closeClientConnection(completion: completion)
}
}
private func closeClientConnection(completion: @escaping ResultHandler<Void>) {
client.connection.on { connectionChange in
switch connectionChange.current {
case .closed:
logger.info("Ably connection closed successfully.")
completion(.success)
case .failed:
let errorInfo = connectionChange.reason?.toErrorInformation() ?? ErrorInformation(type: .publisherError(errorMessage: "Cannot close connection"))
completion(.failure(errorInfo))
default:
return
}
}
client.close()
}
private func closeAllChannels(completion: @escaping ResultHandler<Void>) {
guard !channels.isEmpty else {
completion(.success)
return
}
let closingDispatchGroup = DispatchGroup()
channels.forEach { channel in
closingDispatchGroup.enter()
self.stopTracking(trackable: channel.key) { result in
switch result {
case .success(let wasPresent):
logger.info("Trackable \(channel.key.id) removed successfully. Was present \(wasPresent)")
closingDispatchGroup.leave()
case .failure(let error):
logger.error("Removing trackable \(channel.key) failed. Error \(error.message)")
closingDispatchGroup.leave()
}
}
}
closingDispatchGroup.notify(queue: .main) {
logger.info("All trackables removed.")
completion(.success)
}
}
func stopTracking(trackable: Trackable, completion: ResultHandler<Bool>?) {
guard let channel = channels.removeValue(forKey: trackable) else {
completion?(.success(false))
return
}
// Force cast intentional here. It's a fatal error if we are unable to create presenceData JSON
let data = try! presenceData.toJSONString()
channel.presence.unsubscribe()
channel.presence.leave(data) { error in
guard let error = error else {
completion?(.success(true))
return
}
let errorInformation = error.toErrorInformation()
completion?(.failure(errorInformation))
}
}
}
| 39.293194 | 169 | 0.60453 |
22c7a51924d9541112948a9d866dc82073ee3eff | 2,709 | import Foundation
/// HTTPClient is responsible for sending and canceling url requests
public class HTTPClient: HTTPClientType {
/// batchFactory is used for creating batch request for JSONRPC request
private let batchFactory = BatchFactory(version: "2.0")
/// configuration is used for configuring request information
public let configuration: Configuration
/// init initialize HTTPClient
///
/// - Parameter configuration: configuration to use to configure requests
public init(configuration: Configuration) {
self.configuration = configuration
}
/// send method sends specified jsonrpc request and returns a session task.
///
/// - Parameters:
/// - request: request to send. needs to be conformed to JSONRPCRequest protocol
/// - completionHandler:
/// - Returns: session task used to send request
@discardableResult
public func send<Request: JSONRPCRequest>(_ request: Request, completionHandler: @escaping (Result<Request.Response>) -> Void) -> Cancellable? {
let httpRequest = HTTPJSONRPCRequest(batch: batchFactory.create(request), endpoint: URL(string: configuration.nodeEndpoint)!)
return send(httpRequest, completionHandler: completionHandler)
}
/// send method sends specified json request and returns a session task.
///
/// - Parameters:
/// - request: request to send, needs to be conformed to RequestType protocol
/// - completionHandler:
/// - Returns: session task used to send request
@discardableResult
public func send<Request: RequestType>(_ request: Request, completionHandler: @escaping (Result<Request.Response>) -> Void) -> Cancellable? {
switch request.build() {
case .success(let urlRequest):
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
let result = request.buildResponse(from: data, response: response, error: error)
DispatchQueue.main.async {
completionHandler(self.intercept(request, result: result))
}
}
task.resume()
return task
case .failure(let error):
completionHandler(.failure(error))
return nil
}
}
private func intercept<Request: RequestType>(_ request: Request, result: Result<Request.Response>) -> Result<Request.Response> {
if configuration.debugPrints {
print(
"""
\(request.description)
\(result.description)\n
"""
)
}
return result
}
}
| 39.838235 | 148 | 0.632706 |
4b621d7c272c33e1272fe95d9c66b9d53fbc56af | 1,301 | //
// ViewController.Wrapper.swift
// SwiftUIWrapper
//
// Created by Haider Khan on 6/4/19.
// Copyright © 2019 zkhaider. All rights reserved.
//
import Foundation
import SwiftUI
struct ViewControllerWrapping<C: ViewControllerCoordinator>: UIViewControllerRepresentable, AnyRepresentable {
typealias UIViewControllerType = C.ViewController
typealias ViewController = UIViewControllerType
typealias Coordinator = C
// MARK: - ViewController
var viewController: ViewController
// MARK: - Init
init(viewController: ViewController = ViewController(nibName: nil, bundle: nil)) {
self.viewController = viewController
}
// MARK: - Coordinator
func makeCoordinator() -> Coordinator {
Coordinator.init(self)
}
// MARK: - Make
func makeUIViewController(context: UIViewControllerRepresentableContext<ViewControllerWrapping<C>>) -> ViewController {
let vc = ViewController(nibName: nil, bundle: nil)
return vc
}
func updateUIViewController(_ uiViewController: ViewController,
context: UIViewControllerRepresentableContext<ViewControllerWrapping<C>>) {
context.coordinator.updateViewController(uiViewController)
}
}
| 27.680851 | 123 | 0.685626 |
563857b247d41070759caa162f004ab1c581fecf | 8,412 | //
// M A R S H A L
//
// ()
// /\
// ()--' '--()
// `. .'
// / .. \
// ()' '()
//
//
import Foundation
public protocol MarshaledObject {
func any(for key: KeyType) throws -> Any
func optionalAny(for key: KeyType) -> Any?
}
public extension MarshaledObject {
public func any(for key: KeyType) throws -> Any {
let pathComponents = key.stringValue.characters.split(separator: ".").map(String.init)
var accumulator: Any = self
for component in pathComponents {
if let componentData = accumulator as? Self, let value = componentData.optionalAny(for: component) {
accumulator = value
continue
}
throw MarshalError.keyNotFound(key: key.stringValue)
}
if let _ = accumulator as? NSNull {
throw MarshalError.nullValue(key: key.stringValue)
}
return accumulator
}
public func value<A: ValueType>(for key: KeyType) throws -> A {
let any = try self.any(for: key)
do {
guard let result = try A.value(from: any) as? A else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: type(of: any))
}
return result
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func value<A: ValueType>(for key: KeyType) throws -> A? {
do {
return try self.value(for: key) as A
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A] {
let any = try self.any(for: key)
do {
return try Array<A>.value(from: any, discardingErrors: discardingErrors)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func value<A: ValueType>(for key: KeyType) throws -> [A?] {
let any = try self.any(for: key)
do {
return try Array<A>.value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A]? {
do {
return try self.value(for: key, discardingErrors: discardingErrors) as [A]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: ValueType>(for key: KeyType) throws -> [A?]? {
do {
return try self.value(for: key) as [A]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: ValueType>(for key: KeyType) throws -> [String: A] {
let any = try self.any(for: key)
do {
return try [String: A].value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func value<A: ValueType>(for key: KeyType) throws -> [String: A]? {
do {
let any = try self.any(for: key)
return try [String: A].value(from: any)
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value(for key: KeyType) throws -> [MarshalDictionary] {
let any = try self.any(for: key)
guard let object = any as? [MarshalDictionary] else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: [MarshalDictionary].self, actual: type(of: any))
}
return object
}
public func value(for key: KeyType) throws -> [MarshalDictionary]? {
do {
return try value(for: key) as [MarshalDictionary]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value(for key: KeyType) throws -> MarshalDictionary {
let any = try self.any(for: key)
guard let object = any as? MarshalDictionary else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: MarshalDictionary.self, actual: type(of: any))
}
return object
}
public func value(for key: KeyType) throws -> MarshalDictionary? {
do {
return try value(for: key) as MarshalDictionary
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: ValueType>(for key: KeyType) throws -> Set<A> {
let any = try self.any(for: key)
do {
return try Set<A>.value(from: any)
}
catch let MarshalError.typeMismatch(expected: expected, actual: actual) {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func value<A: ValueType>(for key: KeyType) throws -> Set<A>? {
do {
return try self.value(for: key) as Set<A>
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> A where A.RawValue: ValueType {
let raw = try self.value(for: key) as A.RawValue
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> A? where A.RawValue: ValueType {
do {
return try self.value(for: key) as A
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> [A] where A.RawValue: ValueType {
let rawArray = try self.value(for: key) as [A.RawValue]
return try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> [A]? where A.RawValue: ValueType {
do {
return try self.value(for: key) as [A]
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A> where A.RawValue: ValueType {
let rawArray = try self.value(for: key) as [A.RawValue]
let enumArray: [A] = try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
return Set<A>(enumArray)
}
public func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A>? where A.RawValue: ValueType {
do {
return try self.value(for: key) as Set<A>
}
catch MarshalError.keyNotFound {
return nil
}
catch MarshalError.nullValue {
return nil
}
}
}
| 32.229885 | 131 | 0.567285 |
8fe14beacd250fc705b70793fb79af90a65ae018 | 15,760 | /*
Copyright 2019 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 UIKit
final class KeyBackupSetupPassphraseViewController: UIViewController {
// MARK: - Constants
private enum Constants {
static let animationDuration: TimeInterval = 0.3
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var formBackgroundView: UIView!
@IBOutlet private weak var passphraseTitleLabel: UILabel!
@IBOutlet private weak var passphraseTextField: UITextField!
@IBOutlet private weak var passphraseAdditionalInfoView: UIView!
@IBOutlet private weak var passphraseStrengthView: PasswordStrengthView!
@IBOutlet private weak var passphraseAdditionalLabel: UILabel!
@IBOutlet private weak var formSeparatorView: UIView!
@IBOutlet private weak var confirmPassphraseTitleLabel: UILabel!
@IBOutlet private weak var confirmPassphraseTextField: UITextField!
@IBOutlet private weak var confirmPassphraseAdditionalInfoView: UIView!
@IBOutlet private weak var confirmPassphraseAdditionalLabel: UILabel!
@IBOutlet private weak var setPassphraseButtonBackgroundView: UIView!
@IBOutlet private weak var setPassphraseButton: UIButton!
@IBOutlet private weak var setUpRecoveryKeyInfoLabel: UILabel!
@IBOutlet private weak var setUpRecoveryKeyButton: UIButton!
// MARK: Private
private var isFirstViewAppearing: Bool = true
private var isPassphraseTextFieldEditedOnce: Bool = false
private var isConfirmPassphraseTextFieldEditedOnce: Bool = false
private var keyboardAvoider: KeyboardAvoider?
private var viewModel: KeyBackupSetupPassphraseViewModelType!
private var theme: Theme!
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
private weak var skipAlertController: UIAlertController?
// MARK: - Setup
class func instantiate(with viewModel: KeyBackupSetupPassphraseViewModelType) -> KeyBackupSetupPassphraseViewController {
let viewController = StoryboardScene.KeyBackupSetupPassphraseViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.keyBackupSetupTitle
self.vc_removeBackTitle()
self.setupViews()
self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView)
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.keyboardAvoider?.startAvoiding()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.isFirstViewAppearing {
self.isFirstViewAppearing = false
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.view.endEditing(true)
self.keyboardAvoider?.stopAvoiding()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.isFirstViewAppearing {
// Workaround to layout passphraseStrengthView corner radius
self.passphraseStrengthView.setNeedsLayout()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.titleLabel.textColor = theme.textPrimaryColor
self.informationLabel.textColor = theme.textPrimaryColor
self.formBackgroundView.backgroundColor = theme.backgroundColor
self.passphraseTitleLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onTextField: self.passphraseTextField)
self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupSetupPassphrasePassphrasePlaceholder,
attributes: [.foregroundColor: theme.placeholderTextColor])
self.updatePassphraseAdditionalLabel()
self.formSeparatorView.backgroundColor = theme.lineBreakColor
self.confirmPassphraseTitleLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onTextField: self.confirmPassphraseTextField)
self.confirmPassphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupSetupPassphraseConfirmPassphraseTitle,
attributes: [.foregroundColor: theme.placeholderTextColor])
self.updateConfirmPassphraseAdditionalLabel()
self.setPassphraseButton.backgroundColor = theme.backgroundColor
theme.applyStyle(onButton: self.setPassphraseButton)
self.setUpRecoveryKeyInfoLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onButton: self.setUpRecoveryKeyButton)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.cancelButtonAction()
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.scrollView.keyboardDismissMode = .interactive
self.titleLabel.text = VectorL10n.keyBackupSetupPassphraseTitle
self.informationLabel.text = VectorL10n.keyBackupSetupPassphraseInfo
self.passphraseTitleLabel.text = VectorL10n.keyBackupSetupPassphrasePassphraseTitle
self.passphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.passphraseStrengthView.strength = self.viewModel.passphraseStrength
self.passphraseAdditionalInfoView.isHidden = true
self.confirmPassphraseTitleLabel.text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseTitle
self.confirmPassphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.confirmPassphraseAdditionalInfoView.isHidden = true
self.setPassphraseButton.vc_enableMultiLinesTitle()
self.setPassphraseButton.setTitle(VectorL10n.keyBackupSetupPassphraseSetPassphraseAction, for: .normal)
self.updateSetPassphraseButton()
}
private func showPassphraseAdditionalInfo(animated: Bool) {
guard self.passphraseAdditionalInfoView.isHidden else {
return
}
UIView.animate(withDuration: Constants.animationDuration) {
self.passphraseAdditionalInfoView.isHidden = false
}
}
private func showConfirmPassphraseAdditionalInfo(animated: Bool) {
guard self.confirmPassphraseAdditionalInfoView.isHidden else {
return
}
UIView.animate(withDuration: Constants.animationDuration) {
self.confirmPassphraseAdditionalInfoView.isHidden = false
}
}
private func hideConfirmPassphraseAdditionalInfo(animated: Bool) {
guard self.confirmPassphraseAdditionalInfoView.isHidden == false else {
return
}
UIView.animate(withDuration: Constants.animationDuration) {
self.confirmPassphraseAdditionalInfoView.isHidden = true
}
}
private func updatePassphraseStrengthView() {
self.passphraseStrengthView.strength = self.viewModel.passphraseStrength
}
private func updatePassphraseAdditionalLabel() {
let text: String
let textColor: UIColor
if self.viewModel.isPassphraseValid {
text = VectorL10n.keyBackupSetupPassphrasePassphraseValid
textColor = self.theme.tintColor
} else {
text = VectorL10n.keyBackupSetupPassphrasePassphraseInvalid
textColor = self.theme.noticeColor
}
self.passphraseAdditionalLabel.text = text
self.passphraseAdditionalLabel.textColor = textColor
}
private func updateConfirmPassphraseAdditionalLabel() {
let text: String
let textColor: UIColor
if self.viewModel.isConfirmPassphraseValid {
text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseValid
textColor = self.theme.tintColor
} else {
text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseInvalid
textColor = self.theme.noticeColor
}
self.confirmPassphraseAdditionalLabel.text = text
self.confirmPassphraseAdditionalLabel.textColor = textColor
}
private func updateSetPassphraseButton() {
self.setPassphraseButton.isEnabled = self.viewModel.isFormValid
}
private func render(viewState: KeyBackupSetupPassphraseViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded:
self.renderLoaded()
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.view.endEditing(true)
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded() {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.hideSkipAlert(animated: false)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
private func showSkipAlert() {
guard self.skipAlertController == nil else {
return
}
let alertController = UIAlertController(title: VectorL10n.keyBackupSetupSkipAlertTitle,
message: VectorL10n.keyBackupSetupSkipAlertMessage,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: VectorL10n.continue, style: .cancel, handler: { action in
self.viewModel.process(viewAction: .skipAlertContinue)
}))
alertController.addAction(UIAlertAction(title: VectorL10n.keyBackupSetupSkipAlertSkipAction, style: .default, handler: { action in
self.viewModel.process(viewAction: .skipAlertSkip)
}))
self.present(alertController, animated: true, completion: nil)
self.skipAlertController = alertController
}
private func hideSkipAlert(animated: Bool) {
self.skipAlertController?.dismiss(animated: true, completion: nil)
}
// MARK: - Actions
@IBAction private func passphraseVisibilityButtonAction(_ sender: Any) {
guard self.isPassphraseTextFieldEditedOnce else {
return
}
self.passphraseTextField.isSecureTextEntry = !self.passphraseTextField.isSecureTextEntry
// TODO: Use this when project will be migrated to Swift 4.2
// self.passphraseTextField.isSecureTextEntry.toggle()
}
@objc private func textFieldDidChange(_ textField: UITextField) {
if textField == self.passphraseTextField {
self.viewModel.passphrase = textField.text
self.updatePassphraseAdditionalLabel()
self.updatePassphraseStrengthView()
// Show passphrase additional info at first character entered
if self.isPassphraseTextFieldEditedOnce == false && textField.text?.isEmpty == false {
self.isPassphraseTextFieldEditedOnce = true
self.showPassphraseAdditionalInfo(animated: true)
}
} else {
self.viewModel.confirmPassphrase = textField.text
}
// Show confirm passphrase additional info if needed
self.updateConfirmPassphraseAdditionalLabel()
if self.viewModel.confirmPassphrase?.isEmpty == false && self.viewModel.isPassphraseValid {
self.showConfirmPassphraseAdditionalInfo(animated: true)
} else {
self.hideConfirmPassphraseAdditionalInfo(animated: true)
}
// Enable validate button if form is valid
self.updateSetPassphraseButton()
}
@IBAction private func setPassphraseButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .setupPassphrase)
}
@IBAction private func setUpRecoveryKeyButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .setupRecoveryKey)
}
private func cancelButtonAction() {
self.viewModel.process(viewAction: .skip)
}
}
// MARK: - UITextFieldDelegate
extension KeyBackupSetupPassphraseViewController: UITextFieldDelegate {
func textFieldShouldClear(_ textField: UITextField) -> Bool {
self.textFieldDidChange(textField)
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.passphraseTextField {
self.confirmPassphraseTextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
}
// MARK: - KeyBackupSetupPassphraseViewModelViewDelegate
extension KeyBackupSetupPassphraseViewController: KeyBackupSetupPassphraseViewModelViewDelegate {
func keyBackupSetupPassphraseViewModel(_ viewModel: KeyBackupSetupPassphraseViewModelType, didUpdateViewState viewSate: KeyBackupSetupPassphraseViewState) {
self.render(viewState: viewSate)
}
func keyBackupSetupPassphraseViewModelShowSkipAlert(_ viewModel: KeyBackupSetupPassphraseViewModelType) {
self.showSkipAlert()
}
}
| 38.252427 | 160 | 0.684708 |
e21fa9065f0a080771223090880982dd84244231 | 6,270 | import Foundation
public enum Aggrandizement {
public enum DateFormatStyle {
case none(TimeFormatStyle)
case short(TimeFormatStyle)
case medium(TimeFormatStyle)
case long(TimeFormatStyle)
case rfc2822
case iso8601(includeTime: Bool)
case relative(TimeFormatStyle)
case custom(String)
case howLongAgoUntil
}
public enum TimeFormatStyle {
case none
case short
case medium
case long
var propertyListValue: Any {
switch self {
case .none: return "None"
case .short: return "Short"
case .medium: return "Medium"
case .long: return "Long"
}
}
}
public enum CoercionItemClass {
case anything
case appStoreApp
case article
case boolean
case contact
case date
case dictionary
case emailAddress
case file
case image
case iTunesMedia
case iTunesProduct
case location
case mapsLink
case media
case number
case pdf
case phoneNumber
case photoMedia
case place
case richText
case safariWebPage
case text
case url
case vCard
var propertyListValue: String? {
switch self {
case .anything: return "WFContentItem"
case .appStoreApp: return "WFAppStoreAppContentItem"
case .article: return "WFArticleContentItem"
case .boolean: return "WFBooleanContentItem"
case .contact: return "WFContactContentItem"
case .date: return "WFDateContentItem"
case .dictionary: return "WFDictionaryContentItem"
case .emailAddress: return "WFEmailAddressContentItem"
case .file: return "WFGenericFileContentItem"
case .image: return "WFImageContentItem"
case .iTunesMedia: return "WFMPMediaContentItem"
case .iTunesProduct: return "WFiTunesProductContentItem"
case .location: return "WFLocationContentItem"
case .mapsLink: return "WFDCMapsLinkContentItem"
case .media: return "WFAVAssetContentItem"
case .number: return "WFNumberContentItem"
case .pdf: return "WFPDFContentItem"
case .phoneNumber: return "WFPhoneNumberContentItem"
case .photoMedia: return "WFPhotoMediaContentItem"
case .place: return "WFMKMapItemContentItem"
case .richText: return "WFRichTextContentItem"
case .safariWebPage: return "WFSafariWebPageContentItem"
case .text: return nil
case .url: return "WFURLContentItem"
case .vCard: return "WFVCardContentItem"
}
}
}
public enum PropertyName {
case fileSize
case fileExtension
case name
case custom(String)
var propertyListValue: Any {
switch self {
case .fileSize: return "File Size"
case .fileExtension: return "File Extension"
case .name: return "Name"
case .custom(let propertyName): return propertyName
}
}
}
public enum PropertyUserInfo {
case fileSize
case fileExtension
case number(Number)
var propertyListValue: Any {
switch self {
case .fileSize: return "WFFileSizeProperty"
case .fileExtension: return "WFFileExtensionProperty"
case .number(let number): return number
}
}
}
case coercion(class: CoercionItemClass)
case dateFormat(DateFormatStyle)
case dictionaryValue(key: String?)
case property(name: PropertyName, userInfo: PropertyUserInfo)
var propertyList: PropertyList {
switch self {
case .coercion(let coercionClass):
var result: PropertyList = ["Type": "WFCoercionVariableAggrandizement"]
result["CoercionItemClass"] = coercionClass.propertyListValue
return result
case .dateFormat(let format):
var result: PropertyList = ["Type": "WFDateFormatVariableAggrandizement"]
switch format {
case .none(let timeFormatStyle):
result["WFDateFormatStyle"] = "None"
result["WFTimeFormatStyle"] = timeFormatStyle.propertyListValue
case .short(let timeFormatStyle):
result["WFDateFormatStyle"] = "Short"
result["WFTimeFormatStyle"] = timeFormatStyle.propertyListValue
case .medium(let timeFormatStyle):
result["WFDateFormatStyle"] = "Medium"
result["WFTimeFormatStyle"] = timeFormatStyle.propertyListValue
case .long(let timeFormatStyle):
result["WFDateFormatStyle"] = "Long"
result["WFTimeFormatStyle"] = timeFormatStyle.propertyListValue
case .rfc2822:
result["WFDateFormatStyle"] = "RFC 2822"
case .iso8601(let includeTime):
result["WFDateFormatStyle"] = "ISO 8601"
result["WFISO8601IncludeTime"] = includeTime
case .relative(let timeFormatStyle):
result["WFDateFormatStyle"] = "Relative"
result["WFTimeFormatStyle"] = timeFormatStyle.propertyListValue
result["WFRelativeDateFormatStyle"] = "Short"
case .custom(let dateFormat):
result["WFDateFormatStyle"] = "Custom"
result["WFDateFormat"] = dateFormat
case .howLongAgoUntil:
result["WFDateFormatStyle"] = "Relative"
}
return result
case .dictionaryValue(let key):
var result: PropertyList = ["Type": "WFDictionaryValueVariableAggrandizement"]
result["DictionaryKey"] = key
return result
case .property(let name, let userInfo):
return [
"Type": "WFPropertyVariableAggrandizement",
"PropertyName": name.propertyListValue,
"PropertyUserInfo": userInfo.propertyListValue,
]
}
}
}
| 35.423729 | 90 | 0.594418 |
61f6234f339bda827d26b3bfc40a97d693ad87b0 | 1,460 | //
// IOS_Codepath_PreworkUITests.swift
// IOS_Codepath_PreworkUITests
//
// Created by Andy Chen on 1/13/22.
//
import XCTest
class IOS_Codepath_PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.953488 | 182 | 0.663699 |
71753be97a6b38ccb6091b7f761c17184dbe441a | 803 | //
// This source file is part of the Web3Swift.io open source project
// Copyright 2018 The Web3Swift Authors
// Licensed under Apache License v2.0
//
// SizeOfTests.swift
//
// Created by Timofey Solonin on 23/05/2018
//
import Nimble
import Quick
@testable import Web3Swift
final class SizeOfTests: XCTestCase {
func testSizeIsTakenCorrectly() {
expect{
try SizeOf(
collection: SimpleCollection(
collection: Array<Int>(
repeating: 0,
count: 6
)
)
).value()
}.to(
equal(
6
),
description: "Number of elements in the collection is expected to be counted correctly"
)
}
} | 22.942857 | 99 | 0.533001 |
91da5d5ff45b3ea1cb653de2d91a19fb93629603 | 1,311 | //
// ViewController.swift
// SlidePage
//
// Created by ibrahim on 10/17/16.
// Copyright © 2016 Indosytem. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let xOrigin = self.view.frame.width
let view1 = View1(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
let view2 = View2(frame: CGRect(x: xOrigin, y: 0, width: self.view.frame.width, height: self.view.frame.height))
let view3 = View3(frame: CGRect(x: xOrigin * 2, y: 0, width: self.view.frame.width, height: self.view.frame.height))
scrollView.addSubview(view1)
scrollView.addSubview(view2)
scrollView.addSubview(view3)
self.scrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)
// hide the scrol bar.
scrollView?.showsHorizontalScrollIndicator = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 31.214286 | 124 | 0.652174 |
fbe417c6880961ef3a303f14d42a540a16632ed2 | 4,588 | //
// AppDelegate.swift
// ModuleSwift
//
// Created by CSSCORP on 3/21/18.
// Copyright © 2018 CSSCORP. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ModuleSwift")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.808511 | 285 | 0.687228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.