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
d521ef465ad8e171a7ecf5e4cfd62a37f70866cd
874
// // LukaSession.swift // LukaiOSSDK // // Created by José Daniel Gómez on 16/9/21. // import Foundation internal struct LukaSession { /** The id of the user */ let id: String /** The token authenticate Luka request with */ let token: String let retrievedAt: Date init(id: String, token: String, retrievedAt: Date) { self.id = id self.token = token self.retrievedAt = retrievedAt } var bearerToken: String { get { return "Bearer \(token)" } } var isExpired: Bool { get { let current = Date() let currentMins = current.timeIntervalSinceReferenceDate / 60 let oldMins = retrievedAt.timeIntervalSinceReferenceDate / 60 return currentMins - oldMins > 10 } } }
19
73
0.550343
dec9074e1055f9930fe8b65c74abb0583fc9593a
2,910
// // MCHaikuOrCanto.swift // Duke Medicine Mobile Companion // // Created by Ricky Bloomfield on 7/7/14. // Copyright (c) 2014 Duke Medicine // // 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 /** Opens the Canto app */ func openCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "epiccanto://")!) } /** Opens the Haiku app */ func openHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "epichaiku://")!) } /** Opens the App Store to the Canto app */ func downloadCanto() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-canto/id395395172?mt=8")!) } /** Opens the App Store to the Haiku app */ func downloadHaiku() { UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/us/app/epic-haiku/id348308661?mt=8")!) } /** Returns the string "Haiku" or "Canto" based on whether each is installed. If on iPad and both are installed, returns the preference in settings */ func HaikuOrCanto() -> String! { let HaikuInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epichaiku://")!) let CantoInstalled: Bool = UIApplication.sharedApplication().canOpenURL(NSURL(string: "epiccanto://")!) if IPAD() { if HaikuInstalled && CantoInstalled { return USER_DEFAULTS().objectForKey("returnTo") as String } else if (HaikuInstalled) { return "Haiku" } else if (CantoInstalled) { return "Canto" } } else if (HaikuInstalled) { return "Haiku" } return nil } /** Opens the appropriate app based on app availability and preference (per HaikuOrCanto() function above) */ func openHaikuOrCanto() { if HaikuOrCanto()? == "Haiku" {openHaiku()} else if HaikuOrCanto()? == "Canto" {openCanto()} }
34.235294
144
0.705155
8a1d9fd1f12e2311fbd557543c282c1c99bb532e
885
// // TYPEPersistenceStrategy.swift // import AmberBase import Foundation public class Dictionary_C_MeasurementFormatUnitUsage_IndexPath_D_PersistenceStrategy: PersistenceStrategy { public var types: Types { return Types.generic("Dictionary", [Types.type("MeasurementFormatUnitUsage"), Types.type("IndexPath")]) } public func save(_ object: Any) throws -> Data { guard let typedObject = object as? Dictionary<MeasurementFormatUnitUsage, IndexPath> else { throw AmberError.wrongTypes(self.types, AmberBase.types(of: object)) } let encoder = JSONEncoder() return try encoder.encode(typedObject) } public func load(_ data: Data) throws -> Any { let decoder = JSONDecoder() return try decoder.decode(Dictionary<MeasurementFormatUnitUsage, IndexPath>.self, from: data) } }
28.548387
111
0.691525
abde48cab4bbb697bb266e0a747af4c270f7da32
8,345
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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. // Compatibility classes for iOS 9 or older import Foundation /// DateTimeInterval represents a closed date interval in the form of [startDate, endDate]. /// It is possible for the start and end dates to be the same with a duration of 0. /// Negative intervals, where end date occurs earlier in time than the start date, are supported but comparisor and /// intersections functions will adjust them to the right order. public struct DateTimeInterval : Comparable { /// The start date. public var start: Date /// The end date. public var end: Date { get { return start.addingTimeInterval(duration) } set { duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate } } /// Absolute start. If duration is < 0 the oldest date is returned as start date. internal var absStart: Date { get { return (duration > 0 ? start : end) } } /// Absolute start. If duration is < 0 the newest date is returned as end date. internal var absEnd: Date { get { return (duration > 0 ? end : start) } } /// Return absolute duration regardeless the order of the dates internal var absDuration: TimeInterval { get { return abs(duration) } } /// The duration of the interval public var duration: TimeInterval /// Initializes a `DateTimeInterval` with start and end dates set to the current date and the duration set to `0`. public init() { let d = Date() start = d duration = 0 } /// Initialize a `DateTimeInterval` with the specified start and end date. public init(start: Date, end: Date) { self.start = start duration = end.timeIntervalSince(start) } /// Initialize a `DateTimeInterval` with the specified start date and duration. public init(start: Date, duration: TimeInterval) { self.start = start self.duration = duration } /// Compare two DateTimeInterval /// Note: if duration is less than zero (end date occurs earlier in time than the start date) are adjusted automatically. /// /// This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration. /// e.g. Given intervals a and b /// ``` /// a. |-----| /// b. |-----| /// ``` /// /// `a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date. /// /// In the event that the start dates are equal, the compare method will attempt to order by duration. /// e.g. Given intervals c and d /// ``` /// c. |-----| /// d. |---| /// ``` /// `c.compare(d)` would result in `.OrderedDescending` because c is longer than d. /// /// If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result. /// /// - Parameter dateInterval: date interval to compare /// - Returns: ComparisonResult public func compare(_ dateInterval: DateTimeInterval) -> ComparisonResult { let result = absStart.compare(dateInterval.absStart) if result == .orderedSame { if self.absDuration < dateInterval.absDuration { return .orderedAscending } if self.absDuration > dateInterval.absDuration { return .orderedDescending } return .orderedSame } return result } /// Returns `true` if `self` intersects the `dateInterval`. /// Note: if duration is less than zero (end date occurs earlier in time than the start date) are adjusted automatically. /// /// - Parameter dateInterval: date interval to intersect /// - Returns: `true` if self intersects input date, `false` otherwise public func intersects(_ other: DateTimeInterval) -> Bool { return contains(other.absStart) || contains(other.absEnd) || other.contains(absStart) || other.contains(absEnd) } /// Returns a DateTimeInterval that represents the interval where the given date interval and the current instance intersect. /// Note: if duration is less than zero (end date occurs earlier in time than the start date) are adjusted automatically. /// /// In the event that there is no intersection, the method returns nil. public func intersection(with dateInterval: DateTimeInterval) -> DateTimeInterval? { if !intersects(dateInterval) { return nil } if self == dateInterval { return self } let timeIntervalForSelfStart = absStart.timeIntervalSinceReferenceDate let timeIntervalForSelfEnd = absEnd.timeIntervalSinceReferenceDate let timeIntervalForGivenStart = dateInterval.absStart.timeIntervalSinceReferenceDate let timeIntervalForGivenEnd = dateInterval.absEnd.timeIntervalSinceReferenceDate let resultStartDate : Date if timeIntervalForGivenStart >= timeIntervalForSelfStart { resultStartDate = dateInterval.absStart } else { // self starts after given resultStartDate = absStart } let resultEndDate : Date if timeIntervalForGivenEnd >= timeIntervalForSelfEnd { resultEndDate = absEnd } else { // given ends before self resultEndDate = dateInterval.absEnd } return DateTimeInterval(start: resultStartDate, end: resultEndDate) } /// Returns `true` if `self` contains `date`. /// Note: if duration is less than zero (end date occurs earlier in time than the start date) are adjusted automatically. /// /// - Parameter date: date check /// - Returns: Boolean public func contains(_ date: Date) -> Bool { let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate let timeIntervalForSelfStart = absStart.timeIntervalSinceReferenceDate let timeIntervalforSelfEnd = absEnd.timeIntervalSinceReferenceDate if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) { return true } return false } /// Compare if two date intervals are equal. /// Note: Inverted date intervals with same duration are different. /// /// - Parameters: /// - lhs: left operand /// - rhs: right operand /// - Returns: Boolean public static func ==(lhs: DateTimeInterval, rhs: DateTimeInterval) -> Bool { return lhs.start == rhs.start && lhs.duration == rhs.duration } /// Compare if duration of the left operand is is smaller than duration of the right operand. /// Note: if duration is less than zero (end date occurs earlier in time than the start date) are adjusted automatically. /// /// - Parameters: /// - lhs: left operand /// - rhs: right operand /// - Returns: Boolean public static func <(lhs: DateTimeInterval, rhs: DateTimeInterval) -> Bool { return lhs.compare(rhs) == .orderedAscending } } extension DateTimeInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { return "(Start Date) \(start) + (Duration) \(duration) seconds = (End Date) \(end)" } public var debugDescription: String { return description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "start", value: start)) c.append((label: "end", value: end)) c.append((label: "duration", value: duration)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } }
37.421525
143
0.725345
1a2ca7afdd0dc4699aee3af0edb933775538adb8
752
// // String.swift // Wired // // Created by Rafael Warnault on 19/08/2019. // Copyright © 2019 Read-Write. All rights reserved. // import Foundation extension String { public var nullTerminated: Data? { if var data = self.data(using: String.Encoding.utf8) { data.append(0) return data } return nil } public func deletingPrefix(_ prefix: String) -> String { guard self.hasPrefix(prefix) else { return self } return String(self.dropFirst(prefix.count)) } public var isBlank: Bool { return allSatisfy({ $0.isWhitespace }) } } extension Optional where Wrapped == String { public var isBlank: Bool { return self?.isBlank ?? true } }
20.324324
62
0.609043
22a2f28b3bcca0c652b76e3d93e59dbd35138594
6,570
// // Geocoding.swift // SwiftLocation // // Created by danielemargutti on 28/10/2017. // Copyright © 2017 Daniele Margutti. All rights reserved. // import Foundation import CoreLocation import MapKit import Contacts import SwiftyJSON //MARK: Geocoder Google public final class Geocoder_Google: GeocoderRequest { /// session task private var task: JSONOperation? = nil public override func execute() { guard self.isFinished == false else { return } switch self.operation { case .getLocation(let a,_): self.execute_getLocation(a) case .getPlace(let l,_): self.execute_getPlace(l) } } /// Cancel any currently running task public override func cancel() { self.task?.cancel() super.cancel() } private func execute_getPlace(_ c: CLLocationCoordinate2D) { guard let APIKey = Locator.api.googleAPIKey else { self.failure?(LocationError.missingAPIKey(forService: "google")) return } let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(c.latitude),\(c.longitude)&key=\(APIKey)")! self.task = JSONOperation(url, timeout: self.timeout) self.task?.onFailure = { [weak self] err in guard let `self` = self else { return } self.failure?(err) self.isFinished = true } self.task?.onSuccess = { [weak self] json in guard let `self` = self else { return } let places = json["results"].arrayValue.map { Place(googleJSON: $0) } self.success?(places) self.isFinished = true } self.task?.execute() } private func execute_getLocation(_ address: String) { guard let APIKey = Locator.api.googleAPIKey else { self.failure?(LocationError.missingAPIKey(forService: "google")) return } let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(address.urlEncoded)&key=\(APIKey)")! self.task = JSONOperation(url, timeout: self.timeout) self.task?.onFailure = { [weak self] err in guard let `self` = self else { return } self.failure?(err) self.isFinished = true } self.task?.onSuccess = { [weak self] json in guard let `self` = self else { return } let places = json["results"].arrayValue.map { Place(googleJSON: $0) } self.success?(places) self.isFinished = true } self.task?.execute() } } //MARK: Geocoder OpenStreetMap public final class Geocoder_OpenStreet: GeocoderRequest { /// session task private var task: JSONOperation? = nil public override func execute() { guard self.isFinished == false else { return } switch self.operation { case .getLocation(let a,_): self.execute_getLocation(a) case .getPlace(let l,_): self.execute_getPlace(l) } } /// Cancel any currently running task public override func cancel() { self.task?.cancel() super.cancel() } private func execute_getPlace(_ coordinates: CLLocationCoordinate2D) { let url = URL(string:"https://nominatim.openstreetmap.org/reverse?format=json&lat=\(coordinates.latitude)&lon=\(coordinates.longitude)&addressdetails=1&limit=1")! self.task = JSONOperation(url, timeout: self.timeout) self.task?.onFailure = { [weak self] err in guard let `self` = self else { return } self.failure?(err) self.isFinished = true } self.task?.onSuccess = { [weak self] json in guard let `self` = self else { return } self.success?([self.parseResultPlace(json)]) self.isFinished = true } self.task?.execute() } private func execute_getLocation(_ address: String) { let fAddr = address.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! let url = URL(string:"https://nominatim.openstreetmap.org/search/\(fAddr)?format=json&addressdetails=1&limit=1")! self.task = JSONOperation(url, timeout: self.timeout) self.task?.onFailure = { [weak self] err in guard let `self` = self else { return } self.failure?(err) self.isFinished = true } self.task?.onSuccess = { [weak self] json in guard let `self` = self else { return } let places = json.arrayValue.map { self.parseResultPlace($0) } self.success?(places) self.isFinished = true } self.task?.execute() } private func parseResultPlace(_ json: JSON) -> Place { let place = Place() place.coordinates = CLLocationCoordinate2DMake(json["lat"].doubleValue, json["lon"].doubleValue) place.countryCode = json["address"]["country_code"].string place.country = json["address"]["country"].string place.administrativeArea = json["address"]["state"].string place.subAdministrativeArea = json["address"]["county"].string place.postalCode = json["address"]["postcode"].string place.city = json["address"]["city"].string place.locality = json["address"]["city_district"].string place.thoroughfare = json["address"]["road"].string place.subThoroughfare = json["address"]["house_number"].string place.name = json["display_name"].string place.rawDictionary = json.dictionaryObject return place } } //MARK: Geocoder Apple public final class Geocoder_Apple: GeocoderRequest { /// Task private var task: CLGeocoder? public override func execute() { guard self.isFinished == false else { return } let geocoder = CLGeocoder() self.task = geocoder let geocodeCompletionHandler: CoreLocation.CLGeocodeCompletionHandler = { [weak self] (placemarks, error) in if let err = error { self?.failure?(LocationError.other(err.localizedDescription)) self?.isFinished = true return } let place = Place.load(placemarks: placemarks ?? []) self?.success?(place) self?.isFinished = true } switch self.operation { case .getLocation(let address, let region): geocoder.geocodeAddressString(address, in: region, completionHandler: geocodeCompletionHandler) case .getPlace(let coordinates, let locale): let loc = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude) if #available(iOS 11, *) { geocoder.reverseGeocodeLocation(loc, preferredLocale: locale, completionHandler: geocodeCompletionHandler) } else { // Fallback on earlier versions geocoder.reverseGeocodeLocation(loc, completionHandler: geocodeCompletionHandler) } } } public override func cancel() { self.task?.cancelGeocode() super.cancel() } public func onSuccess(_ success: @escaping GeocoderRequest_Success) -> Self { self.success = success return self } public func onFailure(_ failure: @escaping GeocoderRequest_Failure) -> Self { self.failure = failure return self } }
30.84507
165
0.695282
89f317090025ccc2dd66025be27208028e7da231
20,572
// // Created by Marko Justinek on 11/4/20. // Copyright © 2020 Marko Justinek. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import XCTest @testable import PactSwift class PactBuilderTests: XCTestCase { // MARK: - EqualTo() func testPact_SetsMatcher_EqualTo() throws { let testBody: Any = [ "data": Matcher.EqualTo("2016-07-19") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.match, "equality") } // MARK: - SomethingLike() func testPact_SetsMatcher_SomethingLike() throws { let testBody: Any = [ "data": Matcher.SomethingLike("2016-07-19") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.match, "type") } // MARK: - EachLike() func testPact_SetsDefaultMin_EachLikeMatcher() throws { let testBody: Any = [ "data": [ "array1": Matcher.EachLike( [ "dob": Matcher.SomethingLike("2016-07-19"), "id": Matcher.SomethingLike("1600309982"), "name": Matcher.SomethingLike("FVsWAGZTFGPLhWjLuBOd") ] ) ] ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(SetLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.min, 1) XCTAssertEqual(testResult.match, "type") } func testPact_SetsProvidedMin_ForEachLikeMatcher() throws { let testBody: Any = [ "data": [ "array1": Matcher.EachLike( [ "dob": Matcher.SomethingLike("2016-07-19"), "id": Matcher.SomethingLike("1600309982"), "name": Matcher.SomethingLike("FVsWAGZTFGPLhWjLuBOd") ] , min: 3 ) ] ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(SetLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.min, 3) XCTAssertEqual(testResult.match, "type") } func testPact_SetsProvidedMax_ForEachLikeMatcher() throws { let testBody: Any = [ "data": [ "array1": Matcher.EachLike( [ "dob": Matcher.SomethingLike("2016-07-19"), "id": Matcher.SomethingLike("1600309982"), "name": Matcher.SomethingLike("FVsWAGZTFGPLhWjLuBOd") ] , max: 5 ) ] ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(SetLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.max, 5) XCTAssertEqual(testResult.match, "type") } func testPact_SetsMinMax_ForEachLikeMatcher() throws { let testBody: Any = [ "data": [ "array1": Matcher.EachLike( [ "dob": Matcher.SomethingLike("2016-07-19"), "id": Matcher.SomethingLike("1600309982"), "name": Matcher.SomethingLike("FVsWAGZTFGPLhWjLuBOd") ], min: 1, max: 5 ) ] ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(SetLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.min, 1) XCTAssertEqual(testResult.max, 5) XCTAssertEqual(testResult.match, "type") } // MARK: - IntegerLike() func testPact_SetsMatcher_IntegerLike() throws { let testBody: Any = [ "data": Matcher.IntegerLike(1234) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.match, "integer") } // MARK: - DecimalLike() func testPact_SetsMatcher_DecimalLike() throws { let testBody: Any = [ "data": Matcher.DecimalLike(1234) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node.matchers.first) XCTAssertEqual(testResult.match, "decimal") } // MARK: - RegexLike() func testPact_SetsMatcher_RegexLike() throws { let testBody: Any = [ "data": Matcher.RegexLike(value: "2020-12-31", pattern: "\\d{4}-\\d{2}-\\d{2}") ] let testPact = prepareTestPact(responseBody: testBody) let matchers = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node) XCTAssertEqual(matchers.matchers.first?.match, "regex") XCTAssertEqual(matchers.matchers.first?.regex, "\\d{4}-\\d{2}-\\d{2}") XCTAssertNil(matchers.combine) } func testPact_FailsMatcher_InvalidRegex() { let interaction = Interaction( description: "test Encodable Pact", providerStates: [ ProviderState( description: "an alligator with the given name exists", params: ["name": "Mary"] ) ] ) .withRequest(method: .GET, path: "/") .willRespondWith( status: 200, headers: ["Content-Type": "application/json; charset=UTF-8", "X-Value": "testCode"], body: ["data": Matcher.RegexLike(value: "foo", pattern: #"\{3}-\w+$"#)] ) do { _ = try PactBuilder(with: interaction, for: .body).encoded() XCTFail("Expecting to fail encoding when Regex matcher's value doesn't match the pattern") } catch { if case .encodingFailure(let message) = error as? EncodingError { XCTAssertTrue(String(describing: message).contains(#"Value \"foo\" does not match the pattern \"\\{3}-\\w+$\""#), "Unexpected error message: \"\(String(describing: message))\"") } else { XCTFail("Expecting an Encoding error!") } } } // MARK: - IncludesLike() func testPact_SetsMatcher_IncludesLike_DefaultsToAND() throws { let expectedValues = ["2020-12-31", "2019-12-31"] let testBody: Any = [ "data": Matcher.IncludesLike("2020-12-31", "2019-12-31") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node) XCTAssertEqual(testResult.combine, "AND") XCTAssertEqual(testResult.matchers.count, 2) XCTAssertTrue(testResult.matchers.allSatisfy { expectedValues.contains($0.value ?? "FAIL!") }) XCTAssertTrue(testResult.matchers.allSatisfy { $0.match == "include" }) } func testPact_SetsMatcher_IncludesLike_CombineMatchersWithOR() throws { let expectedValues = ["2020-12-31", "2019-12-31"] let testBody: Any = [ "data": Matcher.IncludesLike("2020-12-31", "2019-12-31", combine: .OR) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericLikeTestModel.self, from: testPact.data!).interactions.first?.response.matchingRules.body.node) XCTAssertEqual(testResult.combine, "OR") XCTAssertEqual(testResult.matchers.count, 2) XCTAssertTrue(testResult.matchers.allSatisfy { expectedValues.contains($0.value ?? "FAIL!") }) XCTAssertTrue(testResult.matchers.allSatisfy { $0.match == "include" }) } // MARK: - Example generators func testPact_SetsExampleGenerator_RandomBool() throws { let testBody: Any = [ "data": ExampleGenerator.RandomBool() ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "RandomBoolean") } func testPact_SetsExampleGenerator_RandomDate() throws { let testBody: Any = [ "data": ExampleGenerator.RandomDate(format: "dd-MM-yyyy") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "Date") XCTAssertEqual(testResult.format, "dd-MM-yyyy") } func testPact_SetsExampleGenerator_RandomDateTime() throws { let testBody: Any = [ "data": ExampleGenerator.RandomDate(format: "dd-MM-yyyy"), "foo": ExampleGenerator.RandomDateTime(format: "HH:mm (dd/MM)") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body) XCTAssertEqual(testResult.node.type, "Date") XCTAssertEqual(testResult.node.format, "dd-MM-yyyy") XCTAssertEqual(testResult.foo?.type, "DateTime") XCTAssertEqual(testResult.foo?.format, "HH:mm (dd/MM)") } func testPact_SetsExampleGenerator_RandomDecimal() throws { let testBody: Any = [ "data": ExampleGenerator.RandomDecimal(digits: 5) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "RandomDecimal") XCTAssertEqual(testResult.digits, 5) } func testPact_SetsExampleGenerator_RandomHexadecimal() throws { let testBody: Any = [ "data": ExampleGenerator.RandomHexadecimal(digits: 16) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "RandomHexadecimal") XCTAssertEqual(testResult.digits, 16) } func testPact_SetsExampleGenerator_RandomInt() throws { let testBody: Any = [ "data": ExampleGenerator.RandomInt(min: 2, max: 16) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "RandomInt") XCTAssertEqual(testResult.min, 2) XCTAssertEqual(testResult.max, 16) } func testPact_SetsExampleGenerator_RandomString() throws { let testBody: Any = [ "data": ExampleGenerator.RandomString(size: 32), "foo": ExampleGenerator.RandomString(regex: #"\d{3}"#) ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body) XCTAssertEqual(testResult.node.type, "RandomString") XCTAssertEqual(testResult.node.size, 32) XCTAssertEqual(testResult.foo?.type, "Regex") XCTAssertEqual(testResult.foo?.regex, "\\d{3}") } func testPact_SetsExampleGenerator_RandomTime() throws { let testBody: Any = [ "data": ExampleGenerator.RandomTime(format: "hh - mm") ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "Time") XCTAssertEqual(testResult.format, "hh - mm") } func testPact_SetsExampleGenerator_RandomUUID() throws { let testBody: Any = [ "data": ExampleGenerator.RandomUUID() ] let testPact = prepareTestPact(responseBody: testBody) let testResult = try XCTUnwrap(try JSONDecoder().decode(GenericExampleGeneratorTestModel.self, from: testPact.data!).interactions.first?.response.generators.body.node) XCTAssertEqual(testResult.type, "Uuid") } // MARK: - Testing parsing for headers func testPact_ProcessesMatchers_InHeaders() throws { let testHeaders: Any = [ "foo": Matcher.SomethingLike("bar"), "bar": ExampleGenerator.RandomBool(), ] let testBody: Any = [ "foo": Matcher.SomethingLike("baz"), ] let testPact = prepareTestPact(requestBody: testBody, requestHeaders: testHeaders) let testResult = try XCTUnwrap(try JSONDecoder().decode(SomethingLikeTestModel.self, from: testPact.data!).interactions.first?.request) XCTAssertEqual(testResult.matchingRules.header?.foo.matchers.first?.match, "type") XCTAssertEqual(testResult.generators?.header.bar.type, "RandomBoolean") XCTAssertEqual(testResult.matchingRules.body?.foo?.matchers.first?.match, "type") } // MARK: - Testing parsing for path func testPact_ProcessesMatcher_InRequestPath() throws { let path = Matcher.RegexLike(value: "/some/1234", pattern: #"^/some/\d{4}+$"#) let testHeaders: Any = [ "foo": Matcher.SomethingLike("bar"), "bar": ExampleGenerator.RandomBool(), ] let testBody: Any = [ "foo": Matcher.SomethingLike("baz"), ] let testPact = prepareTestPact(path: path, requestBody: testBody, requestHeaders: testHeaders) let testResult = try XCTUnwrap(try JSONDecoder().decode(SomethingLikeTestModel.self, from: testPact.data!).interactions.first?.request.matchingRules.path?.matchers.first) XCTAssertEqual(testResult.match, "regex") XCTAssertEqual(testResult.regex, #"^/some/\d{4}+$"#) } } // MARK: - Private Utils - private extension PactBuilderTests { // This test model is tightly coupled with the SomethingLike Matcher for the purpouse of these tests struct GenericLikeTestModel: Decodable { let interactions: [TestInteractionModel] struct TestInteractionModel: Decodable { let response: TestResponseModel struct TestResponseModel: Decodable { let matchingRules: TestMatchingRulesModel struct TestMatchingRulesModel: Decodable { let body: TestNodeModel struct TestNodeModel: Decodable { let node: TestMatchersModel let foo: TestMatchersModel? let bar: TestMatchersModel? enum CodingKeys: String, CodingKey { case node = "$.data" case foo = "$.foo" case bar = "$.bar" } struct TestMatchersModel: Decodable { let matchers: [TestTypeModel] let combine: String? struct TestTypeModel: Decodable { let match: String let regex: String? let value: String? let min: Int? let max: Int? } } } } } } } // This test model is tightly coupled with the ExampleGenerator for the purpose of these tests struct GenericExampleGeneratorTestModel: Decodable { let interactions: [TestInteractionModel] struct TestInteractionModel: Decodable { let response: TestResponseModel struct TestResponseModel: Decodable { let generators: TestGeneratorModel struct TestGeneratorModel: Decodable { let body: TestNodeModel struct TestNodeModel: Decodable { let node: TestAttributesModel let foo: TestAttributesModel? let bar: TestAttributesModel? enum CodingKeys: String, CodingKey { case node = "$.data" case foo = "$.foo" case bar = "$.bar" } struct TestAttributesModel: Decodable { let type: String let min: Int? let max: Int? let digits: Int? let size: Int? let regex: String? let format: String? } } } } } } // This test model is tightly coupled with the EachLike Matcher for the purpouse of these tests struct SetLikeTestModel: Decodable { let interactions: [TestInteractionModel] struct TestInteractionModel: Decodable { let response: TestRequestModel struct TestRequestModel: Decodable { let matchingRules: TestMatchingRulesModel struct TestMatchingRulesModel: Decodable { let body: TestNodeModel struct TestNodeModel: Decodable { let node: TestMatchersModel enum CodingKeys: String, CodingKey { case node = "$.data.array1" } struct TestMatchersModel: Decodable { let matchers: [TestMinModel] struct TestMinModel: Decodable { let min: Int? let max: Int? let match: String } } } } } } } // This test model is tightly coupled with the Pact that includes matchers in request body struct SomethingLikeTestModel: Decodable { let interactions: [TestInteractionModel] struct TestInteractionModel: Decodable { let request: TestResponseModel struct TestResponseModel: Decodable { let matchingRules: TestMatchingRulesModel let generators: TestGeneratorsModel? struct TestMatchingRulesModel: Decodable { let body: TestBodyModel? let header: TestHeadersModel? let path: TestPathModel? struct TestBodyModel: Decodable { let foo: TestMatchersModel? let bar: TestMatchersModel? enum CodingKeys: String, CodingKey { case foo = "$.foo" case bar = "$.bar" } struct TestMatchersModel: Decodable { let matchers: [TestTypeModel] let combine: String? struct TestTypeModel: Decodable { let match: String let regex: String? let value: String? let min: Int? let max: Int? } } } struct TestHeadersModel: Decodable { let foo: TestMatchersModel let bar: TestMatchersModel? struct TestMatchersModel: Decodable { let matchers: [TestTypeModel] let combine: String? struct TestTypeModel: Decodable { let match: String let regex: String? let value: String? let min: Int? let max: Int? } } } struct TestPathModel: Decodable { let matchers: [TestTypeModel] let combine: String? struct TestTypeModel: Decodable { let match: String let regex: String } } } struct TestGeneratorsModel: Decodable { let header: TestHeaderModel struct TestHeaderModel: Decodable { let bar: TestAttributesModel struct TestAttributesModel: Decodable { let type: String let min: Int? let max: Int? let digits: Int? let size: Int? let regex: String? let format: String? } } } } } } func prepareTestPact(responseBody: Any) -> Pact { let firstProviderState = ProviderState(description: "an alligator with the given name exists", params: ["name": "Mary"]) let interaction = Interaction(description: "test Encodable Pact", providerStates: [firstProviderState]) .withRequest(method: .GET, path: "/") .willRespondWith( status: 200, headers: ["Content-Type": "application/json; charset=UTF-8", "X-Value": "testCode"], body: responseBody ) return Pact( consumer: Pacticipant.consumer("test-consumer"), provider: Pacticipant.provider("test-provider"), interactions: [interaction] ) } func prepareTestPact(path: PactPathParameter = "/", requestBody: Any, requestHeaders: Any?) -> Pact { let firstProviderState = ProviderState(description: "an alligator with the given name exists", params: ["name": "Mary"]) let headers: [String: Any]? = requestHeaders != nil ? (requestHeaders as! [String : Any]) : nil let interaction = Interaction(description: "test Encodable Pact", providerStates: [firstProviderState]) .withRequest( method: .GET, path: path, headers: headers, body: requestBody ) .willRespondWith( status: 200 ) return Pact( consumer: Pacticipant.consumer("test-consumer"), provider: Pacticipant.provider("test-provider"), interactions: [interaction] ) } }
33.450407
181
0.710918
d508fccdc53a819963b0c5f9e68e6abaf6df971b
3,943
// The MIT License (MIT) // // Copyright (c) Copyright © 2016 Cayugasoft Technologies // // 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(iOS) import UIKit import FreestylerCore public extension UITabBar { /** Updates `barStyle` property of `UITabBar` instance. */ public static func style(barStyle: UIBarStyle) -> Style { return Style("Bar Style \(barStyle)") { (styleable: UITabBar) in styleable.barStyle = barStyle } } /** Updates `isTranslucent` property of `UITabBar` instance. */ public static func style(isTranslucent: Bool) -> Style { return Style("Is Translucent \(isTranslucent)") { (styleable: UITabBar) in styleable.isTranslucent = isTranslucent } } /** Updates `barTintColor` property of `UITabBar` instance. */ public static func style(barTintColor: Color?) -> Style { return Style("Bar Tint Color \(barTintColor)") { (styleable: UITabBar) in styleable.barTintColor = barTintColor?.color } } /** Updates `itemPositioning` property of `UITabBar` instance. */ public static func style(itemPositioning: UITabBarItemPositioning) -> Style { return Style("Item Positioning \(itemPositioning)") { (styleable: UITabBar) in styleable.itemPositioning = itemPositioning } } /** Updates `itemSpacing` property of `UITabBar` instance. */ public static func style(itemSpacing: CGFloat) -> Style { return Style("Item Spacing \(itemSpacing)") { (styleable: UITabBar) in styleable.itemSpacing = itemSpacing } } /** Updates `itemWidth` property of `UITabBar` instance. */ public static func style(itemWidth: CGFloat) -> Style { return Style("Item Width \(itemWidth)") { (styleable: UITabBar) in styleable.itemWidth = itemWidth } } /** Updates `backgroundImage` property of `UITabBar` instance. */ public static func style(backgroundImage: UIImage?) -> Style { return Style("Background Image \(backgroundImage)") { (styleable: UITabBar) in styleable.backgroundImage = backgroundImage } } /** Updates `shadowImage` property of `UITabBar` instance. */ public static func style(shadowImage: UIImage?) -> Style { return Style("Shadow Image \(shadowImage)") { (styleable: UITabBar) in styleable.shadowImage = shadowImage } } /** Updates `selectionIndicatorImage` property of `UITabBar` instance. */ public static func style(selectionIndicatorImage: UIImage?) -> Style { return Style("Selection Indicator Image \(selectionIndicatorImage)") { (styleable: UITabBar) in styleable.selectionIndicatorImage = selectionIndicatorImage } } } #endif
38.281553
81
0.664215
62f0f7d57f8ee307aa1737df2a24f86f1d7bf1b3
841
// // WeatherDetailViewController.swift // WeatherApp // // Created by Jack Wong on 10/10/19. // Copyright © 2019 David Rifkin. All rights reserved. // import UIKit class WeatherDetailViewController: UIViewController { var chosenForecast: Forecast! var locationName: String! var imageView: Image! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
23.361111
107
0.648038
7aa4ab10120f32c962a7b52d96c659b4f5c63387
4,469
/******************************************************************************* * MySearchBar.swift * * BindingExample - BindKit Copyright (c) 2018; Electric Bolt Limited. * ******************************************************************************/ import Foundation let MySearchBarText = "text" /** Demonstrates creating a `custom` dynamic subclass of a view in Swift. You can augment any view with binding capabilities that isn't already supported by BindKit. */ class MySearchBar: UISearchBar { fileprivate static var multicastContext = "multicastContext" fileprivate static var searchBarDelegateContext = "searchBarDelegateContext" override func viewDidBindWithModel() { // UIView subclasses can't have a delegate pointing to itself, instead // we need to create another object to be the delegate. let searchBarDelegate = MySearchBarDelegate(self) // With dynamic subclasses you can't use instance variables, instead // we must use associated objects to store any state. objc_setAssociatedObject(self, &MySearchBar.searchBarDelegateContext, searchBarDelegate, .OBJC_ASSOCIATION_RETAIN) // Remember if the delegate was set before we were dynamically subclassed. let previousDelegate = super.delegate // EBKMulticastDelegate can be used when the only way to be notified // of changes to a view is through a delegate. let multicast = EBKMulticastDelegate() objc_setAssociatedObject(self, &MySearchBar.multicastContext, multicast as EBKMulticastDelegate?, .OBJC_ASSOCIATION_RETAIN) super.delegate = unsafeBitCast(multicast, to: UISearchBarDelegate.self) multicast.primaryDelegate = searchBarDelegate // Restore the any previous delegate that may have been set. if previousDelegate != nil { multicast.secondaryDelegate = previousDelegate } } override var delegate: UISearchBarDelegate? { set { // Set updates the EBKMulticastDelegate.secondaryDelegate property let multicast = objc_getAssociatedObject(self, &MySearchBar.multicastContext) as! EBKMulticastDelegate? multicast!.secondaryDelegate = newValue } get { // Get always return the EBKMulticastDelegate instance return (objc_getAssociatedObject(self, &MySearchBar.multicastContext) as! UISearchBarDelegate) } } override func bindableProperties() -> [String:String] { return [MySearchBarText: "NSString"] } override var text: String? { set { // BindKit suggests that you don't set properties if the value // hasn't changed. if self.text != newValue { super.text = newValue } let v = boundValue(viewKey: MySearchBarText) if v is NSNull { if newValue != nil { setBoundValue(nil, viewKey: MySearchBarText) } } else if v is String { if newValue != (v as! String) { setBoundValue(newValue as NSObject?, viewKey: MySearchBarText) } } } get { return self.text } } override func updateViewFromBoundModel() { // BindKit suggests that you don't set properties if the value // hasn't changed. let v = boundValue(viewKey: MySearchBarText) if v is NSNull { if super.text != nil { super.text = nil } } else if v is String { if super.text != (v as! String) { super.text = (v as! String) } } } } class MySearchBarDelegate: NSObject, UISearchBarDelegate { var searchBar: MySearchBar init(_ searchBar: MySearchBar) { self.searchBar = searchBar super.init() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let v = searchBar.boundValue(viewKey: MySearchBarText) if v is String { if (v as! String) != searchText { searchBar.setBoundValue(searchText as NSObject?, viewKey: MySearchBarText) } } } } extension UISearchBar { override open func EBKDynamicSubclass() -> AnyClass? { return MySearchBar.self } }
34.914063
131
0.599239
298a3c79f578c6aef3764e373166bb5fed81b920
704
// // MotorTankTime.swift // Robot // // Created by Luke Van In on 2021/01/11. // import Foundation public struct MoveTankTime: IRequest { public static let name = "scratch.move_tank_time" public var time: Int public var lspeed: Int public var rspeed: Int public var lmotor: MotorPort public var rmotor: MotorPort public var stop: Int public init( time: Int, lspeed: Int, rspeed: Int, lmotor: MotorPort, rmotor: MotorPort, stop: Int = 1 ) { self.time = time self.lspeed = lspeed self.rspeed = rspeed self.lmotor = lmotor self.rmotor = rmotor self.stop = stop } }
20.705882
53
0.590909
0351ce3c5d91136078d47e18296863e0ece5710e
9,150
// // NetworkServiceTests.swift // HyperspaceTests // // Created by Tyler Milner on 6/29/17. // Copyright © 2017 Bottle Rocket Studios. All rights reserved. // import XCTest @testable import Hyperspace class NetworkServiceTests: XCTestCase { // MARK: - Properties private let defaultRequest = URLRequest(url: RequestTestDefaults.defaultURL) // MARK: - Tests func test_MissingURLResponse_GeneratesUnknownError() { let expectedResult = NetworkServiceFailure(error: .unknownError, response: nil) executeNetworkServiceUsingMockHTTPResponse(nil, expectingResult: .failure(expectedResult)) } func test_InvalidStatusCode_GeneratesUnknownStatusCodeError() { let response = HTTP.Response(code: 0, data: nil, headers: [:]) let expectedResult = NetworkServiceFailure(error: .unknownStatusCode, response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .failure(expectedResult)) } func test_SuccessResponseWithNoData_GeneratesNoDataError() { let response = HTTP.Response(code: 200, data: nil, headers: [:]) let expectedResult = NetworkServiceFailure(error: .noData, response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .failure(expectedResult)) } func test_SuccessResponseWithData_Succeeds() { let responseData = "test".data(using: .utf8)! let response = HTTP.Response(code: 200, data: responseData, headers: [:]) let expectedResult = NetworkServiceSuccess(data: responseData, response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .success(expectedResult)) } func test_300Status_GeneratesRedirectionError() { let response = HTTP.Response(code: 300, data: nil, headers: [:]) let expectedResult = NetworkServiceFailure(error: .redirection, response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .failure(expectedResult)) } func test_400Status_GeneratesClientError() { let response = HTTP.Response(code: 400, data: nil, headers: [:]) let expectedResult = NetworkServiceFailure(error: .clientError(.badRequest), response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .failure(expectedResult)) } func test_500Status_GeneratesServerError() { let response = HTTP.Response(code: 500, data: nil, headers: [:]) let expectedResult = NetworkServiceFailure(error: .serverError(.internalServerError), response: response) executeNetworkServiceUsingMockHTTPResponse(response, expectingResult: .failure(expectedResult)) } func test_NoInternet_GeneratesNoInternetError() { let connectionError = NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo: nil) let expectedResult = NetworkServiceFailure(error: .noInternetConnection, response: nil) executeNetworkServiceUsingMockHTTPResponse(nil, mockError: connectionError, expectingResult: .failure(expectedResult)) } func test_RequestTimeout_GeneratesTimeoutError() { let timeoutError = NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil) let expectedResult = NetworkServiceFailure(error: .timedOut, response: nil) executeNetworkServiceUsingMockHTTPResponse(nil, mockError: timeoutError, expectingResult: .failure(expectedResult)) } func test_CancellingRequest_GeneratesCancellationError() { let cancellationError = NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil) let expectedResult = NetworkServiceFailure(error: .cancelled, response: nil) executeNetworkServiceUsingMockHTTPResponse(nil, mockError: cancellationError, expectingResult: .failure(expectedResult)) } func test_ExecutingNetworkService_ExecutesDataTask() { let dataTask = MockNetworkSessionDataTask(request: defaultRequest) _ = execute(dataTask: dataTask) XCTAssertEqual(dataTask.resumeCallCount, 1) } func test_CancellingNetworkService_CancelsDataTask() { let dataTask = MockNetworkSessionDataTask(request: defaultRequest) let service = execute(dataTask: dataTask) service.cancelTask(for: defaultRequest) XCTAssertEqual(dataTask.cancelCallCount, 1) } func test_NetworkServiceDeinit_CancelsDataTask() { let dataTask = MockNetworkSessionDataTask(request: URLRequest(url: RequestTestDefaults.defaultURL)) let asyncExpectation = expectation(description: "\(NetworkService.self) falls out of scope") var service: NetworkServiceProtocol? = execute(dataTask: dataTask) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { XCTAssertNil(service) // To silence the "variable was written to, but never read" warning. See https://stackoverflow.com/a/32861678/4343618 XCTAssertEqual(dataTask.cancelCallCount, 1) asyncExpectation.fulfill() } service = nil waitForExpectations(timeout: 1.0, handler: nil) } func test_NetworkService_ConvenienceInit() { let networkService = NetworkServiceMockSubclass(session: URLSession.shared, networkActivityIndicatable: MockNetworkActivityIndicator()) XCTAssert(networkService.initWithNetworkActivityControllerCalled) } func test_NetworkServiceHelper_InvalidHTTPResponsErrorUnknownError() { let networkServiceFailure = NetworkServiceHelper.networkServiceFailure(for: NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil)) XCTAssert(networkServiceFailure.error == .unknownError) } func test_NetworkServiceError_Equality() { XCTAssertEqual(NetworkServiceError.unknownError, NetworkServiceError.unknownError) XCTAssertEqual(NetworkServiceError.unknownStatusCode, NetworkServiceError.unknownStatusCode) XCTAssertEqual(NetworkServiceError.redirection, NetworkServiceError.redirection) XCTAssertEqual(NetworkServiceError.redirection, NetworkServiceError.redirection) XCTAssertEqual(NetworkServiceError.clientError(.unauthorized), NetworkServiceError.clientError(.unauthorized)) XCTAssertEqual(NetworkServiceError.serverError(.badGateway), NetworkServiceError.serverError(.badGateway)) XCTAssertEqual(NetworkServiceError.noInternetConnection, NetworkServiceError.noInternetConnection) XCTAssertEqual(NetworkServiceError.timedOut, NetworkServiceError.timedOut) XCTAssertEqual(NetworkServiceError.cancelled, NetworkServiceError.cancelled) XCTAssertNotEqual(NetworkServiceError.redirection, NetworkServiceError.cancelled) } func test_AnyError_NeverHasResponse() { let error = AnyError(networkServiceFailure: NetworkServiceFailure(error: .cancelled, response: HTTP.Response(code: 1, data: nil))) XCTAssertNil(error.failureResponse) } // MARK: - Private private func execute(dataTask: NetworkSessionDataTask) -> NetworkServiceProtocol { let mockSession = MockNetworkSession(responseStatusCode: nil, responseData: nil, error: nil) mockSession.nextDataTask = dataTask let service = NetworkService(session: mockSession) service.execute(request: defaultRequest) { (_) in } return service } private func executeNetworkServiceUsingMockHTTPResponse(_ mockHTTPResponse: HTTP.Response?, mockError: Error? = nil, expectingResult expectedResult: Result<NetworkServiceSuccess, NetworkServiceFailure>, file: StaticString = #file, line: UInt = #line) { let mockSession = MockNetworkSession(responseStatusCode: mockHTTPResponse?.code, responseData: mockHTTPResponse?.data, error: mockError) executeNetworkService(using: mockSession, expectingResult: expectedResult, file: file, line: line) } private func executeNetworkService(using session: NetworkSession, expectingResult expectedResult: Result<NetworkServiceSuccess, NetworkServiceFailure>, file: StaticString = #file, line: UInt = #line) { let service = NetworkService(session: session) let asyncExpectation = expectation(description: "\(NetworkService.self) completion") service.execute(request: defaultRequest) { result in XCTAssertTrue(result == expectedResult, "Result '\(result)' did not equal expected result '\(expectedResult)'", file: file, line: line) asyncExpectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } }
48.670213
205
0.706448
23167aec7905442e6d25307cf42c6a25f316f619
289
// // MarkdownHeader+UIKit.swift // MarkdownKit // // Created by Bruno Oliveira on 31/01/2019. // Copyright © 2019 Ivan Bruel. All rights reserved. // import AppKit public extension MarkdownHeader { static let defaultFont = NSFont.boldSystemFont(ofSize: NSFont.systemFontSize) }
20.642857
81
0.737024
b9c567fdbdb143606dc01bb47a7169c0479d6330
199
// // Empty.swift // Networking // // Created by new user on 24.01.2020. // Copyright © 2020 Vasyl Khmil. All rights reserved. // import Foundation public struct Empty: Decodable { }
13.266667
54
0.643216
288ae2a40eceb1d966e504c66d7280789318a4d7
2,448
// // HierarchyBuilder.swift // LayoutInspectorExample // // Created by Igor Savynskyi on 12/26/18. // Copyright © 2018 Ihor Savynskyi. All rights reserved. // import UIKit protocol HierarchyBuilderProtocol { func captureHierarchy() -> ViewDescriptionProtocol? } class HierarchyBuilder: HierarchyBuilderProtocol { func captureHierarchy() -> ViewDescriptionProtocol? { guard let firstWindow = UIApplication.shared.windows.first else { return nil } return buildHierarchy(view: firstWindow) } } // MARK: Private API private extension HierarchyBuilder { func buildHierarchy(view: UIView) -> ViewDescriptionProtocol { let children = view.subviews.map { buildHierarchy(view: $0) } let viewsToHide = view.subviews.filter { $0.isHidden == false } // don't capture visible subviews for current view snapshot viewsToHide.forEach { $0.isHidden = true } let isTransparent = isViewTransparent(view) let image = isTransparent ? nil : view.asImage() // hidden subviews rollback viewsToHide.forEach { $0.isHidden = false } return ViewDescription(frame: view.frame, snapshot: image, subviews: children, parentSize: view.superview?.frame.size, center: view.center, isHidden: view.isHidden, isTransparent: isTransparent, className: String(describing: type(of: view)), isUserInteractionEnabled: view.isUserInteractionEnabled, alpha: Float(view.alpha), backgroundColor: view.backgroundColor, tint: view.tintColor, clipToBounds: view.clipsToBounds) } func isViewTransparent(_ view: UIView) -> Bool { let isTransparent: Bool if view.isKind(of: UIImageView.self) || view.isKind(of: UILabel.self) || view.isKind(of: UITextView.self) { isTransparent = false } else if view.backgroundColor == .clear || view.alpha == 0 || view.backgroundColor?.alphaValue == 0 || view.backgroundColor == nil { isTransparent = true } else { isTransparent = false } return isTransparent } }
39.483871
141
0.582925
9006f1288cf91fcaaf63ac4124656a73b3416559
2,767
// // JwtSignerTests.swift // TwilioVerifyTests // // Copyright © 2020 Twilio. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import TwilioVerifySDK // swiftlint:disable force_cast class JwtSignerTests: XCTestCase { var keyStorage: KeyStorageMock! var jwtSigner: JwtSigner! override func setUpWithError() throws { try super.setUpWithError() keyStorage = KeyStorageMock() jwtSigner = JwtSigner(withKeyStorage: keyStorage) } func testSign_withDERSignature_shouldReturnConcatFormat() { var signerTemplate: SignerTemplate! XCTAssertNoThrow(signerTemplate = try ECP256SignerTemplate(withAlias: Constants.alias, shouldExist: true), "Signer template should not throw") keyStorage.signResult = Data(base64Encoded: Constants.derSignature) var signature: Data! XCTAssertNoThrow(signature = try jwtSigner.sign(message: Constants.message, withSignerTemplate: signerTemplate), "Sign should not throw") XCTAssertEqual(Constants.concatSignature, signature.base64EncodedString()) } func testSign_withInvalidDERSignature_shouldThrow() { var signerTemplate: SignerTemplate! XCTAssertNoThrow(signerTemplate = try ECP256SignerTemplate(withAlias: Constants.alias, shouldExist: true), "Signer template should not throw") var bytes = [UInt8](repeating: 0, count: 1) _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) keyStorage.signResult = Data(bytes) XCTAssertThrowsError(try jwtSigner.sign(message: Constants.message, withSignerTemplate: signerTemplate), "Sign should not throw") { error in XCTAssertEqual((error as! JwtSignerError), JwtSignerError.invalidFormat) } } } private extension JwtSignerTests { struct Constants { static let alias = "alias" static let message = "message" static let derSignature = "MEQCIFtun9Ioo+W+juCG7sOl8PPPuozb8cspsUtpu2TxnzP/AiAi1VpFNTr2eK+VX3b1DLHy8rPm3MOpTvUH14hyNr0Gfg==" static let concatSignature = "W26f0iij5b6O4Ibuw6Xw88+6jNvxyymxS2m7ZPGfM/8i1VpFNTr2eK+VX3b1DLHy8rPm3MOpTvUH14hyNr0Gfg==" } }
40.691176
128
0.716661
4640df07a3d9c8a9895d47250c3fd78dce72595c
8,949
/// Copyright (c) 2017 David Moeller /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import WatchConnectivity public enum RelayError: Error { case moduleIdentNotFound case messageIdentNotFound case noMessageTypeMatchFor(messageIdent: String) case receiverNotFound } open class Relay: NSObject { /// Last initiated Relay public static var shared: Relay? { didSet { debugLog(RelayKitLogCategory.configuration, ["Setting", type(of: shared), "as Relay with", type(of: shared?.core), "."]) } } internal var core: RelayCore internal var sender: [String: (Sender, [Message.Type])] = [:] internal var receiver: [String: (Receiver, [Message.Type])] = [:] public var errorHandler: ((Error) -> Void)? = nil public init(core: RelayCore) { self.core = core super.init() // Attach the receiving end of the core to the receivers self.core.didReceiveMessage = { [weak self] data, method, replyHandler in // Check for the Module Indent do { debugLog(.messageContent, ["Received Message Data", data]) guard let moduleIdent = data["moduleIdent"] as? String else { throw RelayError.moduleIdentNotFound } // Check for the receiver guard let (receiver, messageTypes) = self?.receiver[moduleIdent] else { throw RelayError.receiverNotFound } // Check for the Message Ident guard let messageIdent = data["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Get the appropriate Message Type guard let messageType = messageTypes.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let message = try messageType.decode(data) debugLog(.messages, ["Received", messageType, "with", method]) if let replyHandler = replyHandler { receiver.didReceiveMessage(message, method, { replyMessage in var encodedData = replyMessage.encode() encodedData["moduleIdent"] = moduleIdent encodedData["messageIdent"] = type(of: replyMessage).messageIdent replyHandler(encodedData) }) } else { receiver.didReceiveMessage(message, method, nil) } } catch { debugLog(.messages, ["Receiving message failed with", error, "by", method]) self?.errorHandler?(error) } } Relay.shared = self } /// Try to activate WC Session if it was not successful on init public func activateWCSession() -> Bool { return self.core.activateWCSession() } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: Message.Type ...) { self.register(sender, with: messages) } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: [Message.Type]) { self.sender[sender.moduleIdent] = (sender, messages) // Set the necessary blocks sender.sendMessageBlock = { [weak self] message, method, replyHandler, errorHandler in debugLog(.messages, ["Sending Message", type(of: message), "with", method]) // Error Handling if wrong Method var data = message.encode() data["moduleIdent"] = sender.moduleIdent data["messageIdent"] = type(of: message).messageIdent debugLog(.messageContent, ["Sending Message Data", data]) do { try self?.core.sendMessage(data, method, replyHandler: { replyData in do { debugLog(.messageContent, ["Got Reply Data with", replyData]) // Find Message ident guard let messageIdent = replyData["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Find a suitable Message to return guard let messageClass = messages.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let responseMessage = try messageClass.decode(replyData) debugLog(.messages, ["Got Reply with", type(of: message), "with", method]) replyHandler(responseMessage) } catch { debugLog(.messages, ["Receiving reply failed with", error, "by", method]) errorHandler(error) } }, errorHandler: errorHandler) } catch { debugLog(.messages, ["Sending message failed with", error, "by", method]) errorHandler(error) } } } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: Message.Type ...) { self.register(receiver, with: messages) } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: [Message.Type]) { self.receiver[receiver.moduleIdent] = (receiver, messages) } /// Registering a Communicator can only be done once per object public func register(_ allrounder: Allrounder, with messages: Message.Type ...) { self.register(allrounder, with: messages) } public func register(_ allrounder: Allrounder, with messages: [Message.Type]) { self.register(allrounder as Sender, with: messages) self.register(allrounder as Receiver, with: messages) } public func deregister(_ sender: Sender) { // Set the Blocks nil sender.sendMessageBlock = nil self.sender.removeValue(forKey: sender.moduleIdent) } public func deregister(_ receiver: Receiver) { self.receiver.removeValue(forKey: receiver.moduleIdent) } public func deregister(_ allrounder: Allrounder) { self.deregister(allrounder as Sender) self.deregister(allrounder as Receiver) } }
38.908696
178
0.579953
03fde7cc8a8eb6368f4da25a758819b8b24052ec
1,509
// // OptionParsingError.swift // Bouncer // // Copyright (c) 2018 Jason Nam (https://jasonnam.com) // // 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 /// Option parsing error. /// /// - missingOptionArgument: Option argument is required but not given. /// - missingOptions: Options are required but not given. public enum OptionParsingError: Error { case missingOptionArgument(Command, Option) case missingOptions(Command, [Option]) }
41.916667
81
0.748178
1ee860a9d89107e06473a15ba7d1a5a5b2a762bd
662
// // PlayerController.swift // slowed // // Created by Artem Golovin on 2021-01-27. // import Foundation import Combine class PlayerController: ObservableObject { @Published var files: [URL] static var instance: PlayerController = PlayerController() private init() { self.files = [] } func appendFile(link: URL) { files.append(link) } func getNext(_ index: Int) -> Int { if index == (files.count - 1) { return index } return index + 1 } func getPrev(_ index: Int) -> Int { if index == 0 { return 0 } return index - 1 } }
16.55
62
0.548338
0953c057d6c02ef62614af9c395e7ec9510dccd8
2,909
// // Commons.swift // Commons // // Created by Samiyuru Senarathne on 1/25/20. // Copyright © 2020 Samiyuru Senarathne. // // 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 let MENU_ITEM_CLICKED_NOTIF = "menuItemClickedNotif" public let MENU_ITEM_INFO_NOTIF = "menuItemInfoNotif" public let MENU_ITEM_INFO_REQUEST_NOTIF = "menuItemInfoRequestNotif" // Get the directory for the menu item programs. // The programs can be apple scripts, bash scripts or executables. public func programsDir() -> URL { // Name of the menu programs directory. let menuProgramsDirName = ".findermenu" // Get the path to user home dir. let scriptParentDirURL = FileManager.default.homeDirectoryForCurrentUser // Get the URL for menu programs dir path. let menuProgramsDirURL = scriptParentDirURL.appendingPathComponent(menuProgramsDirName) return menuProgramsDirURL } // Class to represent an item in the right click menu. public class MenuItemInfo: Encodable, Decodable { public var id: Int public var title: String public init(id: Int, title: String) { self.id = id self.title = title } public static func fromJson(menuItemInfosStr: String?) -> [MenuItemInfo]? { guard let jsonData = menuItemInfosStr?.data(using: .utf8) else { return nil } return try? JSONDecoder().decode([MenuItemInfo].self, from: jsonData) } public static func json(menuItemInfos: [MenuItemInfo]?) -> String? { guard let jsonData = (try? JSONEncoder().encode(menuItemInfos)) else { return nil } return String(data: jsonData, encoding: .utf8) } } // Class to represent a click of a right click item. public class MenuItemClickInfo: Encodable, Decodable { public var id: Int public var target: String public init(id: Int, target: String) { self.id = id self.target = target } public static func fromJson(str: String?) -> MenuItemClickInfo? { guard let jsonData = str?.data(using: .utf8) else { return nil } return try? JSONDecoder().decode(MenuItemClickInfo.self, from: jsonData) } public func json() -> String? { guard let jsonData = (try? JSONEncoder().encode(self)) else { return nil } return String(data: jsonData, encoding: .utf8) } }
30.946809
91
0.669302
f750e7a91157e4785ee0c3f499fb11d9be484a13
3,497
// // ReactiveExtensions // Copyright © 2017 Evan Coleman. All rights reserved. // import Alamofire import ReactiveSwift extension DataRequest: ReactiveExtensionsProvider { } extension Reactive where Base: DataRequest { /// A signal that sends the response as a string. public func responseString() -> SignalProducer<DataResponse<String>, NSError> { return SignalProducer { observer, disposable in let request = self.base.responseString { response in if let error = response.result.error { observer.send(error: error as NSError) } else { observer.send(value: response) observer.sendCompleted() } } disposable += ActionDisposable() { request.cancel() } } } /// A signal that sends the response as a JSON object. public func responseJSON() -> SignalProducer<DataResponse<Any>, NSError> { return SignalProducer { observer, disposable in let request = self.base.responseJSON { response in if let error = response.result.error { observer.send(error: error as NSError) } else { observer.send(value: response) observer.sendCompleted() } } disposable += ActionDisposable() { request.cancel() } } } /// A signal that sends the response as Data. public func responseData() -> SignalProducer<DataResponse<Data>, NSError> { return SignalProducer { observer, disposable in let request = self.base.responseData { response in if let error = response.result.error { observer.send(error: error as NSError) } else { observer.send(value: response) observer.sendCompleted() } } disposable += ActionDisposable() { request.cancel() } } } /// A signal that sends the response as a property list object. public func responsePropertyList() -> SignalProducer<DataResponse<Any>, NSError> { return SignalProducer { observer, disposable in let request = self.base.responsePropertyList { response in if let error = response.result.error { observer.send(error: error as NSError) } else { observer.send(value: response) observer.sendCompleted() } } disposable += ActionDisposable() { request.cancel() } } } /// A signal that sends the response as a property list object. public func response() -> SignalProducer<DefaultDataResponse, NSError> { return SignalProducer { observer, disposable in let request = self.base.response { response in if let error = response.error { observer.send(error: error as NSError) } else { observer.send(value: response) observer.sendCompleted() } } disposable += ActionDisposable() { request.cancel() } } } }
34.284314
86
0.523306
fc9e7dfd2a7fc36dba92f0e3ec4e49855cdfd20c
4,270
/// Copyright (c) 2022 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 MetalKit struct Fireworks { let particleCount = 10000 let maxEmitters = 8 var emitters: [FireworksEmitter] = [] let life: Float = 256 var timer: Float = 0 let clearScreenPSO: MTLComputePipelineState let fireworksPSO: MTLComputePipelineState init() { clearScreenPSO = PipelineStates.createComputePSO(function: "clearScreen") fireworksPSO = PipelineStates.createComputePSO(function: "fireworks") } mutating func update(size: CGSize) { timer += 1 if timer >= 50 { timer = 0 if emitters.count > maxEmitters { emitters.removeFirst() } let emitter = FireworksEmitter( particleCount: particleCount, size: size, life: life) emitters.append(emitter) } } func draw( commandBuffer: MTLCommandBuffer, view: MTKView ) { // 1 guard let computeEncoder = commandBuffer.makeComputeCommandEncoder(), let drawable = view.currentDrawable else { return } computeEncoder.setComputePipelineState(clearScreenPSO) computeEncoder.setTexture(drawable.texture, index: 0) // 2 var threadsPerGrid = MTLSize( width: Int(view.drawableSize.width), height: Int(view.drawableSize.height), depth: 1) // 3 let width = clearScreenPSO.threadExecutionWidth var threadsPerThreadgroup = MTLSize( width: width, height: clearScreenPSO.maxTotalThreadsPerThreadgroup / width, depth: 1) // 4 computeEncoder.dispatchThreads( threadsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup) computeEncoder.endEncoding() // 1 guard let particleEncoder = commandBuffer.makeComputeCommandEncoder() else { return } particleEncoder.setComputePipelineState(fireworksPSO) particleEncoder.setTexture(drawable.texture, index: 0) // 2 threadsPerGrid = MTLSize( width: particleCount, height: 1, depth: 1) for emitter in emitters { // 3 let particleBuffer = emitter.particleBuffer particleEncoder.setBuffer(particleBuffer, offset: 0, index: 0) threadsPerThreadgroup = MTLSize( width: fireworksPSO.threadExecutionWidth, height: 1, depth: 1) particleEncoder.dispatchThreads( threadsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup) } particleEncoder.endEncoding() } }
35.882353
83
0.713583
f938642b1fbf791c495249064eb0527641b082d6
105
import Foundation @testable import TestProject class MockOverloadProtocol: OverloadProtocol { <caret> }
15
46
0.828571
87bbc1de93de27cc091b6b5de7dec3500c3c522d
1,959
// // MLService.swift // NotesML // // Created by Michael Thomas on 9/18/17. // Copyright © 2017 WillowTree, Inc. All rights reserved. // import Foundation import CoreML final class MLService { private enum Error: Swift.Error { case featuresMissing } private let model = SentimentPolarity() private let options: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .omitOther] private lazy var tagger: NSLinguisticTagger = { return NSLinguisticTagger(tagSchemes: NSLinguisticTagger.availableTagSchemes(forLanguage: "en"), options: 0) }() // MARK: - Prediction func predictSentiment(from text: String) -> Sentiment { do { let inputFeatures = features(from: text) guard inputFeatures.count > 1 else { throw Error.featuresMissing } let output = try model.prediction(input: inputFeatures) switch output.classLabel { case "Pos": return .positive case "Neg": return .negative default: return .neutral } } catch { return .neutral } } // MARK: - Features func features(from text: String) -> [String: Double] { var wordCounts = [String: Double]() tagger.string = text let range = NSRange(location: 0, length: text.utf16.count) // Tokenize and count the sentence tagger.enumerateTags(in: range, scheme: .nameType, options: options) { _, tokenRange, _, _ in let token = (text as NSString).substring(with: tokenRange).lowercased() if let value = wordCounts[token] { wordCounts[token] = value + 1.0 } else { wordCounts[token] = 1.0 } } return wordCounts } }
27.591549
115
0.555385
62458f4898d4a5904832ec6e39a76e7bac49c18f
8,918
// // DataManager.swift // Eatery // // Created by Eric Appel on 10/8/14. // Copyright (c) 2014 CUAppDev. All rights reserved. // import Foundation import Alamofire import SwiftyJSON let separator = ":------------------------------------------" /** Router Endpoints enum */ internal enum Router: URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. public func asURL() throws -> URL { let path: String = { switch self { case .root: return "/" case .eateries: return "/eateries.json" } }() if let url = URL(string: Router.baseURLString + path) { return url } else { throw AFError.invalidURL(url: self) } } static let baseURLString = "https://now.dining.cornell.edu/api/1.0/dining" case root case eateries } /** Keys for Cornell API These will be in the response dictionary */ public enum APIKey : String { // Top Level case status = "status" case data = "data" case meta = "meta" case message = "message" // Data case eateries = "eateries" // Eatery case identifier = "id" case slug = "slug" case name = "name" case nameShort = "nameshort" case eateryTypes = "eateryTypes" case aboutShort = "aboutshort" case latitude = "latitude" case longitude = "longitude" case hours = "operatingHours" case payment = "payMethods" case phoneNumber = "contactPhone" case campusArea = "campusArea" case address = "location" case diningItems = "diningItems" // Hours case date = "date" case events = "events" // Events case startTime = "startTimestamp" case endTime = "endTimestamp" case startFormat = "start" case endFormat = "end" case menu = "menu" case summary = "calSummary" // Events/Payment/CampusArea/EateryTypes case description = "descr" case shortDescription = "descrshort" // Menu case items = "items" case category = "category" case item = "item" case healthy = "healthy" // Meta case copyright = "copyright" case timestamp = "responseDttm" // External case weekday = "weekday" case external = "external" } /** Enumerated Server Response - Success: String for the status if the request was a success. */ enum Status: String { case success = "success" } /** Error Types - ServerError: An error arose from the server-side of things */ enum DataError: Error { case serverError } public enum DayOfTheWeek: Int { case sunday = 1 case monday case tuesday case wednesday case thursday case friday case saturday init?(string: String) { switch string.lowercased() { case "sunday": self = .sunday case "monday": self = .monday case "tuesday": self = .tuesday case "wednesday": self = .wednesday case "thursday": self = .thursday case "friday": self = .friday case "saturday": self = .saturday default: return nil } } static func ofDateSpan(_ string: String) -> [DayOfTheWeek]? { let partition = string.lowercased().split { $0 == "-" } .map(String.init) switch partition.count { case 2: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } guard let end = DayOfTheWeek(string: partition[1]) else { return nil } var result: [DayOfTheWeek] = [] let endValue = start.rawValue <= end.rawValue ? end.rawValue : end.rawValue + 7 for dayValue in start.rawValue...endValue { guard let day = DayOfTheWeek(rawValue: dayValue % 7) else { return nil } result.append(day) } return result case 1: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } return [start] default: return nil } } func getDate() -> Date { let startOfToday = Calendar.current.startOfDay(for: Date()) let weekDay = Calendar.current.component(.weekday, from: Date()) let daysAway = (rawValue - weekDay + 7) % 7 let endDate = Calendar.current.date(byAdding: .weekday, value: daysAway, to: startOfToday) ?? Date() return endDate } func getDateString() -> String { let date = getDate() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: date) } func getTimeStamp(_ timeString: String) -> Date { let endDate = getDate() let formatter = DateFormatter() formatter.dateFormat = "h:mma" let timeIntoEndDate = formatter.date(from: timeString) ?? Date() let components = Calendar.current.dateComponents([.hour, .minute], from: timeIntoEndDate) return Calendar.current.date(byAdding: components, to: endDate) ?? Date() } } /// Top-level class to communicate with Cornell Dining public class DataManager: NSObject { /// Gives a shared instance of `DataManager` public static let sharedInstance = DataManager() /// List of all the Dining Locations with parsed events and menus private (set) public var eateries: [Eatery] = [] /** Sends a GET request to the Cornell API to get the events for all eateries and stores them in user documents. - parameter force: Boolean indicating that the data should be refreshed even if the cache is invalid. - parameter completion: Completion block called upon successful receipt and parsing of the data or with an error if there was one. Use `-eateries` to get the parsed response. */ public func fetchEateries(_ force: Bool, completion: ((Error?) -> Void)?) { if eateries.count > 0 && !force { completion?(nil) return } let req = Alamofire.request(Router.eateries) func processData (_ data: Data) { let json = JSON(data) if (json[APIKey.status.rawValue].stringValue != Status.success.rawValue) { completion?(DataError.serverError) // do something is message return } let eateryList = json["data"]["eateries"] self.eateries = eateryList.map { Eatery(json: $0.1) } let externalEateryList = kExternalEateries["eateries"]! let externalEateries = externalEateryList.map { Eatery(json: $0.1) } //don't add duplicate external eateries //Uncomment after CU Dining Pushes Eatery with marketing for external in externalEateries { if !eateries.contains(where: { $0.slug == external.slug }) { eateries.append(external) } } completion?(nil) } if let request = req.request, !force { let cached = URLCache.shared.cachedResponse(for: request) if let info = cached?.userInfo { // This is hacky because the server doesn't support caching really // and even if it did it is too slow to respond to make it worthwhile // so I'm going to try to screw with the cache policy depending // upon the age of the entry in the cache if let date = info["date"] as? Double { let maxAge: Double = 24 * 60 * 60 let now = Date().timeIntervalSince1970 if now - date <= maxAge { processData(cached!.data) return } } } } req.responseData { (resp) -> Void in let data = resp.result let request = resp.request let response = resp.response if let data = data.value, let response = response, let request = request { let cached = CachedURLResponse(response: response, data: data, userInfo: ["date": NSDate().timeIntervalSince1970], storagePolicy: .allowed) URLCache.shared.storeCachedResponse(cached, for: request) } if let jsonData = data.value { processData(jsonData) } else { completion?(data.error) } } } }
30.128378
159
0.560327
7695aebef553984b5d663bae8cb2744ead528f64
459
import Foundation public struct Constants { struct ViewControllerIdentifiers { static let NearbyViewController = "nearbyPlacesVC" static let PlaceDetailsViewController = "placeDetailsVC" } struct LocationOptions { static let Radius = 50 } struct Default { static let ImageUrl = "https://bento.cdn.pbs.org/hostedbento-prod/filer_public/_bento_media/img/no-image-available.jpg" } }
21.857143
127
0.671024
1efb596aa729a15cdf9f2d31c0806fc159ffc16a
673
import Foundation // How Much? // https://www.codewars.com/kata/55b4d87a3766d9873a0000d4/train/swift func howMuch(_ m: Int, _ n: Int) -> [(String, String, String)] { var array: [(String, String, String)] = [] let range = min(m,n)...max(m,n) for a in range where ((a - 2) % 7 == 0 && (a - 1) % 9 == 0) { let b = (a - 2) / 7, c = (a - 1) / 9 array.append(("M: \(a)", "B: \(b)", "C: \(c)")) } return array } // Solution 2: /** func howMuch(_ m: Int, _ n: Int) -> [(String, String, String)] { let value = min(m, n)...max(m, n) return value.filter { $0 % 9 == 1 && $0 % 7 == 2 }.map { ("M: \($0)", "B: \($0 / 7)", "C: \($0 / 9)") } } */
29.26087
104
0.484398
e214b59cd232145c0c4e642456afdc68bc299d41
6,309
// // SurrogatesUserScript.swift // Core // // Copyright © 2020 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import WebKit import os import TrackerRadarKit import BrowserServicesKit public protocol SurrogatesUserScriptDelegate: NSObjectProtocol { func surrogatesUserScriptShouldProcessTrackers(_ script: SurrogatesUserScript) -> Bool func surrogatesUserScript(_ script: SurrogatesUserScript, detectedTracker tracker: DetectedTracker, withSurrogate host: String) } public protocol SurrogatesUserScriptConfigSource { var privacyConfig: PrivacyConfiguration { get } var encodedTrackerData: String? { get } var surrogates: String { get } } public class DefaultSurrogatesUserScriptConfigSource: SurrogatesUserScriptConfigSource { public var privacyConfig: PrivacyConfiguration { return PrivacyConfigurationManager.shared.privacyConfig } public var encodedTrackerData: String? { return ContentBlockerRulesManager.shared.currentRules?.encodedTrackerData } private var cachedSurrogatesETag = "" private var cachedSurrogates = "" public var surrogates: String { let etagStore = UserDefaultsETagStorage() let surrogatesETag = etagStore.etag(for: .surrogates) ?? "" if cachedSurrogates != surrogatesETag { cachedSurrogates = FileStore().loadAsString(forConfiguration: .surrogates) ?? "" cachedSurrogatesETag = surrogatesETag } return cachedSurrogates } } public class SurrogatesUserScript: NSObject, UserScript { struct TrackerDetectedKey { static let protectionId = "protectionId" static let blocked = "blocked" static let networkName = "networkName" static let url = "url" static let isSurrogate = "isSurrogate" static let pageUrl = "pageUrl" } private let configurationSource: SurrogatesUserScriptConfigSource public init(configurationSource: SurrogatesUserScriptConfigSource) { self.configurationSource = configurationSource super.init() } public override convenience init() { self.init(configurationSource: DefaultSurrogatesUserScriptConfigSource()) } public var source: String { let privacyConfiguration = configurationSource.privacyConfig let remoteUnprotectedDomains = (privacyConfiguration.tempUnprotectedDomains.joined(separator: "\n")) + "\n" + (privacyConfiguration.exceptionsList(forFeature: .contentBlocking).joined(separator: "\n")) // Encode whatever the tracker data manager is using to ensure it's in sync and because we know it will work let trackerData: String if let data = configurationSource.encodedTrackerData { trackerData = data } else { let encodedData = try? JSONEncoder().encode(TrackerData(trackers: [:], entities: [:], domains: [:], cnames: [:])) trackerData = String(data: encodedData!, encoding: .utf8)! } return Self.loadJS("contentblocker", from: Bundle.core, withReplacements: [ "$IS_DEBUG$": isDebugBuild ? "true" : "false", "$TEMP_UNPROTECTED_DOMAINS$": remoteUnprotectedDomains, "$USER_UNPROTECTED_DOMAINS$": privacyConfiguration.userUnprotectedDomains.joined(separator: "\n"), "$TRACKER_ALLOWLIST_ENTRIES$": TrackerAllowlistInjection.prepareForInjection(allowlist: privacyConfiguration.trackerAllowlist), "$TRACKER_DATA$": trackerData, "$SURROGATES$": configurationSource.surrogates, "$BLOCKING_ENABLED$": privacyConfiguration.isEnabled(featureKey: .contentBlocking) ? "true" : "false" ]) } public var injectionTime: WKUserScriptInjectionTime = .atDocumentStart public var forMainFrameOnly: Bool = false public var messageNames: [String] = [ "trackerDetectedMessage" ] public weak var delegate: SurrogatesUserScriptDelegate? public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { os_log("trackerDetected %s", log: generalLog, type: .debug, String(describing: message.body)) guard let delegate = delegate else { return } guard delegate.surrogatesUserScriptShouldProcessTrackers(self) else { return } guard let dict = message.body as? [String: Any] else { return } guard let blocked = dict[TrackerDetectedKey.blocked] as? Bool else { return } guard let urlString = dict[TrackerDetectedKey.url] as? String else { return } guard let pageUrlStr = dict[TrackerDetectedKey.pageUrl] as? String else { return } let tracker = trackerFromUrl(urlString.trimWhitespace(), pageUrlString: pageUrlStr, blocked) if let isSurrogate = dict[TrackerDetectedKey.isSurrogate] as? Bool, isSurrogate, let host = URL(string: urlString)?.host { delegate.surrogatesUserScript(self, detectedTracker: tracker, withSurrogate: host) os_log("surrogate for %s Injected", log: generalLog, type: .debug, tracker.domain ?? "") } } private func trackerFromUrl(_ urlString: String, pageUrlString: String, _ blocked: Bool) -> DetectedTracker { let currentTrackerData = ContentBlockerRulesManager.shared.currentRules?.trackerData let knownTracker = currentTrackerData?.findTracker(forUrl: urlString) let entity = currentTrackerData?.findEntity(byName: knownTracker?.owner?.name ?? "") return DetectedTracker(url: urlString, knownTracker: knownTracker, entity: entity, blocked: blocked, pageUrl: pageUrlString) } }
41.506579
139
0.699477
0acd820dd25d7c6e24a3b281755df5ff22dc4706
8,202
// // CanvasView.swift // ios-example // // Created by Sergey Muravev on 23.12.2019. // Copyright © 2019 VipaHelda BV. All rights reserved. // import SwiftUI import SceneKit import ConfigWiseSDK struct CanvasView: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> private let canvasAdapter = CanvasAdapter() @ObservedObject private var observableState: ObservableState init(_ component: ComponentEntity) { self.observableState = ObservableState(component) } var body: some View { let componentDataFailed = Binding<Bool>( get: { self.observableState.isFailed }, set: { _ = $0 } ) let selectedSceneEnvironmentBinding = Binding<SceneEnvironment>( get: { self.canvasAdapter.sceneEnvironment }, set: { self.canvasAdapter.sceneEnvironment = $0 } ) let showSizesBinding = Binding<Bool>( get: { self.canvasAdapter.showSizes }, set: { self.canvasAdapter.showSizes = $0 } ) return ZStack { SceneView( onInitView: { (view: SCNView) in self.canvasAdapter.sceneView = view self.canvasAdapter.gesturesEnabled = true self.canvasAdapter.cameraControlEnabled = true self.canvasAdapter.groundEnabled = false self.canvasAdapter.resetCameraPropertiesOnFocusToCenter = true }, onUpdateView: { (view: SCNView) in } ) .onAppear { self.observableState.loadModel() } .onReceive(self.observableState.$modelNodeLoadable, perform: { modelNodeLoadable in if modelNodeLoadable.isLoaded, let model = modelNodeLoadable.value { self.canvasAdapter.addModel(modelNode: model) self.canvasAdapter.focusToCenter(animate: false, resetCameraZoom: true, resetCameraOrientation: true) } }) if self.observableState.isLoading { VStack { VStack { Text("Loading \(self.observableState.loadingProgress != nil ? "\(self.observableState.loadingProgress!)%" : "...")") ActivityIndicator(isAnimating: true) { (indicator: UIActivityIndicatorView) in indicator.style = .large indicator.hidesWhenStopped = false } } .padding() } .modifier(LoadingViewStyle()) } } .alert(isPresented: componentDataFailed) { Alert( title: Text("ERROR"), message: Text(self.observableState.error?.localizedDescription ?? "Unable to load component data."), dismissButton: .default(Text("OK")) { self.presentationMode.wrappedValue.dismiss() } ) } .navigationBarItems( trailing: HStack { // 'Open product link' button Button(action: { guard let component = self.observableState.component else { return } ComponentService.sharedInstance.obtainProductUrlByComponentOfCurrentCompany(component: component) { productUrl, error in if let error = error { print("Unable to open product link due error: \(error.localizedDescription)") return } guard let productUrl = productUrl else { print("Unable to open product link due no product url") return } UIApplication.shared.open(productUrl, options: [:]) } }) { Image(systemName: "safari") .resizable() .aspectRatio(contentMode: .fit) } .frame(width: 30, height: 30, alignment: .center) .disabled(!self.observableState.isLoaded || self.observableState.component?.productLinkUrl == nil) Spacer() // 'Scene environment' selector Picker(selection: selectedSceneEnvironmentBinding, label: Text("")) { Image(systemName: "sun.max").tag(SceneEnvironment.basicLight) Image(systemName: "moon").tag(SceneEnvironment.basicDark) Image(systemName: "lightbulb").tag(SceneEnvironment.studio) } .pickerStyle(SegmentedPickerStyle()) Spacer() // 'Show / Hide sizes' switcher Toggle(isOn: showSizesBinding) { Text("") } } ) } } private class ObservableState: ObservableObject { @Published var componentLoadable: Loadable<ComponentEntity> = .notRequested @Published var modelNodeLoadable: Loadable<ModelNode> = .notRequested @Published var loadingProgress: Int? var model: ModelNode? { modelNodeLoadable.value } var component: ComponentEntity? { componentLoadable.value } var isLoading: Bool { componentLoadable.isLoading || modelNodeLoadable.isLoading } var isLoaded: Bool { componentLoadable.isLoaded && modelNodeLoadable.isLoaded } var isFailed: Bool { componentLoadable.isFailed || modelNodeLoadable.isFailed } var error: Error? { componentLoadable.error ?? modelNodeLoadable.error } init(_ component: ComponentEntity) { self.componentLoadable = .isLoading(last: component) guard let componentId = component.objectId else { self.componentLoadable = .failed("Invalid component - no identifier found.") return } ComponentService.sharedInstance.obtainComponentById(id: componentId) { component, error in if let error = error { self.componentLoadable = .failed(error) return } guard let component = component else { self.componentLoadable = .failed("Fetched component is nil.") return } self.componentLoadable = .loaded(component) } } func loadModel() { self.modelNodeLoadable = .isLoading(last: self.modelNodeLoadable.value) guard !componentLoadable.isFailed else { self.modelNodeLoadable = .failed(componentLoadable.error!) return } guard let component = self.componentLoadable.value else { self.modelNodeLoadable = .failed("Unable to load model due component is nil.") return } self.loadingProgress = 0 ModelLoaderService.sharedInstance.loadModelBy(component: component, block: { [weak self] model, error in self?.loadingProgress = 100 delay(0.3) { self?.loadingProgress = nil } if let error = error { self?.modelNodeLoadable = .failed(error) return } guard let model = model else { self?.modelNodeLoadable = .failed("Loaded model is nil") return } self?.modelNodeLoadable = .loaded(model) }, progressBlock: { [weak self] status, completed in self?.loadingProgress = Int(completed * 100) }) } } #if DEBUG struct CanvasView_Previews: PreviewProvider { static var previews: some View { CanvasView(ComponentEntity()) } } #endif
34.902128
140
0.533285
8a28d3c40cc29cc83bf0a1703bf2d3bcb51238d3
1,094
// // StatusIndicatiorView.swift // LimoService // // Created by Sameer Totey on 4/14/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class StatusIndicatiorView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 3.0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var preferredWidth: CGFloat = 6 @IBInspectable var preferredHeight: CGFloat = 100 override func intrinsicContentSize() -> CGSize { return CGSizeMake(preferredWidth, preferredHeight) } }
23.782609
78
0.629799
1eda5109b4da1a1486c1ab3d55d8d7ac4452c533
2,815
import Foundation import SourceKittenFramework public struct PatternMatchingKeywordsRule: ASTRule, ConfigurationProviderRule, OptInRule, AutomaticTestableRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "pattern_matching_keywords", name: "Pattern Matching Keywords", description: "Combine multiple pattern matching bindings by moving keywords out of tuples.", kind: .idiomatic, nonTriggeringExamples: [ "default", "case 1", "case bar", "case let (x, y)", "case .foo(let x)", "case let .foo(x, y)", "case .foo(let x), .bar(let x)", "case .foo(let x, var y)", "case var (x, y)", "case .foo(var x)", "case var .foo(x, y)" ].map(wrapInSwitch), triggeringExamples: [ "case (↓let x, ↓let y)", "case .foo(↓let x, ↓let y)", "case (.yamlParsing(↓let x), .yamlParsing(↓let y))", "case (↓var x, ↓var y)", "case .foo(↓var x, ↓var y)", "case (.yamlParsing(↓var x), .yamlParsing(↓var y))" ].map(wrapInSwitch) ) public func validate(file: SwiftLintFile, kind: StatementKind, dictionary: SourceKittenDictionary) -> [StyleViolation] { guard kind == .case else { return [] } let contents = file.stringView return dictionary.elements.flatMap { subDictionary -> [StyleViolation] in guard subDictionary.kind == "source.lang.swift.structure.elem.pattern", let offset = subDictionary.offset, let length = subDictionary.length, let caseRange = contents.byteRangeToNSRange(start: offset, length: length) else { return [] } let letMatches = file.match(pattern: "\\blet\\b", with: [.keyword], range: caseRange) let varMatches = file.match(pattern: "\\bvar\\b", with: [.keyword], range: caseRange) if !letMatches.isEmpty && !varMatches.isEmpty { return [] } guard letMatches.count > 1 || varMatches.count > 1 else { return [] } return (letMatches + varMatches).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } } } private func wrapInSwitch(_ str: String) -> String { return "switch foo {\n" + " \(str): break\n" + "}" }
36.558442
113
0.539964
399bebbc954cfc0ce2b29f781b35404e293a3d1d
708
// // OTVoiceBLayer.swift // OralStunts // // Created by Noah_Shan on 2018/5/17. // Copyright © 2018年 Inspur. All rights reserved. // import Foundation import UIKit @_exported import IIUIAndBizConfig /// bottom path class OTVoiceBLayer: CAShapeLayer { override init() { super.init() self.lineWidth = 5 self.strokeColor = APPUIConfig.cloudThemeColor.cgColor self.path = self.realPath.cgPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var realPath: UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) return path } }
20.823529
62
0.627119
23a36d0fcc2e7edacdc52ec38fd004bf3e2e515c
531
// // LineView.swift // ios-hwloc // // Created by vhoyet on 11/06/2020. // Copyright © 2020 vhoyet. All rights reserved. // import SwiftUI class LineView: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context!.setLineWidth(1.5) context!.setStrokeColor(UIColor.black.cgColor) context?.move(to: CGPoint(x: 0, y: self.frame.size.height)) context?.addLine(to: CGPoint(x: self.frame.size.width, y: 0)) context!.strokePath() } }
24.136364
69
0.644068
b9022ce36fcc51911d79601dec4bad06214d9b35
816
//___FILEHEADER___ import Foundation import UIKit enum ___VARIABLE_sceneName___Scene { case `default` func configure() -> UIViewController? { switch self { case .`default`: return configure___VARIABLE_sceneName___() } } private func configure___VARIABLE_sceneName___() -> UIViewController? { // Setup let viewController = ___VARIABLE_sceneName___ViewController.storyboardInstance let interactor = ___VARIABLE_sceneName___Interactor(presenter: ___VARIABLE_sceneName___Presenter(viewController: viewController), router: ___VARIABLE_sceneName___Router(viewController: viewController), worker: ___VARIABLE_sceneName___Worker(apiService: APIService())) viewController?.interactor = interactor return viewController } }
31.384615
275
0.741422
8ab75673629dc7aed2bb9c34a82dbd836e4281b1
405
// // QSImageView.swift // QuickStart // // Created by zhu on 16/9/18. // Copyright © 2016年 zxp. All rights reserved. // import UIKit open class QSImageView: UIImageView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
18.409091
78
0.649383
f5f9d9dc7ec251651c55edbe9eb4c63db8ef56b3
43,920
// // 🦠 Corona-Warn-App // // swiftlint:disable file_length // swiftlint:disable:next type_body_length enum AccessibilityIdentifiers { enum ExposureNotificationSetting { static let descriptionTitleInactive = "AppStrings.ExposureNotificationSetting.descriptionTitleInactive" static let descriptionTitle = "AppStrings.ExposureNotificationSetting.descriptionTitle" static let descriptionText1 = "AppStrings.ExposureNotificationSetting.descriptionText1" static let descriptionText2 = "AppStrings.ExposureNotificationSetting.descriptionText2" static let descriptionText3 = "AppStrings.ExposureNotificationSetting.descriptionText3" static let descriptionText4 = "AppStrings.ExposureNotificationSetting.descriptionText4" static let enableTracing = "AppStrings.ExposureNotificationSetting.enableTracing" } enum NotificationSettings { enum DeltaOnboarding { static let imageOn = "AppStrings.NotificationSettings.imageDescriptionOn" static let imageOff = "AppStrings.NotificationSettings.imageDescriptionOff" static let description = "AppStrings.NotificationSettings.DeltaOnboarding.description" } static let notifications = "AppStrings.NotificationSettings.notifications" static let notificationsOn = "AppStrings.NotificationSettings.notificationsOn" static let notificationsOff = "AppStrings.NotificationSettings.notificationsOff" static let bulletDescOn = "AppStrings.NotificationSettings.bulletDescOn" static let bulletDescOff = "AppStrings.NotificationSettings.bulletDescOff" static let bulletPoint1 = "AppStrings.NotificationSettings.bulletPoint1" static let bulletPoint2 = "AppStrings.NotificationSettings.bulletPoint2" static let bulletPoint3 = "AppStrings.NotificationSettings.bulletPoint3" static let bulletDesc2 = "AppStrings.NotificationSettings.bulletDesc2" static let openSystemSettings = "AppStrings.NotificationSettings.openSystemSettings" static let close = "AppStrings.NotificationSettings.DeltaOnboarding.primaryButtonTitle" } enum Home { static let leftBarButtonDescription = "AppStrings.Home.leftBarButtonDescription" static let rightBarButtonDescription = "AppStrings.Home.rightBarButtonDescription" static let activateCardOnTitle = "AppStrings.Home.activateCardOnTitle" static let activateCardOffTitle = "AppStrings.Home.activateCardOffTitle" static let activateCardBluetoothOffTitle = "AppStrings.Home.activateCardBluetoothOffTitle" static let riskCardIntervalUpdateTitle = "AppStrings.Home.riskCardIntervalUpdateTitle" static let tableView = "AppStrings.Home.tableView" enum RiskTableViewCell { static let topContainer = "[AccessibilityIdentifiers.Home.RiskTableViewCell.topContainer]" static let bodyLabel = "HomeRiskTableViewCell.bodyLabel" static let updateButton = "HomeRiskTableViewCell.updateButton" } enum TestResultCell { static let pendingPCRButton = "AccessibilityIdentifiers.Home.pendingPCRButton" static let pendingAntigenButton = "AccessibilityIdentifiers.Home.pendingAntigenButton" static let negativePCRButton = "AccessibilityIdentifiers.Home.negativePCRButton" static let negativeAntigenButton = "AccessibilityIdentifiers.Home.negativeAntigenButton" static let availablePCRButton = "AccessibilityIdentifiers.Home.availablePCRButton" static let availableAntigenButton = "AccessibilityIdentifiers.Home.availableAntigenButton" static let invalidPCRButton = "AccessibilityIdentifiers.Home.invalidPCRButton" static let invalidAntigenButton = "AccessibilityIdentifiers.Home.invalidAntigenButton" static let expiredPCRButton = "AccessibilityIdentifiers.Home.expiredPCRButton" static let expiredAntigenButton = "AccessibilityIdentifiers.Home.expiredAntigenButton" static let outdatedAntigenButton = "AccessibilityIdentifiers.Home.outdatedAntigenButton" static let loadingPCRButton = "AccessibilityIdentifiers.Home.loadingPCRButton" static let loadingAntigenButton = "AccessibilityIdentifiers.Home.loadingAntigenButton" static let unconfiguredButton = "AccessibilityIdentifiers.Home.unconfiguredButton" } enum ShownPositiveTestResultCell { static let pcrCell = "AccessibilityIdentifiers.Home.pcrCell" static let antigenCell = "AccessibilityIdentifiers.Home.antigenCell" static let submittedPCRCell = "AccessibilityIdentifiers.Home.submittedPCRCell" static let submittedAntigenCell = "AccessibilityIdentifiers.Home.submittedAntigenCell" static let removeTestButton = "AppStrings.Home.TestResult.ShownPositive.removeTestButton" static let deleteAlertDeleteButton = "AppStrings.Home.TestResult.ShownPositive.deleteAlertDeleteButton" } enum MoreInfoCell { static let moreCell = "AppStrings.Home.moreCell" static let settingsLabel = "AppStrings.Home.settingsActionView" static let recycleBinLabel = "AppStrings.Home.recycleBinActionView" static let appInformationLabel = "AppStrings.Home.appInformationActionView" static let faqLabel = "AppStrings.Home.faqActionView" static let socialMediaLabel = "AppStrings.Home.socialMediaActionView" static let shareLabel = "AppStrings.Home.shareActionView" } static let submitCardButton = "AppStrings.Home.submitCardButton" static let traceLocationsCardButton = "AppStrings.Home.traceLocationsCardButton" } enum ContactDiary { static let segmentedControl = "AppStrings.ContactDiary.Day" static let dayTableView = "AppStrings.ContactDiary.Day.TableView" } enum ContactDiaryInformation { static let imageDescription = "AppStrings.ContactDiaryInformation.imageDescription" static let descriptionTitle = "AppStrings.ContactDiaryInformation.descriptionTitle" static let descriptionSubHeadline = "AppStrings.ContactDiaryInformation.descriptionSubHeadline" static let dataPrivacyTitle = "AppStrings.ContactDiaryInformation.dataPrivacyTitle" static let legal_1 = "AppStrings.ContactDiaryInformation.legalHeadline_1" enum Day { static let durationSegmentedContol = "AppStrings.ContactDiaryInformation.durationSegmentedContol" static let maskSituationSegmentedControl = "AppStrings.ContactDiaryInformation.maskSituationSegmentedControl" static let settingSegmentedControl = "AppStrings.ContactDiaryInformation.settingSegmentedControl" static let notesTextField = "AppStrings.ContactDiaryInformation.notesTextField" static let notesInfoButton = "AppStrings.ContactDiaryInformation.notesInfoButton" } enum EditEntries { static let tableView = "AppStrings.ContactDiary.EditEntries.tableView" static let nameTextField = "AppStrings.ContactDiary.EditEntries.nameTextField" static let phoneNumberTextField = "AppStrings.ContactDiary.EditEntries.phoneNumberTextField" static let eMailTextField = "AppStrings.ContactDiary.EditEntries.eMailTextField" } enum Overview { static let riskLevelLow = "AppStrings.ContactDiary.Overview.lowRiskTitle" static let riskLevelHigh = "AppStrings.ContactDiary.Overview.increasedRiskTitle" static let tableView = "AppStrings.ContactDiary.Overview.tableView" static let checkinRiskLevelLow = "AppStrings.ContactDiary.Overview.CheckinEncounter.titleLowRisk" static let checkinRiskLevelHigh = "AppStrings.ContactDiary.Overview.CheckinEncounter.titleHighRisk" static let checkinTableView = "AppStrings.ContactDiary.Overview.CheckinEncounter.tableView" static let cell = "ContactDiary_Overview_cell-%d" static let person = "ContactDiary_Overview_personEntry-%d" static let location = "ContactDiary_Overview_locationEntry-%d" } enum NotesInformation { static let titel = "AppStrings.ContactDiary.NotesInformation.title" } } enum Onboarding { static let onboardingInfo_togetherAgainstCoronaPage_title = "AppStrings.Onboarding.onboardingInfo_togetherAgainstCoronaPage_title" static let onboardingInfo_togetherAgainstCoronaPage_imageDescription = "AppStrings.Onboarding.onboardingInfo_togetherAgainstCoronaPage_imageDescription" static let onboardingLetsGo = "AppStrings.Onboarding.onboardingLetsGo" static let onboardingInfo_privacyPage_title = "AppStrings.Onboarding.onboardingInfo_privacyPage_title" static let onboardingInfo_privacyPage_imageDescription = "AppStrings.Onboarding.onboardingInfo_privacyPage_imageDescription" static let onboardingContinue = "AppStrings.Onboarding.onboardingContinue" static let onboardingInfo_enableLoggingOfContactsPage_button = "AppStrings.Onboarding.onboardingInfo_enableLoggingOfContactsPage_button" static let onboardingDoNotActivate = "AppStrings.Onboarding.onboardingDoNotActivate" static let onboardingInfo_howDoesDataExchangeWorkPage_title = "AppStrings.Onboarding.onboardingInfo_howDoesDataExchangeWorkPage_title" static let onboardingInfo_howDoesDataExchangeWorkPage_imageDescription = "AppStrings.Onboarding.onboardingInfo_howDoesDataExchangeWorkPage_imageDescription" static let onboardingInfo_alwaysStayInformedPage_title = "AppStrings.Onboarding.onboardingInfo_alwaysStayInformedPage_title" static let onboardingInfo_alwaysStayInformedPage_imageDescription = "AppStrings.Onboarding.onboardingInfo_alwaysStayInformedPage_imageDescription" } enum RiskLegend { static let subtitle = "AppStrings.RiskLegend.subtitle" static let titleImageAccLabel = "AppStrings.RiskLegend.titleImageAccLabel" static let legend1Text = "AppStrings.RiskLegend.legend1Text" static let legend2Text = "AppStrings.RiskLegend.legend2Text" static let legend2RiskLevels = "AppStrings.RiskLegend.legend2RiskLevels" static let legend2High = "AppStrings.RiskLegend.legend2High" static let legend2LowColor = "AppStrings.RiskLegend.legend2LowColor" static let legend3Text = "AppStrings.RiskLegend.legend3Text" static let definitionsTitle = "AppStrings.RiskLegend.definitionsTitle" static let storeTitle = "AppStrings.RiskLegend.storeTitle" static let storeText = "AppStrings.RiskLegend.storeText" static let checkTitle = "AppStrings.RiskLegend.checkTitle" static let checkText = "AppStrings.RiskLegend.checkText" static let contactTitle = "AppStrings.RiskLegend.contactTitle" static let contactText = "AppStrings.RiskLegend.contactText" static let notificationTitle = "AppStrings.RiskLegend.notificationTitle" static let notificationText = "AppStrings.RiskLegend.notificationText" static let randomTitle = "AppStrings.RiskLegend.randomTitle" static let randomText = "AppStrings.RiskLegend.randomText" } enum RecycleBin { static let itemCell = "RecycleBin.itemCell" static let restorationConfirmationButton = "RecycleBin.restorationConfirmationButton" } enum Settings { static let tracingLabel = "AppStrings.Settings.tracingLabel" static let notificationLabel = "AppStrings.Settings.notificationLabel" static let backgroundAppRefreshLabel = "AppStrings.Settings.backgroundAppRefreshLabel" static let resetLabel = "AppStrings.Settings.resetLabel" static let backgroundAppRefreshImageDescription = "AppStrings.Settings.backgroundAppRefreshImageDescription" static let dataDonation = "AppStrings.Settings.Datadonation.description" } enum AppInformation { static let newFeaturesNavigation = "AppStrings.AppInformation.newFeaturesNavigation" static let aboutNavigation = "AppStrings.AppInformation.aboutNavigation" static let faqNavigation = "AppStrings.AppInformation.faqNavigation" static let termsNavigation = "AppStrings.AppInformation.termsNavigation" static let accessibilityNavigation = "AppStrings.AppInformation.accessibility" static let privacyNavigation = "AppStrings.AppInformation.privacyNavigation" static let legalNavigation = "AppStrings.AppInformation.legalNavigation" static let contactNavigation = "AppStrings.AppInformation.contactNavigation" static let imprintNavigation = "AppStrings.AppInformation.imprintNavigation" static let aboutImageDescription = "AppStrings.AppInformation.aboutImageDescription" static let aboutTitle = "AppStrings.AppInformation.aboutTitle" static let aboutDescription = "AppStrings.AppInformation.aboutDescription" static let aboutText = "AppStrings.AppInformation.aboutText" static let aboutLink = "AppStrings.AppInformation.aboutLink" static let aboutLinkText = "AppStrings.AppInformation.aboutLinkText" static let contactImageDescription = "AppStrings.AppInformation.contactImageDescription" static let contactTitle = "AppStrings.AppInformation.contactTitle" static let contactDescription = "AppStrings.AppInformation.contactDescription" static let contactHotlineTitle = "AppStrings.AppInformation.contactHotlineTitle" static let contactHotlineDomesticText = "AppStrings.AppInformation.contactHotlineDomesticText" static let contactHotlineDomesticDetails = "AppStrings.AppInformation.contactHotlineDomesticDetails" static let contactHotlineForeignText = "AppStrings.AppInformation.contactHotlineForeignText" static let contactHotlineForeignDetails = "AppStrings.AppInformation.contactHotlineForeignDetails" static let contactHotlineTerms = "AppStrings.AppInformation.contactHotlineTerms" static let imprintImageDescription = "AppStrings.AppInformation.imprintImageDescription" static let imprintSection1Title = "AppStrings.AppInformation.imprintSection1Title" static let imprintSection1Text = "AppStrings.AppInformation.imprintSection1Text" static let imprintSection2Text = "AppStrings.AppInformation.imprintSection2Text" static let imprintSection3Title = "AppStrings.AppInformation.imprintSection3Title" static let imprintSection3Text = "AppStrings.AppInformation.imprintSection3Text" static let imprintSection4Title = "AppStrings.AppInformation.imprintSection4Title" static let imprintSection4Text = "AppStrings.AppInformation.imprintSection4Text" static let privacyImageDescription = "AppStrings.AppInformation.privacyImageDescription" static let privacyTitle = "AppStrings.AppInformation.privacyTitle" static let termsImageDescription = "AppStrings.AppInformation.termsImageDescription" static let termsTitle = "AppStrings.AppInformation.termsTitle" static let imprintSection2Title = "AppStrings.AppInformation.imprintSection2Title" static let legalImageDescription = "AppStrings.AppInformation.legalImageDescription" } enum ExposureDetection { static let explanationTextOff = "AppStrings.ExposureDetection.explanationTextOff" static let explanationTextOutdated = "AppStrings.ExposureDetection.explanationTextOutdated" static let explanationTextUnknown = "AppStrings.ExposureDetection.explanationTextUnknown" static let explanationTextLowNoEncounter = "AppStrings.ExposureDetection.explanationTextLowNoEncounter" static let explanationTextLowWithEncounter = "AppStrings.ExposureDetection.explanationTextLowWithEncounter" static let explanationTextHigh = "AppStrings.ExposureDetection.explanationTextHigh" static let activeTracingSectionText = "AppStrings.ExposureDetection.activeTracingSectionText" static let activeTracingSection = "AppStrings.ExposureDetection.activeTracingSection" static let lowRiskExposureSection = "AppStrings.ExposureDetection.lowRiskExposureSection" static let infectionRiskExplanationSection = "AppStrings.ExposureDetection.infectionRiskExplanationSection" static let surveyCardCell = "AppStrings.ExposureDetection.surveyCardCell" static let surveyCardButton = "AppStrings.ExposureDetection.surveyCardButton" static let surveyStartButton = "AppStrings.ExposureDetection.surveyStartButton" static let closeButtonSuffix = "HygieneRulesCloseButton" static let hygieneRulesTitle = "AppStrings.ExposureDetection.hygieneRulesTitle" static let contagionTitle = "AppStrings.ExposureDetection.contagionTitle" static let detailsGuideHygiene = "AppStrings.ExposureDetection.guideHygiene" static let detailsGuideHome = "AppStrings.ExposureDetection.guideHome" } enum SurveyConsent { static let acceptButton = "AppStrings.SurveyConsent.acceptButton" static let titleImage = "AppStrings.SurveyConsent.titleImage" static let title = "AppStrings.SurveyConsent.title" static let legalDetailsButton = "AppStrings.SurveyConsent.legalDetailsButton" } enum UniversalQRScanner { static let flash = "ExposureSubmissionQRScanner_flash" static let file = "QRScanner_file" static let info = "QRScanner_info" enum Info { static let title = "QRScanner_Info_title" static let dataPrivacy = "QRScanner_Info_dataPrivacy" } static let fakeHC1 = "QRScanner_FAKE_HC1" static let fakeHC2 = "QRScanner_FAKE_HC2" static let fakePCR = "QRScanner_FAKE_PCR" static let fakePCR2 = "QRScanner_FAKE_PCR2" static let fakeEvent = "QRScanner_FAKE_EVENT" static let fakeTicketValidation = "QRScanner_FAKE_TICKET_VALIDATION" static let other = "QRScanner_OTHER" static let cancel = "QRScanner_CANCEL" } enum FileScanner { static let cancelSheet = "FileScanner_Sheet_Cancel_Button" static let photo = "FileScanner_Sheet_Photo_Button" static let file = "FileScanner_Sheet_File_Button" } enum ExposureSubmissionQRInfo { static let headerSection1 = "AppStrings.ExposureSubmissionQRInfo.headerSection1" static let headerSection2 = "AppStrings.ExposureSubmissionQRInfo.headerSection2" static let acknowledgementTitle = "ExposureSubmissionQRInfo_acknowledgement_title" static let countryList = "ExposureSubmissionQRInfo_countryList" static let dataProcessingDetailInfo = "AppStrings.AutomaticSharingConsent.dataProcessingDetailInfo" } enum ExposureSubmissionDispatch { static let description = "AppStrings.ExposureSubmissionDispatch.description" static let sectionHeadline = "AppStrings.ExposureSubmission_DispatchSectionHeadline" static let sectionHeadline2 = "AppStrings.ExposureSubmission_DispatchSectionHeadline2" static let qrCodeButtonDescription = "AppStrings.ExposureSubmissionDispatch.qrCodeButtonDescription" static let tanButtonDescription = "AppStrings.ExposureSubmissionDispatch.tanButtonDescription" static let hotlineButtonDescription = "AppStrings.ExposureSubmissionDispatch.hotlineButtonDescription" static let findTestCentersButtonDescription = "AppStrings.ExposureSubmissionDispatch.findTestCentersButtonDescription" } enum ExposureSubmissionResult { static let procedure = "AppStrings.ExposureSubmissionResult.procedure" static let furtherInfos_Title = "AppStrings.ExposureSubmissionResult.furtherInfos_Title" static let warnOthersConsentGivenCell = "AppStrings.ExposureSubmissionResult.warnOthersConsentGiven" static let warnOthersConsentNotGivenCell = "AppStrings.ExposureSubmissionResult.warnOthersConsentNotGiven" enum Antigen { static let proofDesc = "AppStrings.ExposureSubmissionResult.Antigen.proofDesc" } } enum ExposureSubmissionPositiveTestResult { static let noConsentTitle = "TestResultPositive_NoConsent_Title" static let noConsentInfo1 = "TestResultPositive_NoConsent_Info1" static let noConsentInfo2 = "TestResultPositive_NoConsent_Info2" static let noConsentInfo3 = "TestResultPositive_NoConsent_Info3" static let noConsentPrimaryButtonTitle = "TestResultPositive_NoConsent_PrimaryButton" static let noConsentSecondaryButtonTitle = "TestResultPositive_NoConsent_SecondaryButton" static let noConsentAlertTitle = "TestResultPositive_NoConsent_AlertNotWarnOthers_Title" static let noConsentAlertDescription = "TestResultPositive_NoConsent_AlertNotWarnOthers_Description" static let noConsentAlertButton1 = "TestResultPositive_NoConsent_AlertNotWarnOthers_ButtonOne" static let noConsentAlertButton2 = "TestResultPositive_NoConsent_AlertNotWarnOthers_ButtonTwo" static let withConsentTitle = "TestResultPositive_WithConsent_Title" static let withConsentInfo1 = "TestResultPositive_WithConsent_Info1" static let withConsentInfo2 = "TestResultPositive_WithConsent_Info2" static let withConsentPrimaryButtonTitle = "TestResultPositive_WithConsent_PrimaryButton" static let withConsentSecondaryButtonTitle = "TestResultPositive_WithConsent_SecondaryButton" } enum ExposureSubmissionSuccess { static let accImageDescription = "AppStrings.ExposureSubmissionSuccess.accImageDescription" static let description = "AppStrings.ExposureSubmissionSuccess.description" static let listTitle = "AppStrings.ExposureSubmissionSuccess.listTitle" static let subTitle = "AppStrings.ExposureSubmissionSuccess.subTitle" static let closeButton = "AppStrings.ExposureSubmissionSuccess.button" } enum ExposureSubmissionHotline { static let imageDescription = "AppStrings.ExposureSubmissionHotline.imageDescription" static let description = "AppStrings.ExposureSubmissionHotline.description" static let sectionTitle = "AppStrings.ExposureSubmissionHotline.sectionTitle" static let primaryButton = "AppStrings.ExposureSubmissionHotline.tanInputButtonTitle" } enum ExposureSubmissionIntroduction { static let subTitle = "AppStrings.ExposureSubmissionIntroduction.subTitle" static let usage01 = "AppStrings.ExposureSubmissionIntroduction.usage01" static let usage02 = "AppStrings.ExposureSubmissionIntroduction.usage02" } enum ExposureSubmissionSymptoms { static let description = "AppStrings.ExposureSubmissionSymptoms.description" static let introduction = "AppStrings.ExposureSubmissionSymptoms.introduction" static let answerOptionYes = "AppStrings.ExposureSubmissionSymptoms.answerOptionYes" static let answerOptionNo = "AppStrings.ExposureSubmissionSymptoms.answerOptionNo" static let answerOptionPreferNotToSay = "AppStrings.ExposureSubmissionSymptoms.answerOptionPreferNotToSay" } enum ExposureSubmissionSymptomsOnset { static let description = "AppStrings.ExposureSubmissionSymptomsOnset.description" static let answerOptionExactDate = "AppStrings.ExposureSubmissionSymptomsOnset.answerOptionExactDate" static let answerOptionLastSevenDays = "AppStrings.ExposureSubmissionSymptomsOnset.answerOptionLastSevenDays" static let answerOptionOneToTwoWeeksAgo = "AppStrings.ExposureSubmissionSymptomsOnset.answerOptionOneToTwoWeeksAgo" static let answerOptionMoreThanTwoWeeksAgo = "AppStrings.ExposureSubmissionSymptomsOnset.answerOptionMoreThanTwoWeeksAgo" static let answerOptionPreferNotToSay = "AppStrings.ExposureSubmissionSymptomsOnset.answerOptionPreferNotToSay" } enum ExposureSubmissionWarnOthers { static let accImageDescription = "AppStrings.ExposureSubmissionWarnOthers.accImageDescription" static let sectionTitle = "AppStrings.ExposureSubmissionWarnOthers.sectionTitle" static let description = "AppStrings.ExposureSubmissionWarnOthers.description" static let acknowledgementTitle = "AppStrings.ExposureSubmissionWarnOthers.acknowledgement_title" static let countryList = "AppStrings.ExposureSubmissionWarnOthers.countryList" static let dataProcessingDetailInfo = "AppStrings.AppStrings.ExposureSubmissionWarnOthers.dataProcessingDetailInfo" } enum DeltaOnboarding { static let accImageDescription = "AppStrings.DeltaOnboarding.accImageLabel" static let newVersionFeaturesAccImageDescription = "AppStrings.DeltaOnboarding.newVersionFeaturesAccImageLabel" static let newVersionFeaturesGeneralDescription = "AppStrings.DeltaOnboarding.NewVersionFeatures.GeneralDescription" static let newVersionFeaturesGeneralAboutAppInformation = "AppStrings.DeltaOnboarding.NewVersionFeatures.AboutAppInformation" static let newVersionFeaturesVersionInfo = "AppStrings.DeltaOnboarding.NewVersionFeatures.VersionInfo" static let sectionTitle = "AppStrings.DeltaOnboarding.title" static let description = "AppStrings.DeltaOnboarding.description" static let downloadInfo = "AppStrings.DeltaOnboarding.downloadInfo" static let participatingCountriesListUnavailable = "AppStrings.DeltaOnboarding.participatingCountriesListUnavailable" static let participatingCountriesListUnavailableTitle = "AppStrings.DeltaOnboarding.participatingCountriesListUnavailableTitle" static let primaryButton = "AppStrings.DeltaOnboarding.primaryButton" } enum ExposureSubmissionWarnEuropeConsent { static let imageDescription = "AppStrings.ExposureSubmissionWarnEuropeConsent.imageDescription" static let sectionTitle = "AppStrings.ExposureSubmissionWarnEuropeConsent.sectionTitle" static let consentSwitch = "AppStrings.ExposureSubmissionWarnEuropeConsent.consentSwitch" } enum ExposureSubmissionWarnEuropeTravelConfirmation { static let description1 = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.description1" static let description2 = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.description2" static let optionYes = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.optionYes" static let optionNo = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.optionNo" static let optionNone = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.optionNone" } enum LocalStatistics { static let title = "AppStrings.Statistics.Card.Incidence.title" static let infoButton = "AppStrings.Statistics.Card.Incidence.infoButton" static let selectState = "AppStrings.LocalStatistics.selectState" static let selectDistrict = "AppStrings.LocalStatistics.selectDistrict" static let manageStatisticsCard = "AppStrings.LocalStatistics.manageStatisticsCard" static let localStatisticsCard = "AppStrings.LocalStatistics.localStatisticsCard" static let localStatisticsCardTitle = "AppStrings.LocalStatistics.localStatisticsCardTitle" static let addLocalIncidencesButton = "AppStrings.LocalStatistics.addLocalIncidencesButton" static let addLocalIncidenceLabel = "AppStrings.LocalStatistics.addLocalIncidenceLabel" static let modifyLocalIncidencesButton = "AppStrings.LocalStatistics.modifyLocalIncidencesButton" static let modifyLocalIncidenceLabel = "AppStrings.LocalStatistics.modifyLocalIncidenceLabel" } enum ExposureSubmissionWarnEuropeCountrySelection { static let description1 = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.description1" static let description2 = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.description2" static let answerOptionCountry = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.answerOptionCountry" static let answerOptionOtherCountries = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.answerOptionOtherCountries" static let answerOptionNone = "AppStrings.ExposureSubmissionWarnEuropeTravelConfirmation.answerOptionNone" } enum ExposureSubmission { static let primaryButton = "AppStrings.ExposureSubmission.primaryButton" static let secondaryButton = "AppStrings.ExposureSubmission.secondaryButton" enum OverwriteNotice { static let imageDescription = "AppStrings.ExposureSubmission.OverwriteNotice.imageDescription" enum Pcr { static let headline = "AppStrings.ExposureSubmission.OverwriteNotice.Pcr.headline" static let text = "AppStrings.ExposureSubmission.OverwriteNotice.Pcr.text" } enum Antigen { static let headline = "AppStrings.ExposureSubmission.OverwriteNotice.Antigen.headline" static let text = "AppStrings.ExposureSubmission.OverwriteNotice.Antigen.text" } } enum AntigenTest { enum Information { static let imageDescription = "AppStrings.ExposureSubmission.AntigenTest.Information.imageDescription" static let descriptionTitle = "AppStrings.ExposureSubmission.AntigenTest.Information.descriptionTitle" static let descriptionSubHeadline = "AppStrings.ExposureSubmission.AntigenTest.Information.descriptionSubHeadline" static let acknowledgementTitle = "AntigenTest_Information_acknowledgement_title" static let dataPrivacyTitle = "AppStrings.ExposureSubmission.AntigenTest.Information.dataPrivacyTitle" static let continueButton = "AppStrings.ExposureSubmission.AntigenTest.Information.primaryButton" } enum Create { static let saveButton = "AppStrings.AntigenProfile.Create.saveButtonTitle" } enum Profile { static let profileTile_Description = "AppStrings.ExposureSubmission.AntigenTest.Profile.profileTile_Description" static let createProfileTile_Description = "AppStrings.ExposureSubmission.AntigenTest.Profile.createProfileTile_Description" static let continueButton = "AppStrings.ExposureSubmission.AntigenTest.Profile.primaryButton" static let editButton = "AppStrings.ExposureSubmission.AntigenTest.Profile.secondaryButton" static let deleteAction = "AppStrings.ExposureSubmission.AntigenTest.Profile.deleteAction" static let editAction = "AppStrings.ExposureSubmission.AntigenTest.Profile.editAction" } } enum TestCertificate { enum Info { static let imageDescription = "AppStrings.ExposureSubmission.TestCertificate.Info.imageDescription" static let body = "AppStrings.ExposureSubmission.TestCertificate.Info.body" static let acknowledgementTitle = "ExposureSubmissionTestCertificateInfo_acknowledgement_title" static let dataPrivacyTitle = "AppStrings.ExposureSubmission.TestCertificate.Info.dataPrivacyTitle" static let birthdayPlaceholder = "AppStrings.ExposureSubmission.TestCertificate.Info.birthDayPlaceholder" static let birthdayText = "AppStrings.ExposureSubmission.TestCertificate.Info.birthDayText" } } } enum ExposureSubmissionTestResultConsent { static let switchIdentifier = "ExposureSubmissionTestResultConsent.SwitchIdentifier" } enum ExposureSubmissionTestResultAvailable { static let primaryButton = "AppStrings.ExposureSubmissionTestResultAvailable.primaryButtonTitle" } enum Reset { static let imageDescription = "AppString.Reset.imageDescription" } enum AccessibilityLabel { static let close = "AppStrings.AccessibilityLabel.close" } enum InviteFriends { static let imageAccessLabel = "AppStrings.InviteFriends.imageAccessLabel" } enum General { static let exposureSubmissionNavigationControllerTitle = "ExposureSubmissionNavigationController" static let image = "ExposureSubmissionIntroViewController.image" static let primaryFooterButton = "General.primaryFooterButton" static let secondaryFooterButton = "General.secondaryFooterButton" static let cancelButton = "General.cancelButton" static let defaultButton = "General.defaultButton" static let deleteButton = "General.deleteButton" static let webView = "HTMLView" } enum DatePickerOption { static let day = "AppStrings.DatePickerOption.day" } enum ThankYouScreen { static let accImageDescription = "AppStrings.ThankYouScreen.accImageDescription" } enum Statistics { enum Infections { static let title = "AppStrings.Statistics.Card.Infections.title" static let infoButton = "AppStrings.Statistics.Card.Infections.infoButton" } enum KeySubmissions { static let title = "AppStrings.Statistics.Card.KeySubmissions.title" static let infoButton = "AppStrings.Statistics.Card.KeySubmissions.infoButton" } enum ReproductionNumber { static let title = "AppStrings.Statistics.Card.ReproductionNumber.title" static let infoButton = "AppStrings.Statistics.Card.ReproductionNumber.infoButton" } enum AtLeastOneVaccination { static let title = "AppStrings.Statistics.Card.AtLeastOneVaccination.title" static let infoButton = "AppStrings.Statistics.Card.AtLeastOneVaccination.infoButton" } enum FullyVaccinated { static let title = "AppStrings.Statistics.Card.FullyVaccinated.title" static let infoButton = "AppStrings.Statistics.Card.FullyVaccinated.infoButton" } enum BoosterVaccination { static let title = "AppStrings.Statistics.Card.BoosterVaccination.title" static let infoButton = "AppStrings.Statistics.Card.BoosterVaccination.infoButton" } enum Doses { static let title = "AppStrings.Statistics.Card.Doses.title" static let infoButton = "AppStrings.Statistics.Card.Doses.infoButton" } enum IntensiveCare { static let title = "AppStrings.Statistics.Card.IntensiveCare.title" static let infoButton = "AppStrings.Statistics.Card.IntensiveCare.infoButton" } enum Combined7DayIncidence { static let title = "AppStrings.Statistics.Card.Combined7DayIncidence.title" static let infoButton = "AppStrings.Statistics.Card.Combined7DayIncidence.infoButton" } enum General { static let tableViewCell = "HomeStatisticsTableViewCell" static let card = "HomeStatisticsCard" } } enum UpdateOSScreen { static let mainImage = "UpdateOSScreen.mainImage" static let logo = "UpdateOSScreen.logo" static let title = "UpdateOSScreen.title" static let text = "UpdateOSScreen.text" } enum TabBar { static let home = "TabBar.home" static let certificates = "TabBar.certificates" static let scanner = "TabBar.scanner" static let checkin = "TabBar.checkin" static let diary = "TabBar.diary" } enum DataDonation { static let accImageDescription = "AppStrings.DataDonation.Info.accImageDescription" static let accDataDonationTitle = "AppStrings.DataDonation.Info.title" static let accDataDonationDescription = "AppStrings.DataDonation.Info.description" static let accSubHeadState = "AppStrings.DataDonation.Info.subHeadState" static let accSubHeadAgeGroup = "AppStrings.DataDonation.Info.subHeadAgeGroup" static let consentSwitch = "DataDonation.Consent.Switch" static let federalStateName = "AppStrings.DataDonation.Info.noSelectionState" static let regionName = "AppStrings.DataDonation.Info.noSelectionRegion" static let ageGroup = "AppStrings.DataDonation.Info.noSelectionAgeGroup" static let federalStateCell = "DataDonation.FederalState.Identifier" static let regionCell = "DataDonation.Region.Identifier" static let ageGroupCell = "DataDonation.AgeGroup.Identifier" } enum ErrorReport { // Main Error Logging Screen // - top ViewController static let navigation = "AppStrings.ErrorReport.navigation" static let topBody = "AppStrings.ErrorReport.topBody" static let faq = "AppStrings.ErrorReport.faq" static let privacyInformation = "AppStrings.ErrorReport.privacyInformation" static let privacyNavigation = "AppStrings.ErrorReport.privacyNavigation" static let historyNavigation = "AppStrings.ErrorReport.historyNavigation" static let historyTitle = "AppStrings.ErrorReport.historyTitle" static let historyDescription = "AppStrings.ErrorReport.historyDescription" static let startButton = "AppStrings.ErrorReport.startButtonTitle" static let sendReportButton = "AppStrings.ErrorReport.sendButtontitle" static let saveLocallyButton = "AppStrings.ErrorReport.saveButtonTitle" static let stopAndDeleteButton = "AppStrings.ErrorReport.stopAndDeleteButtonTitle" static let legalSendReports = "AppStrings.ErrorReport.Legal.sendReports_Headline" static let sendReportsDetails = "AccessibilityIdentifiers.ErrorReport.sendReportsDetails" static let detailedInformationTitle = "AccessibilityIdentifiers.ErrorReport.detailedInformationTitle" static let detailedInformationSubHeadline = "AccessibilityIdentifiers.ErrorReport.detailedInformationSubHeadline" static let detailedInformationContent2 = "AccessibilityIdentifiers.ErrorReport.detailedInformationContent2" static let agreeAndSendButton = "AccessibilityIdentifiers.ErrorReport.agreeAndSendButton" } enum TraceLocation { static let imageDescription = "AppStrings.TraceLocations.imageDescription" static let descriptionTitle = "AppStrings.TraceLocations.descriptionTitle" static let descriptionSubHeadline = "AppStrings.TraceLocations.descriptionSubHeadline" static let dataPrivacyTitle = "AppStrings.TraceLocations.dataPrivacyTitle" static let acknowledgementTitle = "TraceLocation.acknowledgementTitle" static let legal_1 = "AppStrings.TraceLocations.legalHeadline_1" enum Details { static let printVersionButton = "AppStrings.TraceLocations.Details.printVersionButtonTitle" static let duplicateButton = "AppStrings.TraceLocations.Details.duplicateButtonTitle" static let titleLabel = "AppStrings.TraceLocations.Details.titleLabel" static let locationLabel = "AppStrings.TraceLocations.Details.locationLabel" static let checkInButton = "AppStrings.Checkins.Details.checkInButton" } enum Overview { static let tableView = "TableView.TracelocationOverview" static let menueButton = "AppStrings.TraceLocations.Overview.menueButton" } enum Configuration { static let descriptionPlaceholder = "AppStrings.TraceLocations.Configuration.descriptionPlaceholder" static let addressPlaceholder = "AppStrings.TraceLocations.Configuration.addressPlaceholder" static let temporaryDefaultLengthTitleLabel = "AppStrings.TraceLocations.Configuration.temporaryDefaultLengthTitleLabel" static let temporaryDefaultLengthFootnoteLabel = "AppStrings.TraceLocations.Configuration.temporaryDefaultLengthFootnoteLabel" static let permanentDefaultLengthTitleLabel = "AppStrings.TraceLocations.Configuration.permanentDefaultLengthTitleLabel" static let permanentDefaultLengthFootnoteLabel = "AppStrings.TraceLocations.Configuration.permanentDefaultLengthFootnoteLabel" static let eventTableViewCellButton = "AppStrings.TraceLocations.Configuration.eventTableViewCellButton" } } enum Checkin { enum Overview { static let menueButton = "AppStrings.CheckIn.Overview.menueButton" } enum Details { static let typeLabel = "AppStrings.CheckIn.Edit.checkedOut" static let traceLocationTypeLabel = "AppStrings.CheckIn.Edit.traceLocationTypeLabel" static let traceLocationDescriptionLabel = "AppStrings.CheckIn.Edit.traceLocationDescriptionLabel" static let traceLocationAddressLabel = "AppStrings.CheckIn.Edit.traceLocationAddressLabel" static let saveToDiary = "AppStrings.Checkins.Details.saveToDiary" static let automaticCheckout = "AppStrings.Checkins.Details.automaticCheckout" static let checkinFor = "AppStrings.Checkins.Details.checkinFor" } enum Information { static let imageDescription = "AppStrings.Checkins.Information.imageDescription" static let descriptionTitle = "AppStrings.Checkins.Information.descriptionTitle" static let descriptionSubHeadline = "AppStrings.Checkins.Information.descriptionSubHeadline" static let dataPrivacyTitle = "AppStrings.Checkins.Information.dataPrivacyTitle" static let primaryButton = "AppStrings.Checkins.Information.primaryButton" static let acknowledgementTitle = "Checkins.Information.acknowledgement_title" } } enum OnBehalfCheckinSubmission { enum TraceLocationSelection { static let selectionCell = "OnBehalfCheckinSubmission.TraceLocationSelection.selectionCell" } enum DateTimeSelection { static let dateCell = "OnBehalfCheckinSubmission.DateTimeSelection.dateCell" static let durationCell = "OnBehalfCheckinSubmission.DateTimeSelection.durationCell" } } enum AntigenProfile { enum Create { static let title = "AppStrings.AntigenProfile.Create.title" static let description = "AppStrings.AntigenProfile.Create.description" static let firstNameTextField = "AppStrings.AntigenProfile.Create.firstNameTextFieldPlaceholder" static let lastNameTextField = "AppStrings.AntigenProfile.Create.lastNameTextFieldPlaceholder" static let birthDateTextField = "AppStrings.AntigenProfile.Create.birthDateTextFieldPlaceholder" static let streetTextField = "AppStrings.AntigenProfile.Create.streetTextFieldPlaceholder" static let postalCodeTextField = "AppStrings.AntigenProfile.Create.postalCodeTextFieldPlaceholder" static let cityTextField = "AppStrings.AntigenProfile.Create.cityTextFieldPlaceholder" static let phoneNumberTextField = "AppStrings.AntigenProfile.Create.phoneNumberTextFieldPlaceholder" static let emailAddressTextField = "AppStrings.AntigenProfile.Create.emailAddressTextFieldPlaceholder" static let saveButtonTitle = "AppStrings.AntigenProfile.Create.saveButtonTitle" } } enum HealthCertificate { enum Validation { static let countrySelection = "HealthCertificate.Validation.CountrySelection" static let dateTimeSelection = "HealthCertificate.Validation.DateTimeSelection" enum Info { static let imageDescription = "AppStrings.HealthCertificate.Validation.Info.imageDescription" } } enum Overview { static let changeAdmissionScenarioCell = "AppStrings.HealthCertificate.changeAdmissionScenarioCell" static let healthCertifiedPersonCell = "AppStrings.HealthCertificate.healthCertifiedPersonCell" static let testCertificateRequestCell = "AppStrings.HealthCertificate.testCertificateRequestCell" } enum Info { static let imageDescription = "AppStrings.HealthCertificate.Info.imageDescription" enum Register { static let headline = "AppStrings.HealthCertificate.Info.Register.headline" static let text = "AppStrings.HealthCertificate.Info.Register.text" } static let disclaimer = "AppStrings.HealthCertificate.Info.disclaimer" static let acknowledgementTitle = "HealthCertificate.Info.acknowledgement" } enum Person { static let certificateCell = "HealthCertificate.Person.cell" static let validationButton = "HealthCertificate.Person.validationButton" enum UpdateSucceeded { static let image = "HealthCertificate.Person.UpdateSucceeded.image" } } enum AdmissionState { static let roundedView = "HealthCertificate.AdmissionState.roundedView" static let title = "HealthCertificate.AdmissionState.title" static let subtitle = "HealthCertificate.AdmissionState.subtitle" static let description = "HealthCertificate.AdmissionState.description" static let faq = "HealthCertificate.AdmissionState.faq" } enum Certificate { static let headline = "HealthCertificate.title" static let deleteButton = "HealthCertificate.deleteButton" static let deletionConfirmationButton = "HealthCertificate.deletionConfirmationButton" } enum PrintPdf { static let imageDescription = "AppStrings.HealthCertificate.PrintPDF.imageDescription" static let infoPrimaryButton = "AppStrings.HealthCertificate.PrintPDF.infoPrimaryButton" static let printButton = "AppStrings.HealthCertificate.PrintPDF.printButton" static let shareButton = "AppStrings.HealthCertificate.PrintPDF.shareButton" static let faqAction = "AppStrings.HealthCertificate.PrintPDF.faqAction" static let okAction = "AppStrings.HealthCertificate.PrintPDF.okAction" } static let qrCodeCell = "HealthCertificate.qrCodeCell" enum Reissuance { static let cell = "AppStrings.HealthCertificate.Reissuance.cell" static let successTitle = "AppStrings.HealthCertificate.Reissuance.successTitle" } } enum TicketValidation { enum FirstConsent { static let image = "TicketValidation.FirstConsent.image" static let legalBox = "TicketValidation.FirstConsent.legalBox" static let dataPrivacy = "TicketValidation.FirstConsent.dataPrivacy" static let primaryButton = "TicketValidation.FirstConsent.primaryButton" static let secondaryButton = "TicketValidation.FirstConsent.secondaryButton" } enum SecondConsent { static let legalBox = "TicketValidation.SecondConsent.legalBox" static let dataPrivacy = "TicketValidation.SecondConsent.dataPrivacy" static let primaryButton = "TicketValidation.SecondConsent.primaryButton" static let secondaryButton = "TicketValidation.SecondConsent.secondaryButton" } enum ValidationResult { enum Passed { static let headerImageWithTitle = "TicketValidation.ValidationResult.Passed.headerImageWithTitle" static let subtitle = "TicketValidation.ValidationResult.Passed.subtitle" } enum Failed { static let headerImageWithTitle = "TicketValidation.ValidationResult.Failed.headerImageWithTitle" static let subtitle = "TicketValidation.ValidationResult.Failed.subtitle" } enum Open { static let headerImageWithTitle = "TicketValidation.ValidationResult.Open.headerImageWithTitle" static let subtitle = "TicketValidation.ValidationResult.Open.subtitle" } } } enum BoosterNotification { enum Details { static let image = "BoosterNotification.Details.image" static let boosterNotificationCell = "BoosterNotification.Details.boosterNotificationCell" } } }
52.979493
158
0.829668
3ab0867035a3ec58a42dd6301f76727102049162
2,201
// // AppDelegate.swift // PermissionScope-example // // Created by Nick O'Neill on 4/5/15. // Copyright (c) 2015 That Thing in Swift. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> 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:. } }
47.847826
285
0.753294
466ad8f26092255fd2988cba5fc952b0d6d9af18
4,682
// // RequestOperation.swift // Restofire // // Created by Rahul Katariya on 18/04/16. // Copyright © 2016 AarKay. All rights reserved. // import Foundation import Alamofire /// An NSOperation that executes the `Requestable` asynchronously on `start()` /// or when added to a NSOperationQueue /// /// - Note: Auto Retry is available only in `RequestEventuallyOperation`. public class RequestOperation<R: Requestable>: NSOperation { var request: Request! let requestable: R let completionHandler: (Response<R.Model, NSError> -> Void)? var retryAttempts = 0 init(requestable: R, completionHandler: (Response<R.Model, NSError> -> Void)?) { self.requestable = requestable retryAttempts = requestable.maxRetryAttempts self.completionHandler = completionHandler super.init() _ready = super.ready } var successful = false { didSet { if successful { executing = false finished = true } } } var failed = false { didSet { if failed { executing = false finished = true } } } var pause = false { didSet { if pause { resume = false request.suspend() } } } var resume = false { didSet { if resume { pause = false executeRequest() } } } var _ready: Bool = false /// A Boolean value indicating whether the operation can be performed now. (read-only) public override internal(set) var ready: Bool { get { return _ready } set (newValue) { willChangeValueForKey("isReady") _ready = newValue didChangeValueForKey("isReady") } } var _executing: Bool = false /// A Boolean value indicating whether the operation is currently executing. (read-only) public override private(set) var executing: Bool { get { return _executing } set (newValue) { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") } } var _cancelled: Bool = false /// A Boolean value indicating whether the operation has been cancelled. (read-only) public override private(set) var cancelled: Bool { get { return _cancelled } set (newValue) { willChangeValueForKey("isCancelled") _cancelled = newValue didChangeValueForKey("isCancelled") } } var _finished: Bool = false /// A Boolean value indicating whether the operation has finished executing its task. (read-only) public override private(set) var finished: Bool { get { return _finished } set (newValue) { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } /// Begins the execution of the operation. public override func start() { if cancelled { finished = true return } executing = true requestable.didStartRequest() executeRequest() } func executeRequest() { request = AlamofireUtils.alamofireRequestFromRequestable(requestable) request.restofireResponse(queue: requestable.queue, responseSerializer: requestable.responseSerializer) { (response: Response<R.Model, NSError>) in if response.result.error == nil { self.successful = true self.requestable.didCompleteRequestWithResponse(response) if let completionHandler = self.completionHandler { completionHandler(response) } } else { self.handleErrorResponse(response) } if self.requestable.logging { debugPrint(self.request) debugPrint(response) } } } func handleErrorResponse(response: Response<R.Model, NSError>) { self.failed = true self.requestable.didCompleteRequestWithResponse(response) if let completionHandler = self.completionHandler { completionHandler(response) } } /// Advises the operation object that it should stop executing its request. public override func cancel() { request.cancel() executing = false cancelled = true finished = true } }
28.901235
155
0.574754
1d693c24a92b6c8b4358dc7ba704b2ed47e21665
4,897
// // LLAExtensionPackTestString.swift // LLAExtensionPackTests // // Created by Daisuke T on 2018/12/07. // Copyright © 2018 Daisuke T. All rights reserved. // import XCTest @testable import LLAExtensionPack class LLAExtensionPackTestString: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testCompare() { XCTAssertTrue("string".isEqual("string")) XCTAssertFalse("string".isEqual("String")) XCTAssertTrue("string".isEqual("String", caseInsensitive: true)) } func testFind() { XCTAssertTrue("string".hasPrefix("str")) XCTAssertFalse("string".hasPrefix("Str")) XCTAssertTrue("string".hasPrefix("Str", caseInsensitive: true)) XCTAssertTrue("string".hasSuffix("ing")) XCTAssertFalse("string".hasSuffix("Ing")) XCTAssertTrue("string".hasSuffix("Ing", caseInsensitive: true)) XCTAssertTrue("string".contains("tri")) XCTAssertFalse("string".contains("Tri")) XCTAssertTrue("string".contains("Tri", caseInsensitive: true)) XCTAssertNotNil("string".range("str")) XCTAssertNil("string".range("Str")) XCTAssertNotNil("string".range("Str", caseInsensitive: true)) } func testSubstring() { let str = "string" XCTAssertEqual(str[str.startIndex(0)!...], "string") XCTAssertEqual(str[str.startIndex(0)!..<str.startIndex(2)!], "st") XCTAssertEqual(str[str.startIndex(0)!...str.startIndex(2)!], "str") XCTAssertEqual(str[...str.startIndex(str.count - 1)!], "string") XCTAssertEqual(str[..<str.startIndex(str.count)!], "string") XCTAssertEqual(str[...str.endIndex(-1)!], "string") XCTAssertEqual(str[str.endIndex(-3)!..<str.endIndex(-1)!], "in") XCTAssertEqual(str[str.endIndex(-3)!...str.endIndex(-1)!], "ing") XCTAssertEqual(str[str.endIndex(-6)!...], "string") XCTAssertEqual(str.substring(1, end: 3), "tri") XCTAssertEqual(str.substring(NSMakeRange(1, 3)), "tri") XCTAssertEqual(str.substringFromIndex(1), "tring") XCTAssertEqual(str.substringToIndex(3), "str") } func testSubscript() { let str = "string" XCTAssertEqual(str[0..<2], "st") XCTAssertEqual(str[0...2], "str") XCTAssertEqual(str[1..<3], "tr") XCTAssertEqual(str[1...3], "tri") XCTAssertEqual(str[1...], "tring") XCTAssertEqual(str[...2], "str") } func testInspect() { XCTAssertTrue("1".isNumeric) XCTAssertTrue("123".isNumeric) XCTAssertFalse("A".isNumeric) XCTAssertFalse("1A3".isNumeric) } func testReplace() { XCTAssertEqual("string".replace("str", replacement: "STR"), "STRing") XCTAssertEqual("string".replace("string", replacement: ""), "") XCTAssertEqual("string".replace("", replacement: "STR"), "string") XCTAssertEqual("string".replace("Str", replacement: "STR"), "string") XCTAssertEqual("string".replace("STR", replacement: "", caseInsensitive: true), "ing") } func testRemove() { XCTAssertEqual("string".remove("str"), "ing") XCTAssertEqual("string".remove("string"), "") XCTAssertEqual("string".remove(""), "string") XCTAssertEqual("string".remove("Str"), "string") XCTAssertEqual("string".remove("STR", caseInsensitive: true), "ing") } func testEncode() { XCTAssertEqual("abcABC1234/?-._~".urlEncoding, "abcABC1234/?-._~") XCTAssertEqual(":#[]@!$&'()*+,;=".urlEncoding, "%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D") } func testHash() { XCTAssertEqual("string".md2, "a06d078cf87b3349d4400afca892ed42") XCTAssertEqual("string".md4, "70a2421dd08cce128b3af8ad1dfa74ac") XCTAssertEqual("string".md5, "b45cffe084dd3d20d928bee85e7b0f21") XCTAssertEqual("string".sha1, "ecb252044b5ea0f679ee78ec1a12904739e2904d") XCTAssertEqual("string".sha224, "474b4afcaa4303cfc8f697162784293e812f12e2842551d726db8037") XCTAssertEqual("string".sha256, "473287f8298dba7163a897908958f7c0eae733e25d2e027992ea2edc9bed2fa8") XCTAssertEqual("string".sha384, "36396a7e4de3fa1c2156ad291350adf507d11a8f8be8b124a028c5db40785803ca35a7fc97a6748d85b253babab7953e") XCTAssertEqual("string".sha512, "2757cb3cafc39af451abb2697be79b4ab61d63d74d85b0418629de8c26811b529f3f3780d0150063ff55a2beee74c4ec102a2a2731a1f1f7f10d473ad18a6a87") } func testTransform() { XCTAssertEqual("STRING".fullWidth, "STRING") XCTAssertEqual("STRING".halfWidth, "STRING") XCTAssertEqual("STRING".fullWidth, "STRING") XCTAssertEqual("STRING".halfWidth, "STRING") XCTAssertEqual("ことえり".hiragana, "ことえり") XCTAssertEqual("ことえり".katakana, "コトエリ") XCTAssertEqual("コトエリ".hiragana, "ことえり") XCTAssertEqual("コトエリ".katakana, "コトエリ") } }
36.274074
167
0.686339
e28ad4214308281141e8e0e292bf6ccf0e6f8ec2
446
// // Localization.swift // JumuNordost // // Created by Martin Richter on 14/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Foundation /// Returns a localized string for the given key. func localize(key: String) -> String { return NSLocalizedString(key, comment: "") } extension NSLocale { static func localeMatchingAppLanguage() -> NSLocale { return NSLocale(localeIdentifier: "de_DE") } }
21.238095
57
0.692825
0332aaacbc457b9c3bfffba836f2682a44944697
832
// CHECK: @available(swift 5.0) // CHECK-NEXT: func fiveOnly() -> Int @available(swift, introduced: 5.0) public func fiveOnly() -> Int { return 4 } // CHECK: @available(swift 5.0) // CHECK-NEXT: @available(macOS 10.1, *) // CHECK-NEXT: func fiveOnlyWithMac() -> Int @available(swift, introduced: 5.0) @available(macOS, introduced: 10.1) public func fiveOnlyWithMac() -> Int { return 4 } // CHECK: @available(swift 5.0) // CHECK-NEXT: @available(macOS 10.1, *) // CHECK-NEXT: func fiveOnlyWithMac2() -> Int @available(macOS, introduced: 10.1) @available(swift, introduced: 5.0) public func fiveOnlyWithMac2() -> Int { return 4 } // CHECK: @available(swift, introduced: 4.0, obsoleted: 5.0) // CHECK-NEXT: func fourOnly() -> Int @available(swift, introduced: 4.0, obsoleted: 5.0) public func fourOnly() -> Int { return 3 }
26
60
0.677885
d752460a97cf77aabe672784542661cb8c8b2c86
1,537
// REQUIRES: shell // Check that 'swiftpp' and 'swiftpp repl' invoke the REPL. // RUN: rm -rf %t.dir // RUN: mkdir -p %t.dir/usr/bin // RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t.dir/usr/bin/swift) // RUN: %t.dir/usr/bin/swift -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s // RUN: %t.dir/usr/bin/swift repl -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s // CHECK-SWIFT-INVOKES-REPL: {{.*}}/swift -frontend -repl // RUN: %empty-directory(%t.dir) // RUN: %empty-directory(%t.dir/subpath) // RUN: echo "print(\"exec: \" + #file)" > %t.dir/stdin // RUN: echo "print(\"exec: \" + #file)" > %t.dir/t.swift // RUN: echo "print(\"exec: \" + #file)" > %t.dir/subpath/build // RUN: cd %t.dir && %swift_driver_plain -### - < %t.dir/stdin 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-INTERPRETER %s // RUN: cd %t.dir && %swift_driver_plain -### t.swift 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-INTERPRETER %s // RUN: cd %t.dir && %swift_driver_plain -### subpath/build 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-INTERPRETER %s // CHECK-SWIFT-INVOKES-INTERPRETER: {{.*}}/swift -frontend -interpret // Check that 'swift foo' invokes 'swift-foo'. // // RUN: %empty-directory(%t.dir) // RUN: echo "#!/bin/sh" > %t.dir/swift-foo // RUN: echo "echo \"exec: \$0\"" >> %t.dir/swift-foo // RUN: chmod +x %t.dir/swift-foo // RUN: env PATH=%t.dir %swift_driver_plain foo | %FileCheck -check-prefix=CHECK-SWIFT-SUBCOMMAND %s // CHECK-SWIFT-SUBCOMMAND: exec: {{.*}}/swift-foo
45.205882
129
0.648666
de35b00237d121a08da75bf5bb86b466d613c80a
6,527
// TimelineView.swift // // Copyright (c) 2016 Danil Gontovnik (http://gontovnik.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit open class TimelineView: UIView { // MARK: - Vars /// The duration of the video in seconds. open var duration: TimeInterval = 0.0 { didSet { setNeedsDisplay() } } /// Time in seconds when rewind began. open var initialTime: TimeInterval = 0.0 { didSet { currentTime = initialTime } } /// Current timeline time in seconds. open var currentTime: TimeInterval = 0.0 { didSet { setNeedsDisplay() currentTimeDidChange?(currentTime) } } /// Internal zoom variable. fileprivate var _zoom: CGFloat = 1.0 { didSet { setNeedsDisplay() } } /// The zoom of the timeline view. The higher zoom value, the more accurate rewind is. Default is 1.0. open var zoom: CGFloat { get { return _zoom } set { _zoom = max(min(newValue, maxZoom), minZoom) } } /// Indicates minimum zoom value. Default is 1.0. open var minZoom: CGFloat = 1.0 { didSet { zoom = _zoom } } /// Indicates maximum zoom value. Default is 3.5. open var maxZoom: CGFloat = 3.5 { didSet { zoom = _zoom } } /// The width of a line representing a specific time interval on a timeline. If zoom is not equal 1, then actual interval width equals to intervalWidth * zoom. Value will be used during rewind for calculations — for example, if zoom is 1, intervalWidth is 30 and intervalDuration is 15, then when user moves 10pixels left or right we will rewind by +5 or -5 seconds; open var intervalWidth: CGFloat = 24.0 { didSet { setNeedsDisplay() } } /// The duration of an interval in seconds. If video is 55 seconds and interval is 15 seconds — then we will have 3 full intervals and one not full interval. Value will be used during rewind for calculations. open var intervalDuration: CGFloat = 15.0 { didSet { setNeedsDisplay() } } /// Block which will be triggered everytime currentTime value changes. open var currentTimeDidChange: ((TimeInterval) -> ())? // MARK: - Constructors public init() { super.init(frame: .zero) isOpaque = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Methods /** Calculate current interval width. It takes two variables in count - intervalWidth and zoom. */ fileprivate func currentIntervalWidth() -> CGFloat { return intervalWidth * zoom } /** Calculates time interval in seconds from passed width. - Parameter width: The distance. */ open func timeIntervalFromDistance(_ distance: CGFloat) -> TimeInterval { return TimeInterval(distance * intervalDuration / currentIntervalWidth()) } /** Calculates distance from given time interval. - Parameter duration: The duration of an interval. */ open func distanceFromTimeInterval(_ timeInterval: TimeInterval) -> CGFloat { return currentIntervalWidth() * CGFloat(timeInterval) / intervalDuration } /** Rewinds by distance. Calculates interval width and adds it to the current time. - Parameter distance: The distance how far it should rewind by. */ open func rewindByDistance(_ distance: CGFloat) { let newCurrentTime = currentTime + timeIntervalFromDistance(distance) currentTime = max(min(newCurrentTime, duration), 0.0) } // MARK: - Draw override open func draw(_ rect: CGRect) { super.draw(rect) let intervalWidth = currentIntervalWidth() let originX: CGFloat = bounds.width / 2.0 - distanceFromTimeInterval(currentTime) let context = UIGraphicsGetCurrentContext() let lineHeight: CGFloat = 5.0 // Calculate how many intervals it contains let intervalsCount = CGFloat(duration) / intervalDuration // Draw full line context?.setFillColor(UIColor(white: 0.45, alpha: 1.0).cgColor) let totalPath = UIBezierPath(roundedRect: CGRect(x: originX, y: 0.0, width: intervalWidth * intervalsCount, height: lineHeight), cornerRadius: lineHeight).cgPath context?.addPath(totalPath) context?.fillPath() // Draw elapsed line context?.setFillColor(UIColor.white.cgColor) let elapsedPath = UIBezierPath(roundedRect: CGRect(x: originX, y: 0.0, width: distanceFromTimeInterval(currentTime), height: lineHeight), cornerRadius: lineHeight).cgPath context?.addPath(elapsedPath) context?.fillPath() // Draw current time dot context?.fillEllipse(in: CGRect(x: originX + distanceFromTimeInterval(initialTime), y: 7.0, width: 3.0, height: 3.0)) // Draw full line separators context?.setFillColor(UIColor(white: 0.0, alpha: 0.5).cgColor) var intervalIdx: CGFloat = 0.0 repeat { intervalIdx += 1.0 if intervalsCount - intervalIdx > 0.0 { context?.fill(CGRect(x: originX + intervalWidth * intervalIdx, y: 0.0, width: 1.0, height: lineHeight)) } } while intervalIdx < intervalsCount } }
37.085227
370
0.65344
617cf2a6de9d8660c52deeafef448b61905e037a
3,411
// // ProductListViewModel.swift // Example_ProductBrowser // // Created by asdfgh1 on 12/06/2016. // Copyright © 2016 rshev. All rights reserved. // import Foundation import RxSwift import RxCocoa import AlamofireImage protocol ProductListViewModelDelegate: class { func productPassProductDetailsViewModelFurther(viewModel: ProductDetailsViewModel) } class ProductListViewModel { private var category: Category private let disposeBag = DisposeBag() private let imageCache = AutoPurgingImageCache() private let imageDownloader = ImageDownloader() weak var delegate: ProductListViewModelDelegate? init(category: Category) { self.category = category } func requestCategoryDetails() -> Observable<Void> { return Backend.requestProductsInCategory(categoryId: category.id).observeOn(MainScheduler.instance) .flatMap({ [weak self] (categoryDetails) -> Observable<Void> in self?.category.assignDetails(categoryDetails) return Observable.just() }) } func getProductsCount() -> Int { return category.details?.products.count ?? 0 } func getCategoryName() -> String { return category.name } // in completion closure I return wasLocal=true if image was found in cache, suggesting that it took very small amount of time to load it and the image can be assigned to cell immediately without re-referencing the cell by its indexPath. If wasLocal=false the image was downloaded from the Internet and the cell should be re-referenced by its indexPath again to assign the image. func getProductImage(index index: Int, completion: ((wasLocal: Bool, image: UIImage?)->Void)) { guard let imageUrl = category.details?.products[index].imageUrl else { return } let imageUrlRequest = NSURLRequest(URL: imageUrl) if let image = imageCache.imageForRequest(imageUrlRequest) { completion(wasLocal: true, image: image) return } imageDownloader.downloadImage(URLRequest: imageUrlRequest) { [weak self] (response) in if let image = response.result.value { // minding that we could be not on the main queue after image download here NSOperationQueue.mainQueue().addOperationWithBlock({ completion(wasLocal: false, image: image) }) self?.imageCache.addImage(image, forRequest: imageUrlRequest) } } } func getProductPrice(index index: Int) -> String { return category.details?.products[index].formattedPrice ?? "" } func triggerFavorite(index: Int) { guard let product = category.details?.products[index] else { return } FavManager.sharedManager.triggerFav(product: product) } func isFavorite(index index: Int) -> Bool { guard let product = category.details?.products[index] else { return false } return FavManager.sharedManager.isFav(product: product) } func productWasSelected(index index: Int) { guard let product = category.details?.products[index] else { return } let productDetailsViewModel = ProductDetailsViewModel(product: product) delegate?.productPassProductDetailsViewModelFurther(productDetailsViewModel) } }
37.483516
384
0.673996
7178117ef8d32417fa5c5343196591046f548bc4
1,987
// // KnapsackDynamicSolver.swift // Knapsack // // Created by Jan Posz on 14.05.2017. // Copyright © 2017 VORM. All rights reserved. // import Foundation class KnapsackDynamicSolver: KnapsackSolverType { var availableItems: [KnapsackItem] var maximumWeight: Int var maximumVolume: Int var solveTime: TimeInterval? private var solveMatrix: Array<Array<Array<Int>>> = [[[Int]]]() required init(maximumWeight: Int, maximumVolume: Int, availableItems: [KnapsackItem]) { self.maximumWeight = maximumWeight self.maximumVolume = maximumVolume self.availableItems = availableItems } func solve() -> Int { for _ in 0...availableItems.count + 1 { for _ in 0...maximumWeight { let array = Array(repeating: Int(), count: maximumVolume + 1) solveMatrix.append(Array(repeating:array, count:maximumWeight + 1)) } } let startDate = Date() for i in 0...availableItems.count { for j in 0...maximumWeight { for k in 0...maximumVolume { if (i == 0 || j == 0 || k == 0) { solveMatrix[i][j][k] = 0 } else if (availableItems[i - 1].weight <= j && availableItems[i - 1].volume < k) { let item = availableItems[i - 1] let previousCost = solveMatrix[i-1][j][k] let currentCost = item.cost + solveMatrix[i - 1][j - item.weight][k - item.volume] solveMatrix[i][j][k] = max(currentCost, previousCost) } else { solveMatrix[i][j][k] = solveMatrix[i-1][j][k] } } } } solveTime = Date().timeIntervalSince(startDate) return solveMatrix[availableItems.count][maximumWeight][maximumVolume] } }
35.482143
106
0.527428
fc3ee1b6da49af737cb07414c15d1044453233e9
5,323
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import AmplifyPlugins import AWSPinpoint @testable import Amplify @testable import AWSPinpointAnalyticsPlugin @testable import AmplifyTestCommon // swiftlint:disable:next type_name class AWSPinpointAnalyticsPluginIntergrationTests: XCTestCase { static let amplifyConfiguration = "AWSPinpointAnalyticsPluginIntegrationTests-amplifyconfiguration" static let analyticsPluginKey = "awsPinpointAnalyticsPlugin" override func setUp() { do { let config = try TestConfigHelper.retrieveAmplifyConfiguration( forResource: AWSPinpointAnalyticsPluginIntergrationTests.amplifyConfiguration) try Amplify.add(plugin: AWSAuthPlugin()) try Amplify.add(plugin: AWSPinpointAnalyticsPlugin()) try Amplify.configure(config) } catch { XCTFail("Failed to initialize and configure Amplify \(error)") } } override func tearDown() { Amplify.reset() } func testIdentifyUser() { let userId = "userId" let identifyUserEvent = expectation(description: "Identify User event was received on the hub plugin") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in print(payload) if payload.eventName == HubPayload.EventName.Analytics.identifyUser { guard let data = payload.data as? (String, AnalyticsUserProfile?) else { XCTFail("Missing data") return } XCTAssertNotNil(data) XCTAssertEqual(data.0, userId) identifyUserEvent.fulfill() } } let location = AnalyticsUserProfile.Location(latitude: 47.606209, longitude: -122.332069, postalCode: "98122", city: "Seattle", region: "WA", country: "USA") let properties = ["userPropertyStringKey": "userProperyStringValue", "userPropertyIntKey": 123, "userPropertyDoubleKey": 12.34, "userPropertyBoolKey": true] as [String: AnalyticsPropertyValue] let userProfile = AnalyticsUserProfile(name: "name", email: "email", plan: "plan", location: location, properties: properties) Amplify.Analytics.identifyUser(userId, withProfile: userProfile) wait(for: [identifyUserEvent], timeout: TestCommonConstants.networkTimeout) } func testRecordEventsAreFlushed() { let flushEventsInvoked = expectation(description: "Flush events invoked") _ = Amplify.Hub.listen(to: .analytics, isIncluded: nil) { payload in if payload.eventName == HubPayload.EventName.Analytics.flushEvents { // TODO: Remove exposing AWSPinpointEvent guard let pinpointEvents = payload.data as? [AWSPinpointEvent] else { XCTFail("Missing data") return } XCTAssertNotNil(pinpointEvents) flushEventsInvoked.fulfill() } } let globalProperties = ["globalPropertyStringKey": "eventProperyStringValue", "globalPropertyIntKey": 123, "globalPropertyDoubleKey": 12.34, "globalPropertyBoolKey": true] as [String: AnalyticsPropertyValue] Amplify.Analytics.registerGlobalProperties(globalProperties) let properties = ["eventPropertyStringKey": "eventProperyStringValue", "eventPropertyIntKey": 123, "eventPropertyDoubleKey": 12.34, "eventPropertyBoolKey": true] as [String: AnalyticsPropertyValue] let event = BasicAnalyticsEvent(name: "eventName", properties: properties) Amplify.Analytics.record(event: event) Amplify.Analytics.flushEvents() wait(for: [flushEventsInvoked], timeout: TestCommonConstants.networkTimeout) } func testGetEscapeHatch() throws { let plugin = try Amplify.Analytics.getPlugin( for: AWSPinpointAnalyticsPluginIntergrationTests.analyticsPluginKey) guard let pinpointAnalyticsPlugin = plugin as? AWSPinpointAnalyticsPlugin else { XCTFail("Could not get plugin of type AWSPinpointAnalyticsPlugin") return } let awsPinpoint = pinpointAnalyticsPlugin.getEscapeHatch() XCTAssertNotNil(awsPinpoint) XCTAssertNotNil(awsPinpoint.analyticsClient) XCTAssertNotNil(awsPinpoint.targetingClient) XCTAssertNotNil(awsPinpoint.sessionClient) XCTAssertNotNil(awsPinpoint.configuration) XCTAssertTrue(awsPinpoint.configuration.enableAutoSessionRecording) } }
43.991736
110
0.595153
1a01914c05e7402d16b62aff4ef43f2753f832c5
4,686
/* See LICENSE folder for this sample’s licensing information. Abstract: `PerfMeasurements` contains utility code to measure streaming performance KPIs */ import Foundation import AVFoundation import os.log /// - Tag: PerfMeasurements class PerfMeasurements: NSObject { /// Time when this class was created. private var creationTime: CFAbsoluteTime = 0.0 /// Time when playback initially started. private var playbackStartTime: CFAbsoluteTime = 0.0 /// Time of last stall event. private var lastStallTime: CFAbsoluteTime = 0.0 /// Duration of all stalls (time waiting for rebuffering). private var totalStallTime: CFTimeInterval = 0.0 /// Stream startup time measured in seconds. var startupTime: CFTimeInterval { return playbackStartTime - creationTime } /// Total time spent playing, obtained from the AccessLog. /// - Tag: TotalDurationWatched var totalDurationWatched: Double { // Compute total duration watched by iterating through the AccessLog events. var totalDurationWatched = 0.0 if accessLog != nil && !accessLog!.events.isEmpty { for event in accessLog!.events where event.durationWatched > 0 { totalDurationWatched += event.durationWatched } } return totalDurationWatched } /** Time weighted value of the variant indicated bitrate. Measure of overall stream quality. */ var timeWeightedIBR: Double { var timeWeightedIBR = 0.0 let totalDurationWatched = self.totalDurationWatched if accessLog != nil && totalDurationWatched > 0 { // Compute the time-weighted indicated bitrate. for event in accessLog!.events { if event.durationWatched > 0 && event.indicatedBitrate > 0 { let eventTimeWeight = event.durationWatched / totalDurationWatched timeWeightedIBR += event.indicatedBitrate * eventTimeWeight } } } return timeWeightedIBR } /** Stall rate measured in stalls per hour. Normalized measure of stream interruptions caused by stream buffer depleation. */ var stallRate: Double { var totalNumberOfStalls = 0 let totalHoursWatched = self.totalDurationWatched / 3600 if accessLog != nil && totalDurationWatched > 0 { for event in accessLog!.events { totalNumberOfStalls += event.numberOfStalls } } return Double(totalNumberOfStalls) / totalHoursWatched } /** Stall time measured as duration-stalled / duration-watched. Normalized meausre of time waited for the a stream to rebuffer. */ var stallWaitRatio: Double { return totalStallTime / totalDurationWatched } // The AccessLog associated to the current player item. private var accessLog: AVPlayerItemAccessLog? { return playerItem?.accessLog() } /// The player item monitored. private var playerItem: AVPlayerItem? init(playerItem: AVPlayerItem) { super.init() self.playerItem = playerItem creationTime = CACurrentMediaTime() } /// Called when a timebase rate change occurs. func rateChanged(rate: Double) { if playbackStartTime == 0.0 && rate > 0 { // First rate change playbackStartTime = CACurrentMediaTime() os_log("Perf -- Playback started in %.2f seconds", self.startupTime) } else if rate > 0 && lastStallTime > 0 { // Subsequent rate change playbackStallEnded() os_log("Perf -- Playback resumed in %.2f seconds", totalStallTime) } } /// Called when playback stalls. func playbackStalled() { os_log("Perf -- Playback stalled") lastStallTime = CACurrentMediaTime() } /// Called after a stall event, when playback resumes. func playbackStallEnded() { if lastStallTime > 0 { totalStallTime += CACurrentMediaTime() - lastStallTime lastStallTime = 0.0 } } /// Called when the player item is released. func playbackEnded() { playbackStallEnded() os_log("Perf -- Playback ended") os_log("Perf -- Time-weighted Indicated Bitrate: %.2fMbps", timeWeightedIBR / 1_000_000) os_log("Perf -- Stall rate: %.2f stalls/hour", stallRate) os_log("Perf -- Stall wait ratio: %.2f duration-stalled/duration-watched", stallWaitRatio) } }
33.71223
98
0.625907
e29d533a1343f1c731c021b106dc7dcc05b7c5d7
3,153
// // DemoTableTableViewController.swift // Demo02 // // Created by Giovanni on 10/13/17. // Copyright © 2017 Giovanni. All rights reserved. // import UIKit class DemoTableTableViewController: UITableViewController, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.84375
136
0.674913
16b739a11f0671f55717ab4c43ec7d2f21156a8e
1,772
// // Post.swift // instagram // // Created by Rey Oliva on 6/29/17. // Copyright © 2017 Rey Oliva. All rights reserved. // import UIKit import Parse class Post: NSObject { /** * Other methods */ /** Method to add a user post to Parse (uploading image file) - parameter image: Image that the user wants upload to parse - parameter caption: Caption text input by the user - parameter completion: Block to be executed after save operation is complete */ class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock?) { // Create Parse object PFObject let post = PFObject(className: "Post") // Add relevant fields to the object post["media"] = getPFFileFromImage(image: image)// PFFile column type post["author"] = PFUser.current() // Pointer column type that points to PFUser post["caption"] = caption post["likesCount"] = 0 post["commentsCount"] = 0 // Save object (following function will save the object in Parse asynchronously) post.saveInBackground(block: completion) } /** Method to convert UIImage to PFFile - parameter image: Image that the user wants to upload to parse - returns: PFFile for the the data in the image */ class func getPFFileFromImage(image: UIImage?) -> PFFile? { // check if image is not nil if let image = image { // get image data and check if that is not nil if let imageData = UIImagePNGRepresentation(image) { return PFFile(name: "image.png", data: imageData) } } return nil } }
30.551724
127
0.616817
760ed223681e73dfba3f03f3d77840b55058dee0
32,405
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) || os(FreeBSD) || os(Android) import Glibc #else #endif import XCTest import NIO import NIOHTTP1 @testable import NIOHTTP2 import NIOHPACK struct NoFrameReceived: Error { } // MARK:- Test helpers we use throughout these tests to encapsulate verbose // and noisy code. extension XCTestCase { /// Have two `EmbeddedChannel` objects send and receive data from each other until /// they make no forward progress. func interactInMemory(_ first: EmbeddedChannel, _ second: EmbeddedChannel, file: StaticString = #file, line: UInt = #line) { var operated: Bool func readBytesFromChannel(_ channel: EmbeddedChannel) -> ByteBuffer? { guard let data = try? assertNoThrowWithValue(channel.readOutbound(as: IOData.self)) else { return nil } switch data { case .byteBuffer(let b): return b case .fileRegion(let f): return f.asByteBuffer(allocator: channel.allocator) } } repeat { operated = false if let data = readBytesFromChannel(first) { operated = true XCTAssertNoThrow(try second.writeInbound(data), file: (file), line: line) } if let data = readBytesFromChannel(second) { operated = true XCTAssertNoThrow(try first.writeInbound(data), file: (file), line: line) } } while operated } /// Deliver all the bytes currently flushed on `sourceChannel` to `targetChannel`. func deliverAllBytes(from sourceChannel: EmbeddedChannel, to targetChannel: EmbeddedChannel, file: StaticString = #file, line: UInt = #line) { // Collect the serialized data. var frameBuffer = sourceChannel.allocator.buffer(capacity: 1024) while case .some(.byteBuffer(var buf)) = try? assertNoThrowWithValue(sourceChannel.readOutbound(as: IOData.self)) { frameBuffer.writeBuffer(&buf) } XCTAssertNoThrow(try targetChannel.writeInbound(frameBuffer), file: (file), line: line) } /// Given two `EmbeddedChannel` objects, verify that each one performs the handshake: specifically, /// that each receives a SETTINGS frame from its peer and a SETTINGS ACK for its own settings frame. /// /// If the handshake has not occurred, this will definitely call `XCTFail`. It may also throw if the /// channel is now in an indeterminate state. func assertDoHandshake(client: EmbeddedChannel, server: EmbeddedChannel, clientSettings: [HTTP2Setting] = nioDefaultSettings, serverSettings: [HTTP2Setting] = nioDefaultSettings, file: StaticString = #file, line: UInt = #line) throws { // This connects are not semantically right, but are required in order to activate the // channels. //! FIXME: Replace with registerAlreadyConfigured0 once EmbeddedChannel propagates this // call to its channelcore. let socket = try SocketAddress(unixDomainSocketPath: "/fake") _ = try client.connect(to: socket).wait() _ = try server.connect(to: socket).wait() // First the channels need to interact. self.interactInMemory(client, server, file: (file), line: line) // Now keep an eye on things. Each channel should first have been sent a SETTINGS frame. let clientReceivedSettings = try client.assertReceivedFrame(file: (file), line: line) let serverReceivedSettings = try server.assertReceivedFrame(file: (file), line: line) // Each channel should also have a settings ACK. let clientReceivedSettingsAck = try client.assertReceivedFrame(file: (file), line: line) let serverReceivedSettingsAck = try server.assertReceivedFrame(file: (file), line: line) // Check that these SETTINGS frames are ok. clientReceivedSettings.assertSettingsFrame(expectedSettings: serverSettings, ack: false, file: (file), line: line) serverReceivedSettings.assertSettingsFrame(expectedSettings: clientSettings, ack: false, file: (file), line: line) clientReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) serverReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) client.assertNoFramesReceived(file: (file), line: line) server.assertNoFramesReceived(file: (file), line: line) } /// Assert that sending the given `frames` into `sender` causes them all to pop back out again at `receiver`, /// and that `sender` has received no frames. /// /// Optionally returns the frames received. @discardableResult func assertFramesRoundTrip(frames: [HTTP2Frame], sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #file, line: UInt = #line) throws -> [HTTP2Frame] { for frame in frames { sender.write(frame, promise: nil) } sender.flush() self.interactInMemory(sender, receiver, file: (file), line: line) sender.assertNoFramesReceived(file: (file), line: line) var receivedFrames = [HTTP2Frame]() for frame in frames { let receivedFrame = try receiver.assertReceivedFrame(file: (file), line: line) receivedFrame.assertFrameMatches(this: frame, file: (file), line: line) receivedFrames.append(receivedFrame) } return receivedFrames } /// Asserts that sending new settings from `sender` to `receiver` leads to an appropriate settings ACK. Does not assert that no other frames have been /// received. func assertSettingsUpdateWithAck(_ newSettings: HTTP2Settings, sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #file, line: UInt = #line) throws { let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(newSettings))) sender.writeAndFlush(frame, promise: nil) self.interactInMemory(sender, receiver, file: (file), line: line) try receiver.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: frame) try sender.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack))) } } extension EmbeddedChannel { /// This function attempts to obtain a HTTP/2 frame from a connection. It must already have been /// sent, as this function does not call `interactInMemory`. If no frame has been received, this /// will call `XCTFail` and then throw: this will ensure that the test will not proceed past /// this point if no frame was received. func assertReceivedFrame(file: StaticString = #file, line: UInt = #line) throws -> HTTP2Frame { guard let frame: HTTP2Frame = try assertNoThrowWithValue(self.readInbound()) else { XCTFail("Did not receive frame", file: (file), line: line) throw NoFrameReceived() } return frame } /// Asserts that the connection has not received a HTTP/2 frame at this time. func assertNoFramesReceived(file: StaticString = #file, line: UInt = #line) { let content: HTTP2Frame? = try? assertNoThrowWithValue(self.readInbound()) XCTAssertNil(content, "Received unexpected content: \(content!)", file: (file), line: line) } /// Retrieve all sent frames. func sentFrames(file: StaticString = #file, line: UInt = #line) throws -> [HTTP2Frame] { var receivedFrames: [HTTP2Frame] = Array() while let frame = try assertNoThrowWithValue(self.readOutbound(as: HTTP2Frame.self), file: (file), line: line) { receivedFrames.append(frame) } return receivedFrames } } extension HTTP2Frame { /// Asserts that the given frame is a SETTINGS frame. func assertSettingsFrame(expectedSettings: [HTTP2Setting], ack: Bool, file: StaticString = #file, line: UInt = #line) { guard case .settings(let payload) = self.payload else { XCTFail("Expected SETTINGS frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(self.streamID, .rootStream, "Got unexpected stream ID for SETTINGS: \(self.streamID)", file: (file), line: line) switch payload { case .ack: XCTAssertEqual(expectedSettings, [], "Got unexpected settings: expected \(expectedSettings), got []", file: (file), line: line) XCTAssertTrue(ack, "Got unexpected value for ack: expected \(ack), got true", file: (file), line: line) case .settings(let actualSettings): XCTAssertEqual(expectedSettings, actualSettings, "Got unexpected settings: expected \(expectedSettings), got \(actualSettings)", file: (file), line: line) XCTAssertFalse(false, "Got unexpected value for ack: expected \(ack), got false", file: (file), line: line) } } func assertSettingsFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .settings(let payload) = frame.payload else { preconditionFailure("Settings frames can never match non-settings frames") } switch payload { case .ack: self.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) case .settings(let expectedSettings): self.assertSettingsFrame(expectedSettings: expectedSettings, ack: false, file: (file), line: line) } } /// Asserts that this frame matches a give other frame. func assertFrameMatches(this frame: HTTP2Frame, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #file, line: UInt = #line) { switch frame.payload { case .headers: self.assertHeadersFrameMatches(this: frame, file: (file), line: line) case .data: self.assertDataFrameMatches(this: frame, fileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) case .goAway: self.assertGoAwayFrameMatches(this: frame, file: (file), line: line) case .ping: self.assertPingFrameMatches(this: frame, file: (file), line: line) case .settings: self.assertSettingsFrameMatches(this: frame, file: (file), line: line) case .rstStream: self.assertRstStreamFrameMatches(this: frame, file: (file), line: line) case .priority: self.assertPriorityFrameMatches(this: frame, file: (file), line: line) case .pushPromise: self.assertPushPromiseFrameMatches(this: frame, file: (file), line: line) case .windowUpdate: self.assertWindowUpdateFrameMatches(this: frame, file: (file), line: line) case .alternativeService: self.assertAlternativeServiceFrameMatches(this: frame, file: (file), line: line) case .origin: self.assertOriginFrameMatches(this: frame, file: (file), line: line) } } /// Asserts that a given frame is a HEADERS frame matching this one. func assertHeadersFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .headers(let payload) = frame.payload else { preconditionFailure("Headers frames can never match non-headers frames") } self.assertHeadersFrame(endStream: payload.endStream, streamID: frame.streamID, headers: payload.headers, priority: payload.priorityData, file: (file), line: line) } enum HeadersType { case request case response case trailers case doNotValidate } /// Asserts the given frame is a HEADERS frame. func assertHeadersFrame(endStream: Bool, streamID: HTTP2StreamID, headers: HPACKHeaders, priority: HTTP2Frame.StreamPriorityData? = nil, type: HeadersType? = nil, file: StaticString = #file, line: UInt = #line) { guard case .headers(let actualPayload) = self.payload else { XCTFail("Expected HEADERS frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(actualPayload.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualPayload.endStream)", file: (file), line: line) XCTAssertEqual(self.streamID, streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) XCTAssertEqual(headers, actualPayload.headers, "Non-equal headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) XCTAssertEqual(priority, actualPayload.priorityData, "Non-equal priorities: expected \(String(describing: priority)), got \(String(describing: actualPayload.priorityData))", file: (file), line: line) switch type { case .some(.request): XCTAssertNoThrow(try actualPayload.headers.validateRequestBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.response): XCTAssertNoThrow(try actualPayload.headers.validateResponseBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.trailers): XCTAssertNoThrow(try actualPayload.headers.validateTrailersBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.doNotValidate): () // alright, let's not validate then case .none: XCTAssertTrue((try? actualPayload.headers.validateRequestBlock()) != nil || (try? actualPayload.headers.validateResponseBlock()) != nil || (try? actualPayload.headers.validateTrailersBlock()) != nil, "\(actualPayload.headers) not a valid request/response/trailers header block", file: (file), line: line) } } /// Asserts that a given frame is a DATA frame matching this one. /// /// This function always converts the DATA frame to a bytebuffer, for use with round-trip testing. func assertDataFrameMatches(this frame: HTTP2Frame, fileRegionToByteBuffer: Bool = true, file: StaticString = #file, line: UInt = #line) { guard case .data(let payload) = frame.payload else { XCTFail("Expected DATA frame, got \(self.payload) instead", file: (file), line: line) return } switch (payload.data, fileRegionToByteBuffer) { case (.byteBuffer(let bufferPayload), _): self.assertDataFrame(endStream: payload.endStream, streamID: frame.streamID, payload: bufferPayload, file: (file), line: line) case (.fileRegion(let filePayload), true): // Sorry about creating an allocator from thin air here! let expectedPayload = filePayload.asByteBuffer(allocator: ByteBufferAllocator()) self.assertDataFrame(endStream: payload.endStream, streamID: frame.streamID, payload: expectedPayload, file: (file), line: line) case (.fileRegion(let filePayload), false): self.assertDataFrame(endStream: payload.endStream, streamID: frame.streamID, payload: filePayload, file: (file), line: line) } } /// Assert the given frame is a DATA frame with the appropriate settings. func assertDataFrame(endStream: Bool, streamID: HTTP2StreamID, payload: ByteBuffer, file: StaticString = #file, line: UInt = #line) { guard case .data(let actualFrameBody) = self.payload else { XCTFail("Expected DATA frame, got \(self.payload) instead", file: (file), line: line) return } guard case .byteBuffer(let actualPayload) = actualFrameBody.data else { XCTFail("Expected ByteBuffer DATA frame, got \(actualFrameBody.data) instead", file: (file), line: line) return } XCTAssertEqual(actualFrameBody.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) XCTAssertEqual(self.streamID, streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) XCTAssertEqual(actualPayload, payload, "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) } func assertDataFrame(endStream: Bool, streamID: HTTP2StreamID, payload: FileRegion, file: StaticString = #file, line: UInt = #line) { guard case .data(let actualFrameBody) = self.payload else { XCTFail("Expected DATA frame, got \(self.payload) instead", file: (file), line: line) return } guard case .fileRegion(let actualPayload) = actualFrameBody.data else { XCTFail("Expected FileRegion DATA frame, got \(actualFrameBody.data) instead", file: (file), line: line) return } XCTAssertEqual(actualFrameBody.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) XCTAssertEqual(self.streamID, streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) XCTAssertEqual(actualPayload, payload, "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) } func assertGoAwayFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .goAway(let lastStreamID, let errorCode, let opaqueData) = frame.payload else { preconditionFailure("Goaway frames can never match non-Goaway frames.") } self.assertGoAwayFrame(lastStreamID: lastStreamID, errorCode: UInt32(http2ErrorCode: errorCode), opaqueData: opaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }, file: (file), line: line) } func assertGoAwayFrame(lastStreamID: HTTP2StreamID, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #file, line: UInt = #line) { guard case .goAway(let actualLastStreamID, let actualErrorCode, let actualOpaqueData) = self.payload else { XCTFail("Expected GOAWAY frame, got \(self.payload) instead", file: (file), line: line) return } let integerErrorCode = UInt32(http2ErrorCode: actualErrorCode) let byteArrayOpaqueData = actualOpaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) } XCTAssertEqual(self.streamID, .rootStream, "Goaway frame must be on the root stream!", file: (file), line: line) XCTAssertEqual(lastStreamID, actualLastStreamID, "Unexpected last stream ID: expected \(lastStreamID), got \(actualLastStreamID)", file: (file), line: line) XCTAssertEqual(integerErrorCode, errorCode, "Unexpected error code: expected \(errorCode), got \(integerErrorCode)", file: (file), line: line) XCTAssertEqual(byteArrayOpaqueData, opaqueData, "Unexpected opaque data: expected \(String(describing: opaqueData)), got \(String(describing: byteArrayOpaqueData))", file: (file), line: line) } func assertPingFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .ping(let opaqueData, let ack) = frame.payload else { preconditionFailure("Ping frames can never match non-Ping frames.") } self.assertPingFrame(ack: ack, opaqueData: opaqueData, file: (file), line: line) } func assertPingFrame(ack: Bool, opaqueData: HTTP2PingData, file: StaticString = #file, line: UInt = #line) { guard case .ping(let actualPingData, let actualAck) = self.payload else { XCTFail("Expected PING frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(self.streamID, .rootStream, "Ping frame must be on the root stream!", file: (file), line: line) XCTAssertEqual(actualAck, ack, "Non-matching ACK: expected \(ack), got \(actualAck)", file: (file), line: line) XCTAssertEqual(actualPingData, opaqueData, "Non-matching ping data: expected \(opaqueData), got \(actualPingData)", file: (file), line: line) } func assertWindowUpdateFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .windowUpdate(let increment) = frame.payload else { XCTFail("WINDOW_UPDATE frames can never match non-WINDOW_UPDATE frames", file: (file), line: line) return } self.assertWindowUpdateFrame(streamID: frame.streamID, windowIncrement: increment) } func assertWindowUpdateFrame(streamID: HTTP2StreamID, windowIncrement: Int, file: StaticString = #file, line: UInt = #line) { guard case .windowUpdate(let actualWindowIncrement) = self.payload else { XCTFail("Expected WINDOW_UPDATE frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(self.streamID, streamID, "Unexpected stream ID!", file: (file), line: line) XCTAssertEqual(windowIncrement, actualWindowIncrement, "Unexpected window increment!", file: (file), line: line) } func assertRstStreamFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .rstStream(let errorCode) = frame.payload else { preconditionFailure("RstStream frames can never match non-RstStream frames.") } self.assertRstStreamFrame(streamID: frame.streamID, errorCode: errorCode, file: (file), line: line) } func assertRstStreamFrame(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, file: StaticString = #file, line: UInt = #line) { guard case .rstStream(let actualErrorCode) = self.payload else { XCTFail("Expected RST_STREAM frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) XCTAssertEqual(actualErrorCode, errorCode, "Non-matching error-code: expected \(errorCode), got \(actualErrorCode)", file: (file), line: line) } func assertPriorityFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .priority(let expectedPriorityData) = frame.payload else { preconditionFailure("Priority frames can never match non-Priority frames.") } self.assertPriorityFrame(streamPriorityData: expectedPriorityData, file: (file), line: line) } func assertPriorityFrame(streamPriorityData: HTTP2Frame.StreamPriorityData, file: StaticString = #file, line: UInt = #line) { guard case .priority(let actualPriorityData) = self.payload else { XCTFail("Expected PRIORITY frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(streamPriorityData, actualPriorityData, file: (file), line: line) } func assertPushPromiseFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .pushPromise(let payload) = frame.payload else { preconditionFailure("PushPromise frames can never match non-PushPromise frames.") } self.assertPushPromiseFrame(streamID: frame.streamID, pushedStreamID: payload.pushedStreamID, headers: payload.headers, file: (file), line: line) } func assertPushPromiseFrame(streamID: HTTP2StreamID, pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, file: StaticString = #file, line: UInt = #line) { guard case .pushPromise(let actualPayload) = self.payload else { XCTFail("Expected PUSH_PROMISE frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(streamID, self.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) XCTAssertEqual(pushedStreamID, actualPayload.pushedStreamID, "Non matching pushed stream IDs: expected \(pushedStreamID), got \(actualPayload.pushedStreamID)", file: (file), line: line) XCTAssertEqual(headers, actualPayload.headers, "Non matching pushed headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) } func assertAlternativeServiceFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .alternativeService(let origin, let field) = frame.payload else { preconditionFailure("AltSvc frames can never match non-AltSvc frames.") } self.assertAlternativeServiceFrame(origin: origin, field: field, file: (file), line: line) } func assertAlternativeServiceFrame(origin: String?, field: ByteBuffer?, file: StaticString = #file, line: UInt = #line) { guard case .alternativeService(let actualOrigin, let actualField) = self.payload else { XCTFail("Expected ALTSVC frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) XCTAssertEqual(origin, actualOrigin, "Non matching origins: expected \(String(describing: origin)), got \(String(describing: actualOrigin))", file: (file), line: line) XCTAssertEqual(field, actualField, "Non matching field: expected \(String(describing: field)), got \(String(describing: actualField))", file: (file), line: line) } func assertOriginFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { guard case .origin(let payload) = frame.payload else { preconditionFailure("ORIGIN frames can never match non-ORIGIN frames.") } self.assertOriginFrame(streamID: frame.streamID, origins: payload, file: (file), line: line) } func assertOriginFrame(streamID: HTTP2StreamID, origins: [String], file: StaticString = #file, line: UInt = #line) { guard case .origin(let actualPayload) = self.payload else { XCTFail("Expected ORIGIN frame, got \(self.payload) instead", file: (file), line: line) return } XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) XCTAssertEqual(origins, actualPayload, "Non matching origins: expected \(origins), got \(actualPayload)", file: (file), line: line) } } extension Array where Element == HTTP2Frame { func assertFramesMatch<Candidate: Collection>(_ target: Candidate, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #file, line: UInt = #line) where Candidate.Element == HTTP2Frame { guard self.count == target.count else { XCTFail("Different numbers of frames: expected \(target.count), got \(self.count)", file: (file), line: line) return } for (expected, actual) in zip(target, self) { expected.assertFrameMatches(this: actual, dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) } } } /// Runs the body with a temporary file, optionally containing some file content. func withTemporaryFile<T>(content: String? = nil, _ body: (NIOFileHandle, String) throws -> T) rethrows -> T { let (fd, path) = openTemporaryFile() let fileHandle = NIOFileHandle(descriptor: fd) defer { XCTAssertNoThrow(try fileHandle.close()) XCTAssertEqual(0, unlink(path)) } if let content = content { Array(content.utf8).withUnsafeBufferPointer { ptr in var toWrite = ptr.count var start = ptr.baseAddress! while toWrite > 0 { let rc = write(fd, start, toWrite) if rc >= 0 { toWrite -= rc start = start + rc } else { fatalError("Hit error: \(String(cString: strerror(errno)))") } } XCTAssertEqual(0, lseek(fd, 0, SEEK_SET)) } } return try body(fileHandle, path) } func openTemporaryFile() -> (CInt, String) { let template = "/tmp/niotestXXXXXXX" var templateBytes = template.utf8 + [0] let templateBytesCount = templateBytes.count let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { (ptr: UnsafeMutablePointer<Int8>) in return mkstemp(ptr) } } templateBytes.removeLast() return (fd, String(decoding: templateBytes, as: UTF8.self)) } extension FileRegion { func asByteBuffer(allocator: ByteBufferAllocator) -> ByteBuffer { var fileBuffer = allocator.buffer(capacity: self.readableBytes) fileBuffer.writeWithUnsafeMutableBytes(minimumWritableBytes: self.readableBytes) { ptr in let rc = try! self.fileHandle.withUnsafeFileDescriptor { fd -> Int in lseek(fd, off_t(self.readerIndex), SEEK_SET) return read(fd, ptr.baseAddress!, self.readableBytes) } precondition(rc == self.readableBytes) return rc } precondition(fileBuffer.readableBytes == self.readableBytes) return fileBuffer } } extension NIO.NIOFileHandle { func appendBuffer(_ buffer: ByteBuffer) { var written = 0 while written < buffer.readableBytes { let rc = buffer.withUnsafeReadableBytes { ptr in try! self.withUnsafeFileDescriptor { fd -> Int in lseek(fd, 0, SEEK_END) return write(fd, ptr.baseAddress! + written, ptr.count - written) } } precondition(rc > 0) written += rc } } } func assertNoThrowWithValue<T>(_ body: @autoclosure () throws -> T, defaultValue: T? = nil, message: String? = nil, file: StaticString = #file, line: UInt = #line) throws -> T { do { return try body() } catch { XCTFail("\(message.map { $0 + ": " } ?? "")unexpected error \(error) thrown", file: (file), line: line) if let defaultValue = defaultValue { return defaultValue } else { throw error } } }
51.111987
207
0.635704
8aafd47f0b232378f2ceeb1d291473c678bdc08c
3,196
// // AnyPaymentReceiverUT.swift // athmovil-checkoutTests // // Created by Hansy on 2/8/21. // Copyright © 2021 Evertec. All rights reserved. // import Foundation import XCTest @testable import athmovil_checkout class AnyPaymentReceiverUT: XCTestCase { //MARK:- Positive func testWhenCompleteTransactionWithDeepLink_GivenAExpectedResponse_ThenCallCompletedCallBack() { let mockData = getResponseData(key: "status", value: "completed") let paymentRequest = ATHMPaymentRequest(account: "Test", scheme: "https://", payment: 20.0) let paymentHandlerResponse = PaymentHandleableMock(onCompleted: { result in XCTAssertEqual(result.status.status, .completed) }) let responser = AnyPaymentReceiver(paymentContent: paymentRequest, handler: paymentHandlerResponse, session: .shared) responser.completed(by: .deepLink(mockData)) } func testWhenCompleteTransactionFromBecomeActive_GivenADummyPayment_ThenCallClosureCompletedWithDummyData() { let expectationSerive = self.expectation(description: "GettingFromService") let paymentRequest = ATHMPaymentRequest(account: "Test", scheme: "https://", payment: 20.0) let paymentHandlerResponse = PaymentHandleableMock(onCompleted: { result in XCTAssertEqual(result.status.status, .completed) expectationSerive.fulfill() }) let responser = AnyPaymentReceiver(paymentContent: PaymentSimulated(paymentRequest: paymentRequest), handler: paymentHandlerResponse, session: .shared) responser.completed(by: .becomeActive) wait(for: [expectationSerive], timeout: 4) } func getResponseData(key: String, value: Any?) -> Data { var fullResponse: [String: Any] = ["name": "test", "phoneNumber": "7871234567", "metadata1": "test metadata1", "tax": 1, "version": "3.0", "total": 2.0, "referenceNumber": "123456", "subtotal": 1, "metadata2": "test metadata2", "date": 0, "items": [["name": "test", "price": 1, "quantity": 1, "desc": "test"]], "email": "[email protected]", "status": "completed", "dailyTransactionID": 1 ] fullResponse[key] = value let dataResponse = try! JSONSerialization.data(withJSONObject: fullResponse, options: .prettyPrinted) return dataResponse } }
40.455696
114
0.508448
877b50508c14c9fd02de49eab45758fcbe1e4f2f
2,429
// // FadeSegue.swift // KumpeHelpers // // Created by Justin Kumpe on 11/5/20. // import UIKit public class FadeSegue: UIStoryboardSegue { private var selfRetainer: FadeSegue? public override func perform() { destination.transitioningDelegate = self selfRetainer = self destination.modalPresentationStyle = .fullScreen source.present(destination, animated: true, completion: nil) } } extension FadeSegue: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return Presenter() } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { selfRetainer = nil return Dismisser() } private class Presenter: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let toView = transitionContext.view(forKey: .to)! containerView.addSubview(toView) toView.alpha = 0.0 UIView.animate(withDuration: 1.5, animations: { toView.alpha = 1.0 }, completion: { _ in transitionContext.completeTransition(true) } ) } } private class Dismisser: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.2 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.view(forKey: .from)! UIView.animate(withDuration: 1, animations: { fromView.alpha = 0 }, completion: { _ in transitionContext.completeTransition(true) } ) } } }
33.736111
177
0.624537
bb9666cb274d8f15456b005ece8f96c7d58087a0
32,960
// // EditorViewController.swift // FSNotes iOS // // Created by Oleksandr Glushchenko on 1/31/18. // Copyright © 2018 Oleksandr Glushchenko. All rights reserved. // import UIKit import NightNight import Down import AudioToolbox import DKImagePickerController import MobileCoreServices import Photos import GSImageViewerController class EditorViewController: UIViewController, UITextViewDelegate { public var note: Note? private var isHighlighted: Bool = false private var downView: MarkdownView? private var isUndo = false private let storageQueue = OperationQueue() private var toolbar: Toolbar = .markdown @IBOutlet weak var editArea: EditTextView! override func viewDidLoad() { storageQueue.maxConcurrentOperationCount = 1 navigationController?.navigationBar.mixedTitleTextAttributes = [NNForegroundColorAttributeName: Colors.titleText] navigationController?.navigationBar.mixedTintColor = Colors.buttonText navigationController?.navigationBar.mixedBarTintColor = Colors.Header if let n = note, n.isMarkdown() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Preview", style: .done, target: self, action: #selector(preview)) } let tap = SingleTouchDownGestureRecognizer(target: self, action: #selector(tapHandler(_:))) self.editArea.addGestureRecognizer(tap) super.viewDidLoad() self.addToolBar(textField: editArea, toolbar: self.getMarkdownToolbar()) guard let pageController = self.parent as? PageViewController else { return } pageController.enableSwipe() NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil) } override func viewDidAppear(_ animated: Bool) { editArea.isScrollEnabled = true if let n = note, n.isMarkdown() { self.navigationItem.rightBarButtonItem?.title = "Preview" } super.viewDidAppear(animated) if editArea.textStorage.length == 0 { editArea.perform(#selector(becomeFirstResponder), with: nil, afterDelay: 0.0) } guard let pageController = UIApplication.shared.windows[0].rootViewController as? PageViewController else { return } pageController.enableSwipe() if NightNight.theme == .night { editArea.keyboardAppearance = .dark } else { editArea.keyboardAppearance = .default } initLinksColor() } override func viewWillAppear(_ animated: Bool) { self.registerForKeyboardNotifications() } override func viewWillDisappear(_ animated: Bool) { self.deregisterFromKeyboardNotifications() } override var textInputMode: UITextInputMode? { let defaultLang = UserDefaultsManagement.defaultLanguage if UITextInputMode.activeInputModes.count - 1 >= defaultLang { return UITextInputMode.activeInputModes[defaultLang] } return super.textInputMode } private func registerForKeyboardNotifications(){ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } private func deregisterFromKeyboardNotifications(){ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } public func fill(note: Note, preview: Bool = false) { self.note = note EditTextView.note = note UserDefaultsManagement.codeTheme = NightNight.theme == .night ? "monokai-sublime" : "atom-one-light" self.navigationItem.title = note.title UserDefaultsManagement.preview = false removeMdSubviewIfExist() if preview { loadPreview(note: note) return } guard editArea != nil else { return } editArea.initUndoRedoButons() if note.isRTF() { view.backgroundColor = UIColor.white editArea.backgroundColor = UIColor.white } else { view.mixedBackgroundColor = MixedColor(normal: 0xfafafa, night: 0x2e2c32) editArea.mixedBackgroundColor = MixedColor(normal: 0xfafafa, night: 0x2e2c32) } if note.type == .PlainText { let foregroundColor = NightNight.theme == .night ? UIColor.white : UIColor.black editArea.attributedText = NSAttributedString(string: note.content.string, attributes: [NSAttributedStringKey.foregroundColor: foregroundColor]) } else { editArea.attributedText = note.content } self.configureFont() self.configureToolbar() editArea.textStorage.updateFont() if note.isMarkdown() { NotesTextProcessor.fullScan(note: note, storage: editArea.textStorage, range: NSRange(0..<editArea.textStorage.length), async: true) } editArea.delegate = self let cursor = editArea.selectedTextRange let storage = editArea.textStorage let range = NSRange(0..<storage.length) if UserDefaultsManagement.liveImagesPreview { let processor = ImagesProcessor(styleApplier: storage, range: range, note: note) processor.load() } if note.isMarkdown() { while (editArea.textStorage.mutableString.contains("- [ ] ")) { let range = editArea.textStorage.mutableString.range(of: "- [ ] ") if editArea.textStorage.length >= range.upperBound, let unChecked = AttributedBox.getUnChecked() { editArea.textStorage.replaceCharacters(in: range, with: unChecked) } } while (editArea.textStorage.mutableString.contains("- [x] ")) { let range = editArea.textStorage.mutableString.range(of: "- [x] ") if editArea.textStorage.length >= range.upperBound, let checked = AttributedBox.getChecked() { editArea.textStorage.replaceCharacters(in: range, with: checked) } } } let search = getSearchText() if search.count > 0 { let processor = NotesTextProcessor(storage: storage) processor.highlightKeyword(search: search) isHighlighted = true } editArea.selectedTextRange = cursor if note.type != .RichText { editArea.typingAttributes[NSAttributedStringKey.font.rawValue] = UIFont.bodySize() return } editArea.applyLeftParagraphStyle() } private func configureToolbar() { guard let note = self.note else { return } if note.type == .PlainText { if self.toolbar != .plain { self.toolbar = .plain self.addToolBar(textField: editArea, toolbar: self.getPlainTextToolbar()) } return } if note.type == .RichText { if self.toolbar != .rich { self.toolbar = .rich self.addToolBar(textField: editArea, toolbar: self.getRTFToolbar()) } return } if self.toolbar != .markdown { self.toolbar = .markdown self.addToolBar(textField: editArea, toolbar: getMarkdownToolbar()) } } public func configureFont() { if let note = self.note, note.type != .RichText { self.editArea.textStorage.addAttribute(.font, value: UIFont.bodySize(), range: NSRange(0..<self.editArea.textStorage.length)) } self.editArea.typingAttributes.removeAll() self.editArea.typingAttributes[NSAttributedStringKey.font.rawValue] = UIFont.bodySize() } func loadPreview(note: Note) { let path = Bundle.main.path(forResource: "DownView", ofType: ".bundle") let url = NSURL.fileURL(withPath: path!) let bundle = Bundle(url: url) let markdownString = note.getPrettifiedContent() do { guard var imagesStorage = note.project?.url else { return } if note.type == .TextBundle { imagesStorage = note.url } if let downView = try? MarkdownView(imagesStorage: imagesStorage, frame: self.view.frame, markdownString: markdownString, css: "", templateBundle: bundle) { downView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(downView) } } return } func refill() { initLinksColor() if let note = self.note { let range = editArea.selectedRange let keyboardIsOpen = editArea.isFirstResponder if keyboardIsOpen { editArea.endEditing(true) } if NightNight.theme == .night { editArea.keyboardAppearance = .dark } else { editArea.keyboardAppearance = .light } fill(note: note) editArea.selectedRange = range if keyboardIsOpen { editArea.becomeFirstResponder() } } } public func reloadPreview() { if UserDefaultsManagement.preview, let note = self.note { removeMdSubviewIfExist(reload: true, note: note) } } // RTF style completions func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let note = self.note else { return true } self.restoreRTFTypingAttributes(note: note) if note.isMarkdown() { self.applyStrikeTypingAttribute(range: range) } /* // Paste in UITextView if note.isMarkdown() && text == UIPasteboard.general.string { self.editArea.insertText(text) NotesTextProcessor.fullScan(note: note, storage: editArea.textStorage, range: NSRange(0..<editArea.textStorage.length), async: true) return false } // Delete backward pressed if self.deleteBackwardPressed(text: text) { self.editArea.deleteBackward() let formatter = TextFormatter(textView: self.editArea, note: note, shouldScanMarkdown: false) formatter.deleteKey() return false } */ // New line if text == "\n" { let formatter = TextFormatter(textView: self.editArea, note: note, shouldScanMarkdown: false) formatter.newLine() if note.isMarkdown() { let processor = NotesTextProcessor(note: note, storage: editArea.textStorage, range: range) processor.scanParagraph() } return false } // Tab if text == "\t" { let formatter = TextFormatter(textView: self.editArea, note: note, shouldScanMarkdown: false) formatter.tabKey() return false } if let font = self.editArea.typingFont { editArea.typingAttributes[NSAttributedStringKey.font.rawValue] = font } return true } private func applyStrikeTypingAttribute(range: NSRange) { let string = editArea.textStorage.string as NSString let paragraphRange = string.paragraphRange(for: range) let paragraph = editArea.textStorage.attributedSubstring(from: paragraphRange) if paragraph.length > 0, let attachment = paragraph.attribute(NSAttributedStringKey(rawValue: "co.fluder.fsnotes.image.todo"), at: 0, effectiveRange: nil) as? Int, attachment == 1 { editArea.typingAttributes[NSAttributedStringKey.strikethroughStyle.rawValue] = 1 } else { editArea.typingAttributes.removeValue(forKey: NSAttributedStringKey.strikethroughStyle.rawValue) } } private func restoreRTFTypingAttributes(note: Note) { guard note.isRTF() else { return } let formatter = TextFormatter(textView: editArea, note: note) self.editArea.typingAttributes[NSAttributedStringKey.font.rawValue] = formatter.getTypingAttributes() } private func getDefaultFont() -> UIFont { var font = UserDefaultsManagement.noteFont! if #available(iOS 11.0, *) { let fontMetrics = UIFontMetrics(forTextStyle: .body) font = fontMetrics.scaledFont(for: font) } return font } private func deleteBackwardPressed(text: String) -> Bool { if !self.isUndo, let char = text.cString(using: String.Encoding.utf8), strcmp(char, "\\b") == -92 { return true } self.isUndo = false return false } var inProgress = false var change = 0 func textViewDidChange(_ textView: UITextView) { guard let pageController = UIApplication.shared.windows[0].rootViewController as? PageViewController, let vc = pageController.orderedViewControllers[0] as? ViewController else { return } vc.cloudDriveManager?.cloudDriveQuery.disableUpdates() guard let note = self.note else { return } if isHighlighted { let search = getSearchText() let processor = NotesTextProcessor(storage: textView.textStorage) processor.highlightKeyword(search: search, remove: true) isHighlighted = false } let range = editArea.selectedRange let storage = editArea.textStorage let processor = NotesTextProcessor(note: note, storage: storage, range: range) if note.type == .PlainText || note.type == .RichText { processor.higlightLinks() } else { processor.scanParagraph() } self.storageQueue.cancelAllOperations() let operation = BlockOperation() operation.addExecutionBlock { DispatchQueue.main.async { note.content = NSMutableAttributedString(attributedString: self.editArea.attributedText) note.save() } } self.storageQueue.addOperation(operation) if var font = UserDefaultsManagement.noteFont { if #available(iOS 11.0, *) { let fontMetrics = UIFontMetrics(forTextStyle: .body) font = fontMetrics.scaledFont(for: font) } editArea.typingAttributes[NSAttributedStringKey.font.rawValue] = font } editArea.initUndoRedoButons() vc.cloudDriveManager?.cloudDriveQuery.enableUpdates() vc.notesTable.moveRowUp(note: note) } func getSearchText() -> String { if let pageController = UIApplication.shared.windows[0].rootViewController as? PageViewController, let viewController = pageController.orderedViewControllers[0] as? ViewController, let search = viewController.search.text { return search } return "" } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.view.frame.size.height = UIScreen.main.bounds.height self.view.frame.size.height -= keyboardSize.height } } @objc func keyboardWillHide(notification: NSNotification) { self.view.frame.size.height = UIScreen.main.bounds.height } func addToolBar(textField: UITextView, toolbar: UIToolbar) { let scroll = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: toolbar.frame.height)) scroll.mixedBackgroundColor = MixedColor(normal: 0xfafafa, night: 0x47444e) scroll.showsHorizontalScrollIndicator = false scroll.contentSize = CGSize(width: toolbar.frame.width, height: toolbar.frame.height) scroll.addSubview(toolbar) textField.delegate = self textField.inputAccessoryView = scroll if let etv = textField as? EditTextView { etv.initUndoRedoButons() } } private func getMarkdownToolbar() -> UIToolbar { let toolBar = UIToolbar() toolBar.mixedBarTintColor = MixedColor(normal: 0xfafafa, night: 0x47444e) toolBar.barStyle = .blackTranslucent toolBar.mixedTintColor = MixedColor(normal: 0x4d8be6, night: 0x7eeba1) let imageButton = UIBarButtonItem(image: UIImage(named: "image"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.imagePressed)) let boldButton = UIBarButtonItem(image: #imageLiteral(resourceName: "bold.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.boldPressed)) let italicButton = UIBarButtonItem(image: #imageLiteral(resourceName: "italic.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.italicPressed)) let indentButton = UIBarButtonItem(image: #imageLiteral(resourceName: "indent.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.indentPressed)) let unindentButton = UIBarButtonItem(image: #imageLiteral(resourceName: "unindent.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.unIndentPressed)) let headerButton = UIBarButtonItem(image: #imageLiteral(resourceName: "header.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.headerPressed)) let todoButton = UIBarButtonItem(image: UIImage(named: "todo"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.todoPressed)) let undoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "undo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.undoPressed)) let redoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "redo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.redoPressed)) let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(EditorViewController.donePressed)) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) toolBar.setItems([todoButton, boldButton, italicButton, indentButton, unindentButton, headerButton, imageButton, spaceButton, undoButton, redoButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true toolBar.frame = CGRect.init(x: 0, y: 0, width: 420, height: 44) return toolBar } private func getRTFToolbar() -> UIToolbar { let toolBar = UIToolbar() toolBar.mixedBarTintColor = MixedColor(normal: 0xfafafa, night: 0x47444e) toolBar.isTranslucent = true toolBar.mixedTintColor = MixedColor(normal: 0x4d8be6, night: 0x7eeba1) let boldButton = UIBarButtonItem(image: #imageLiteral(resourceName: "bold.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.boldPressed)) let italicButton = UIBarButtonItem(image: #imageLiteral(resourceName: "italic.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.italicPressed)) let strikeButton = UIBarButtonItem(image: UIImage(named: "strike.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.strikePressed)) let underlineButton = UIBarButtonItem(image: UIImage(named: "underline.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.underlinePressed)) let undoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "undo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.undoPressed)) let redoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "redo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.redoPressed)) let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(EditorViewController.donePressed)) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) toolBar.setItems([boldButton, italicButton, strikeButton, underlineButton, spaceButton, undoButton, redoButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true toolBar.sizeToFit() return toolBar } private func getPlainTextToolbar() -> UIToolbar { let toolBar = UIToolbar() toolBar.mixedBarTintColor = MixedColor(normal: 0xfafafa, night: 0x47444e) toolBar.isTranslucent = true toolBar.mixedTintColor = MixedColor(normal: 0x4d8be6, night: 0x7eeba1) let undoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "undo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.undoPressed)) let redoButton = UIBarButtonItem(image: #imageLiteral(resourceName: "redo.png"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(EditorViewController.redoPressed)) let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(EditorViewController.donePressed)) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, undoButton, redoButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true toolBar.sizeToFit() return toolBar } @objc func boldPressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.bold() } } @objc func italicPressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.italic() } } @objc func strikePressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.strike() } } @objc func underlinePressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.underline() } } @objc func indentPressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.tab() } } @objc func unIndentPressed(){ if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.unTab() } } @objc func headerPressed() { if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.header("#") } } @objc func todoPressed() { if let note = note { let formatter = TextFormatter(textView: editArea, note: note) formatter.toggleTodo() AudioServicesPlaySystemSound(1519) } } @objc func imagePressed() { if let note = self.note { let pickerController = DKImagePickerController() pickerController.assetType = .allPhotos pickerController.didSelectAssets = { (assets: [DKAsset]) in var processed = 0 var markup = "" for asset in assets { asset.fetchOriginalImage(true, completeBlock: { image, info in processed += 1 guard var url = info?["PHImageFileURLKey"] as? URL else { return } let data: Data? let isHeic = url.pathExtension.lowercased() == "heic" if isHeic, let imageUnwrapped = image { data = UIImageJPEGRepresentation(imageUnwrapped, 0.7); url.deletePathExtension() url.appendPathExtension("jpg") } else { do { data = try Data(contentsOf: url) } catch { return } } guard let imageData = data else { return } guard let fileName = ImagesProcessor.writeImage(data: imageData, url: url, note: note) else { return } if note.type == .TextBundle { markup += "![](assets/\(fileName))" } else { markup += "![](/i/\(fileName))" } markup += "\n\n" guard processed == assets.count else { return } DispatchQueue.main.async { self.editArea.insertText(markup) note.content = NSMutableAttributedString(attributedString: self.editArea.attributedText) note.save() self.editArea.undoManager?.removeAllActions() self.refill() } }) } } present(pickerController, animated: true) {} } } @objc func donePressed(){ view.endEditing(true) } @objc func cancelPressed(){ view.endEditing(true) } @objc func preferredContentSizeChanged() { if let n = note { self.fill(note: n) } } @objc func undoPressed() { guard let pageController = UIApplication.shared.windows[0].rootViewController as? PageViewController, let vc = pageController.orderedViewControllers[1] as? UINavigationController, let evc = vc.viewControllers[0] as? EditorViewController, let ea = evc.editArea, let um = ea.undoManager else { return } self.isUndo = true um.undo() ea.initUndoRedoButons() } @objc func redoPressed() { guard let pageController = UIApplication.shared.windows[0].rootViewController as? PageViewController, let vc = pageController.orderedViewControllers[1] as? UINavigationController, let evc = vc.viewControllers[0] as? EditorViewController, let ea = evc.editArea, let um = ea.undoManager else { return } um.redo() ea.initUndoRedoButons() } @objc func preview() { let isPreviewMode = !UserDefaultsManagement.preview guard let n = note else { return } if isPreviewMode { view.endEditing(true) } navigationItem.rightBarButtonItem?.title = isPreviewMode ? "Edit" : "Preview" fill(note: n, preview: isPreviewMode) UserDefaultsManagement.preview = isPreviewMode } func removeMdSubviewIfExist(reload: Bool = false, note: Note? = nil) { guard view.subviews.indices.contains(1) else { return } DispatchQueue.main.async { for sub in self.view.subviews { if sub.isKind(of: MarkdownView.self) { sub.removeFromSuperview() } } if reload, let note = note { self.loadPreview(note: note) } } } func initLinksColor() { guard let note = self.note else { return } var linkAttributes: [String : Any] = [ NSAttributedStringKey.foregroundColor.rawValue: NightNight.theme == .night ? UIColor(red:0.49, green:0.92, blue:0.63, alpha:1.0) : UIColor(red:0.24, green:0.51, blue:0.89, alpha:1.0) ] if !note.isRTF() { linkAttributes[NSAttributedStringKey.underlineColor.rawValue] = UIColor.lightGray linkAttributes[NSAttributedStringKey.underlineStyle.rawValue] = NSUnderlineStyle.styleNone.rawValue } if editArea != nil { editArea.linkTextAttributes = linkAttributes } } @objc private func tapHandler(_ sender: UITapGestureRecognizer) { let myTextView = sender.view as! UITextView let layoutManager = myTextView.layoutManager var location = sender.location(in: myTextView) location.x -= myTextView.textContainerInset.left; location.y -= myTextView.textContainerInset.top; var characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // Image preview on click if self.editArea.isImage(at: characterIndex) { let todoKey = NSAttributedStringKey(rawValue: "co.fluder.fsnotes.image.path") guard let path = myTextView.textStorage.attribute(todoKey, at: characterIndex, effectiveRange: nil) as? String, let note = self.note, let url = note.getImageUrl(imageName: path) else { return } if let someImage = UIImage(contentsOfFile: url.path) { let imageInfo = GSImageInfo(image: someImage, imageMode: .aspectFit) let transitiionInfo = GSTransitionInfo(fromRect: CGRect.init()) let imageViewer = GSImageViewerController(imageInfo: imageInfo, transitionInfo: transitiionInfo) present(imageViewer, animated: true, completion: nil) } return } let char = Array(myTextView.textStorage.string)[characterIndex] // Toggle todo on click if characterIndex + 1 < myTextView.textStorage.length, char != "\n", self.isTodo(location: characterIndex, textView: myTextView), let note = self.note { self.editArea.isAllowedScrollRect = false let textFormatter = TextFormatter(textView: self.editArea!, note: note) textFormatter.toggleTodo(characterIndex) Timer.scheduledTimer(withTimeInterval: 0.05, repeats: false) { _ in self.editArea.isAllowedScrollRect = true } AudioServicesPlaySystemSound(1519) return } DispatchQueue.main.async { self.editArea.becomeFirstResponder() if myTextView.textStorage.length > 0 && characterIndex == myTextView.textStorage.length - 1 { characterIndex += 1 } self.editArea.selectedRange = NSMakeRange(characterIndex, 0) } } private func isTodo(location: Int, textView: UITextView) -> Bool { let storage = textView.textStorage let todoKey = NSAttributedStringKey(rawValue: "co.fluder.fsnotes.image.todo") if storage.attribute(todoKey, at: location, effectiveRange: nil) != nil { return true } let range = (storage.string as NSString).paragraphRange(for: NSRange(location: location, length: 0)) let string = storage.attributedSubstring(from: range).string as NSString var length = string.range(of: "- [ ]").length if length == 0 { length = string.range(of: "- [x]").length } if length > 0 { let upper = range.location + length if location >= range.location && location <= upper { return true } } return false } }
38.822144
230
0.616414
ab81404c0202e25687810308374f2930174e6a27
663
import Foundation //========================================================= // Client socket public class ClientSocket { public func talkToServer(query: ClientQuery) -> ServerResponse { let connection = query.connection let client = TcpClient(host: connection.host, port: connection.port) client.connect() let outputData = query.encode() let outputPacket = Array(outputData) client.send(packet: outputPacket) let inputPacket = client.receive() client.close() let result = ServerResponse(inputPacket) return result } // func talkToServer } // class ClientSocket
30.136364
76
0.598793
505ff46c24b8e5bd3a13f84ef9e8b4ab1a1ba004
1,195
// // ViewController.swift // STFakeLabel-Swift // // Created by TangJR on 12/4/15. // Copyright © 2015 tangjr. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var fakeLabel: UILabel! private var flag = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func buttonTapped(sender: UIButton) { let tag = sender.tag let toText = flag % 2 == 1 ? "EGG" : "FALL" flag++ if tag == 100 { self.fakeLabel.st_startAnimation(UILabel.STFakeAnimationDirection.Down, toText: toText) return } if tag == 101 { self.fakeLabel.st_startAnimation(UILabel.STFakeAnimationDirection.Left, toText: toText) return } if tag == 102 { self.fakeLabel.st_startAnimation(UILabel.STFakeAnimationDirection.Right, toText: toText) return } if tag == 103 { self.fakeLabel.st_startAnimation(UILabel.STFakeAnimationDirection.Up, toText: toText) return } } }
27.790698
100
0.604184
ac5167860f6521d457cbe30d53529c57be2e0c05
1,692
// // NSCoding+Ext.swift // // Clipy // GitHub: https://github.com/clipy // HP: https://clipy-app.com // // Created by Econa77 on 2016/11/19. // // Copyright © 2015-2018 Clipy Project. // import Foundation extension Data { func unarchive() -> Any? { do { return try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(self) } catch { lError(error) return nil } } } extension NSCoding { func archive() -> Data? { do { return try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false) } catch { lError(error) return nil } } func archive(toFilePath filePath: String) { do { let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false) try data.write(to: .init(fileURLWithPath: filePath)) } catch { lError(error) } } } extension Array where Element: NSCoding { func archive() -> Data? { do { return try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false) } catch { lError(error) return nil } } } extension UserDefaults { func setArchiveObject<T: NSCoding>(_ object: T, forKey key: String) { if let data = object.archive() { set(data, forKey: key) } } func archiveObject<T: NSCoding>(forKey key: String, with type: T.Type) -> T? { guard let data = object(forKey: key) as? Data, let object = data.unarchive() as? T else { return nil } return object } }
24.171429
107
0.573877
ac8bbf1bbfcc939ac12cdc497022c0be0c18c87f
486
// // AnySubscription.swift // SwiftUI-Flux // // Created by David S on 6/9/19. // Copyright © 2019 David S. All rights reserved. // import Foundation import Combine final class AnySubscription: Subscription { private let cancellable: AnyCancellable init(_ cancel: @escaping () -> Void) { self.cancellable = AnyCancellable(cancel) } func request(_ demand: Subscribers.Demand) {} func cancel() { cancellable.cancel() } }
18.692308
50
0.635802
38b9e521a4a5775dcff6e8a034507f485981d30d
258
// // EnlargeImageCellProtocal.swift // MemoryMaster // // Created by apple on 27/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import Foundation protocol EnlargeImageCellDelegate: class { func enlargeTapedImage(image: UIImage) }
18.428571
52
0.736434
e0fb5aba7f6a6e1598bf41ce8dd675922e1b365b
2,028
import PolymorphCore import CommandLineArgs var arguments = CommandLine.arguments arguments[0] = PolymorphCommand.Consts.name let cla = CommandLineArgs() let polymorph = cla.root(command: PolymorphCommand()) let projectCommands = polymorph.add(child: ProjectCommand()) projectCommands.add(child: InitProjectCommand()) projectCommands.add(child: InfoProjectCommand()) projectCommands.add(child: UpdateProjectCommand()) projectCommands.add(child: RemoveProjectCommand()) let classCommands = polymorph.add(child: ClassCommand()) classCommands.add(child: NewClassCommand()) classCommands.add(child: ListClassCommand()) classCommands.add(child: UpdateClassCommand()) classCommands.add(child: RemoveClassCommand()) let propertyCommands = classCommands.add(child: ClassPropertyCommand()) propertyCommands.add(child: ClassNewPropertyCommand()) propertyCommands.add(child: ClassRemovePropertyCommand()) propertyCommands.add(child: ClassUpdatePropertyCommand()) propertyCommands.add(child: ClassSortPropertyCommand()) let enumCommands = polymorph.add(child: EnumCommand()) enumCommands.add(child: NewEnumCommand()) enumCommands.add(child: ListEnumCommand()) enumCommands.add(child: RemoveEnumCommand()) enumCommands.add(child: EnumValueCommand()) let valueCommands = enumCommands.add(child: EnumValueCommand()) valueCommands.add(child: EnumNewValueCommand()) let serviceCommands = polymorph.add(child: ServiceCommand()) serviceCommands.add(child: NewServiceCommand()) let externalCommands = polymorph.add(child: ExternalCommand()) externalCommands.add(child: NewExternalCommand()) externalCommands.add(child: ListExternalCommand()) externalCommands.add(child: UpdateExternalCommand()) externalCommands.add(child: RemoveExternalCommand()) polymorph.add(child: BuildCommand()) let nativeCommands = polymorph.add(child: NativeCommand()) nativeCommands.add(child: ListNativeCommand()) let transfomerCommands = polymorph.add(child: TransformerCommand()) transfomerCommands.add(child: ListTransformerCommand()) cla.handle(arguments)
38.264151
71
0.822485
ddaac0e84bd02d37d2aab364f3abda5c83f005db
1,950
// APIs.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class SwaggerClientAPI { public static var basePath = Constant.appEnvironment.rawValue public static var credential: URLCredential? public static var customHeaders: [String:String] = Constant.getCustomHeaders() public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var defaultTimeout: Double = 60.0 } open class RequestBuilder<T> { var credential: URLCredential? var headers: [String:String] public let parameters: [String:Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody self.headers = headers addHeaders(SwaggerClientAPI.customHeaders) } open func addHeaders(_ aHeaders:[String:String]) { for (header, value) in aHeaders { headers[header] = value } } open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } return self } open func addCredential() -> Self { self.credential = SwaggerClientAPI.credential return self } } public protocol RequestBuilderFactory { func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type }
30.952381
134
0.677436
6a41f57558d57834e7bac7480fc18383708b7747
2,231
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController { // TODO: Use TSan to check for race condition // TODO: Make Number class in Number.swift thread-safe to remove race condition let changingNumber = Number(value: 0, name: "zero") let numberArray = [(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"), (6, "six")] let workerQueue = DispatchQueue(label: "com.raywenderlich.worker", attributes: DispatchQueue.Attributes.concurrent) let numberGroup = DispatchGroup() override func viewDidLoad() { super.viewDidLoad() changeNumber() } // When made thread-safe: printed pairs match, although not all will print, due to random delays func changeNumber() { for pair in numberArray { workerQueue.async(group: numberGroup) { self.changingNumber.changeNumber(pair.0, name: pair.1) print("Current number: \(self.changingNumber.number)") } } // When made thread-safe, prints Final number: 6 :: six numberGroup.notify(queue: DispatchQueue.main) { print("Final number: \(self.changingNumber.number)") } } }
38.465517
117
0.714926
796629e4dbaec604ff63364ea8d54b549fe4dd3f
7,643
// // HeaderRefresh.swift // HeaderRefreshing // // Created by wangfei on 16/7/5. // Copyright © 2016年 fei.wang. All rights reserved. // import Foundation import UIKit enum RefreshState { case Normal case Pulling case Refreshing } private let maxPullOffset:CGFloat = 75.0 typealias RefreshCallback = () ->() public class HeaderRefresh:NSObject { private var onceToken: dispatch_once_t = 0 private var tableView:UITableView! private var tableBkgView:RefreshTableBkgView! private var refreshState:RefreshState = .Normal { willSet { switch newValue { case .Normal,.Pulling: self.tableBkgView.refreshingMsg = NSLocalizedString("下拉刷新", comment: "") case .Refreshing: self.tableBkgView.refreshingMsg = NSLocalizedString("释放开始刷新", comment: "") } } } /// 是否正在加载 public var isLoading:Bool = false /// 是否下拉到规定的最大偏移 private var isDragingToMaxOffset = false private var callback:RefreshCallback! /// 默认top偏移量 private var defaultTableInsetTop:CGFloat = 0.0 private var defaultTableInsetBottom: CGFloat = 0.0 override init() { super.init() tableBkgView = RefreshTableBkgView() } deinit { self.tableView.removeObserver(self, forKeyPath: "contentOffset") self.tableView.removeObserver(self, forKeyPath: "contentInset") self.callback = nil } ///根据view反向寻找controller func viewController(view:UIView)->UIViewController?{ var next:UIView? = view repeat{ if let nextResponder = next?.nextResponder() where nextResponder.isKindOfClass(UIViewController.self){ return (nextResponder as! UIViewController) } next = next?.superview }while next != nil return nil } /** 注意 需要传入tableView的bkgColor - parameter tableView: 刷新控件要添加到的View - parameter tableViewBkgColor: tableView的bkgColor - parameter callBack: 刷新完成回调 */ func handleScrollView(tableView:UITableView, tableViewBkgColor:UIColor, callBack:()->()) { tableBkgView.circleView.lineColor = tableViewBkgColor handleScrollView(tableView, callBack: callBack) } /** 对tableView添加刷新控件 - parameter tableView: 刷新控件要添加到的view - parameter callBack: 刷新完成回调 */ func handleScrollView(tableView:UITableView, callBack:()->()) { self.callback = callBack self.tableView = tableView tableBkgView.circleView.lineColor = tableView.backgroundColor tableBkgView.bkgTopView.backgroundColor = tableView.backgroundColor tableBkgView.frame = self.tableView.frame self.tableView.backgroundView = tableBkgView self.tableView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil) self.tableView.addObserver(self, forKeyPath: "contentInset", options: .New, context: nil) } /** 重置一次bkgView的子视图的frame - parameter top: 默认top inset - parameter bottom: 默认bottom inset */ private func resetBkgFrameOnce(top:CGFloat, withInsetBottom bottom: CGFloat) { // dispatch_once(&onceToken) { self.defaultTableInsetTop = top self.defaultTableInsetBottom = bottom self.tableBkgView.resetFrame(withContentInsetTop: top) // } } override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "contentInset" { guard !isDragingToMaxOffset else { return } resetBkgFrameOnce(self.tableView.contentInset.top, withInsetBottom: self.tableView.contentInset.bottom) } let offsetY = -self.tableView.contentOffset.y - self.defaultTableInsetTop if offsetY >= 1.0 { tableBkgView.bkgTopView.hidden = true }else if offsetY < 0{ tableBkgView.bkgTopView.hidden = false } if isLoading { return } if keyPath == "contentOffset" { //for test (offsetY - circleViewTopY) / ((self.defaultTableInsetTop - circleViewTopY * 2 - 4)) let progress = abs((offsetY - circleViewTopY) / (maxPullOffset - circleViewTopY) * 2) if offsetY <= circleViewTopY { //下拉到开始绘制image的offset之前状态 self.refreshState = .Normal } if offsetY > circleViewTopY && offsetY < maxPullOffset { //下拉绘制loading状态的image if self.refreshState == .Refreshing { }else { self.refreshState = RefreshState.Pulling } }else if offsetY >= maxPullOffset { //下拉到最大偏移量时 转为松手开始刷新 self.refreshState = .Refreshing } refreshStateChanged(progress, isDraging: self.tableView.dragging) } } private func refreshStateChanged(progress:CGFloat, isDraging:Bool) { if self.refreshState == .Normal { self.tableView.contentInset.top = self.defaultTableInsetTop self.tableView.contentInset.bottom = self.defaultTableInsetBottom return }else if self.refreshState == .Pulling { self.tableBkgView.imgView.layer.transform = CATransform3DIdentity self.tableBkgView.circleView.hidden = false self.tableBkgView.circleView.progress = progress }else if self.refreshState == .Refreshing { if isDraging { //拖动时转动 isDragingToMaxOffset = true //不在修改contentinset 的 top if progress < 2.0 { self.refreshState = .Pulling }else { self.tableBkgView.circleView.hidden = true self.tableBkgView.circleViewRotate(progress) } }else { //松手后转动并开始刷新 UIView.animateWithDuration(0.5, delay: 0, options: .TransitionNone, animations: { self.tableBkgView.refreshingMsg = NSLocalizedString("正在刷新...", comment: "") self.tableBkgView.circleView.hidden = true self.tableView.contentInset = UIEdgeInsetsMake(self.defaultTableInsetTop + maxPullOffset, 0, self.defaultTableInsetBottom, 0) }, completion: { (finished) in if self.isLoading == false { self.startLoading() } }) } } } /** 开始加载 */ private func startLoading() { self.isLoading = true self.tableBkgView.startAnimation() callback?() } /** 结束加载 */ func endLoading() { self.refreshState = .Normal UIView.animateWithDuration(0.5, delay: 0, options: .TransitionNone, animations: { var inset = self.tableView.contentInset inset = UIEdgeInsetsMake(inset.top - maxPullOffset, 0, self.defaultTableInsetBottom, 0) self.tableView.contentInset = inset }) { (finished) in UIView.animateWithDuration(0, animations: { self.tableBkgView.endAnimation() }, completion: { (finished) in self.isLoading = false }) } } }
33.375546
164
0.589036
0a55d179665cc7ca52dcee6d6c6658189191ccc0
719
// // BarLineScatterCandleBubbleChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation public class BarLineScatterCandleBubbleChartData: ChartData { public override init() { super.init() } public override init(xVals: [String?]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } }
21.787879
72
0.662031
e8c41a0aa1da729f499cca3629e7b5ced15b9608
1,339
/** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func maxAncestorDiff(_ root: TreeNode?) -> Int { // helper 返回最大和最小的子孙(包括自己),同时更新当前的result var result = 0 func helper(_ root: TreeNode?) -> (Int, Int)? { guard let root = root else { return nil } let (minl, maxl) = helper(root.left) ?? (root.val, root.val) let (minr, maxr) = helper(root.right) ?? (root.val, root.val) let thismin = min(minl, minr) let thismax = max(maxl, maxr) let retmin = min(thismin, root.val) let retmax = max(thismax, root.val) let thisResult = max(abs(root.val - thismin), abs(root.val - thismax)) result = max(result, thisResult) return (retmin, retmax) } // 遍历一遍出结果 helper(root) return result } }
35.236842
85
0.537715
7668aa27a147be1cb6096101e6a283c964f7bac6
1,223
// RUN: %target-parse-verify-swift -sdk %S/Inputs -I %S/Inputs/custom-modules -I %S/../Inputs/custom-modules // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -sdk %S/Inputs -I %S/Inputs/custom-modules -I %S/../Inputs/custom-modules -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: objc_interop import AttrObjc_FooClangModule import ObjCRuntimeVisible @objc class infer_instanceVar1 { // CHECK-LABEL: @objc class infer_instanceVar1 { var var_ClangEnum: FooEnum1 var var_ClangStruct: FooStruct1 // CHECK-LABEL: @objc var var_ClangEnum: FooEnum1 // CHECK-LABEL: @objc var var_ClangStruct: FooStruct1 init(fe: FooEnum1, fs: FooStruct1) { var_ClangEnum = fe var_ClangStruct = fs } } class ObjC_Class1 : NSObject, Hashable { var hashValue: Int { return 0 } } func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool { return true } @objc class ObjC_Class2 : Hashable { var hashValue: Int { return 0 } } func ==(lhs: ObjC_Class2, rhs: ObjC_Class2) -> Bool { return true } extension A { // CHECK: {{^}} func foo() func foo() { } }
27.795455
323
0.718724
4b865c8dbe33550cb9c4053d0ccccf45150d1105
4,524
// // Repository.swift // task2_generic_api_client // // Created by Roman Brazhnikov on 26.06.2018. // Copyright © 2018 Roman Brazhnikov. All rights reserved. // import Foundation import UIKit class Repository { // // HTTP session // private let session: URLSession = { let config = URLSessionConfiguration.default return URLSession(configuration: config) }() // // Singleton // private static var instance: Repository? public static func getInstance() -> Repository{ if instance == nil { instance = Repository() } return instance! } private init() { } // // Commands // /// Gets array of vacancy according to the resuest. API HH func getVacanciesForRequest(_ request: Request, with completion: @escaping (VacanciesRequestResult)->()) { // Executing request in separate thread // and then calling completion() request.execute { (result) in DispatchQueue.global(qos: .userInteractive).async { completion(result) } } } // // for favorites // TODO: use CoreData // /// Gets all favorite vacancies as an array (in-memory) func getAllFavorites(with completion: @escaping ([Vacancy])->()) { // trying to get everything from favorites // in a separate thread // then calling completion() DispatchQueue.global(qos: .userInteractive).async { sleep(1) completion(FavoritesBank.getInstance().getAllVacancies()) } } /// Checks out if the vacancy is in favorites func isFavorite(vacancy: Vacancy, with completion: @escaping (Bool)->()) { // TODO: use CoreData DispatchQueue.global(qos: .userInteractive).async { completion(FavoritesBank.getInstance().contains(vacancy)) } } /// Inverts Vacancy's favorite state: /// - adds to favorites if it wasn't /// - deletes from favorites if it was there func toggleFavoriteStateForVacancy(_ vacancy: Vacancy, with completion: @escaping (Bool)->()) { DispatchQueue.global(qos: .userInteractive).async { let bank = FavoritesBank.getInstance() // toggling if bank.contains(vacancy) { bank.removeVacancy(vacancy) } else { bank.addVacancy(vacancy) } // sending result contains now or not completion(FavoritesBank.getInstance().contains(vacancy)) } } // // Getting Image // func getImageForUrl(_ url:URL, with completion: @escaping(ImageResult) -> Void){ DispatchQueue.global(qos: .userInteractive).async { // trying to get image from cache by key let logoKey = (url.absoluteString as NSString).lastPathComponent if let image = ImageCachingBank.getInstance().image(forKey: logoKey) { completion(.success(image)) return } // else trying to download let request = URLRequest(url: url) let task = self.session.dataTask(with: request) { (data, response, error) -> Void in // Delay intended, to demonstrate async lazy loading usleep(333000) // trying to build image let result = self.processingImageRequest(data: data, error: error) // adding to cache if case let .success(image) = result { ImageCachingBank.getInstance().setImage(image, forKey: logoKey) } // returning result completion(result) } task.resume() } } /// creates and returns actual UIImage from Data private func processingImageRequest(data: Data?, error: Error?) -> ImageResult { guard let imageData = data, let image = UIImage(data: imageData) else { // can't create image if data == nil { return .failure(error!) } else { return .failure(PhotoError.imageCreationError) } } return .success(image) } }
30.362416
110
0.542219
140b7912ce886e418d36c9cf8980266d644e5718
688
import XCTest @testable import AtCoderSupport final class RangeSumTests: XCTestCase { func testSum() { XCTAssertEqual((1 ... 10).sum(), 55) XCTAssertEqual((-10 ... 100).sum(), 4995) XCTAssertEqual((-10 ... -1).sum(), -55) XCTAssertEqual((-100 ... 10).sum(), -4995) XCTAssertEqual((1 ... 10).sum(modulus: 13), 55 % 13) XCTAssertEqual((-10 ... 100).sum(modulus: 13), 4995 % 13) XCTAssertEqual((-10 ... -1).sum(modulus: 13), -55 % 13 + 13) XCTAssertEqual((-100 ... 10).sum(modulus: 13), -4995 % 13 + 13) XCTAssertEqual((1 ... 1000000000).sum(modulus: 998244353), (1000000000 * 1000000001 / 2) % 998244353) } }
40.470588
109
0.578488
e8e597b5112e6a707b11060c3e9e563dcc24411b
1,759
// // TxAddressCell.swift // breadwallet // // Created by Ehsan Rezaie on 2017-12-20. // Copyright © 2017 breadwallet LLC. All rights reserved. // import UIKit class TxAddressCell: TxDetailRowCell { // MARK: Views internal let addressButton = UIButton(type: .system) // MARK: - Init override func addSubviews() { super.addSubviews() container.addSubview(addressButton) } override func addConstraints() { super.addConstraints() addressButton.constrain([ addressButton.leadingAnchor.constraint(greaterThanOrEqualTo: titleLabel.trailingAnchor, constant: C.padding[1]), addressButton.constraint(.trailing, toView: container), addressButton.constraint(.top, toView: container), addressButton.constraint(.bottom, toView: container) ]) } override func setupStyle() { super.setupStyle() addressButton.titleLabel?.font = .customBody(size: 14.0) addressButton.titleLabel?.adjustsFontSizeToFitWidth = true addressButton.titleLabel?.minimumScaleFactor = 0.7 addressButton.titleLabel?.lineBreakMode = .byTruncatingMiddle addressButton.titleLabel?.textAlignment = .right addressButton.tintColor = .darkGray addTapAction() } func addTapAction() { addressButton.tap = strongify(self) { myself in myself.addressButton.tempDisable() Store.trigger(name: .lightWeightAlert(S.Receive.copied)) UIPasteboard.general.string = myself.addressButton.titleLabel?.text } } func set(address: String) { addressButton.setTitle(address, for: .normal) } }
27.920635
124
0.641842
5d4f5fcdf286adba2b176034b52c55ec65717997
59,397
import Foundation import Mapbox import MapboxDirections import MapboxCoreNavigation import Turf /** `NavigationMapView` is a subclass of `MGLMapView` with convenience functions for adding `Route` lines to a map. */ @objc(MBNavigationMapView) open class NavigationMapView: MGLMapView, UIGestureRecognizerDelegate { // MARK: Class Constants struct FrameIntervalOptions { fileprivate static let durationUntilNextManeuver: TimeInterval = 7 fileprivate static let durationSincePreviousManeuver: TimeInterval = 3 fileprivate static let defaultFramesPerSecond: Int = 60 fileprivate static let pluggedInFramesPerSecond: Int = 30 fileprivate static let decreasedFramesPerSecond: Int = 5 } /** Returns the altitude that the map camera initally defaults to. */ @objc public static let defaultAltitude: CLLocationDistance = 1000.0 /** Returns the altitude the map conditionally zooms out to when user is on a motorway, and the maneuver length is sufficently long. */ @objc public static let zoomedOutMotorwayAltitude: CLLocationDistance = 2000.0 /** Returns the threshold for what the map considers a "long-enough" maneuver distance to trigger a zoom-out when the user enters a motorway. */ @objc public static let longManeuverDistance: CLLocationDistance = 1000.0 /** Maximum distance the user can tap for a selection to be valid when selecting an alternate route. */ @objc public var tapGestureDistanceThreshold: CGFloat = 50 /** The object that acts as the navigation delegate of the map view. */ public weak var navigationMapDelegate: NavigationMapViewDelegate? /** The object that acts as the course tracking delegate of the map view. */ public weak var courseTrackingDelegate: NavigationMapViewCourseTrackingDelegate? let sourceOptions: [MGLShapeSourceOption: Any] = [.maximumZoomLevel: 16] // MARK: - Instance Properties let sourceIdentifier = "routeSource" let sourceCasingIdentifier = "routeCasingSource" let routeLayerIdentifier = "routeLayer" let routeLayerCasingIdentifier = "routeLayerCasing" let waypointSourceIdentifier = "waypointsSource" let waypointCircleIdentifier = "waypointsCircle" let waypointSymbolIdentifier = "waypointsSymbol" let arrowSourceIdentifier = "arrowSource" let arrowSourceStrokeIdentifier = "arrowSourceStroke" let arrowLayerIdentifier = "arrowLayer" let arrowSymbolLayerIdentifier = "arrowSymbolLayer" let arrowLayerStrokeIdentifier = "arrowStrokeLayer" let arrowCasingSymbolLayerIdentifier = "arrowCasingSymbolLayer" let arrowSymbolSourceIdentifier = "arrowSymbolSource" let instructionSource = "instructionSource" let instructionLabel = "instructionLabel" let instructionCircle = "instructionCircle" @objc dynamic public var trafficUnknownColor: UIColor = .trafficUnknown @objc dynamic public var trafficLowColor: UIColor = .trafficLow @objc dynamic public var trafficModerateColor: UIColor = .trafficModerate @objc dynamic public var trafficHeavyColor: UIColor = .trafficHeavy @objc dynamic public var trafficSevereColor: UIColor = .trafficSevere @objc dynamic public var routeCasingColor: UIColor = .defaultRouteCasing @objc dynamic public var routeAlternateColor: UIColor = .defaultAlternateLine @objc dynamic public var routeAlternateCasingColor: UIColor = .defaultAlternateLineCasing @objc dynamic public var maneuverArrowColor: UIColor = .defaultManeuverArrow @objc dynamic public var maneuverArrowStrokeColor: UIColor = .defaultManeuverArrowStroke var userLocationForCourseTracking: CLLocation? var animatesUserLocation: Bool = false var altitude: CLLocationDistance = defaultAltitude var routes: [Route]? fileprivate var preferredFramesPerSecond: Int = 60 { didSet { if #available(iOS 10.0, *) { displayLink?.preferredFramesPerSecond = preferredFramesPerSecond } else { displayLink?.frameInterval = FrameIntervalOptions.defaultFramesPerSecond / preferredFramesPerSecond } } } var shouldPositionCourseViewFrameByFrame = false { didSet { if shouldPositionCourseViewFrameByFrame { preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond } } } var showsRoute: Bool { get { return style?.layer(withIdentifier: routeLayerIdentifier) != nil } } open override var showsUserLocation: Bool { get { if tracksUserCourse || userLocationForCourseTracking != nil { return !(userCourseView?.isHidden ?? true) } return super.showsUserLocation } set { if tracksUserCourse || userLocationForCourseTracking != nil { super.showsUserLocation = false if userCourseView == nil { userCourseView = UserPuckCourseView(frame: CGRect(origin: .zero, size: CGSize(width: 75, height: 75))) } userCourseView?.isHidden = !newValue } else { userCourseView?.isHidden = true super.showsUserLocation = newValue } } } /** Center point of the user course view in screen coordinates relative to the map view. - seealso: NavigationMapViewDelegate.navigationMapViewUserAnchorPoint(_:) */ var userAnchorPoint: CGPoint { if let anchorPoint = navigationMapDelegate?.navigationMapViewUserAnchorPoint?(self), anchorPoint != .zero { return anchorPoint } let contentFrame = UIEdgeInsetsInsetRect(bounds, contentInset) let courseViewWidth = userCourseView?.frame.width ?? 0 let courseViewHeight = userCourseView?.frame.height ?? 0 let edgePadding = UIEdgeInsets(top: 50 + courseViewHeight / 2, left: 50 + courseViewWidth / 2, bottom: 50 + courseViewHeight / 2, right: 50 + courseViewWidth / 2) return CGPoint(x: max(min(contentFrame.midX, contentFrame.maxX - edgePadding.right), contentFrame.minX + edgePadding.left), y: max(max(min(contentFrame.minY + contentFrame.height * 0.8, contentFrame.maxY - edgePadding.bottom), contentFrame.minY + edgePadding.top), contentFrame.minY + contentFrame.height * 0.5)) } /** Determines whether the map should follow the user location and rotate when the course changes. - seealso: NavigationMapViewCourseTrackingDelegate */ open var tracksUserCourse: Bool = false { didSet { if tracksUserCourse { enableFrameByFrameCourseViewTracking(for: 2) altitude = NavigationMapView.defaultAltitude showsUserLocation = true courseTrackingDelegate?.navigationMapViewDidStartTrackingCourse?(self) } else { courseTrackingDelegate?.navigationMapViewDidStopTrackingCourse?(self) } if let location = userLocationForCourseTracking { updateCourseTracking(location: location, animated: true) } } } /** A `UIView` used to indicate the user’s location and course on the map. If the view conforms to `UserCourseView`, its `UserCourseView.update(location:pitch:direction:animated:)` method is frequently called to ensure that its visual appearance matches the map’s camera. */ @objc public var userCourseView: UIView? { didSet { oldValue?.removeFromSuperview() if let userCourseView = userCourseView { if let location = userLocationForCourseTracking { updateCourseTracking(location: location, animated: false) } else { userCourseView.center = userAnchorPoint } addSubview(userCourseView) } } } private lazy var mapTapGesture = UITapGestureRecognizer(target: self, action: #selector(didRecieveTap(sender:))) //MARK: - Initalizers public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder decoder: NSCoder) { super.init(coder: decoder) commonInit() } public override init(frame: CGRect, styleURL: URL?) { super.init(frame: frame, styleURL: styleURL) commonInit() } fileprivate func commonInit() { makeGestureRecognizersRespectCourseTracking() makeGestureRecognizersUpdateCourseView() resumeNotifications() } deinit { suspendNotifications() } //MARK: - Overrides open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() let image = UIImage(named: "feedback-map-error", in: .mapboxNavigation, compatibleWith: nil) let imageView = UIImageView(image: image) imageView.contentMode = .center imageView.backgroundColor = .gray imageView.frame = bounds addSubview(imageView) } open override func layoutSubviews() { super.layoutSubviews() //If the map is in tracking mode, make sure we update the camera after the layout pass. if (tracksUserCourse) { updateCourseTracking(location: userLocationForCourseTracking, animated: false) } } open override func anchorPoint(forGesture gesture: UIGestureRecognizer) -> CGPoint { if tracksUserCourse { return userAnchorPoint } else { return super.anchorPoint(forGesture: gesture) } } open override func mapViewDidFinishRenderingFrameFullyRendered(_ fullyRendered: Bool) { super.mapViewDidFinishRenderingFrameFullyRendered(fullyRendered) guard shouldPositionCourseViewFrameByFrame else { return } guard let location = userLocationForCourseTracking else { return } userCourseView?.center = convert(location.coordinate, toPointTo: self) } // MARK: - Notifications func resumeNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) let gestures = gestureRecognizers ?? [] let mapTapGesture = self.mapTapGesture mapTapGesture.requireFailure(of: gestures) addGestureRecognizer(mapTapGesture) } func suspendNotifications() { NotificationCenter.default.removeObserver(self, name: .routeControllerProgressDidChange, object: nil) } @objc func progressDidChange(_ notification: Notification) { guard tracksUserCourse else { return } let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as! RouteProgress let stepProgress = routeProgress.currentLegProgress.currentStepProgress let expectedTravelTime = stepProgress.step.expectedTravelTime let durationUntilNextManeuver = stepProgress.durationRemaining let durationSincePreviousManeuver = expectedTravelTime - durationUntilNextManeuver guard !UIDevice.current.isPluggedIn else { preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond return } if let upcomingStep = routeProgress.currentLegProgress.upComingStep, upcomingStep.maneuverDirection == .straightAhead || upcomingStep.maneuverDirection == .slightLeft || upcomingStep.maneuverDirection == .slightRight { preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond } else if durationUntilNextManeuver > FrameIntervalOptions.durationUntilNextManeuver && durationSincePreviousManeuver > FrameIntervalOptions.durationSincePreviousManeuver { preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond } else { preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond } } // Track position on a frame by frame basis. Used for first location update and when resuming tracking mode func enableFrameByFrameCourseViewTracking(for duration: TimeInterval) { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(disableFrameByFramePositioning), object: nil) perform(#selector(disableFrameByFramePositioning), with: nil, afterDelay: duration) shouldPositionCourseViewFrameByFrame = true } //MARK: - User Tracking @objc fileprivate func disableFrameByFramePositioning() { shouldPositionCourseViewFrameByFrame = false } @objc private func disableUserCourseTracking() { tracksUserCourse = false } @objc public func updateCourseTracking(location: CLLocation?, animated: Bool) { let duration: TimeInterval = animated ? 1 : 0 animatesUserLocation = animated userLocationForCourseTracking = location guard let location = location, CLLocationCoordinate2DIsValid(location.coordinate) else { return } if tracksUserCourse { let point = userAnchorPoint let padding = UIEdgeInsets(top: point.y, left: point.x, bottom: bounds.height - point.y, right: bounds.width - point.x) let newCamera = MGLMapCamera(lookingAtCenter: location.coordinate, fromDistance: altitude, pitch: 45, heading: location.course) let function: CAMediaTimingFunction? = animated ? CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) : nil setCamera(newCamera, withDuration: duration, animationTimingFunction: function, edgePadding: padding, completionHandler: nil) } else { UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear, .beginFromCurrentState], animations: { self.userCourseView?.center = self.convert(location.coordinate, toPointTo: self) }, completion: nil) } if let userCourseView = userCourseView as? UserCourseView { if let customTransformation = userCourseView.update?(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) { customTransformation } else { self.userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) } } else { userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) } } //MARK: - Gesture Recognizers /** Fired when NavigationMapView detects a tap not handled elsewhere by other gesture recognizers. */ @objc func didRecieveTap(sender: UITapGestureRecognizer) { guard let routes = routes, let tapPoint = sender.point else { return } let waypointTest = waypoints(on: routes, closeTo: tapPoint) //are there waypoints near the tapped location? if let selected = waypointTest?.first { //test passes navigationMapDelegate?.navigationMapView?(self, didSelect: selected) return } else if let routes = self.routes(closeTo: tapPoint) { guard let selectedRoute = routes.first else { return } navigationMapDelegate?.navigationMapView?(self, didSelect: selectedRoute) } } @objc func updateCourseView(_ sender: UIGestureRecognizer) { preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond if sender.state == .ended { altitude = self.camera.altitude enableFrameByFrameCourseViewTracking(for: 2) } // Capture altitude for double tap and two finger tap after animation finishes if sender is UITapGestureRecognizer, sender.state == .ended { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: { self.altitude = self.camera.altitude }) } if let pan = sender as? UIPanGestureRecognizer { if sender.state == .ended || sender.state == .cancelled { let velocity = pan.velocity(in: self) let didFling = sqrt(velocity.x * velocity.x + velocity.y * velocity.y) > 100 if didFling { enableFrameByFrameCourseViewTracking(for: 1) } } } if sender.state == .changed { guard let location = userLocationForCourseTracking else { return } userCourseView?.layer.removeAllAnimations() userCourseView?.center = convert(location.coordinate, toPointTo: self) } } // MARK: Feature Addition/Removal /** Adds or updates both the route line and the route line casing */ @objc public func showRoutes(_ routes: [Route], legIndex: Int = 0) { guard let style = style else { return } guard let mainRoute = routes.first else { return } self.routes = routes let polylines = navigationMapDelegate?.navigationMapView?(self, shapeFor: routes) ?? shape(for: routes, legIndex: legIndex) let mainPolylineSimplified = navigationMapDelegate?.navigationMapView?(self, simplifiedShapeFor: mainRoute) ?? shape(forCasingOf: mainRoute, legIndex: legIndex) if let source = style.source(withIdentifier: sourceIdentifier) as? MGLShapeSource, let sourceSimplified = style.source(withIdentifier: sourceCasingIdentifier) as? MGLShapeSource { source.shape = polylines sourceSimplified.shape = mainPolylineSimplified } else { let lineSource = MGLShapeSource(identifier: sourceIdentifier, shape: polylines, options: nil) let lineCasingSource = MGLShapeSource(identifier: sourceCasingIdentifier, shape: mainPolylineSimplified, options: nil) style.addSource(lineSource) style.addSource(lineCasingSource) let line = navigationMapDelegate?.navigationMapView?(self, routeStyleLayerWithIdentifier: routeLayerIdentifier, source: lineSource) ?? routeStyleLayer(identifier: routeLayerIdentifier, source: lineSource) let lineCasing = navigationMapDelegate?.navigationMapView?(self, routeCasingStyleLayerWithIdentifier: routeLayerCasingIdentifier, source: lineCasingSource) ?? routeCasingStyleLayer(identifier: routeLayerCasingIdentifier, source: lineSource) for layer in style.layers.reversed() { if !(layer is MGLSymbolStyleLayer) && layer.identifier != arrowLayerIdentifier && layer.identifier != arrowSymbolLayerIdentifier && layer.identifier != arrowCasingSymbolLayerIdentifier && layer.identifier != arrowLayerStrokeIdentifier && layer.identifier != waypointCircleIdentifier { style.insertLayer(line, below: layer) style.insertLayer(lineCasing, below: line) break } } } } /** Removes route line and route line casing from map */ @objc public func removeRoutes() { guard let style = style else { return } if let line = style.layer(withIdentifier: routeLayerIdentifier) { style.removeLayer(line) } if let lineCasing = style.layer(withIdentifier: routeLayerCasingIdentifier) { style.removeLayer(lineCasing) } if let lineSource = style.source(withIdentifier: sourceIdentifier) { style.removeSource(lineSource) } if let lineCasingSource = style.source(withIdentifier: sourceCasingIdentifier) { style.removeSource(lineCasingSource) } } /** Adds the route waypoints to the map given the current leg index. Previous waypoints for completed legs will be omitted. */ @objc public func showWaypoints(_ route: Route, legIndex: Int = 0) { guard let style = style else { return } let waypoints = Array(route.legs.map { $0.destination }.dropLast()) let source = navigationMapDelegate?.navigationMapView?(self, shapeFor: waypoints, legIndex: legIndex) ?? shape(for: waypoints, legIndex: legIndex) if route.routeOptions.waypoints.count > 2 { //are we on a multipoint route? routes = [route] //update the model if let waypointSource = style.source(withIdentifier: waypointSourceIdentifier) as? MGLShapeSource { waypointSource.shape = source } else { let sourceShape = MGLShapeSource(identifier: waypointSourceIdentifier, shape: source, options: sourceOptions) style.addSource(sourceShape) let circles = navigationMapDelegate?.navigationMapView?(self, waypointStyleLayerWithIdentifier: waypointCircleIdentifier, source: sourceShape) ?? routeWaypointCircleStyleLayer(identifier: waypointCircleIdentifier, source: sourceShape) let symbols = navigationMapDelegate?.navigationMapView?(self, waypointSymbolStyleLayerWithIdentifier: waypointSymbolIdentifier, source: sourceShape) ?? routeWaypointSymbolStyleLayer(identifier: waypointSymbolIdentifier, source: sourceShape) if let arrowLayer = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) { style.insertLayer(circles, below: arrowLayer) } else { style.addLayer(circles) } style.insertLayer(symbols, above: circles) } } if let lastLeg = route.legs.last { removeAnnotations(annotations ?? []) let destination = MGLPointAnnotation() destination.coordinate = lastLeg.destination.coordinate addAnnotation(destination) } } /** Removes all waypoints from the map. */ @objc public func removeWaypoints() { guard let style = style else { return } removeAnnotations(annotations ?? []) if let circleLayer = style.layer(withIdentifier: waypointCircleIdentifier) { style.removeLayer(circleLayer) } if let symbolLayer = style.layer(withIdentifier: waypointSymbolIdentifier) { style.removeLayer(symbolLayer) } if let waypointSource = style.source(withIdentifier: waypointSourceIdentifier) { style.removeSource(waypointSource) } if let circleSource = style.source(withIdentifier: waypointCircleIdentifier) { style.removeSource(circleSource) } if let symbolSource = style.source(withIdentifier: waypointSymbolIdentifier) { style.removeSource(symbolSource) } } /** Shows the step arrow given the current `RouteProgress`. */ @objc public func addArrow(route: Route, legIndex: Int, stepIndex: Int) { guard route.legs.indices.contains(legIndex), route.legs[legIndex].steps.indices.contains(stepIndex) else { return } let step = route.legs[legIndex].steps[stepIndex] let maneuverCoordinate = step.maneuverLocation guard let routeCoordinates = route.coordinates else { return } guard let style = style else { return } guard let triangleImage = Bundle.mapboxNavigation.image(named: "triangle")?.withRenderingMode(.alwaysTemplate) else { return } style.setImage(triangleImage, forName: "triangle-tip-navigation") guard step.maneuverType != .arrive else { return } let minimumZoomLevel: Float = 14.5 let shaftLength = max(min(30 * metersPerPoint(atLatitude: maneuverCoordinate.latitude), 30), 10) let polyline = Polyline(routeCoordinates) let shaftCoordinates = Array(polyline.trimmed(from: maneuverCoordinate, distance: -shaftLength).coordinates.reversed() + polyline.trimmed(from: maneuverCoordinate, distance: shaftLength).coordinates.suffix(from: 1)) if shaftCoordinates.count > 1 { var shaftStrokeCoordinates = shaftCoordinates let shaftStrokePolyline = ArrowStrokePolyline(coordinates: &shaftStrokeCoordinates, count: UInt(shaftStrokeCoordinates.count)) let shaftDirection = shaftStrokeCoordinates[shaftStrokeCoordinates.count - 2].direction(to: shaftStrokeCoordinates.last!) let maneuverArrowStrokePolylines = [shaftStrokePolyline] let shaftPolyline = ArrowFillPolyline(coordinates: shaftCoordinates, count: UInt(shaftCoordinates.count)) let arrowShape = MGLShapeCollection(shapes: [shaftPolyline]) let arrowStrokeShape = MGLShapeCollection(shapes: maneuverArrowStrokePolylines) let arrowSourceStroke = MGLShapeSource(identifier: arrowSourceStrokeIdentifier, shape: arrowStrokeShape, options: sourceOptions) let arrowStroke = MGLLineStyleLayer(identifier: arrowLayerStrokeIdentifier, source: arrowSourceStroke) let arrowSource = MGLShapeSource(identifier: arrowSourceIdentifier, shape: arrowShape, options: sourceOptions) let arrow = MGLLineStyleLayer(identifier: arrowLayerIdentifier, source: arrowSource) if let source = style.source(withIdentifier: arrowSourceIdentifier) as? MGLShapeSource { source.shape = arrowShape } else { arrow.minimumZoomLevel = minimumZoomLevel arrow.lineCap = NSExpression(forConstantValue: "butt") arrow.lineJoin = NSExpression(forConstantValue: "round") arrow.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.70)) arrow.lineColor = NSExpression(forConstantValue: maneuverArrowColor) style.addSource(arrowSource) style.addLayer(arrow) } if let source = style.source(withIdentifier: arrowSourceStrokeIdentifier) as? MGLShapeSource { source.shape = arrowStrokeShape } else { arrowStroke.minimumZoomLevel = arrow.minimumZoomLevel arrowStroke.lineCap = arrow.lineCap arrowStroke.lineJoin = arrow.lineJoin arrowStroke.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.80)) arrowStroke.lineColor = NSExpression(forConstantValue: maneuverArrowStrokeColor) style.addSource(arrowSourceStroke) style.insertLayer(arrowStroke, below: arrow) } // Arrow symbol let point = MGLPointFeature() point.coordinate = shaftStrokeCoordinates.last! let arrowSymbolSource = MGLShapeSource(identifier: arrowSymbolSourceIdentifier, features: [point], options: sourceOptions) if let source = style.source(withIdentifier: arrowSymbolSourceIdentifier) as? MGLShapeSource { source.shape = arrowSymbolSource.shape if let arrowSymbolLayer = style.layer(withIdentifier: arrowSymbolLayerIdentifier) as? MGLSymbolStyleLayer { arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber) } if let arrowSymbolLayerCasing = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) as? MGLSymbolStyleLayer { arrowSymbolLayerCasing.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber) } } else { let arrowSymbolLayer = MGLSymbolStyleLayer(identifier: arrowSymbolLayerIdentifier, source: arrowSymbolSource) arrowSymbolLayer.minimumZoomLevel = minimumZoomLevel arrowSymbolLayer.iconImageName = NSExpression(forConstantValue: "triangle-tip-navigation") arrowSymbolLayer.iconColor = NSExpression(forConstantValue: maneuverArrowColor) arrowSymbolLayer.iconRotationAlignment = NSExpression(forConstantValue: "map") arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber) arrowSymbolLayer.iconScale = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.12)) arrowSymbolLayer.iconAllowsOverlap = NSExpression(forConstantValue: true) let arrowSymbolLayerCasing = MGLSymbolStyleLayer(identifier: arrowCasingSymbolLayerIdentifier, source: arrowSymbolSource) arrowSymbolLayerCasing.minimumZoomLevel = arrowSymbolLayer.minimumZoomLevel arrowSymbolLayerCasing.iconImageName = arrowSymbolLayer.iconImageName arrowSymbolLayerCasing.iconColor = NSExpression(forConstantValue: maneuverArrowStrokeColor) arrowSymbolLayerCasing.iconRotationAlignment = arrowSymbolLayer.iconRotationAlignment arrowSymbolLayerCasing.iconRotation = arrowSymbolLayer.iconRotation arrowSymbolLayerCasing.iconScale = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.14)) arrowSymbolLayerCasing.iconAllowsOverlap = arrowSymbolLayer.iconAllowsOverlap style.addSource(arrowSymbolSource) style.insertLayer(arrowSymbolLayer, above: arrow) style.insertLayer(arrowSymbolLayerCasing, below: arrow) } } } /** Removes the step arrow from the map. */ @objc public func removeArrow() { guard let style = style else { return } if let arrowLayer = style.layer(withIdentifier: arrowLayerIdentifier) { style.removeLayer(arrowLayer) } if let arrowLayerStroke = style.layer(withIdentifier: arrowLayerStrokeIdentifier) { style.removeLayer(arrowLayerStroke) } if let arrowSymbolLayer = style.layer(withIdentifier: arrowSymbolLayerIdentifier) { style.removeLayer(arrowSymbolLayer) } if let arrowCasingSymbolLayer = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) { style.removeLayer(arrowCasingSymbolLayer) } if let arrowSource = style.source(withIdentifier: arrowSourceIdentifier) { style.removeSource(arrowSource) } if let arrowStrokeSource = style.source(withIdentifier: arrowSourceStrokeIdentifier) { style.removeSource(arrowStrokeSource) } if let arrowSymboleSource = style.source(withIdentifier: arrowSymbolSourceIdentifier) { style.removeSource(arrowSymboleSource) } } // MARK: Utility Methods /** Modifies the gesture recognizers to also disable course tracking. */ func makeGestureRecognizersRespectCourseTracking() { for gestureRecognizer in gestureRecognizers ?? [] where gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UIRotationGestureRecognizer { gestureRecognizer.addTarget(self, action: #selector(disableUserCourseTracking)) } } func makeGestureRecognizersUpdateCourseView() { for gestureRecognizer in gestureRecognizers ?? [] { gestureRecognizer.addTarget(self, action: #selector(updateCourseView(_:))) } } //TODO: Change to point-based distance calculation private func waypoints(on routes: [Route], closeTo point: CGPoint) -> [Waypoint]? { let tapCoordinate = convert(point, toCoordinateFrom: self) let multipointRoutes = routes.filter { $0.routeOptions.waypoints.count >= 3} guard multipointRoutes.count > 0 else { return nil } let waypoints = multipointRoutes.flatMap({$0.routeOptions.waypoints}) //lets sort the array in order of closest to tap let closest = waypoints.sorted { (left, right) -> Bool in let leftDistance = left.coordinate.distance(to: tapCoordinate) let rightDistance = right.coordinate.distance(to: tapCoordinate) return leftDistance < rightDistance } //lets filter to see which ones are under threshold let candidates = closest.filter({ let coordinatePoint = self.convert($0.coordinate, toPointTo: self) return coordinatePoint.distance(to: point) < tapGestureDistanceThreshold }) return candidates } private func routes(closeTo point: CGPoint) -> [Route]? { let tapCoordinate = convert(point, toCoordinateFrom: self) //do we have routes? If so, filter routes with at least 2 coordinates. guard let routes = routes?.filter({ $0.coordinates?.count ?? 0 > 1 }) else { return nil } //Sort routes by closest distance to tap gesture. let closest = routes.sorted { (left, right) -> Bool in //existance has been assured through use of filter. let leftLine = Polyline(left.coordinates!) let rightLine = Polyline(right.coordinates!) let leftDistance = leftLine.closestCoordinate(to: tapCoordinate)!.distance let rightDistance = rightLine.closestCoordinate(to: tapCoordinate)!.distance return leftDistance < rightDistance } //filter closest coordinates by which ones are under threshold. let candidates = closest.filter { let closestCoordinate = Polyline($0.coordinates!).closestCoordinate(to: tapCoordinate)!.coordinate let closestPoint = self.convert(closestCoordinate, toPointTo: self) return closestPoint.distance(to: point) < tapGestureDistanceThreshold } return candidates } func shape(for routes: [Route], legIndex: Int?) -> MGLShape? { guard let firstRoute = routes.first else { return nil } guard let congestedRoute = addCongestion(to: firstRoute, legIndex: legIndex) else { return nil } var altRoutes: [MGLPolylineFeature] = [] for route in routes.suffix(from: 1) { let polyline = MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count)) polyline.attributes["isAlternateRoute"] = true altRoutes.append(polyline) } return MGLShapeCollectionFeature(shapes: altRoutes + congestedRoute) } func addCongestion(to route: Route, legIndex: Int?) -> [MGLPolylineFeature]? { guard let coordinates = route.coordinates else { return nil } var linesPerLeg: [[MGLPolylineFeature]] = [] for (index, leg) in route.legs.enumerated() { // If there is no congestion, don't try and add it guard let legCongestion = leg.segmentCongestionLevels else { return [MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count))] } guard legCongestion.count + 1 <= coordinates.count else { return [MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count))] } // The last coord of the preceding step, is shared with the first coord of the next step. // We don't need both. var legCoordinates = Array(leg.steps.compactMap { $0.coordinates?.suffix(from: 1) }.joined()) // We need to add the first coord of the route in. if let firstCoord = leg.steps.first?.coordinates?.first { legCoordinates.insert(firstCoord, at: 0) } // We're trying to create a sequence that conforms to `((segmentStartCoordinate, segmentEndCoordinate), segmentCongestionLevel)`. // This is represents a segment on the route and it's associated congestion level. let segments = zip(legCoordinates, legCoordinates.suffix(from: 1)).map { [$0.0, $0.1] } let congestionSegments = Array(zip(segments, legCongestion)) // Merge adjacent segments with the same congestion level var mergedCongestionSegments = [CongestionSegment]() for seg in congestionSegments { let coordinates = seg.0 let congestionLevel = seg.1 if let last = mergedCongestionSegments.last, last.1 == congestionLevel { mergedCongestionSegments[mergedCongestionSegments.count - 1].0 += coordinates } else { mergedCongestionSegments.append(seg) } } let lines = mergedCongestionSegments.map { (congestionSegment: CongestionSegment) -> MGLPolylineFeature in let polyline = MGLPolylineFeature(coordinates: congestionSegment.0, count: UInt(congestionSegment.0.count)) polyline.attributes[MBCongestionAttribute] = String(describing: congestionSegment.1) if let legIndex = legIndex { polyline.attributes[MBCurrentLegAttribute] = index == legIndex } else { polyline.attributes[MBCurrentLegAttribute] = index == 0 } polyline.attributes["isAlternateRoute"] = false return polyline } linesPerLeg.append(lines) } return Array(linesPerLeg.joined()) } func shape(forCasingOf route: Route, legIndex: Int?) -> MGLShape? { var linesPerLeg: [MGLPolylineFeature] = [] for (index, leg) in route.legs.enumerated() { let legCoordinates = Array(leg.steps.compactMap { $0.coordinates }.joined()) let polyline = MGLPolylineFeature(coordinates: legCoordinates, count: UInt(legCoordinates.count)) if let legIndex = legIndex { polyline.attributes[MBCurrentLegAttribute] = index == legIndex } else { polyline.attributes[MBCurrentLegAttribute] = index == 0 } linesPerLeg.append(polyline) } return MGLShapeCollectionFeature(shapes: linesPerLeg) } func shape(for waypoints: [Waypoint], legIndex: Int) -> MGLShape? { var features = [MGLPointFeature]() for (waypointIndex, waypoint) in waypoints.enumerated() { let feature = MGLPointFeature() feature.coordinate = waypoint.coordinate feature.attributes = [ "waypointCompleted": waypointIndex < legIndex, "name": waypointIndex + 1 ] features.append(feature) } return MGLShapeCollectionFeature(shapes: features) } func routeWaypointCircleStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer { let circles = MGLCircleStyleLayer(identifier: waypointCircleIdentifier, source: source) let opacity = NSExpression(forConditional: NSPredicate(format: "waypointCompleted == true"), trueExpression: NSExpression(forConstantValue: 0.5), falseExpression: NSExpression(forConstantValue: 1)) circles.circleColor = NSExpression(forConstantValue: UIColor(red:0.9, green:0.9, blue:0.9, alpha:1.0)) circles.circleOpacity = opacity circles.circleRadius = NSExpression(forConstantValue: 10) circles.circleStrokeColor = NSExpression(forConstantValue: UIColor.black) circles.circleStrokeWidth = NSExpression(forConstantValue: 1) circles.circleStrokeOpacity = opacity return circles } func routeWaypointSymbolStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer { let symbol = MGLSymbolStyleLayer(identifier: identifier, source: source) symbol.text = NSExpression(format: "CAST(name, 'NSString')") symbol.textOpacity = NSExpression(forConditional: NSPredicate(format: "waypointCompleted == true"), trueExpression: NSExpression(forConstantValue: 0.5), falseExpression: NSExpression(forConstantValue: 1)) symbol.textFontSize = NSExpression(forConstantValue: 10) symbol.textHaloWidth = NSExpression(forConstantValue: 0.25) symbol.textHaloColor = NSExpression(forConstantValue: UIColor.black) return symbol } func routeStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer { let line = MGLLineStyleLayer(identifier: identifier, source: source) line.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel) line.lineOpacity = NSExpression(forConditional: NSPredicate(format: "isAlternateRoute == true"), trueExpression: NSExpression(forConstantValue: 1), falseExpression: NSExpression(forConditional: NSPredicate(format: "isCurrentLeg == true"), trueExpression: NSExpression(forConstantValue: 1), falseExpression: NSExpression(forConstantValue: 0))) line.lineColor = NSExpression(format: "TERNARY(isAlternateRoute == true, %@, MGL_MATCH(congestion, 'low' , %@, 'moderate', %@, 'heavy', %@, 'severe', %@, %@))", routeAlternateColor, trafficLowColor, trafficModerateColor, trafficHeavyColor, trafficSevereColor, trafficUnknownColor) line.lineJoin = NSExpression(forConstantValue: "round") return line } func routeCasingStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer { let lineCasing = MGLLineStyleLayer(identifier: identifier, source: source) // Take the default line width and make it wider for the casing lineCasing.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 1.5)) lineCasing.lineColor = NSExpression(forConditional: NSPredicate(format: "isAlternateRoute == true"), trueExpression: NSExpression(forConstantValue: routeAlternateCasingColor), falseExpression: NSExpression(forConstantValue: routeCasingColor)) lineCasing.lineCap = NSExpression(forConstantValue: "round") lineCasing.lineJoin = NSExpression(forConstantValue: "round") lineCasing.lineOpacity = NSExpression(forConditional: NSPredicate(format: "isAlternateRoute == true"), trueExpression: NSExpression(forConstantValue: 1), falseExpression: NSExpression(forConditional: NSPredicate(format: "isCurrentLeg == true"), trueExpression: NSExpression(forConstantValue: 1), falseExpression: NSExpression(forConstantValue: 0.85))) return lineCasing } /** Attempts to localize road labels into the local language and other labels into the system’s preferred language. When this property is enabled, the style automatically modifies the `text` property of any symbol style layer whose source is the <a href="https://www.mapbox.com/vector-tiles/mapbox-streets-v7/#overview">Mapbox Streets source</a>. On iOS, the user can set the system’s preferred language in Settings, General Settings, Language & Region. Unlike the `MGLStyle.localizeLabels(into:)` method, this method localizes road labels into the local language, regardless of the system’s preferred language, in an effort to match road signage. The turn banner always displays road names and exit destinations in the local language, so you should call this method in the `MGLMapViewDelegate.mapView(_:didFinishLoading:)` method of any delegate of a standalone `NavigationMapView`. The map view embedded in `NavigationViewController` is localized automatically, so you do not need to call this method on the value of `NavigationViewController.mapView`. */ @objc public func localizeLabels() { guard let style = style else { return } let streetsSourceIdentifiers = style.sources.compactMap { $0 as? MGLVectorTileSource }.filter { $0.isMapboxStreets }.map { $0.identifier } for layer in style.layers where layer is MGLSymbolStyleLayer { let layer = layer as! MGLSymbolStyleLayer guard let sourceIdentifier = layer.sourceIdentifier, streetsSourceIdentifiers.contains(sourceIdentifier) else { continue } guard let text = layer.text else { continue } // Road labels should match road signage. let locale = layer.sourceLayerIdentifier == "road_label" ? Locale(identifier: "mul") : nil let localizedText = text.mgl_expressionLocalized(into: locale) if localizedText != text { layer.text = localizedText } } } @objc public func showVoiceInstructionsOnMap(route: Route) { guard let style = style else { return } var features = [MGLPointFeature]() for (legIndex, leg) in route.legs.enumerated() { for (stepIndex, step) in leg.steps.enumerated() { for instruction in step.instructionsSpokenAlongStep! { let feature = MGLPointFeature() feature.coordinate = Polyline(route.legs[legIndex].steps[stepIndex].coordinates!.reversed()).coordinateFromStart(distance: instruction.distanceAlongStep)! feature.attributes = [ "instruction": instruction.text ] features.append(feature) } } } let instructionPointSource = MGLShapeCollectionFeature(shapes: features) if let instructionSource = style.source(withIdentifier: instructionSource) as? MGLShapeSource { instructionSource.shape = instructionPointSource } else { let sourceShape = MGLShapeSource(identifier: instructionSource, shape: instructionPointSource, options: nil) style.addSource(sourceShape) let symbol = MGLSymbolStyleLayer(identifier: instructionLabel, source: sourceShape) symbol.text = NSExpression(format: "instruction") symbol.textFontSize = NSExpression(forConstantValue: 14) symbol.textHaloWidth = NSExpression(forConstantValue: 1) symbol.textHaloColor = NSExpression(forConstantValue: UIColor.white) symbol.textOpacity = NSExpression(forConstantValue: 0.75) symbol.textAnchor = NSExpression(forConstantValue: "bottom-left") symbol.textJustification = NSExpression(forConstantValue: "left") let circle = MGLCircleStyleLayer(identifier: instructionCircle, source: sourceShape) circle.circleRadius = NSExpression(forConstantValue: 5) circle.circleOpacity = NSExpression(forConstantValue: 0.75) circle.circleColor = NSExpression(forConstantValue: UIColor.white) style.addLayer(circle) style.addLayer(symbol) } } /** Sets the camera directly over a series of coordinates. */ @objc public func setOverheadCameraView(from userLocation: CLLocationCoordinate2D, along coordinates: [CLLocationCoordinate2D], for bounds: UIEdgeInsets) { let slicedLine = Polyline(coordinates).sliced(from: userLocation).coordinates let line = MGLPolyline(coordinates: slicedLine, count: UInt(slicedLine.count)) tracksUserCourse = false // If the user has a short distance left on the route, prevent the camera from zooming all the way. // `MGLMapView.setVisibleCoordinateBounds(:edgePadding:animated:)` will go beyond what is convenient for the driver. guard line.overlayBounds.ne.distance(to: line.overlayBounds.sw) > NavigationMapViewMinimumDistanceForOverheadZooming else { let camera = self.camera camera.pitch = 0 camera.heading = 0 camera.centerCoordinate = userLocation camera.altitude = NavigationMapView.defaultAltitude setCamera(camera, animated: true) return } // Sadly, `MGLMapView.setVisibleCoordinateBounds(:edgePadding:animated:)` uses the current pitch and direction of the mapview. Ideally, we'd be able to pass in zero. let camera = self.camera camera.pitch = 0 camera.heading = 0 self.camera = camera setVisibleCoordinateBounds(line.overlayBounds, edgePadding: bounds, animated: true) } } /** The `NavigationMapViewDelegate` provides methods for configuring the NavigationMapView, as well as responding to events triggered by the NavigationMapView. */ @objc(MBNavigationMapViewDelegate) public protocol NavigationMapViewDelegate: class { /** Asks the receiver to return an MGLStyleLayer for routes, given an identifier and source. This method is invoked when the map view loads and any time routes are added. - parameter mapView: The NavigationMapView. - parameter identifier: The style identifier. - parameter source: The Layer source containing the route data that this method would style. - returns: An MGLStyleLayer that the map applies to all routes. */ @objc optional func navigationMapView(_ mapView: NavigationMapView, routeStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? /** Asks the receiver to return an MGLStyleLayer for waypoints, given an identifier and source. This method is invoked when the map view loads and any time waypoints are added. - parameter mapView: The NavigationMapView. - parameter identifier: The style identifier. - parameter source: The Layer source containing the waypoint data that this method would style. - returns: An MGLStyleLayer that the map applies to all waypoints. */ @objc optional func navigationMapView(_ mapView: NavigationMapView, waypointStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? /** Asks the receiver to return an MGLStyleLayer for waypoint symbols, given an identifier and source. This method is invoked when the map view loads and any time waypoints are added. - parameter mapView: The NavigationMapView. - parameter identifier: The style identifier. - parameter source: The Layer source containing the waypoint data that this method would style. - returns: An MGLStyleLayer that the map applies to all waypoint symbols. */ @objc optional func navigationMapView(_ mapView: NavigationMapView, waypointSymbolStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? /** Asks the receiver to return an MGLStyleLayer for route casings, given an identifier and source. This method is invoked when the map view loads and anytime routes are added. - note: Specify a casing to ensure good contrast between the route line and the underlying map layers. - parameter mapView: The NavigationMapView. - parameter identifier: The style identifier. - parameter source: The Layer source containing the route data that this method would style. - returns: An MGLStyleLayer that the map applies to the route. */ @objc optional func navigationMapView(_ mapView: NavigationMapView, routeCasingStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? /** Tells the receiver that the user has selected a route by interacting with the map view. - parameter mapView: The NavigationMapView. - parameter route: The route that was selected. */ @objc(navigationMapView:didSelectRoute:) optional func navigationMapView(_ mapView: NavigationMapView, didSelect route: Route) /** Tells the receiver that a waypoint was selected. - parameter mapView: The NavigationMapView. - parameter waypoint: The waypoint that was selected. */ @objc(navigationMapView:didSelectWaypoint:) optional func navigationMapView(_ mapView: NavigationMapView, didSelect waypoint: Waypoint) /** Asks the receiver to return an MGLShape that describes the geometry of the route. - note: The returned value represents the route in full detail. For example, individual `MGLPolyline` objects in an `MGLShapeCollectionFeature` object can represent traffic congestion segments. For improved performance, you should also implement `navigationMapView(_:simplifiedShapeFor:)`, which defines the overall route as a single feature. - parameter mapView: The NavigationMapView. - parameter routes: The routes that the sender is asking about. The first route will always be rendered as the main route, while all subsequent routes will be rendered as alternate routes. - returns: Optionally, a `MGLShape` that defines the shape of the route, or `nil` to use default behavior. */ @objc(navigationMapView:shapeForRoutes:) optional func navigationMapView(_ mapView: NavigationMapView, shapeFor routes: [Route]) -> MGLShape? /** Asks the receiver to return an MGLShape that describes the geometry of the route at lower zoomlevels. - note: The returned value represents the simplfied route. It is designed to be used with `navigationMapView(_:shapeFor:), and if used without its parent method, can cause unexpected behavior. - parameter mapView: The NavigationMapView. - parameter route: The route that the sender is asking about. - returns: Optionally, a `MGLShape` that defines the shape of the route at lower zoomlevels, or `nil` to use default behavior. */ @objc(navigationMapView:simplifiedShapeForRoute:) optional func navigationMapView(_ mapView: NavigationMapView, simplifiedShapeFor route: Route) -> MGLShape? /** Asks the receiver to return an MGLShape that describes the geometry of the waypoint. - parameter mapView: The NavigationMapView. - parameter waypoints: The waypoints to be displayed on the map. - returns: Optionally, a `MGLShape` that defines the shape of the waypoint, or `nil` to use default behavior. */ @objc(navigationMapView:shapeForWaypoints:legIndex:) optional func navigationMapView(_ mapView: NavigationMapView, shapeFor waypoints: [Waypoint], legIndex: Int) -> MGLShape? /** Asks the receiver to return an MGLAnnotationImage that describes the image used an annotation. - parameter mapView: The MGLMapView. - parameter annotation: The annotation to be styled. - returns: Optionally, a `MGLAnnotationImage` that defines the image used for the annotation. */ @objc(navigationMapView:imageForAnnotation:) optional func navigationMapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? /** Asks the receiver to return an MGLAnnotationView that describes the image used an annotation. - parameter mapView: The MGLMapView. - parameter annotation: The annotation to be styled. - returns: Optionally, a `MGLAnnotationView` that defines the view used for the annotation. */ @objc(navigationMapView:viewForAnnotation:) optional func navigationMapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? /** Asks the receiver to return a CGPoint to serve as the anchor for the user icon. - important: The return value should be returned in the normal UIKit coordinate-space, NOT CoreAnimation's unit coordinate-space. - parameter mapView: The NavigationMapView. - returns: A CGPoint (in regular coordinate-space) that represents the point on-screen where the user location icon should be drawn. */ @objc(navigationMapViewUserAnchorPoint:) optional func navigationMapViewUserAnchorPoint(_ mapView: NavigationMapView) -> CGPoint } // MARK: NavigationMapViewCourseTrackingDelegate /** The `NavigationMapViewCourseTrackingDelegate` provides methods for responding to the `NavigationMapView` starting or stopping course tracking. */ @objc(MBNavigationMapViewCourseTrackingDelegate) public protocol NavigationMapViewCourseTrackingDelegate: class { /** Tells the receiver that the map is now tracking the user course. - seealso: NavigationMapView.tracksUserCourse - parameter mapView: The NavigationMapView. */ @objc(navigationMapViewDidStartTrackingCourse:) optional func navigationMapViewDidStartTrackingCourse(_ mapView: NavigationMapView) /** Tells the receiver that `tracksUserCourse` was set to false, signifying that the map is no longer tracking the user course. - seealso: NavigationMapView.tracksUserCourse - parameter mapView: The NavigationMapView. */ @objc(navigationMapViewDidStopTrackingCourse:) optional func navigationMapViewDidStopTrackingCourse(_ mapView: NavigationMapView) }
49.663043
347
0.666195
23d9fa367142aebc2243447573bb0431156a6dff
1,119
// // OperationManager.swift // P // // Created by Nguyen Dung on 4/26/17. // // import Foundation class OperationManager : Component{ class func instance() -> OperationManager?{ return GameEngine.sharedInstance.getComponent(.Operations) as? OperationManager } let operationQueue: OperationQueue = OperationQueue() override public func ComponentType() -> ComponentType { return .Operations } override public func loadConfig() throws { operationQueue.maxConcurrentOperationCount = OperationQueue.defaultMaxConcurrentOperationCount operationQueue.qualityOfService = .default } override public func stop() { operationQueue.cancelAllOperations() } override public func start() throws { } func enqueue(operation:ConcurrentOperation) { self.operationQueue.addOperation(operation) } func dequeue(operation:ConcurrentOperation) { for op in self.operationQueue.operations { if op == operation { operation.cancel() } } } }
25.431818
102
0.648794
cc8840c39bf485f97a9d85dedbf1c2a8b12b5504
5,080
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import Foundation extension Array where Element: DeltaIdentifiable & Hashable { func matchedIds(with other: Self) -> [DeltaIdentifier] { let ownIds = Set(identifiers()) let otherIds = Set(other.identifiers()) return ownIds.intersection(otherIds).asArray } } infix operator ?= /// RelaxedDeltaIdentifiable protocol is an additional attempt to catch renamings of certain elements, /// where the renameable element is used as `identifier` throughout the logic of the comparison. `RelaxedDeltaIdentifiable` /// serves the purpose to not classify a rename as one addition and one removal. /// Operation is always applied on compared elements that do not posses a matching `identifier` on different versions. protocol RelaxedDeltaIdentifiable: DeltaIdentifiable { static func ?= (lhs: Self, rhs: Self) -> Bool } private struct DeltaSimilarity: Comparable { let similarity: Double let identifier: DeltaIdentifier static func < (lhs: DeltaSimilarity, rhs: DeltaSimilarity) -> Bool { lhs.similarity < rhs.similarity } } extension DeltaIdentifier { func distance(between other: DeltaIdentifier) -> Double { rawValue.distance(between: other.rawValue) } } extension RelaxedDeltaIdentifiable { func mostSimilarWithSelf(in array: [Self], useRawValueDistance: Bool = true, limit: Double = 0.5) -> (similarity: Double?, element: Self)? { let similarity = array.compactMap { deltaIdentifiable -> DeltaSimilarity? in let currentId = deltaIdentifiable.deltaIdentifier let similarity = deltaIdentifier.distance(between: currentId) return similarity < limit ? nil : DeltaSimilarity(similarity: similarity, identifier: currentId) } .max() if let matched = array.first(where: { (self ?= $0) && $0.deltaIdentifier == (useRawValueDistance ? similarity?.identifier : $0.deltaIdentifier) }) { return (similarity?.similarity, matched) } return nil } } /// Endpoint extension to `RelaxedDeltaIdentifiable` extension Endpoint: RelaxedDeltaIdentifiable { static func ?= (lhs: Endpoint, rhs: Endpoint) -> Bool { lhs.identifier(for: Operation.self) == rhs.identifier(for: Operation.self) && lhs.identifier(for: EndpointPath.self) == rhs.identifier(for: EndpointPath.self) } } /// Parameter extension to `RelaxedDeltaIdentifiable` extension Parameter: RelaxedDeltaIdentifiable { static func ?= (lhs: Parameter, rhs: Parameter) -> Bool { true } } extension EnumCase: DeltaIdentifiable { /// DeltaIdentifier of `self` initialized from the `name` public var deltaIdentifier: DeltaIdentifier { .init(name) } } extension EnumCase: RelaxedDeltaIdentifiable { static func ?= (lhs: EnumCase, rhs: EnumCase) -> Bool { true } } extension TypeProperty: DeltaIdentifiable { /// DeltaIdentifier of the property initialized from the `name` public var deltaIdentifier: DeltaIdentifier { .init(name) } } extension TypeProperty: RelaxedDeltaIdentifiable { static func ?= (lhs: TypeProperty, rhs: TypeProperty) -> Bool { true } } extension TypeName: DeltaIdentifiable { /// DeltaIdentifier of the type name initialized from the `name` public var deltaIdentifier: DeltaIdentifier { .init(buildName()) } } extension TypeName: RelaxedDeltaIdentifiable { static func ?= (lhs: TypeName, rhs: TypeName) -> Bool { if lhs == rhs { return true } let primitiveTypeNames = PrimitiveType.allCases.map { $0.typeName } let lhsIsPrimitive = primitiveTypeNames.contains(lhs) let rhsIsPrimitive = primitiveTypeNames.contains(rhs) // if not already equal in the first check, we are dealing with two different primitive types, e.g. Bool and Int if lhsIsPrimitive && rhsIsPrimitive { return false } // If one is primitive and the other one not, returning false, otherwise string similarity of // complex type names to ensure that we are dealing with a rename return lhsIsPrimitive != rhsIsPrimitive ? false : lhs.deltaIdentifier.distance(between: rhs.deltaIdentifier) > 0.5 } } extension TypeInformation: DeltaIdentifiable { public var deltaIdentifier: DeltaIdentifier { if case .reference = self { fatalError("Cannot retrieve the deltaIdentifier of a .reference!") } return typeName.deltaIdentifier } } extension TypeInformation: RelaxedDeltaIdentifiable { static func ?= (lhs: TypeInformation, rhs: TypeInformation) -> Bool { lhs.typeName ?= rhs.typeName } }
35.277778
144
0.674606
568877ec6382985b928cfb7a97b621623817d4e6
1,157
// https://github.com/Quick/Quick import Quick import Nimble import NYDownLoadLib class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.686275
60
0.359551
0a7248328310e23a3f49ca2f1210bc1efd604a5b
11,748
// // DeepChannel.swift // AIToolbox // // Created by Kevin Coble on 6/25/16. // Copyright © 2016 Kevin Coble. All rights reserved. // #if !os(Linux) import Foundation public struct DeepChannelSize { public let numDimensions : Int public var dimensions : [Int] public init(dimensionCount: Int, dimensionValues: [Int]) { numDimensions = dimensionCount dimensions = dimensionValues } public var totalSize: Int { get { var result = 1 for i in 0..<numDimensions { result *= dimensions[i] } return result } } public func asString() ->String { var result = "\(numDimensions)D - [" if (numDimensions > 0) { result += "\(dimensions[0])" } if (numDimensions > 1) { for i in 1..<numDimensions { result += ", \(dimensions[i])" } } result += "]" return result } /// Function to determine if another input of a specified size can be added to an input of this size public func canAddInput(ofSize: DeepChannelSize) -> Bool { // All but the last dimension must match if (abs(numDimensions - ofSize.numDimensions) > 1) { return false } var numMatchingDimensions = numDimensions if (numDimensions < ofSize.numDimensions) { numMatchingDimensions = ofSize.numDimensions } if (numDimensions != ofSize.numDimensions) { numMatchingDimensions -= 1 } let ourDimensionsExtended = dimensions + [1, 1, 1] let theirDimensionsExtended = ofSize.dimensions + [1, 1, 1] for index in 0..<numMatchingDimensions { if ourDimensionsExtended[index] != theirDimensionsExtended[index] { return false } } return true } } /// Class for a single channel of a deep layer /// A deep channel manages a network topology for a single data-stream within a deep layer /// It contains an ordered array of 'network operators' that manipulate the channel data (convolutions, poolings, feedforward nets, etc.) final public class DeepChannel : MLPersistence { public let idString : String // The string ID for the channel. i.e. "red component" public private(set) var sourceChannelIDs : [String] // ID's of the channels that are the source for this channel from the previous layer public private(set) var resultSize : DeepChannelSize // Size of the result of this channel var networkOperators : [DeepNetworkOperator] = [] fileprivate var inputErrorGradient : [Float] = [] public init(identifier: String, sourceChannels: [String]) { idString = identifier sourceChannelIDs = sourceChannels resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0]) } public init?(fromDictionary: [String: AnyObject]) { // Init for nil return (hopefully Swift 3 removes this need) resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0]) // Get the id string type let id = fromDictionary["idString"] as? NSString if id == nil { return nil } idString = id! as String // Get the array of source IDs sourceChannelIDs = [] let sourceIDArray = fromDictionary["sourceChannelIDs"] as? NSArray if (sourceIDArray == nil) { return nil } for item in sourceIDArray! { let source = item as? NSString if source == nil { return nil } sourceChannelIDs.append(source! as String) } // Get the array of network operators let networkOpArray = fromDictionary["networkOperators"] as? NSArray if (networkOpArray == nil) { return nil } for item in networkOpArray! { let element = item as? [String: AnyObject] if (element == nil) { return nil } let netOperator = DeepNetworkOperatorType.getDeepNetworkOperatorFromDict(element!) if (netOperator == nil) { return nil } networkOperators.append(netOperator!) } } /// Function that indicates if a given input ID is used by this channel public func usesInputID(_ id : String) -> Bool { for usedID in sourceChannelIDs { if usedID == id { return true } } return false } /// Function to add a network operator to the channel public func addNetworkOperator(_ newOperator: DeepNetworkOperator) { networkOperators.append(newOperator) } /// Function to get the number of defined operators public var numOperators: Int { get { return networkOperators.count } } /// Function to get a network operator at the specified index public func getNetworkOperator(_ operatorIndex: Int) ->DeepNetworkOperator? { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { return networkOperators[operatorIndex] } return nil } /// Function to replace a network operator at the specified index public func replaceNetworkOperator(_ operatorIndex: Int, newOperator: DeepNetworkOperator) { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { networkOperators[operatorIndex] = newOperator } } /// Functions to remove a network operator from the channel public func removeNetworkOperator(_ operatorIndex: Int) { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { networkOperators.remove(at: operatorIndex) } } // Method to validate inputs exist and match requirements func validateAgainstPreviousLayer(_ prevLayer: DeepNetworkInputSource, layerIndex: Int) ->[String] { var errors : [String] = [] var firstInputSize : DeepChannelSize? // Check each source ID to see if it exists and matches for sourceID in sourceChannelIDs { // Get the input sizing from the previous layer that has our source if let inputSize = prevLayer.getInputDataSize([sourceID]) { // It exists, see if it matches any previous size if let firstSize = firstInputSize { if (!firstSize.canAddInput(ofSize: inputSize)) { errors.append("Layer \(layerIndex), channel \(idString) uses input \(sourceID), which does not match size of other inputs") } } else { // First input firstInputSize = inputSize } } else { // Source channel not found errors.append("Layer \(layerIndex), channel \(idString) uses input \(sourceID), which does not exist") } } // If all the sources exist and are of appropriate size, update the output sizes if let inputSize = prevLayer.getInputDataSize(sourceChannelIDs) { // We have the input, update the output size of the channel updateOutputSize(inputSize) } else { // Source channel not found errors.append("Combining sources of for Layer \(layerIndex), channel \(idString) fails") } return errors } // Method to determine the output size based on the input size and the operation layers func updateOutputSize(_ inputSize : DeepChannelSize) { // Iterate through each operator, adjusting the size var currentSize = inputSize for networkOperator in networkOperators { currentSize = networkOperator.getResultingSize(currentSize) } resultSize = currentSize } func getResultRange() ->(minimum: Float, maximum: Float) { if let lastOperator = networkOperators.last { return lastOperator.getResultRange() } return (minimum: 0.0, maximum: 1.0) } public func initializeParameters() { for networkOperator in networkOperators { networkOperator.initializeParameters() } } // Method to feed values forward through the channel func feedForward(_ inputSource: DeepNetworkInputSource) { // Get the inputs from the previous layer var inputs = inputSource.getValuesForIDs(sourceChannelIDs) var inputSize = inputSource.getInputDataSize(sourceChannelIDs) if (inputSize == nil) { return } // Process each operator for networkOperator in networkOperators { inputs = networkOperator.feedForward(inputs, inputSize: inputSize!) inputSize = networkOperator.getResultSize() } } // Function to clear weight-change accumulations for the start of a batch public func startBatch() { for networkOperator in networkOperators { networkOperator.startBatch() } } func backPropagate(_ gradientSource: DeepNetworkOutputDestination) { // Get the gradients from the previous layer inputErrorGradient = gradientSource.getGradientForSource(idString) // Process the gradient backwards through all the operators for operatorIndex in stride(from: (networkOperators.count - 1), through: 0, by: -1) { inputErrorGradient = networkOperators[operatorIndex].backPropogateGradient(inputErrorGradient) } } public func updateWeights(_ trainingRate : Float, weightDecay: Float) { for networkOperator in networkOperators { networkOperator.updateWeights(trainingRate, weightDecay: weightDecay) } } public func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool { // Have each operator check var result = true for operatorIndex in 0..<networkOperators.count { if (!networkOperators[operatorIndex].gradientCheck(ε: ε, Δ: Δ, network: network)) { result = false } } return result } func getGradient() -> [Float] { return inputErrorGradient } /// Function to get the result of the last operation public func getFinalResult() -> [Float] { if let lastOperator = networkOperators.last { return lastOperator.getResults() } return [] } public func getResultOfItem(_ operatorIndex: Int) ->(values : [Float], size: DeepChannelSize)? { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { let values = networkOperators[operatorIndex].getResults() let size = networkOperators[operatorIndex].getResultSize() return (values : values, size: size) } return nil } public func getPersistenceDictionary() -> [String: AnyObject] { var resultDictionary : [String: AnyObject] = [:] // Set the id string type resultDictionary["idString"] = idString as AnyObject? // Set the array of source IDs resultDictionary["sourceChannelIDs"] = sourceChannelIDs as AnyObject? // Set the array of network operators var operationsArray : [[String: AnyObject]] = [] for networkOperator in networkOperators { operationsArray.append(networkOperator.getOperationPersistenceDictionary()) } resultDictionary["networkOperators"] = operationsArray as AnyObject? return resultDictionary } } #endif
35.926606
147
0.615339
721143f1628f8cfbaf6c68335af5805ed6303a1b
1,704
// // SPIExtensions.swift // TablePos // // Created by Amir Kamali on 6/6/18. // Copyright © 2018 mx51. All rights reserved. // import Foundation import SPIClient_iOS extension SPIMessageSuccessState { var name: String { switch self { case .failed: return "failed" case .success: return "success" case .unknown: return "unknown" default: return "" } } } extension SPIStatus { var name: String { switch self { case .unpaired: return "Unpaired" case .pairedConnecting: return "Connecting" case .pairedConnected: return "Connected" default: return "" } } } extension SPIFlow { var name: String { switch self { case .idle: return "Idle" case .pairing: return "Pairing" case .transaction: return "Transaction" default: return "" } } } extension SPITransactionType { var name: String { switch self { case .getLastTransaction: return "Get Last Transaction" case .purchase: return "Purchase" case .refund: return "Refund" case .settle: return "Settle" case .cashoutOnly: return "Cashout Only" case .MOTO: return "MOTO" case .settleEnquiry: return "Settle Enquiry" case .preAuth: return "Pre Auth" case .accountVerify: return "Account Verify" default: return "" } } }
20.53012
47
0.503521
20e28c76f5b62fc6c2fc24e4d34ca24107a3f1c3
3,011
/* This source file is part of the Swift.org open source project Copyright 2020 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 Swift project authors */ @_implementationOnly import SwiftDriver import TSCBasic import Foundation final class SPMSwiftDriverExecutor: DriverExecutor { private enum Error: Swift.Error, DiagnosticData { case inPlaceExecutionUnsupported var description: String { switch self { case .inPlaceExecutionUnsupported: return "the integrated Swift driver does not support in-place execution" } } } let resolver: ArgsResolver let fileSystem: FileSystem let env: [String: String] init(resolver: ArgsResolver, fileSystem: FileSystem, env: [String: String]) { self.resolver = resolver self.fileSystem = fileSystem self.env = env } func execute(job: Job, forceResponseFiles: Bool, recordedInputModificationDates: [TypedVirtualPath : Date]) throws -> ProcessResult { let arguments: [String] = try resolver.resolveArgumentList(for: job, forceResponseFiles: forceResponseFiles) try job.verifyInputsNotModified(since: recordedInputModificationDates, fileSystem: fileSystem) if job.requiresInPlaceExecution { throw Error.inPlaceExecutionUnsupported } var childEnv = env childEnv.merge(job.extraEnvironment, uniquingKeysWith: { (_, new) in new }) let process = try Process.launchProcess(arguments: arguments, env: childEnv) return try process.waitUntilExit() } func execute(jobs: [Job], delegate: JobExecutionDelegate, numParallelJobs: Int, forceResponseFiles: Bool, recordedInputModificationDates: [TypedVirtualPath : Date]) throws { fatalError("Multi-job build plans should be lifted into the SPM build graph.") } func checkNonZeroExit(args: String..., environment: [String : String]) throws -> String { return try Process.checkNonZeroExit(arguments: args, environment: environment) } func description(of job: Job, forceResponseFiles: Bool) throws -> String { // FIXME: This is duplicated from SwiftDriver, maybe it shouldn't be a protocol requirement. let (args, usedResponseFile) = try resolver.resolveArgumentList(for: job, forceResponseFiles: forceResponseFiles) var result = args.joined(separator: " ") if usedResponseFile { // Print the response file arguments as a comment. result += " # \(job.commandLine.joinedArguments)" } if !job.extraEnvironment.isEmpty { result += " #" for (envVar, val) in job.extraEnvironment { result += " \(envVar)=\(val)" } } return result } }
33.455556
107
0.669545
119cdc8955ab45917eab5d81f978c37b0c1b53f7
401
// // AnyTableViewSectionComponent.swift // TableViewLiaison // // Created by Dylan Shine on 5/29/18. // import UIKit public protocol AnyTableViewSectionComponent: TableViewContent { func perform(_ command: TableViewSectionComponentCommand, liaison: TableViewLiaison, view: UIView, section: Int) func view(for liaison: TableViewLiaison, in section: Int) -> UITableViewHeaderFooterView? }
28.642857
116
0.775561
fb52a8e7af8452b9e948ceab4a6e6435599b2b48
4,861
// // MQTTSessionStream.swift // SwiftMQTT // // Created by Ankit Aggarwal on 12/11/15. // Copyright © 2015 Ankit. All rights reserved. // import Foundation protocol MQTTSessionStreamDelegate: class { func mqttReady(_ ready: Bool, in stream: MQTTSessionStream) func mqttErrorOccurred(in stream: MQTTSessionStream, error: Error?) func mqttReceived(in stream: MQTTSessionStream, _ read: StreamReader) } class MQTTSessionStream: NSObject { private var currentRunLoop: RunLoop? private var currentThread: Thread? private let inputStream: InputStream? private let outputStream: OutputStream? private var sessionQueue: DispatchQueue private weak var delegate: MQTTSessionStreamDelegate? private var inputReady = false private var outputReady = false init(host: String, port: UInt16, ssl: Bool, timeout: TimeInterval, delegate: MQTTSessionStreamDelegate?) { var inputStream: InputStream? var outputStream: OutputStream? Stream.getStreamsToHost(withName: host, port: Int(port), inputStream: &inputStream, outputStream: &outputStream) let queueLabel = host.components(separatedBy: ".").reversed().joined(separator: ".") + ".stream\(port)" self.sessionQueue = DispatchQueue(label: queueLabel, qos: .background, target: nil) self.delegate = delegate self.inputStream = inputStream self.outputStream = outputStream super.init() inputStream?.delegate = self outputStream?.delegate = self sessionQueue.async { [weak self] in guard let `self` = self else { return } self.currentRunLoop = RunLoop.current self.currentThread = Thread.current inputStream?.schedule(in: self.currentRunLoop!, forMode: .default) outputStream?.schedule(in: self.currentRunLoop!, forMode: .default) inputStream?.open() outputStream?.open() if ssl { let securityLevel = StreamSocketSecurityLevel.negotiatedSSL.rawValue inputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey) outputStream?.setProperty(securityLevel, forKey: .socketSecurityLevelKey) } if timeout > 0 { DispatchQueue.global().asyncAfter(deadline: .now() + timeout) { self.connectTimeout() } } var isCancelled = self.currentThread?.isCancelled ?? true while !isCancelled && (self.currentRunLoop != nil && self.currentRunLoop!.run(mode: .default, before: Date.distantFuture)) { isCancelled = self.currentThread?.isCancelled ?? true } } } deinit { delegate = nil guard let currentRunLoop = currentRunLoop else { return } inputStream?.close() inputStream?.remove(from: currentRunLoop, forMode: .default) outputStream?.close() outputStream?.remove(from: currentRunLoop, forMode: .default) } var write: StreamWriter? { if let outputStream = outputStream, outputReady { return outputStream.write } return nil } internal func connectTimeout() { if inputReady == false || outputReady == false { delegate?.mqttReady(false, in: self) } } func stopThread() { currentThread?.cancel() } } extension MQTTSessionStream: StreamDelegate { @objc internal func stream(_ aStream: Stream, handle eventCode: Stream.Event) { switch eventCode { case Stream.Event.openCompleted: let wasReady = inputReady && outputReady if aStream == inputStream { inputReady = true } else if aStream == outputStream { // output almost ready } if !wasReady && inputReady && outputReady { delegate?.mqttReady(true, in: self) } case Stream.Event.hasBytesAvailable: if aStream == inputStream { delegate?.mqttReceived(in: self, inputStream!.read) } case Stream.Event.errorOccurred: delegate?.mqttErrorOccurred(in: self, error: aStream.streamError) case Stream.Event.endEncountered: if aStream.streamError != nil { delegate?.mqttErrorOccurred(in: self, error: aStream.streamError) } case Stream.Event.hasSpaceAvailable: let wasReady = inputReady && outputReady if aStream == outputStream { outputReady = true } if !wasReady && inputReady && outputReady { delegate?.mqttReady(true, in: self) } default: break } } }
32.624161
136
0.610163
f970bb102cfaacfe9bdcf15ab45b96ee601db068
3,361
import KsApi import Library import Prelude import UIKit internal final class UpdatePreviewViewController: WebViewController { private let viewModel: UpdatePreviewViewModelType = UpdatePreviewViewModel() @IBOutlet private weak var publishBarButtonItem: UIBarButtonItem! internal static func configuredWith(draft draft: UpdateDraft) -> UpdatePreviewViewController { let vc = Storyboard.UpdateDraft.instantiate(UpdatePreviewViewController) vc.viewModel.inputs.configureWith(draft: draft) return vc } internal override func viewDidLoad() { super.viewDidLoad() self.publishBarButtonItem |> UIBarButtonItem.lens.targetAction .~ (self, #selector(publishButtonTapped)) self.viewModel.inputs.viewDidLoad() } internal override func bindStyles() { self |> baseControllerStyle() self.publishBarButtonItem |> updatePreviewBarButtonItemStyle self.navigationItem.title = nil } internal override func bindViewModel() { self.viewModel.outputs.webViewLoadRequest .observeForControllerAction() .observeNext { [weak self] in self?.webView.loadRequest($0) } self.viewModel.outputs.showPublishConfirmation .observeForControllerAction() .observeNext { [weak self] in self?.showPublishConfirmation(message: $0) } self.viewModel.outputs.showPublishFailure .observeForControllerAction() .observeNext { [weak self] in self?.showPublishFailure() } self.viewModel.outputs.goToUpdate .observeForControllerAction() .observeNext { [weak self] in self?.goTo(update: $1, forProject: $0) } } internal func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { decisionHandler( self.viewModel.inputs.decidePolicyFor(navigationAction: .init(navigationAction: navigationAction)) ) } @objc private func publishButtonTapped() { self.viewModel.inputs.publishButtonTapped() } private func showPublishConfirmation(message message: String) { let alert = UIAlertController( title: Strings.dashboard_post_update_preview_confirmation_alert_title(), message: message, preferredStyle: .Alert ) alert.addAction( UIAlertAction( title: Strings.dashboard_post_update_preview_confirmation_alert_confirm_button(), style: .Default) { _ in self.viewModel.inputs.publishConfirmationButtonTapped() } ) alert.addAction( UIAlertAction( title: Strings.dashboard_post_update_preview_confirmation_alert_cancel_button(), style: .Cancel) { _ in self.viewModel.inputs.publishCancelButtonTapped() } ) self.presentViewController(alert, animated: true, completion: nil) } private func showPublishFailure() { let alert = UIAlertController .genericError(Strings.dashboard_post_update_preview_confirmation_alert_error_something_wrong()) self.presentViewController(alert, animated: true, completion: nil) } private func goTo(update update: Update, forProject project: Project) { let vc = UpdateViewController.configuredWith(project: project, update: update) self.navigationController?.setViewControllers([vc], animated: true) } }
34.295918
110
0.72895
18435deb53c29145508801d7afc2130caa703488
1,721
// // SectionedListContaining.swift // Daily // // Created by Isa Aliev on 02.02.2021. // import ReactiveKit import Bond #if canImport(MVVMKit_Base) import MVVMKit_Base #endif public typealias ReactiveSectionedArray = MutableObservableArray2D<Section.SectionMeta, CollectionItemViewModel> public typealias SectionedArrayChangeset = TreeChangeset<Array2D<Section.SectionMeta, CollectionItemViewModel>> public struct Section { public struct SectionMeta { public let header: CollectionItemViewModel? public let footer: CollectionItemViewModel? public init( header: CollectionItemViewModel? = nil, footer: CollectionItemViewModel? = nil ) { self.header = header self.footer = footer } } public let meta: SectionMeta public let metadata: CollectionItemViewModel? public var items = [CollectionItemViewModel]() public init( metadata: CollectionItemViewModel, items: [CollectionItemViewModel] = [CollectionItemViewModel](), footer: CollectionItemViewModel? = nil ) { self.metadata = metadata self.items = items self.meta = .init(header: metadata, footer: nil) } public init(_ meta: SectionMeta, items: [CollectionItemViewModel] = [CollectionItemViewModel]()) { self.meta = meta self.items = items self.metadata = meta.header } } public protocol SectionedListContaining { var items: ReactiveSectionedArray { get } } public extension SectionedListContaining { func setSections(_ sections: [Section]) { items.value = SectionedArrayChangeset( collection: .init(sectionsWithItems: sections.map({ ($0.meta, $0.items) })), diff: OrderedCollectionDiff() ) } }
26.890625
112
0.712958
eb6954d3ebbcbe524bcf1be6986cc3cdf8a2dea7
3,184
// // ChooseViewController.swift // TikTok // // Created by IJ . on 2019/12/27. // Copyright © 2019 김준성. All rights reserved. // import UIKit import XLPagerTabStrip class ChooseViewController: ButtonBarPagerTabStripViewController { override func viewDidLoad() { self.settings.style.buttonBarItemBackgroundColor = UIColor.white self.settings.style.buttonBarItemTitleColor = UIColor.init(red: 213.0/255.0, green: 213.0/255.0, blue: 213.0/255.0, alpha: 1) //선택된거 검은색 없음 self.settings.style.buttonBarBackgroundColor = UIColor.white // UIColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1) self.settings.style.selectedBarBackgroundColor = UIColor.init(red: 19.0/255.0, green: 139.0/255.0, blue: 255.0/255.0, alpha: 1) self.settings.style.selectedBarHeight = 2.0 changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in guard changeCurrentIndex == true else { return } oldCell?.label.textColor = UIColor.init(red: 213.0/255.0, green: 213.0/255.0, blue: 213.0/255.0, alpha: 1) newCell?.label.textColor = UIColor.black } super.viewDidLoad() } override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { let child1 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "PopularCityVC") as! PopularCityTableViewController child1.childNumber = "인기 여행지" let child2 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "CityChooseTableVC") as! CityChooseTableViewController child2.childNumber = "유럽" let child3 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "CityChooseTableVC") as! CityChooseTableViewController child3.childNumber = "동남아시아" let child4 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "CityChooseTableVC") as! CityChooseTableViewController child4.childNumber = "동아시아" let child5 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "CityChooseTableVC") as! CityChooseTableViewController child5.childNumber = "아메리카" let child6 = UIStoryboard.init(name: "InjunStoryboard", bundle: nil).instantiateViewController(withIdentifier: "CityChooseTableVC") as! CityChooseTableViewController child6.childNumber = "오세아니아" return [child1, child2, child3, child4, child5, child6] } @IBAction func touchUpBackButton(_ sender: Any) { self.navigationController?.popViewController(animated: true) } }
38.829268
182
0.657349
e2ff9e09429a6fe08935f189bd79e13367092d6a
448
import XCTest @testable import NavigatableCollection final class NavigatableCollectionTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(NavigatableCollection().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
28
87
0.678571
095902e701380099c9d3839c78df27183dab08cd
342
// // LinkTableViewCell.swift // Smashtag // // Created by Raphael on 3/23/16. // Copyright © 2016 Skyleaf Design. All rights reserved. // import UIKit class LinkTableViewCell: UITableViewCell { var url: NSURL? { didSet { label.text = url?.absoluteString } } @IBOutlet weak var label: UILabel! }
18
57
0.625731
225e1de86a06da83cb3e5078fd62ab893f1975c5
515
// // ViewController.swift // MTLocalized // // Created by Mehmet Tarhan on 08/02/2020. // Copyright (c) 2020 Mehmet Tarhan. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.6
80
0.673786
0e2cae7dbd3162ad5eaf8ce0470c9c6849ecf2d7
1,767
// HypertextApplicationLanguage Link+CustomDebugStringConvertible.swift // // Copyright © 2015, 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. // //------------------------------------------------------------------------------ extension Link: CustomDebugStringConvertible { public var debugDescription: String { var description = "rel=\(rel) href=\(href)" if let name = name { description += " \(name)" } if let title = title { description += " \(title)" } if let hreflang = hreflang { description += " \(hreflang)" } if let profile = profile { description += " \(profile)" } return description } }
39.266667
80
0.685908
01259f36c3cc88cc7feb8cf1154f93d91a16c695
5,383
/// /// StorageContainerEqualTests.swift /// /// Copyright 2017 Tony Stone /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Created by Tony Stone on 11/8/17. /// import XCTest @testable import StickyEncoding class StorageContainerEqualTests: XCTestCase { func testEqualWithNullStorageContainer() { let input = NullStorageContainer.null let expected = NullStorageContainer.null XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithNullStorageContainer() { let input = NullStorageContainer.null let expected = UnkeyedStorageContainer() XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } func testEqualWithKeyedStorageContainer() { let input = KeyedStorageContainer() let expected = KeyedStorageContainer() XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithKeyedStorageContainer() { let input = KeyedStorageContainer() let expected = UnkeyedStorageContainer() XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } func testEqualWithUnkeyedStorageContainer() { let input = UnkeyedStorageContainer() let expected = UnkeyedStorageContainer() XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithUnkeyedStorageContainer() { let input = UnkeyedStorageContainer() let expected = KeyedStorageContainer() XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } func testEqualWithSingleValueContainer() { let input = SingleValueContainer("Test String") let expected = SingleValueContainer("Test String") XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithSingleValueContainer() { let input = SingleValueContainer("Test String") let expected = SingleValueContainer(32) XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } func testEqualWithUnkeyedStorageContainerAndNestedSingleValueeContainer() { let input: UnkeyedStorageContainer = { let container = UnkeyedStorageContainer() container.push(SingleValueContainer("Test String")) return container }() let expected: UnkeyedStorageContainer = { let container = UnkeyedStorageContainer() container.push(SingleValueContainer("Test String")) return container }() XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithUnkeyedStorageContainerAndNestedSingleValueContainer() { let input: UnkeyedStorageContainer = { let container = UnkeyedStorageContainer() container.push(SingleValueContainer("Test String")) return container }() let expected: UnkeyedStorageContainer = { let container = UnkeyedStorageContainer() container.push(SingleValueContainer("Incorrect Test String")) return container }() XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } func testEqualWithKeyedStorageContainerAndNestedSingleValueeContainer() { let input: KeyedStorageContainer = { let keyed = KeyedStorageContainer() let unkeyed = UnkeyedStorageContainer() unkeyed.push(SingleValueContainer("Test String")) keyed["key 1"] = unkeyed return keyed }() let expected: KeyedStorageContainer = { let keyed = KeyedStorageContainer() let unkeyed = UnkeyedStorageContainer() unkeyed.push(SingleValueContainer("Test String")) keyed["key 1"] = unkeyed return keyed }() XCTAssert(input.equal(expected), "\(expected) does not equal \(input)") } func testNotEqualWithKeyedStorageContainerAndNestedSingleValueContainer() { let input: KeyedStorageContainer = { let keyed = KeyedStorageContainer() let unkeyed = UnkeyedStorageContainer() unkeyed.push(SingleValueContainer("Test String")) keyed["key 1"] = unkeyed return keyed }() let expected: KeyedStorageContainer = { let keyed = KeyedStorageContainer() let unkeyed = UnkeyedStorageContainer() unkeyed.push(SingleValueContainer("Incorrect Test String")) keyed["key 1"] = unkeyed return keyed }() XCTAssert(!input.equal(expected), "\(expected) equals \(input) but should not.") } }
35.886667
88
0.655397
f8595cc34d1941a3966b849012ae7aaf2a557b34
1,766
// // Created by taktem on 2022/04/14. // Copyright © 2022 taktem All rights reserved. // import UIKit // TODO: - レイアウト仮組みしているのでメニューUIを確定させること final class ChatItemInteractionMenuContainerView: UIView { final class ButtonView: UIView { private let onTapHandler: (() -> Void) init(name: String, onTap: @escaping () -> Void) { onTapHandler = onTap super.init(frame: .zero) backgroundColor = UIColor.green let button = UIButton(frame: .zero) button.setTitle(name, for: .normal) button.addTarget(self, action: #selector(Self.onTap), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.widthAnchor.constraint(equalToConstant: 80).isActive = true button.heightAnchor.constraint(equalToConstant: 44).isActive = true addSubview(button) button.snap(to: self) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func onTap() { onTapHandler() } } struct Item { let name: String let executer: (() -> Void) } init(items: [Item]) { super.init(frame: .zero) let stackView = UIStackView(frame: .zero) stackView.axis = .horizontal addSubview(stackView) stackView.snap(to: self) items.forEach { stackView.addArrangedSubview(ButtonView(name: $0.name, onTap: $0.executer)) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
28.031746
87
0.563986
202c9c80bfdeba17021cc57aec435a1bdc67369a
3,233
// // mappingTests.swift // ws // // Created by Max Konovalov on 04/11/2016. // Copyright © 2016 s4cha. All rights reserved. // import Arrow import then @testable import ws import XCTest struct Article { var id: Int = 0 var name: String = "" } extension Article: ArrowParsable { mutating func deserialize(_ json: JSON) { id <-- json["id"] name <-- json["name"] } } enum FooBar: String { case foo = "Foo" case bar = "Bar" } extension FooBar: ArrowInitializable {} /** TEST JSON: { "count": 2, "articles": [ { "id": 1, "name": "Foo" }, { "id": 2, "name": "Bar" } ], "error": { "code": 0, "message": "No error" } } */ class MappingTests: XCTestCase { var ws: WS! private let path = "581c82711000003c24ea7806" override func setUp() { super.setUp() ws = WS("http://www.mocky.io/v2/") ws.logLevels = .debug ws.errorHandler = { json in if let errorPayload = json["error"] { var code = 0 var message = "" code <-- errorPayload["code"] message <-- errorPayload["message"] if code != 0 { return NSError(domain: "WS", code: code, userInfo: [NSLocalizedDescriptionKey: message]) } } return nil } } func testMapping() { let e = expectation(description: "") getArticles() .then({ articles in XCTAssertEqual(articles.count, 2) e.fulfill() }) .onError({ error in print("ERROR: \(error)") XCTFail("Mapping fails") e.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func testTypeMapping() { let e = expectation(description: "") getArticlesCount() .then({ count in XCTAssertEqual(count, 2) e.fulfill() }) .onError({ error in print("ERROR: \(error)") XCTFail("Type Mapping Fails") e.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func testRawTypeMapping() { let e = expectation(description: "") getFooBar() .then({ foobar in XCTAssertEqual(foobar, FooBar.foo) e.fulfill() }) .onError({ error in print("ERROR: \(error)") XCTFail("Raw type mapping fails") e.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func getArticles() -> Promise<[Article]> { return ws.get(path, keypath: "articles") } func getArticlesCount() -> Promise<Int> { return ws.get(path, keypath: "count") } func getFooBar() -> Promise<FooBar> { return ws.get(path, keypath: "articles.0.name") } }
22.296552
108
0.4618
1ae40a4d15e637b65c4a60501e5d68e4ebba00b9
3,625
// // YelpClient.swift // Yelp // // Created by Timothy Lee on 9/19/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // import UIKit import AFNetworking import BDBOAuth1Manager // You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA" let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ" let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV" let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y" enum YelpSortMode: Int { case bestMatched = 0, distance, highestRated } class YelpClient: BDBOAuth1RequestOperationManager { var accessToken: String! var accessSecret: String! //MARK: Shared Instance static let sharedInstance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) { self.accessToken = accessToken self.accessSecret = accessSecret let baseUrl = URL(string: "https://api.yelp.com/v2/") super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret); let token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil) self.requestSerializer.saveAccessToken(token) } func searchWithTerm(_ term: String, completion: @escaping ([Business]?, Error?) -> Void) -> AFHTTPRequestOperation { return searchWithTerm(term, sort: nil, distance: nil, categories: nil, deals: nil, offSet: nil, completion: completion) } func searchWithTerm(_ term: String, sort: YelpSortMode?, distance: Int?, categories: [String]?, deals: Bool?, offSet: Int?, completion: @escaping ([Business]?, Error?) -> Void) -> AFHTTPRequestOperation { // For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api // Default the location to San Francisco var parameters: [String : AnyObject] = ["term": term as AnyObject, "ll": "37.785771,-122.406165" as AnyObject] if sort != nil { parameters["sort"] = sort!.rawValue as AnyObject? } if categories != nil && categories!.count > 0 { parameters["category_filter"] = (categories!).joined(separator: ",") as AnyObject? } if deals != nil { parameters["deals_filter"] = deals! as AnyObject? } if distance != nil { parameters["radius_filter"] = distance! as AnyObject? } print(parameters) return self.get("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation, response: Any) -> Void in if let response = response as? [String: Any]{ let dictionaries = response["businesses"] as? [NSDictionary] if dictionaries != nil { completion(Business.businesses(array: dictionaries!), nil) } } }, failure: { (operation: AFHTTPRequestOperation?, error: Error) -> Void in completion(nil, error) print("eas not able to search \(error)") })! } }
40.277778
208
0.60331
7a3191b3a16a2278654ee6b0e755629c30bb67ed
7,669
import Component import ComposableArchitecture import Introspect import Model import SwiftUI import Styleguide public struct MediaScreen: View { private let store: Store<MediaState, MediaAction> @ObservedObject private var viewStore: ViewStore<ViewState, MediaAction> @SearchController private var searchController: UISearchController public init(store: Store<MediaState, MediaAction>) { self.store = store let viewStore = ViewStore(store.scope(state: ViewState.init(state:))) self.viewStore = viewStore self._searchController = .init( searchBarPlaceHolder: L10n.MediaScreen.SearchBar.placeholder, searchTextDidChangeTo: { text in withAnimation(.easeInOut) { viewStore.send(.searchTextDidChange(to: text)) } }, isEditingDidChangeTo: { isEditing in withAnimation(.easeInOut) { viewStore.send(.isEditingDidChange(to: isEditing)) } } ) } struct ViewState: Equatable { var isSearchTextEditing: Bool var isMoreActive: Bool init(state: MediaState) { isSearchTextEditing = state.isSearchTextEditing isMoreActive = state.moreActiveType != nil } } public var body: some View { NavigationView { ZStack { AssetColor.Background.primary.color.ignoresSafeArea() .zIndex(0) MediaListView(store: store) .zIndex(1) Color.black.opacity(0.4) .ignoresSafeArea() .opacity(viewStore.isSearchTextEditing ? 1 : .zero) .zIndex(2) IfLetStore( store.scope( state: \.searchedFeedContents, action: MediaAction.init(action:) ), then: SearchResultScreen.init(store:) ) .zIndex(3) } .background( NavigationLink( destination: IfLetStore( store.scope( state: MediaDetailScreen.ViewState.init(state:), action: MediaAction.init(action:) ), then: MediaDetailScreen.init(store:) ), isActive: viewStore.binding( get: \.isMoreActive, send: { _ in .moreDismissed } ) ) { EmptyView() } ) .navigationTitle(L10n.MediaScreen.title) .navigationBarItems( trailing: Button(action: { viewStore.send(.showSetting) }, label: { AssetImage.iconSetting.image .renderingMode(.template) .foregroundColor(AssetColor.Base.primary.color) }) ) .introspectViewController { viewController in guard viewController.navigationItem.searchController == nil else { return } viewController.navigationItem.searchController = searchController viewController.navigationItem.hidesSearchBarWhenScrolling = false // To keep the navigation bar expanded viewController.navigationController?.navigationBar.sizeToFit() } } } private var separator: some View { Separator() .padding() } } private extension MediaAction { init(action: MediaDetailScreen.ViewAction) { switch action { case .tap(let content): self = .tap(content) case .tapFavorite(let isFavorited, let contentId): self = .tapFavorite(isFavorited: isFavorited, id: contentId) case .tapPlay(let content): self = .tapPlay(content) } } init(action: SearchResultScreen.ViewAction) { switch action { case .tap(let content): self = .tap(content) case .tapFavorite(let isFavorited, let contentId): self = .tapFavorite(isFavorited: isFavorited, id: contentId) case .tapPlay(let content): self = .tapPlay(content) } } } private extension MediaDetailScreen.ViewState { init?(state: MediaState) { guard let moreActiveType = state.moreActiveType else { return nil } switch moreActiveType { case .blog: title = L10n.MediaScreen.Section.Blog.title contents = state.blogs case .video: title = L10n.MediaScreen.Section.Video.title contents = state.videos case .podcast: title = L10n.MediaScreen.Section.Podcast.title contents = state.podcasts } } } #if DEBUG public struct MediaScreen_Previews: PreviewProvider { public static var previews: some View { ForEach(ColorScheme.allCases, id: \.self) { colorScheme in Group { MediaScreen( store: .init( initialState: .init( feedContents: [ .blogMock(), .blogMock(), .blogMock(), .videoMock(), .videoMock(), .videoMock(), .podcastMock(), .podcastMock(), .podcastMock() ] ), reducer: .empty, environment: {} ) ) .previewDevice(.init(rawValue: "iPhone 12")) .environment(\.colorScheme, colorScheme) MediaScreen( store: .init( initialState: .init( feedContents: [ .blogMock( title: .init(enTitle: "", jaTitle: "ForSearch") ), .blogMock( title: .init(enTitle: "", jaTitle: "ForSearch") ), .blogMock( title: .init(enTitle: "", jaTitle: "ForSearch") ), .videoMock( title: .init(enTitle: "", jaTitle: "ForSearch") ), .videoMock( title: .init(enTitle: "", jaTitle: "ForSearch") ), .videoMock(), .podcastMock(), .podcastMock(), .podcastMock() ], searchText: "Search", isSearchTextEditing: true ), reducer: .empty, environment: {} ) ) .previewDevice(.init(rawValue: "iPhone 12")) .environment(\.colorScheme, colorScheme) } } } } #endif
35.836449
91
0.454036
21c107d6cb08b3c554b6f40c3a366d07d12f0f4b
867
// // CategoriesCell.swift // Quickscop // // Created by GnolDrol on 11/3/21. // import UIKit class CategoriesCell: UICollectionViewCell { @IBOutlet weak var imgv_bottomRight: UIImageView! @IBOutlet weak var imgv_bottomLeft: UIImageView! @IBOutlet weak var imgv_Top: UIImageView! @IBOutlet weak var btn_star: UIButton! @IBOutlet weak var top_title: UILabel! static let identifier = "CategoriesCell" static let cellHeight = 186.0 override func awakeFromNib() { super.awakeFromNib() // Initialization code imgv_Top.layer.masksToBounds = true imgv_Top.layer.cornerRadius = 3 imgv_bottomLeft.layer.masksToBounds = true imgv_bottomLeft.layer.cornerRadius = 3 imgv_bottomRight.layer.masksToBounds = true imgv_bottomRight.layer.cornerRadius = 3 } }
26.272727
53
0.685121
2f5c4c6c18f10ee03f99230a9b43b25ed3ff760e
2,891
// // Copyright (C) 2019 Twilio, 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 TwilioVideo protocol VideoStoreWriting: LaunchStore, WindowSceneObserving { } class VideoStore: VideoStoreWriting { static let shared: VideoStoreWriting = VideoStore( appSettingsStore: AppSettingsStore.shared, environmentVariableStore: EnvironmentVariableStore(), notificationCenter: NotificationCenter.default ) private let appSettingsStore: AppSettingsStoreWriting private let environmentVariableStore: EnvironmentVariableStoreWriting private let notificationCenter: NotificationCenterProtocol init( appSettingsStore: AppSettingsStoreWriting, environmentVariableStore: EnvironmentVariableStoreWriting, notificationCenter: NotificationCenterProtocol ) { self.appSettingsStore = appSettingsStore self.environmentVariableStore = environmentVariableStore self.notificationCenter = notificationCenter } func start() { configure() notificationCenter.addObserver(forName: .appSettingDidChange, object: nil, queue: nil) { [weak self] _ in self?.configure() } } @available(iOS 13, *) func interfaceOrientationDidChange(windowScene: UIWindowScene) { UserInterfaceTracker.sceneInterfaceOrientationDidChange(windowScene) } private func configure() { TwilioVideoSDK.setLogLevel(.init(sdkLogLevel: appSettingsStore.coreSDKLogLevel), module: .core) TwilioVideoSDK.setLogLevel(.init(sdkLogLevel: appSettingsStore.platformSDKLogLevel), module: .platform) TwilioVideoSDK.setLogLevel(.init(sdkLogLevel: appSettingsStore.signalingSDKLogLevel), module: .signaling) TwilioVideoSDK.setLogLevel(.init(sdkLogLevel: appSettingsStore.webRTCSDKLogLevel), module: .webRTC) environmentVariableStore.twilioEnvironment = appSettingsStore.environment } } private extension TwilioVideoSDK.LogLevel { init(sdkLogLevel: SDKLogLevel) { switch sdkLogLevel { case .off: self = .off case .fatal: self = .fatal case .error: self = .error case .warning: self = .warning case .info: self = .info case .debug: self = .debug case .trace: self = .trace case .all: self = .all } } }
37.545455
113
0.711173
d68e3646df7146a5352fae340ba90cc093d0b628
12,144
// // DelegationTests.swift // // // Created by Max Obermeier on 17.05.21. // @testable import Apodini import ApodiniREST import XCTApodini import XCTVapor import XCTest final class DelegationTests: ApodiniTests { class TestObservable: Apodini.ObservableObject { @Apodini.Published var date: Date init() { self.date = Date() } } struct TestDelegate { @Parameter var message: String @Apodini.Environment(\.connection) var connection @ObservedObject var observable: TestObservable } struct TestHandler: Handler { let testD: Delegate<TestDelegate> @Parameter var name: String @Parameter var sendDate = false @Throws(.forbidden) var badUserNameError: ApodiniError @Apodini.Environment(\.connection) var connection init(_ observable: TestObservable? = nil) { self.testD = Delegate(TestDelegate(observable: observable ?? TestObservable())) } func handle() throws -> Apodini.Response<String> { guard name == "Max" else { switch connection.state { case .open: return .send("Invalid Login") case .end: return .final("Invalid Login") } } let delegate = try testD() switch delegate.connection.state { case .open: return .send(sendDate ? delegate.observable.date.timeIntervalSince1970.description : delegate.message) case .end: return .final(sendDate ? delegate.observable.date.timeIntervalSince1970.description : delegate.message) } } } func testValidDelegateCall() throws { var testHandler = TestHandler().inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Max", false, "Hello, World!") let context = endpoint.createConnectionContext(for: exporter) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next()), content: "Hello, World!", connectionEffect: .close ) } func testMissingParameterDelegateCall() throws { var testHandler = TestHandler().inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Max") let context = endpoint.createConnectionContext(for: exporter) XCTAssertThrowsError(try context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next()).wait()) } func testLazynessDelegateCall() throws { var testHandler = TestHandler().inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Not Max") let context = endpoint.createConnectionContext(for: exporter) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next()), content: "Invalid Login", connectionEffect: .close ) } func testConnectionAwareDelegate() throws { var testHandler = TestHandler().inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Max", false, "Hello, Paul!", "Max", false, "Hello, World!") let context = endpoint.createConnectionContext(for: exporter) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next(), final: false), content: "Hello, Paul!", connectionEffect: .open ) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next()), content: "Hello, World!", connectionEffect: .close ) } func testDelayedActivation() throws { var testHandler = TestHandler().inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Not Max", false, "Max", true, "") let context = endpoint.createConnectionContext(for: exporter) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next(), final: false), content: "Invalid Login", connectionEffect: .open ) let before = Date().timeIntervalSince1970 // this call is first to invoke delegate let response = try context.handle(request: "Example Request", eventLoop: app.eventLoopGroup.next()).wait() let observableInitializationTime = TimeInterval(response.content!)! XCTAssertGreaterThan(observableInitializationTime, before) } class TestListener<H: Handler>: ObservedListener where H.Response.Content: StringProtocol { var eventLoop: EventLoop var context: ConnectionContext<String, H> var result: EventLoopFuture<TimeInterval>? init(eventLoop: EventLoop, context: ConnectionContext<String, H>) { self.eventLoop = eventLoop self.context = context } func onObservedDidChange(_ observedObject: AnyObservedObject, _ event: TriggerEvent) { result = context.handle(eventLoop: eventLoop, observedObject: observedObject, event: event).map { response in TimeInterval(response.content!)! } } } func testObservability() throws { let eventLoop = app.eventLoopGroup.next() let observable = TestObservable() var testHandler = TestHandler(observable).inject(app: app) activate(&testHandler) let endpoint = testHandler.mockEndpoint(app: app) let exporter = MockExporter<String>(queued: "Not Max", false, "Max", true, "", "Max", true, "", "Not Max", false) let context = endpoint.createConnectionContext(for: exporter) let listener = TestListener<TestHandler>(eventLoop: eventLoop, context: context) context.register(listener: listener) try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: eventLoop, final: false), content: "Invalid Login", connectionEffect: .open ) // should not fire observable.date = Date() // this call is first to invoke delegate _ = try context.handle(request: "Example Request", eventLoop: eventLoop, final: false).wait() // should trigger third evaluation let date = Date() observable.date = date let result = try listener.result?.wait() XCTAssertNotNil(result) XCTAssertEqual(result!, date.timeIntervalSince1970) // final evaluation try XCTCheckResponse( context.handle(request: "Example Request", eventLoop: eventLoop), content: "Invalid Login", connectionEffect: .close ) } struct BindingTestDelegate { @Binding var number: Int } func testBindingInjection() throws { var bindingD = Delegate(BindingTestDelegate(number: Binding.constant(0))) bindingD.activate() let connection = Connection(request: MockRequest.createRequest(running: app.eventLoopGroup.next())) bindingD.inject(connection, for: \Apodini.Application.connection) bindingD.set(\.$number, to: 1) let prepared = try bindingD() XCTAssertEqual(prepared.number, 1) } struct EnvKey: EnvironmentAccessible { var name: String } struct NestedEnvironmentDelegate { @EnvironmentObject var number: Int @Apodini.Environment(\EnvKey.name) var string: String } struct DelegatingEnvironmentDelegate { var nestedD = Delegate(NestedEnvironmentDelegate()) func evaluate() throws -> String { let nested = try nestedD() return "\(nested.string):\(nested.number)" } } func testEnvironmentInjection() throws { var envD = Delegate(DelegatingEnvironmentDelegate()) inject(app: app, to: &envD) envD.activate() let connection = Connection(request: MockRequest.createRequest(running: app.eventLoopGroup.next())) envD.inject(connection, for: \Apodini.Application.connection) envD .environment(\EnvKey.name, "Max") .environmentObject(1) let prepared = try envD() XCTAssertEqual(try prepared.evaluate(), "Max:1") } func testSetters() throws { struct BindingObservedObjectDelegate { @ObservedObject var observable = TestObservable() @Binding var binding: Int init() { _binding = .constant(0) } } var envD = Delegate(BindingObservedObjectDelegate()) inject(app: app, to: &envD) envD.activate() let connection = Connection(request: MockRequest.createRequest(running: app.eventLoopGroup.next())) envD.inject(connection, for: \Apodini.Application.connection) let afterInitializationBeforeInjection = Date() envD .set(\.$binding, to: 1) .setObservable(\.$observable, to: TestObservable()) let prepared = try envD() XCTAssertEqual(prepared.binding, 1) XCTAssertGreaterThan(prepared.observable.date, afterInitializationBeforeInjection) } func testOptionalOptionality() throws { struct OptionalDelegate { @Parameter var name: String } struct RequiredDelegatingDelegate { let delegate = Delegate(OptionalDelegate()) } struct SomeHandler: Handler { let delegate = Delegate(RequiredDelegatingDelegate(), .required) func handle() throws -> some ResponseTransformable { try delegate().delegate().name } } let parameter = try XCTUnwrap(SomeHandler().buildParametersModel().first as? EndpointParameter<String>) XCTAssertEqual(ObjectIdentifier(parameter.propertyType), ObjectIdentifier(String.self)) XCTAssertEqual(parameter.necessity, .required) XCTAssertEqual(parameter.nilIsValidValue, false) XCTAssertEqual(parameter.hasDefaultValue, false) XCTAssertEqual(parameter.option(for: .optionality), .optional) } func testRequiredOptionality() throws { struct RequiredDelegate { @Parameter var name: String } struct RequiredDelegatingDelegate { var delegate = Delegate(RequiredDelegate(), .required) } struct SomeHandler: Handler { let delegate = Delegate(RequiredDelegatingDelegate(), .required) func handle() throws -> some ResponseTransformable { try delegate().delegate().name } } let parameter = try XCTUnwrap(SomeHandler().buildParametersModel().first as? EndpointParameter<String>) XCTAssertEqual(ObjectIdentifier(parameter.propertyType), ObjectIdentifier(String.self)) XCTAssertEqual(parameter.necessity, .required) XCTAssertEqual(parameter.nilIsValidValue, false) XCTAssertEqual(parameter.hasDefaultValue, false) XCTAssertEqual(parameter.option(for: .optionality), .required) } }
34.402266
121
0.608449
33acf3a17c8f2389437418900f9d18e52bc383c2
2,965
// // JWTToken.swift // Proba // // Created by Proba on 22/07/2020. // Copyright © 2020 Proba. All rights reserved. // import Foundation import CommonCrypto public struct JWTToken { public static func generate( deviceId: String, deviceProperties: [String: Any], appsFlyerId: String?, amplitudeId: String?, sdkToken: String ) -> String? { let header: [String: Any] = [ "alg": "HS256", "typ": "JWT" ] let payload: [String: Any] = [ "deviceId": deviceId, "deviceProperties": deviceProperties, "appsFlyerId": appsFlyerId ?? "", "amplitudeId": amplitudeId ?? "" ] guard let jsonHeader = try? JSONSerialization.data(withJSONObject: header, options: []), let jsonPayload = try? JSONSerialization.data(withJSONObject: payload, options: []) else { return nil } let encodedHeader = base64encodeURISafe(jsonHeader) let encodedPayload = base64encodeURISafe(jsonPayload) let signatureInput = "\(encodedHeader).\(encodedPayload)" guard let signature = getSignature(sdkToken, input: signatureInput) else { return nil } return String( format: "%@.%@", stringURISafe(signatureInput), stringURISafe(signature) ) } private static func getSignature(_ secret: String, input: String) -> String? { guard let inputData = input.data(using: .utf8, allowLossyConversion: false), let secretData = secret.data(using: .utf8, allowLossyConversion: false) else { return nil } let hmacData = hmac(secretData: secretData, inputData: inputData) return hmacData.base64EncodedString() } private static func hmac(secretData: Data, inputData: Data) -> Data { var hmacOutData = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) // Force unwrapping is ok, since input count is checked and key and algorithm are assumed not to be empty. // From the docs: If the baseAddress of this buffer is nil, the count is zero. hmacOutData.withUnsafeMutableBytes { hmacOutBytes in secretData.withUnsafeBytes { keyBytes in inputData.withUnsafeBytes { inputBytes in CCHmac( CCHmacAlgorithm(kCCHmacAlgSHA256), keyBytes.baseAddress!, secretData.count, inputBytes.baseAddress!, inputData.count, hmacOutBytes.baseAddress! ) } } } return hmacOutData } private static func stringURISafe(_ input: String) -> String { return input .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") } private static func base64encodeURISafe(_ input: Data) -> String { if let string = String(data: input.base64EncodedData(), encoding: .utf8) { return string .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") } return "" } }
29.65
110
0.652277
dee68e3a33c0e1d57a61a227a08a7cb12fa34fa1
2,681
// // ContractTermActionSubject.swift // Asclepius // Module: STU3 // // Copyright (c) 2022 Bitmatic Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import AsclepiusCore /// Entity of the action open class ContractTermActionSubject: BackboneElement { /// Entity of the action public var reference: [Reference] /// Role type of the agent public var role: CodeableConcept? public init(reference: [Reference]) { self.reference = reference super.init() } public convenience init( fhirExtension: [Extension]? = nil, modifierExtension: [Extension]? = nil, fhirId: AsclepiusPrimitive<AsclepiusString>? = nil, reference: [Reference], role: CodeableConcept ) { self.init(reference: reference) self.fhirExtension = fhirExtension self.modifierExtension = modifierExtension self.fhirId = fhirId self.role = role } // MARK: - Codable private enum CodingKeys: String, CodingKey { case reference case role } public required init(from decoder: Decoder) throws { let codingKeyContainer = try decoder.container(keyedBy: CodingKeys.self) self.reference = try [Reference](from: codingKeyContainer, forKey: .reference) self.role = try CodeableConcept(from: codingKeyContainer, forKeyIfPresent: .role) try super.init(from: decoder) } override public func encode(to encoder: Encoder) throws { var codingKeyContainer = encoder.container(keyedBy: CodingKeys.self) try reference.encode(on: &codingKeyContainer, forKey: .reference) try role?.encode(on: &codingKeyContainer, forKey: .role) try super.encode(to: encoder) } // MARK: - Equatable override public func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ContractTermActionSubject else { return false } guard super.isEqual(to: _other) else { return false } return reference == _other.reference && role == _other.role } // MARK: - Hashable override public func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(reference) hasher.combine(role) } }
28.521277
85
0.693025
296342b0309dd1196aa984c9ac52688d52d01bc6
1,391
// // Synchronized.swift // Moltonf // // Copyright (c) 2016 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public func synchronized(_ object: Any, closure: () throws -> Void) rethrows { do { objc_sync_enter(object) defer { objc_sync_exit(object) } try closure() } }
38.638889
80
0.739037
8ab79ec0a6636cfe33b39d5c89cf6182e11c3ba7
822
// // MainTableViewC.swift // DouyuZB-Swift // // Created by Gabriella on 2017/3/10. // Copyright © 2017年 Gabriella. All rights reserved. // import UIKit class MainTableViewC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildVC(storyName: "Home") addChildVC(storyName: "Live") addChildVC(storyName: "Concern") addChildVC(storyName: "Me") } fileprivate func addChildVC(storyName:String){ let childVC = UIStoryboard(name:storyName,bundle:nil).instantiateInitialViewController()! addChildViewController(childVC) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source }
19.571429
97
0.666667
6a852b12adae7a59ee93e027b61875aff2805ca7
4,080
// // SubmitPersonFormPresenter.swift // PersonsFeature // // Created by Joachim Kret on 10/07/2019. // Copyright © 2019 Joachim Kret. All rights reserved. // import Foundation import Shared import AppCore import AdaptersCore final class SubmitPersonFormPresenter { private let localizer: PersonFormLocalizing private let module: PersonFormModule private let errorsConsumer: PersonFormErrorsConsumer private let submitProgress = Once.Lock() private let progress = DebounceCounter() private weak var ui: PersonFormUserInterface? private weak var wireframe: PersonFormWireframe? init(localizer: PersonFormLocalizing, module: PersonFormModule, errorsConsumer: @escaping PersonFormErrorsConsumer) { self.localizer = localizer self.module = module self.errorsConsumer = errorsConsumer } } extension SubmitPersonFormPresenter: PersonFormModule { func attach(ui: PersonFormUserInterface, wireframe: PersonFormWireframe) { self.ui = ui self.wireframe = wireframe self.module.attach(ui: self, wireframe: self) } func detach() { module.detach() wireframe = nil ui = nil } } extension SubmitPersonFormPresenter: PersonFormUserInterface { func present(viewData: PersonFormViewData) { tellUserInterfaceToPresentViewData(viewData) } func present(error viewData: ErrorViewData) { tellUserInterfaceToPresentError(viewData) } func presentProgress() { tellUserInterfaceToPresentProgress() } func dismissProgress() { tellUserInterfaceToDismissProgress() } } extension SubmitPersonFormPresenter: PersonFormWireframe { func submitedPerson(with context: PersonContext) { wireframe?.submitedPerson(with: context) } } extension SubmitPersonFormPresenter: SubmitPersonFormModelResponse { func didUpdate(with state: DataState<PersonId, ApplicationError>) { switch state { case .idle: break case .processing: submitProgress.lock { tellUserInterfaceToPresentProgress() } case .success(let id): submitProgress.unlock { tellUserInterfaceToDismissProgress() } tellWireframePersonSubmited(with: id) case .failure(let error): submitProgress.unlock { tellUserInterfaceToDismissProgress() } handleError(error) } } private func handleError(_ error: ApplicationError) { if let invalidData = invalidDataError(from: error) { errorsConsumer(invalidData) } else { tellUserInterfaceToPresentError(error) } } private func invalidDataError(from error: ApplicationError) -> InvalidPersonData? { switch error { case .other(let custom): return custom as? InvalidPersonData default: return nil } } } extension SubmitPersonFormPresenter { private func tellUserInterfaceToPresentViewData(_ viewData: PersonFormViewData) { ui?.present(viewData: viewData) } private func tellUserInterfaceToPresentError(_ error: ApplicationError) { let viewData = ApplicationErrorViewDataFactory(error: error, localizer: localizer).create() ui?.present(error: viewData) } private func tellUserInterfaceToPresentError(_ viewData: ErrorViewData) { ui?.present(error: viewData) } private func tellUserInterfaceToPresentProgress() { progress.start { ui?.presentProgress() } } private func tellUserInterfaceToDismissProgress() { progress.finish { ui?.dismissProgress() } } } extension SubmitPersonFormPresenter { private func tellWireframePersonSubmited(with id: PersonId) { let context = PersonContext(id: id) wireframe?.submitedPerson(with: context) } }
27.2
99
0.657108
1802338950ccd20cec37d4e0526015183144c679
2,067
// // ADAddPhotoCell.swift // ADPhotoKit // // Created by MAC on 2021/3/24. // import UIKit /// Cell for add asset in thumbnail controller. public class ADAddPhotoCell: UICollectionViewCell { var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) imageView = UIImageView(image: Bundle.image(name: "addPhoto")) imageView.backgroundColor = UIColor(white: 0.3, alpha: 1) imageView.contentMode = .center contentView.addSubview(imageView) imageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /// UIAppearance extension ADAddPhotoCell { /// Key for attribute. public class Key: NSObject { let rawValue: String init(rawValue: String) { self.rawValue = rawValue } static func == (lhs: Key, rhs: Key) -> Bool { return lhs.rawValue == rhs.rawValue } } /// You may specify the corner radius, bg color properties for the cell in the attributes dictionary, using the keys found in `ADAddPhotoCell.Key`. /// - Parameter attrs: Attributes dictionary. @objc public func setAttributes(_ attrs: [Key : Any]?) { if let kvs = attrs { for (k,v) in kvs { if k == .bgColor { imageView.backgroundColor = (v as? UIColor) ?? UIColor(white: 0.3, alpha: 1) } if k == .cornerRadius { contentView.layer.cornerRadius = CGFloat((v as? Int) ?? 0) contentView.layer.masksToBounds = true } } } } } extension ADAddPhotoCell.Key { /// Int, default 0 public static let cornerRadius = ADAddPhotoCell.Key(rawValue: "cornerRadius") /// UIColor, default UIColor(white: 0.3, alpha: 1) public static let bgColor = ADAddPhotoCell.Key(rawValue: "bgColor") }
29.112676
151
0.586841
11c14db4452438a84e1fdaec9120ef9f7ea7aec5
258
import Foundation public func WMFLocalizedString(_ key: String, siteURL: URL? = nil, bundle: Bundle = Bundle.wmf_localization, value: String, comment: String) -> String { return WMFLocalizedStringWithDefaultValue(key, siteURL, bundle, value, comment) }
43
152
0.771318
14bcbda3fda5e50da857feba2f41940af3692ee5
1,653
// // LoginViewController.swift // FledgerMac // // Created by Robert Conrad on 8/16/15. // Copyright (c) 2015 Robert Conrad. All rights reserved. // import Cocoa import FledgerCommon class LoginViewController: NSViewController { lazy var helper: LoginViewHelper = { return LoginViewHelper(self, self) }() var loginHandler: ((Bool) -> ())? @IBOutlet weak var email: NSTextField! @IBOutlet weak var emailLabel: NSTextField! @IBOutlet weak var password: NSSecureTextField! @IBOutlet weak var passwordLabel: NSTextField! @IBOutlet weak var loginButton: NSButton! override func viewDidLoad() { super.viewDidLoad() helper.loginFromCache() loginButton.keyEquivalent = "\r" } @IBAction func login(sender: AnyObject) { helper.login() } @IBAction func signup(sender: AnyObject) { helper.signup() } } extension LoginViewController: LoginViewHelperDataSource { func getEmail() -> String { return email.stringValue } func getPassword() -> String { return password.stringValue } } extension LoginViewController: LoginViewHelperDelegate { func notifyEmailValidity(valid: Bool) { emailLabel.textColor = valid ? AppColors.text() : AppColors.textError() } func notifyPasswordValidity(valid: Bool) { passwordLabel.textColor = valid ? AppColors.text() : AppColors.textError() } func notifyLoginResult(valid: Bool) { notifyEmailValidity(valid) notifyPasswordValidity(valid) loginHandler?(valid) } }
23.28169
82
0.647913