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
e278f105151ebad0c85c6a219c5e44b253d7effc
623
// // UIScreen+ScreenCorners.swift // // // Created by Kyle Bashour on 10/24/20. // import UIKit extension UIScreen { private static let cornerRadiusKey: String = { let components = ["Radius", "Corner", "display", "_"] return components.reversed().joined() }() /// The corner radius of the display. Uses a private property of `UIScreen`, /// and may report 0 if the API changes. public var displayCornerRadius: CGFloat { guard let cornerRadius = self.value(forKey: Self.cornerRadiusKey) as? CGFloat else { return 0 } return cornerRadius } }
23.961538
92
0.632424
7589d69d6a9d7e321264f4e41eb3b8d8f38c7448
984
// // GithubService.swift // RxApolloClient_Example // // Created by Kanghoon on 18/01/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import RxSwift import RxOptional typealias Repository = SearchRepositoriesQuery.Data.Search.Edge.Node.AsRepository protocol GithubServiceType { func searchRepositories(request: (String, String?)) -> Single<List<Repository>> } final class GithubService: GithubServiceType { private let client: Client init(client: Client) { self.client = client } func searchRepositories(request: (String, String?)) -> Single<List<Repository>> { let (query, after) = request return self.client .fetch(query: SearchRepositoriesQuery(query: query, first: 20, after: after)) .map { List<Repository>( query: query, items: $0.search.edges?.compactMap { $0?.node?.asRepository } ?? [], after: $0.search.pageInfo.endCursor ) } .asSingle() } }
24.6
83
0.678862
ebcbf1f657ef33887511610c70a6d5b380c9e619
1,971
// // MLBaseNavigationController.swift // MissLi // // Created by chengxianghe on 16/7/24. // Copyright © 2016年 cn. All rights reserved. // import UIKit class MLBaseNavigationController: UINavigationController, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() self.delegate = self // Do any additional setup after loading the view. } // MARK: - Status Bar override var childViewControllerForStatusBarStyle : UIViewController? { return self.topViewController } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count == 1 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } // func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // if navigationController.viewControllers.count > 1 { // viewController.hidesBottomBarWhenPushed = true //// self.hidesTabBar(true) // } // } // // func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // if navigationController.viewControllers.count <= 1 { // self.hidesTabBar(false) // } // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.790323
140
0.683917
ef44031a938a302b8cda849bbb7796e8da983fb7
1,367
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 SendingStatusCollectionViewCell: UICollectionViewCell { @IBOutlet private weak var label: UILabel! var text: NSAttributedString? { didSet { self.label.attributedText = self.text } } }
36.945946
78
0.764448
db6e377e94680c4802d6ee54b3ffec50ca323975
1,418
// // AppDelegate.swift // RRSwiftUIAPICalling // // Created by Nocero Beguhe on 09/07/21. // Copyright © 2021 RR. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
38.324324
179
0.748942
21064a336332080f630db0ec8af30ea8f30ce2de
7,088
// // EditViewControllerTests.swift // pathsTests // // Created by Kevin Finn on 2/27/18. // Copyright © 2018 Kevin Finn. All rights reserved. // import XCTest import Quick import Nimble import RxSwift import RxCocoa import CoreLocation import CoreData import RandomKit import Eureka @testable import paths class EditPathViewControllerTests: QuickSpec { override func spec(){ var contextWrapper : ContextWrapper! var editPathViewController: EditPathViewController! //var mockPathManager : MockPathManager! var window : UIWindow! var expectedPath : Path! var disposeBag : DisposeBag! var onNextCalled : Bool! var actualPath : Path! var pathManager : PathManager! describe("EditPathViewController"){ beforeEach { expectedPath = nil disposeBag = DisposeBag() contextWrapper = ContextWrapper() pathManager = PathManager() pathManager.currentPathObservable?.subscribe(onNext: { path in onNextCalled = true actualPath = path }).disposed(by: disposeBag) window = UIWindow(frame: UIScreen.main.bounds) editPathViewController = EditPathViewController(pathManager: pathManager) window.makeKeyAndVisible() window.rootViewController = editPathViewController // Act: editPathViewController.beginAppearanceTransition(true, animated: false) // Triggers viewWillAppear } describe("the updateForm method"){ beforeEach { expectedPath = PathTools.generateRandomPath() editPathViewController.updateForm(with: expectedPath) } it("updates the form to match a Path object"){ expectFormDataToEqual(path: expectedPath) } } context("The view appeared"){ describe("the form") { context("current path is nil"){ beforeEach{ expectedPath = nil pathManager.setCurrentPath(expectedPath) } it("displays empty fields"){ expectFormDataToBeNil() } } context("current path is NOT nil"){ beforeEach{ expectedPath = PathTools.generateRandomPath() pathManager.setCurrentPath(expectedPath) } it("displays the current path data"){ expect(onNextCalled).toEventually(be(true)) expectFormDataToEqual(path: actualPath) } } context("the save method runs"){ var pathId : String! var completions : Int! var expectedCompletions = 2 //one for nil beforeEach { completions = 0 expectedPath = PathTools.generateRandomPath() waitUntil(timeout: 50, action: { done in pathManager.currentPathObservable?.subscribe(onNext: { path in onNextCalled = true completions! += 1 if completions == expectedCompletions { actualPath = path pathId = actualPath.localid generateRandomFormData() editPathViewController.save() done() } }).disposed(by: disposeBag) pathManager.setCurrentPath(expectedPath) }) } it("updates the current path with the updated form values"){ expect(onNextCalled).toEventually(equal(true)) expectFormDataToEqual(path: actualPath) } it("updates the current path in the Path Manager"){ let currentPath = pathManager.currentPath expect(currentPath).toNot(beNil()) expectFormDataToEqual(path: currentPath!) } } } } } func generateRandomFormData(){ let form = editPathViewController.form (form.rowBy(tag: "title") as? TextRow)?.value = String.random(ofLength: 10, using: &Xorshift.default) (form.rowBy(tag: "notes") as? TextRow)?.value = String.random(ofLength: 10, using: &Xorshift.default) (form.rowBy(tag: "locations") as? TextRow)?.value = String.random(ofLength: 10, using: &Xorshift.default) (form.rowBy(tag: "startdate") as? DateRow)?.value = Date.random(using: &Xorshift.default) (form.rowBy(tag: "enddate") as? DateRow)?.value = Date.random(using: &Xorshift.default) } func expectFormDataToEqual(path: Path){ expect(editPathViewController.form.rowBy(tag: "title")?.baseValue as! String?).toEventually(equal(path.title)) expect(editPathViewController.form.rowBy(tag: "notes")?.baseValue as! String?).toEventually(equal(path.notes)) expect(editPathViewController.form.rowBy(tag: "locations")?.baseValue as! String?).toEventually(equal(path.locations)) expect(editPathViewController.form.rowBy(tag: "startdate")?.baseValue as! Date?).toEventually(equal(path.startdate)) expect(editPathViewController.form.rowBy(tag: "enddate")?.baseValue as! Date?).toEventually(equal(path.enddate)) } func expectFormDataToBeNil(){ expect(editPathViewController.form.rowBy(tag: "title")?.baseValue as! String?).to(beNil()) expect(editPathViewController.form.rowBy(tag: "notes")?.baseValue as! String?).to(beNil()) expect(editPathViewController.form.rowBy(tag: "locations")?.baseValue as! String?).to(beNil()) expect(editPathViewController.form.rowBy(tag: "startdate")?.baseValue as! Date?).to(beNil()) expect(editPathViewController.form.rowBy(tag: "enddate")?.baseValue as! Date?).to(beNil()) } } }
45.729032
130
0.502257
11b12436fc9d2028702d2180688f380f52a84a87
7,995
import XCTest @testable import GPXKit #if canImport(FoundationXML) import FoundationXML #endif class GPXParserTests: XCTestCase { private var sut: GPXFileParser! private var parseError: GPXParserError? private var result: GPXTrack? private func parseXML(_ xml: String) { sut = GPXFileParser(xmlString: xml) switch sut.parse() { case .success(let track): result = track case .failure(let error): parseError = error } } // MARK: Tests func testImportingAnEmptyGPXString() { parseXML("") XCTAssertNil(result) if case let .parseError(error, line) = parseError { XCTAssertEqual(0, line) XCTAssertEqual(1, error.code) } else { XCTFail("Exepcted parse error, got \(String(describing: parseError))") } } func testParsingGPXFilesWithoutATrack() { parseXML(""" <?xml version="1.0" encoding="UTF-8"?> <gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"> <metadata> <time>2020-03-17T11:27:02Z</time> </metadata> </gpx> """) XCTAssertNil(result) XCTAssertEqual(.noTracksFound, parseError) } func testParsingTrackTitles() { parseXML(""" <?xml version="1.0" encoding="UTF-8"?> <gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"> <metadata> <time>2020-03-17T11:27:02Z</time> </metadata> <trk> <name>Frühjahrsgeschlender ach wie schön!</name> <type>1</type> </trk> </gpx> """) XCTAssertEqual("Frühjahrsgeschlender ach wie schön!", result?.title) } func testParsingTrackSegmentsWithoutExtensions() { parseXML(testXMLWithoutExtensions) let expected = [ TrackPoint(coordinate: Coordinate(latitude: 51.2760600, longitude: 12.3769500, elevation: 114.2), date: expectedDate(for: "2020-03-18T12:39:47Z")), TrackPoint(coordinate: Coordinate(latitude: 51.2760420, longitude: 12.3769760, elevation: 114.0), date: expectedDate(for: "2020-03-18T12:39:48Z")) ] assertTracksAreEqual(GPXTrack(date: expectedDate(for: "2020-03-18T12:39:47Z"), title: "Haus- und Seenrunde Ausdauer", trackPoints: expected), result!) } func testParsingTrackSegmentsWithExtensions() { parseXML(testXMLData) let expected = [ TrackPoint(coordinate: Coordinate(latitude: 51.2760600, longitude: 12.3769500, elevation: 114.2), date: expectedDate(for: "2020-03-18T12:39:47Z"), power: Measurement<UnitPower>(value: 42, unit: .watts)), TrackPoint(coordinate: Coordinate(latitude: 51.2760420, longitude: 12.3769760, elevation: 114.0), date: expectedDate(for: "2020-03-18T12:39:48Z"), power: Measurement<UnitPower>(value: 272, unit: .watts)) ] assertTracksAreEqual(GPXTrack(date: expectedDate(for: "2020-03-18T12:39:47Z"), title: "Haus- und Seenrunde Ausdauer", trackPoints: expected), result!) } func testParsingTrackSegmentsWithoutTimeHaveANilDate() { parseXML(""" <?xml version="1.0" encoding="UTF-8"?> <gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"> <metadata> </metadata> <trk> <name>Haus- und Seenrunde Ausdauer</name> <type>1</type> <trkseg> <trkpt lat="51.2760600" lon="12.3769500"> <ele>114.2</ele> </trkpt> <trkpt lat="51.2760420" lon="12.3769760"> <ele>114.0</ele> </trkpt> </trkseg> </trk> </gpx> """) let expected = [ TrackPoint(coordinate: Coordinate(latitude: 51.2760600, longitude: 12.3769500, elevation: 114.2), date: nil), TrackPoint(coordinate: Coordinate(latitude: 51.2760420, longitude: 12.3769760, elevation: 114.0), date: nil) ] assertTracksAreEqual(GPXTrack(date: nil, title: "Haus- und Seenrunde Ausdauer", trackPoints: expected), result!) } func testParsingTrackWithoutElevation() { parseXML(""" <?xml version="1.0" encoding="UTF-8"?> <gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"> <metadata> </metadata> <trk> <name>Haus- und Seenrunde Ausdauer</name> <type>1</type> <trkseg> <trkpt lat="51.2760600" lon="12.3769500"></trkpt> <trkpt lat="51.2760420" lon="12.3769760"></trkpt> </trkseg> </trk> </gpx> """) let expected = [ TrackPoint(coordinate: Coordinate(latitude: 51.2760600, longitude: 12.3769500, elevation: 0), date: nil), TrackPoint(coordinate: Coordinate(latitude: 51.2760420, longitude: 12.3769760, elevation: 0), date: nil) ] assertTracksAreEqual(GPXTrack(date: nil, title: "Haus- und Seenrunde Ausdauer", trackPoints: expected), result!) } func testTrackLength() throws { parseXML(sampleGPX) let distance = try XCTUnwrap(result?.graph.distance) let elevation = try XCTUnwrap(result?.graph.elevationGain) XCTAssertEqual(3100.5625, distance, accuracy: 10) XCTAssertEqual(158.4000015258789, elevation, accuracy: 0.001) } }
46.482558
592
0.614009
69c3eaa02f98dfdbe37ce1145a441e2cd90049f9
1,778
// // Helpers.swift // FoodTrackerTests // // Created by Tizin MacBook Pro on 16/01/2018. // Copyright © 2018 Apple Inc. All rights reserved. // import Foundation class ArrayHelper { class func generateArray(elementCount: Int) -> [String] { var testArray = [String]() for i in 0..<elementCount { testArray.append(tempString + String(i)) } return testArray } class func randomArrayIndex(array: [String]) -> Int { return Random.rndInt(0, to: array.count - 1) } class func randomArrayElement(array: [String], randomIndex: Int) -> String { return array[randomIndex] } } class SetHelper { class func generateSet(elementCount: Int) -> Set<String> { var testSet = Set<String>() for i in 0..<elementCount { testSet.insert(tempString + String(i)) } return testSet } class func randomSetIndex(set: Set<String>) -> Int { return Random.rndInt(0, to: set.count - 1) } class func randomSetElement(set: Set<String>, randomIndex: Int) -> String { return tempString + String(randomIndex) } } class DictionaryHelper { class func generateDictionary(elementCount: Int) -> [String: String] { var testDictionary = [String: String]() for i in 0..<elementCount { testDictionary[String(i)] = tempString + String(i) } return testDictionary } class func randomDictionaryIndex(dict: [String: String]) -> String { return String(Random.rndInt(0, to: dict.count - 1)) } class func randomDictionaryElement(dict: [String: String], randomIndex: String) -> String { return dict[randomIndex]! } }
26.537313
95
0.601237
7927393aaa9d2c9a862a960ac411c9327fe97d32
1,092
import XCTest @testable import ReWebKit class RxWkNavigationDelegateProxyTests: XCTestCase { var actor: ReWebView? var navigationMock: WKNavigationDelegateMock? override func setUp() { actor = ReWebView(frame: .zero) navigationMock = WKNavigationDelegateMock() } override func tearDown() { actor = nil navigationMock = nil } } // Single method test extension RxWkNavigationDelegateProxyTests { func test_ShouldBeNilIfWKUIDelegateNotSetInMock() { let expected = RXWkNavigationDelegateProxy.currentDelegate(for: actor!) XCTAssertNil(expected) } func test_ShouldBeNotNilIfInitMethodCalled() { let proxy = RXWkNavigationDelegateProxy(parentObject: actor!) XCTAssertNotNil(proxy) } func test_ShouldNotBeNilIfWKUIDelegateSetInMock() { let _ = RXWkNavigationDelegateProxy.setCurrentDelegate(navigationMock, to: actor!) let expected = RXWkNavigationDelegateProxy.currentDelegate(for: actor!) XCTAssertNotNil(expected) } }
26
90
0.695055
5b101e515aa5b7be09987b22580f8e05064a67f4
699
// // AnyComparable.swift // // // Created by Daniel Illescas Romero on 05/06/2020. // public struct AnyComparable { public let value: Any public let equals: (Any?) -> Bool public let less: (Any?) -> Bool public init<T: Comparable>(_ value: T) { self.value = value self.equals = { ($0 as? T) == value } self.less = { guard let any = $0, let casted = any as? T else { return false } return casted < value } } } extension AnyComparable: Equatable, Comparable { public static func ==(lhs: AnyComparable, rhs: AnyComparable) -> Bool { return lhs.equals(rhs.value) } public static func < (lhs: AnyComparable, rhs: AnyComparable) -> Bool { return lhs.less(rhs.value) } }
23.3
72
0.655222
cc70eb0fc2fb673e5556ab0b0fcce4757309a7ba
3,490
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: contact/EmailAddress.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ ///* /// Provides a structured record to store email addresses. import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// Specifies information about an electronic mail (email) address, and optionally, its validation status. public struct Opencannabis_Contact_EmailAddress { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Email address, in standard format ('[email protected]'). public var address: String = String() /// Validation status. Usable by providers to indicate an email address that has already been validated, or that an /// address remains unvalidated. public var validated: Bool = false /// Display name for the email address, if known/specified. public var name: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "opencannabis.contact" extension Opencannabis_Contact_EmailAddress: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EmailAddress" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "address"), 2: .same(proto: "validated"), 3: .same(proto: "name"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.address) case 2: try decoder.decodeSingularBoolField(value: &self.validated) case 3: try decoder.decodeSingularStringField(value: &self.name) default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.address.isEmpty { try visitor.visitSingularStringField(value: self.address, fieldNumber: 1) } if self.validated != false { try visitor.visitSingularBoolField(value: self.validated, fieldNumber: 2) } if !self.name.isEmpty { try visitor.visitSingularStringField(value: self.name, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Opencannabis_Contact_EmailAddress, rhs: Opencannabis_Contact_EmailAddress) -> Bool { if lhs.address != rhs.address {return false} if lhs.validated != rhs.validated {return false} if lhs.name != rhs.name {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
38.777778
145
0.743553
01f7968f70bbcf0729b5f7d760b634f79f812c49
1,980
/// Copyright (c) 2020 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 Foundation enum Scene { case tasks(TasksViewModel) case editTask(EditTaskViewModel) }
50.769231
83
0.759596
f4e4e2a35f5a025aacaabe9dcd2e40641b3ff7bc
3,041
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public class StreetSegment: Codable, Equatable { /** geoJSON formatted LineString containing two latitude/longitude (WGS84) pairs that identify the start and end points of the street segment. */ public var lineString: String? /** The ID from the source system of the disruption that this street belongs to. */ public var sourceSystemId: Int? /** The key of the source system of the disruption that this street belongs to. */ public var sourceSystemKey: String? /** A 16 digit unique integer identifying a OS ITN (Ordnance Survey Integrated Transport Network) road link. */ public var toid: String? public init(lineString: String? = nil, sourceSystemId: Int? = nil, sourceSystemKey: String? = nil, toid: String? = nil) { self.lineString = lineString self.sourceSystemId = sourceSystemId self.sourceSystemKey = sourceSystemKey self.toid = toid } private enum CodingKeys: String, CodingKey { case lineString case sourceSystemId case sourceSystemKey case toid } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) lineString = try container.decodeIfPresent(.lineString) sourceSystemId = try container.decodeIfPresent(.sourceSystemId) sourceSystemKey = try container.decodeIfPresent(.sourceSystemKey) toid = try container.decodeIfPresent(.toid) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(lineString, forKey: .lineString) try container.encodeIfPresent(sourceSystemId, forKey: .sourceSystemId) try container.encodeIfPresent(sourceSystemKey, forKey: .sourceSystemKey) try container.encodeIfPresent(toid, forKey: .toid) } public func isEqual(to object: Any?) -> Bool { guard let object = object as? StreetSegment else { return false } guard self.lineString == object.lineString else { return false } guard self.sourceSystemId == object.sourceSystemId else { return false } guard self.sourceSystemKey == object.sourceSystemKey else { return false } guard self.toid == object.toid else { return false } return true } public static func == (lhs: StreetSegment, rhs: StreetSegment) -> Bool { return lhs.isEqual(to: rhs) } }
21.721429
149
0.584018
9004c1f892bfc3024cb0b249e77ed26c42fdfa57
2,218
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // FIXME: Should go into the standard library. public extension _ObjectiveCBridgeable { static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self { var result: Self? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } // CHECK: testing... print("testing...") class C {} func bridgedStatus<T>(_: T.Type) -> String { let bridged = _isBridgedToObjectiveC(T.self) let verbatim = _isBridgedVerbatimToObjectiveC(T.self) if !bridged && verbatim { return "IS NOT BRIDGED BUT IS VERBATIM?!" } return bridged ? verbatim ? "is bridged verbatim" : "is custom-bridged" : "is unbridged" } func testBridging<T>(_ x: T, _ name: String) { print("\(name) \(bridgedStatus(T.self))") var b : String let result = _bridgeAnythingToObjectiveC(x) b = "bridged as " + ( result is C ? "C" : result is T ? "itself" : "an unknown type") print("\(name) instance \(b)") } //===----------------------------------------------------------------------===// struct BridgedValueType : _ObjectiveCBridgeable { func _bridgeToObjectiveC() -> C { return C() } static func _forceBridgeFromObjectiveC( _ x: C, result: inout BridgedValueType? ) { preconditionFailure("implement") } static func _conditionallyBridgeFromObjectiveC( _ x: C, result: inout BridgedValueType? ) -> Bool { preconditionFailure("implement") } } // CHECK-NEXT: BridgedValueType is custom-bridged // CHECK-NEXT: BridgedValueType instance bridged as C testBridging(BridgedValueType(), "BridgedValueType") //===----------------------------------------------------------------------===// struct UnbridgedValueType {} // CHECK-NEXT: UnbridgedValueType is unbridged // CHECK-NEXT: UnbridgedValueType instance bridged as itself testBridging(UnbridgedValueType(), "UnbridgedValueType") //===----------------------------------------------------------------------===// class PlainClass {} // CHECK-NEXT: PlainClass is bridged verbatim // CHECK-NEXT: PlainClass instance bridged as itself testBridging(PlainClass(), "PlainClass")
28.435897
80
0.631199
6729bb7fb1a5a43bb31cdbeeec8543ce3c265913
4,149
// // LibraryService.swift // The Palace Project // // Created by Mickaël Menu on 20.02.19. // // Copyright 2019 European Digital Reading Lab. All rights reserved. // Licensed to the Readium Foundation under one or more contributor license agreements. // Use of this source code is governed by a BSD-style license which is detailed in the // LICENSE file present in the project repository where this source code is maintained. // import Foundation import UIKit import R2Shared import R2Streamer /// The LibraryService makes a book ready for presentation without dealing /// with the specifics of how a book should be presented. /// /// It sets up the various components necessary for presenting a book, /// such as the streamer, publication server, DRM systems. Presentation /// iself is handled by the `ReaderModule`. final class LibraryService: Loggable { private let streamer: Streamer private let publicationServer: PublicationServer private var drmLibraryServices = [DRMLibraryService]() private lazy var documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) init(publicationServer: PublicationServer) { self.publicationServer = publicationServer #if LCP drmLibraryServices.append(LCPLibraryService()) #endif #if FEATURE_DRM_CONNECTOR drmLibraryServices.append(AdobeDRMLibraryService()) #endif streamer = Streamer( contentProtections: drmLibraryServices.compactMap { $0.contentProtection } ) } // MARK: Opening /// Opens the Readium 2 Publication for the given `book`. /// /// - Parameters: /// - book: The book to be opened. /// - sender: The VC that requested the opening and that will handle /// error alerts or other messages for the user. /// - completion: When this is called, the book is ready for /// presentation if there are no errors. func openBook(_ book: TPPBook, sender: UIViewController, completion: @escaping (CancellableResult<Publication, LibraryServiceError>) -> Void) { guard let bookUrl = book.url else { completion(.failure(.invalidBook)) return } deferredCatching { .success(bookUrl) } .flatMap { self.openPublication(at: $0, allowUserInteraction: true, sender: sender) } .flatMap { publication in guard !publication.isRestricted else { self.stopOpeningIndicator(identifier: book.identifier) if let error = publication.protectionError { return .failure(error) } else { return .cancelled } } self.preparePresentation(of: publication, book: book) return .success(publication) } .mapError { self.stopOpeningIndicator(identifier: book.identifier) return LibraryServiceError.openFailed($0) } .resolve(completion) } /// Opens the Readium 2 Publication at the given `url`. private func openPublication(at url: URL, allowUserInteraction: Bool, sender: UIViewController?) -> Deferred<Publication, Error> { return deferred { self.streamer.open(asset: FileAsset(url: url), allowUserInteraction: allowUserInteraction, sender: sender, completion: $0) } .eraseToAnyError() } private func preparePresentation(of publication: Publication, book: TPPBook) { // If the book is a webpub, it means it is loaded remotely from a URL, and it doesn't need to be added to the publication server. guard publication.format != .webpub else { return } publicationServer.removeAll() do { try publicationServer.add(publication) } catch { log(.error, error) } } /// Stops activity indicator on the`Read` button. private func stopOpeningIndicator(identifier: String) { let userInfo: [String: Any] = [ TPPNotificationKeys.bookProcessingBookIDKey: identifier, TPPNotificationKeys.bookProcessingValueKey: false ] NotificationCenter.default.post(name: NSNotification.TPPBookProcessingDidChange, object: nil, userInfo: userInfo) } }
34.289256
148
0.697276
db0cdd6b6ca6ce2dfcb6e789fb77a89ceacc94f7
1,140
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Rivendell", platforms: [.iOS(.v15)], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "Rivendell", targets: ["Rivendell"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), .package(path: "../Hobbiton"), .package(path: "../Erebor") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "Rivendell", dependencies: ["Hobbiton", "Erebor"]), .testTarget( name: "RivendellTests", dependencies: ["Rivendell"]), ] )
35.625
117
0.608772
8fde46b9f103f59b600c69ded23d5cb61e4792f5
488
public protocol Queueable { func process() -> Bool } public extension Array where Element : Queueable { public mutating func processQueue(from: Int = 0, _ to: Int? = nil, process: ((element: Element) -> Void)? = nil) { let to = to != nil ? to! : count let currentQueue = self[from..<to] for (index, element) in currentQueue.enumerate() where element.process() { process?(element: element) removeAtIndex(index - (currentQueue.count - self.count)) } } }
30.5
116
0.651639
7597fbc075cca133eaf8515c72618c282de2be54
2,625
// Created by eric_horacek on 2/12/20. // Copyright © 2020 Airbnb Inc. All rights reserved. import Foundation // sourcery: skipJSExport /// :nodoc: @objcMembers public final class ProtocolComposition: Type { /// Returns "protocolComposition" public override var kind: String { return "protocolComposition" } /// The names of the types composed to form this composition public let composedTypeNames: [TypeName] // sourcery: skipEquality, skipDescription public var composedTypes: [Type]? /// :nodoc: public init(name: String = "", parent: Type? = nil, accessLevel: AccessLevel = .internal, isExtension: Bool = false, variables: [Variable] = [], methods: [Method] = [], subscripts: [Subscript] = [], inheritedTypes: [String] = [], containedTypes: [Type] = [], typealiases: [Typealias] = [], attributes: [String: Attribute] = [:], annotations: [String: NSObject] = [:], isGeneric: Bool = false, composedTypeNames: [TypeName] = [], composedTypes: [Type]? = nil) { self.composedTypeNames = composedTypeNames self.composedTypes = composedTypes super.init( name: name, parent: parent, accessLevel: accessLevel, isExtension: isExtension, variables: variables, methods: methods, subscripts: subscripts, inheritedTypes: inheritedTypes, containedTypes: containedTypes, typealiases: typealiases, annotations: annotations, isGeneric: isGeneric ) } // sourcery:inline:ProtocolComposition.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let composedTypeNames: [TypeName] = aDecoder.decode(forKey: "composedTypeNames") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["composedTypeNames"])); fatalError() }; self.composedTypeNames = composedTypeNames self.composedTypes = aDecoder.decode(forKey: "composedTypes") super.init(coder: aDecoder) } /// :nodoc: override public func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.composedTypeNames, forKey: "composedTypeNames") aCoder.encode(self.composedTypes, forKey: "composedTypes") } // sourcery:end }
37.5
296
0.594667
91c522517d1fe5a74b17181a796cd88ef02f3028
2,198
// // Copyright (c) 2020, Jonathan Lynch // // This source code is licensed under the BSD 3-Clause License license found in the // LICENSE file in the root directory of this source tree. // import CoreGraphics import CoreServices import Foundation import ImageIO struct CodableCGImage: Codable { let image: CGImage init(with anImage: CGImage) { image = anImage } enum CodingKeys: CodingKey { case imageData } func encode(to encoder: Encoder) throws { guard let imageData = CFDataCreateMutable(kCFAllocatorDefault, 0) else { throw EncodingError.invalidValue(image, EncodingError.Context(codingPath: [CodingKeys.imageData], debugDescription: "Could not create CFMutableData while encoding CGImage")) } guard let imageDestination = CGImageDestinationCreateWithData(imageData, kUTTypePNG, 1, nil) else { throw EncodingError.invalidValue(image, EncodingError.Context(codingPath: [CodingKeys.imageData], debugDescription: "Could not create CGImageDestination while encoding CGImage")) } CGImageDestinationAddImage(imageDestination, image, nil) CGImageDestinationFinalize(imageDestination) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(imageData as Data, forKey: .imageData) } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let imageData = try container.decode(Data.self, forKey: .imageData) guard let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [CodingKeys.imageData], debugDescription: "Could not create CGImageSource from decoded data")) } guard let decodedImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [CodingKeys.imageData], debugDescription: "Could not create CGImage from decoded CGImageSource")) } image = decodedImage } }
39.963636
190
0.703822
5d69073db7a72d4d5a9d12dbb26115f4794f42b0
40,934
// // DataService.swift // Listpie // // Created by Ebru on 27/09/2017. // Copyright © 2017 Ebru Kaya. All rights reserved. // import Foundation import Firebase import FirebaseStorage let DB_BASE = Database.database().reference() let STORAGE_BASE = Storage.storage().reference() class DataService { static let instance = DataService() private var _REF_BASE = DB_BASE private var _REF_USERS = DB_BASE.child("users") private var _REF_LISTS = DB_BASE.child("lists") private var _REF_ITEMS = DB_BASE.child("items") var REF_BASE: DatabaseReference { return _REF_BASE } var REF_USERS: DatabaseReference { return _REF_USERS } var REF_LISTS: DatabaseReference { return _REF_LISTS } var REF_ITEMS: DatabaseReference { return _REF_ITEMS } func getLoginCredential(forInput input: String, handler: @escaping (_ email: String) -> ()) { if isEmail(input: input) { handler(input) } else { let query = REF_USERS.queryOrdered(byChild: "username").queryEqual(toValue: input) query.observeSingleEvent(of: .value) { (snapshot) in if snapshot.exists() { guard let userSnapshot = snapshot.children.allObjects as? [DataSnapshot] else { return } for userSnap in userSnapshot { let userDict = userSnap.value as! [String:AnyObject] handler(userDict["email"] as! String) } } else { handler("noUser") } } } } func createList(withTitle title: String, withDescription description: String, withVisibility isPublic: Bool, withImage image: UIImage, withCategory category: String, withCreationDate date: String, forUID uid: String, withItemNames itemNames: [String], withItemDescriptions itemDescriptions: [String], withItemImages itemImages: [UIImage], creationComplete: @escaping (_ status: Bool) -> ()) { let itemCount = itemNames.count var itemIDs = [String]() let group = DispatchGroup() for i in 0 ..< itemCount { group.enter() var downloadItemImageURL = String() let size = CGSize(width: 0, height: 0) if itemImages[i].size.width == size.width { let newItemRef = self.REF_ITEMS.childByAutoId() newItemRef.updateChildValues(["name": itemNames[i], "description": itemDescriptions[i], "image": downloadItemImageURL]) itemIDs.append(newItemRef.key) group.leave() } else { let randomItemImageName = randomString(length: 9) let uploadItemImageRef = STORAGE_BASE.child("images/items/\(randomItemImageName).jpg") let itemImageData = UIImageJPEGRepresentation(itemImages[i], 0.8) uploadItemImageRef.putData(itemImageData!, metadata: nil) { (metaData,error) in if let error = error { print(error.localizedDescription) return } else { downloadItemImageURL = metaData!.downloadURL()!.absoluteString let newItemRef = self.REF_ITEMS.childByAutoId() newItemRef.updateChildValues(["name": itemNames[i], "description": itemDescriptions[i], "image": downloadItemImageURL]) itemIDs.append(newItemRef.key) group.leave() } } } } group.notify(queue: .main) { var downloadListImageURL = DEFAULT_LIST_BACKGROUND_URL let size = CGSize(width: 0, height: 0) if image.size.width == size.width { self.REF_LISTS.childByAutoId().updateChildValues(["title": title, "description": description, "isPublic": isPublic, "image": downloadListImageURL, "category": category, "creationDate": date, "authorID": uid, "itemIDs": itemIDs]) creationComplete(true) } else { let randomListImageName = randomString(length: 9) let uploadListImageRef = STORAGE_BASE.child("images/lists/\(randomListImageName).jpg") let listImageData = UIImageJPEGRepresentation(image, 0.8) uploadListImageRef.putData(listImageData!, metadata: nil) { (metaData,error) in if let error = error { print(error.localizedDescription) return } else { downloadListImageURL = metaData!.downloadURL()!.absoluteString self.REF_LISTS.childByAutoId().updateChildValues(["title": title, "description": description, "isPublic": isPublic, "image": downloadListImageURL, "category": category, "creationDate": date, "authorID": uid, "itemIDs": itemIDs]) creationComplete(true) } } } } } func getUsername(forUID uid: String, handler: @escaping (_ username: String) -> ()) { REF_USERS.observeSingleEvent(of: .value) { (userSnapshot) in guard let userSnapshot = userSnapshot.children.allObjects as? [DataSnapshot] else { return } for user in userSnapshot { if user.key == uid { handler(user.childSnapshot(forPath: "username").value as! String) } } } } func getUserProfilePicture(forUID uid: String, handler: @escaping (_ username: String) -> ()) { var profilePicture: String! REF_USERS.observeSingleEvent(of: .value) { (userSnapshot) in guard let userSnapshot = userSnapshot.children.allObjects as? [DataSnapshot] else { return } for user in userSnapshot { if user.key == uid { if user.childSnapshot(forPath: "profilePicture").exists() { profilePicture = user.childSnapshot(forPath: "profilePicture").value as? String } else { profilePicture = NO_PROFILE_PICTURE_URL } handler(profilePicture) } } } } func getUser(forUID uid: String, forCID cid: String, handler: @escaping (_ user: User) -> ()) { var userToReturn: User! let group = DispatchGroup() REF_USERS.observeSingleEvent(of: .value) { (userSnapshot) in guard let userSnapshot = userSnapshot.children.allObjects as? [DataSnapshot] else { return } for user in userSnapshot { if user.key == uid { group.enter() let email = user.childSnapshot(forPath: "email").value as! String let username = user.childSnapshot(forPath: "username").value as! String let fullname = user.childSnapshot(forPath: "name").value as! String var bioDescription: String if user.childSnapshot(forPath: "bioDescription").exists() { bioDescription = user.childSnapshot(forPath: "bioDescription").value as! String } else { bioDescription = String() } var profilePictureDownloadURL: String if user.childSnapshot(forPath: "profilePicture").exists() { profilePictureDownloadURL = user.childSnapshot(forPath: "profilePicture").value as! String } else { profilePictureDownloadURL = String() } var isFollowed = Bool() self.REF_USERS.child(cid).child("follows").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(uid){ isFollowed = true } else { isFollowed = false } } var followerIDs = [String]() var followIDs = [String]() self.REF_USERS.child(uid).child("followers").observeSingleEvent(of: .value) { (followerSnapshot) in guard let followerSnapshot = followerSnapshot.children.allObjects as? [DataSnapshot] else { return } for follower in followerSnapshot { followerIDs.append(follower.key) } } self.REF_USERS.child(uid).child("follows").observeSingleEvent(of: .value) { (followSnapshot) in guard let followSnapshot = followSnapshot.children.allObjects as? [DataSnapshot] else { return } for follow in followSnapshot { followIDs.append(follow.key) } } var lists = [List]() self.getUserProfileLists(forUID: uid, forCID: cid) { (returnedListArray) in lists = returnedListArray.reversed() userToReturn = User(ID: uid, email: email, username: username, fullname: fullname, bioDescription: bioDescription, profilePictureDownloadURL: profilePictureDownloadURL, lists: lists, isFollowed: isFollowed, followerIDs: followerIDs, followIDs: followIDs) group.leave() } } } group.notify(queue: .main) { handler(userToReturn) } } } func getList(forID id: String, forUID uid: String, handler: @escaping (_ list: List) -> ()) { var listToReturn = List() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { if list.key == id { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } var isFavorited = Bool() self.REF_USERS.child(uid).child("lists").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(ID){ isFavorited = true } else { isFavorited = false } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in self.getItemsOfList(forIDs: itemIDs, forUID: uid, handler: { (returnedItemArray) in self.getUserProfilePicture(forUID: authorID, handler: { (returnedUserProfilePicture) in listToReturn = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: returnedUserProfilePicture, creationDate: creationDate, itemIDs: itemIDs, items: returnedItemArray, completedItemCount: completedItemCount, isFavorited: isFavorited) group.leave() }) }) }) } } group.notify(queue: .main) { handler(listToReturn) } } } func getItemsOfList(forIDs ids: [String], forUID uid: String, handler: @escaping (_ items: [Item]) -> ()) { var itemArray = [Item]() REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in for id in ids { guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == id { let ID = item.key as String let name = item.childSnapshot(forPath: "name").value as! String var description: String if item.childSnapshot(forPath: "description").exists() { description = item.childSnapshot(forPath: "description").value as! String } else { description = String() } var imageDownloadURL: String if item.childSnapshot(forPath: "image").exists() { imageDownloadURL = item.childSnapshot(forPath: "image").value as! String } else { imageDownloadURL = String() } var isCompleted = Bool() if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { isCompleted = true } else { isCompleted = false } let item = Item(ID: ID, name: name, description: description, imageDownloadURL: imageDownloadURL, isCompleted: isCompleted) itemArray.append(item) } } } handler(itemArray) } } func getAllFollowedLists(forUID uid: String, handler: @escaping (_ lists: [List]) -> ()) { var listArray = [List]() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { self.REF_USERS.child(uid).child("follows").observeSingleEvent(of: .value) { (snapshot) in let isFollowed = list.childSnapshot(forPath: "isPublic").value as! Bool && snapshot.hasChild(list.childSnapshot(forPath: "authorID").value as! String) if isFollowed { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: true) listArray.append(list) group.leave() }) } group.notify(queue: .main) { handler(listArray) } } } } } func getUserProfileLists(forUID uid: String, forCID cid: String, handler: @escaping (_ lists: [List]) -> ()) { var listArray = [List]() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { if list.childSnapshot(forPath: "authorID").value as! String == uid { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } var isFavorited = Bool() self.REF_USERS.child(uid).child("lists").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(ID){ isFavorited = true } else { isFavorited = false } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in if isPublic { let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: isFavorited) listArray.append(list) } else if uid == cid { let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: isFavorited) listArray.append(list) } group.leave() }) } } group.notify(queue: .main) { handler(listArray) } } } func getAllCreatedLists(forUID uid: String, handler: @escaping (_ lists: [List]) -> ()) { var listArray = [List]() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { if list.childSnapshot(forPath: "authorID").value as! String == uid { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } var isFavorited = Bool() self.REF_USERS.child(uid).child("lists").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(ID){ isFavorited = true } else { isFavorited = false } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: isFavorited) listArray.append(list) group.leave() }) } } group.notify(queue: .main) { handler(listArray) } } } func getAllFavoritedLists(forUID uid: String, handler: @escaping (_ lists: [List]) -> ()) { var listArray = [List]() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { self.REF_USERS.child(uid).child("lists").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(list.key as String){ if list.childSnapshot(forPath: "isPublic").value as! Bool || list.childSnapshot(forPath: "authorID").value as! String == uid { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: true) listArray.append(list) group.leave() }) } } group.notify(queue: .main) { handler(listArray) } } } } } func completeItem(withItemID itemID: String, forUID uid: String, completion: @escaping (_ status: Bool) -> ()) { REF_USERS.child(uid).child("items").updateChildValues([itemID: true]) REF_ITEMS.child(itemID).child("users").updateChildValues([uid: true]) completion(true) } func removeItemFromCompleted(withItemID itemID: String, forUID uid: String, removingComplete: @escaping (_ status: Bool) -> ()) { REF_USERS.child(uid).child("items").child(itemID).removeValue() REF_ITEMS.child(itemID).child("users").child(uid).removeValue() removingComplete(true) } func addListToFavorites(withListID listID: String, forUID uid: String, completion: @escaping (_ status: Bool) -> ()) { REF_USERS.child(uid).child("lists").updateChildValues([listID: true]) REF_LISTS.child(listID).child("users").updateChildValues([uid: true]) completion(true) } func removeListFromFavorites(withListID listID: String, forUID uid: String, completion: @escaping (_ status: Bool) -> ()) { REF_USERS.child(uid).child("lists").child(listID).removeValue() REF_LISTS.child(listID).child("users").child(uid).removeValue() completion(true) } func followUser(withUserID userID: String, forUID uid: String, completion: @escaping (_ status: Bool) -> ()) { REF_USERS.child(userID).child("followers").updateChildValues([uid: true]) REF_USERS.child(uid).child("follows").updateChildValues([userID: true]) completion(true) } func removeUserFromFollowings(withUserID userID: String, forUID uid: String, completion: @escaping (_ status: Bool) -> ()) { REF_USERS.child(userID).child("followers").child(uid).removeValue() REF_USERS.child(uid).child("follows").child(userID).removeValue() completion(true) } // Search Functions func getSearchLists(forSearchQuery query: String, forUID uid: String, handler: @escaping (_ searchListArray: [List]) -> ()) { var searchListArray = [List]() let group = DispatchGroup() REF_LISTS.observeSingleEvent(of: .value) { (listSnapshot) in guard let listSnapshot = listSnapshot.children.allObjects as? [DataSnapshot] else { return } for list in listSnapshot { let title = list.childSnapshot(forPath: "title").value as! String if list.childSnapshot(forPath: "isPublic").value as! Bool && title.lowercased().contains(query.lowercased()) { group.enter() let ID = list.key as String let title = list.childSnapshot(forPath: "title").value as! String let description = list.childSnapshot(forPath: "description").value as! String let isPublic = list.childSnapshot(forPath: "isPublic").value as! Bool let imageDownloadURL = list.childSnapshot(forPath: "image").value as! String let category = list.childSnapshot(forPath: "category").value as! String let creationDate = list.childSnapshot(forPath: "creationDate").value as! String let itemIDs = list.childSnapshot(forPath: "itemIDs").value as! [String] let authorID = list.childSnapshot(forPath: "authorID").value as! String var completedItemCount = 0 for itemID in itemIDs { self.REF_ITEMS.observeSingleEvent(of: .value) { (itemSnapshot) in guard let itemSnapshot = itemSnapshot.children.allObjects as? [DataSnapshot] else { return } for item in itemSnapshot { if item.key == itemID { if (item.childSnapshot(forPath: "users/\(uid)").value as? Bool) != nil { completedItemCount += 1 } } } } } self.getUsername(forUID: authorID, handler: { (returnedAuthorName) in let list = List(ID: ID, title: title, description: description, isPublic: isPublic, imageDownloadURL: imageDownloadURL, category: category, authorID: authorID, authorName: returnedAuthorName, authorProfilePicture: String(), creationDate: creationDate, itemIDs: itemIDs, items: [Item](), completedItemCount: completedItemCount, isFavorited: true) searchListArray.append(list) group.leave() }) } } group.notify(queue: .main) { handler(searchListArray) } } } func getSearchUsers(forSearchQuery query: String, forUID uid: String, handler: @escaping (_ searchUserArray: [User]) -> ()) { var searchUserArray = [User]() let group = DispatchGroup() REF_USERS.observeSingleEvent(of: .value) { (userSnapshot) in guard let userSnapshot = userSnapshot.children.allObjects as? [DataSnapshot] else { return } for user in userSnapshot { let cid = user.key let username = user.childSnapshot(forPath: "username").value as! String let fullname = user.childSnapshot(forPath: "name").value as! String if username.lowercased().contains(query.lowercased()) || fullname.lowercased().contains(query.lowercased()) { group.enter() let email = user.childSnapshot(forPath: "email").value as! String let username = user.childSnapshot(forPath: "username").value as! String let fullname = user.childSnapshot(forPath: "name").value as! String var bioDescription: String if user.childSnapshot(forPath: "bioDescription").exists() { bioDescription = user.childSnapshot(forPath: "bioDescription").value as! String } else { bioDescription = String() } var profilePictureDownloadURL: String if user.childSnapshot(forPath: "profilePicture").exists() { profilePictureDownloadURL = user.childSnapshot(forPath: "profilePicture").value as! String } else { profilePictureDownloadURL = String() } var isFollowed = Bool() self.REF_USERS.child(cid).child("follows").observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(uid){ isFollowed = true } else { isFollowed = false } } var followerIDs = [String]() var followIDs = [String]() self.REF_USERS.child(uid).child("followers").observeSingleEvent(of: .value) { (followerSnapshot) in guard let followerSnapshot = followerSnapshot.children.allObjects as? [DataSnapshot] else { return } for follower in followerSnapshot { followerIDs.append(follower.key) } } self.REF_USERS.child(uid).child("follows").observeSingleEvent(of: .value) { (followSnapshot) in guard let followSnapshot = followSnapshot.children.allObjects as? [DataSnapshot] else { return } for follow in followSnapshot { followIDs.append(follow.key) } } var lists = [List]() self.getUserProfileLists(forUID: uid, forCID: cid) { (returnedListArray) in lists = returnedListArray.reversed() let user = User(ID: cid, email: email, username: username, fullname: fullname, bioDescription: bioDescription, profilePictureDownloadURL: profilePictureDownloadURL, lists: lists, isFollowed: isFollowed, followerIDs: followerIDs, followIDs: followIDs) searchUserArray.append(user) group.leave() } } } group.notify(queue: .main) { handler(searchUserArray) } } } // Update User Function func updateUser(forUID uid: String, withFullName fullname: String, withUsername username: String, withBio bioDescription: String, withProfilePicture profilePicture: UIImage, completion: @escaping (_ status: Bool) -> ()) { let size = CGSize(width: 0, height: 0) if profilePicture.size.width == size.width { self.REF_USERS.child(uid).updateChildValues(["name": fullname, "username": username, "bioDescription": bioDescription]) completion(true) } else { let randomProfilePictureName = randomString(length: 9) let uploadProfilePictureRef = STORAGE_BASE.child("images/users/\(randomProfilePictureName).jpg") let profilePictureData = UIImageJPEGRepresentation(profilePicture, 0.8) var downloadProfilePictureURL = String() uploadProfilePictureRef.putData(profilePictureData!, metadata: nil) { (metaData,error) in if let error = error { print(error.localizedDescription) return } else { downloadProfilePictureURL = metaData!.downloadURL()!.absoluteString self.REF_USERS.child(uid).updateChildValues(["name": fullname, "username": username, "bioDescription": bioDescription, "profilePicture": downloadProfilePictureURL]) } completion(true) } } } }
51.946701
415
0.499536
461e87a3aa54ef95405dd217af25cee707dbf5d9
925
// // HomeAPI.swift // TextDemo // // Created by Andylau on 2018/9/27. // Copyright © 2018年 Andylau. All rights reserved. // import Foundation import Moya // 首页模块接口 let LCHomeProvider = MoyaProvider<HomeApi>() enum HomeApi { case recommedList case recommedAdList } extension HomeApi: TargetType { var baseURL: URL { return URL(string: "xxx")! } var path: String { switch self { case .recommedAdList: return "xxx" default: return "xxx" } } var method: Moya.Method { return .get } var sampleData: Data { return "{}".data(using: String.Encoding.utf8)! } var task: Task { let parmeters = [String:Any]() return .requestParameters(parameters: parmeters, encoding: URLEncoding.default) } var headers: [String : String]? { return nil } }
17.45283
87
0.570811
4be612f2df103a52ff06469be2ad80e2bcea419b
735
// // UIInterfaceOrientation+VideoOrientation.swift // FrontCamera // // Created by laprasDrum on 2019/02/14. // Copyright © 2019 calap. All rights reserved. // import UIKit import AVFoundation extension UIInterfaceOrientation { var videoOrientation: AVCaptureVideoOrientation { print("\(String(describing: UIApplication.shared.statusBarOrientation.rawValue))") switch self { case .unknown, .portrait: return .portrait case .portraitUpsideDown: return .portraitUpsideDown case .landscapeLeft: return .landscapeLeft case .landscapeRight: return .landscapeRight @unknown default: fatalError() } } }
25.344828
90
0.64898
4a57102a48609c27d86c05ede85aec2dcf1c97de
972
extension Optional: Parser where Wrapped: Parser { public func parse(_ input: inout Wrapped.Input) rethrows -> Wrapped.Output? { guard let self = self else { return nil } return try self.parse(&input) } } extension Parsers { /// A parser that attempts to run a given void parser, succeeding with void. /// /// You will not typically need to interact with this type directly. Instead you will usually use /// `if` statements in parser builder blocks: /// /// ```swift /// Parse { /// "Hello" /// if useComma { /// "," /// } /// " " /// Rest() /// } /// ``` public struct OptionalVoid<Wrapped: Parser>: Parser where Wrapped.Output == Void { let wrapped: Wrapped? public init(wrapped: Wrapped?) { self.wrapped = wrapped } public func parse(_ input: inout Wrapped.Input) rethrows { guard let wrapped = self.wrapped else { return } try wrapped.parse(&input) } } }
23.707317
99
0.608025
bb5cef0c9a059c7c72f585148c52db8ecd8e9d5f
505
// // UIApplication+StatusBar.swift // FZBuildingBlock // // Created by FranZhou on 2019/8/5. // import Foundation extension FZBuildingBlockWrapper where Base: UIApplication { /// statusBarHeight public var statusBarHeight: CGFloat { get { return base.statusBarFrame.height } } /// 状态栏旋转菊花是否展示 /// /// - Parameter visible: visible public func networkActivity(visible: Bool) { base.isNetworkActivityIndicatorVisible = visible } }
18.703704
60
0.651485
38d2b592237d764f9b1be0c2e69152f26eb50246
774
// // Copyright 2022 Felipe Joglar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI @main struct TaskodoroApp: App { var body: some Scene { WindowGroup { TasksUIComposer.makeTasksScreen() } } }
27.642857
76
0.692506
1e65ac11e35e6a3fff7a09dc8aa563606c6a41b3
1,238
// // IQKeyboardManagerConstantsInternal.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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
49.52
80
0.771405
eda419e2b38e8485d738e9ebf17b732d9f934b0e
578
// // AppDelegate.swift // FastlneIOS // // Created by Remi Robert on 17/11/15. // Copyright © 2015 Remi Robert. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let navigationBar = UINavigationBar.appearance() navigationBar.barStyle = .Black navigationBar.tintColor = UIColor(white: 0, alpha: 0.6) return true } }
23.12
127
0.704152
f4d92e8fcdc0a8e44534c35312ac512281bcd1c3
4,163
// // SynthStyleKit.swift // AnalogSynthX // // Created by Matthew Fecher on 1/9/16. // Copyright (c) 2016 AudioKit. All rights reserved. import UIKit public class SynthStyleKit: NSObject { //// Drawing Methods public class func drawKnobMedium(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob140_base = UIImage(named: "knob140_base.png")! let knob140_indicator = UIImage(named: "knob140_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// knob base Drawing let knobBasePath = UIBezierPath(rect: CGRect(x: 5, y: 5, width: 70, height: 70)) CGContextSaveGState(context) knobBasePath.addClip() knob140_base.drawInRect(CGRectMake(5, 5, knob140_base.size.width, knob140_base.size.height)) CGContextRestoreGState(context) //// Indicator Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 40, 40) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let indicatorPath = UIBezierPath(rect: CGRect(x: -35, y: -35, width: 70, height: 70)) CGContextSaveGState(context) indicatorPath.addClip() knob140_indicator.drawInRect(CGRectMake(-35, -35, knob140_indicator.size.width, knob140_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } public class func drawKnobLarge(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob212_base = UIImage(named: "knob212_base.png")! let knob212_indicator = UIImage(named: "knob212_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// Picture Drawing let picturePath = UIBezierPath(rect: CGRect(x: 10, y: 10, width: 106, height: 106)) CGContextSaveGState(context) picturePath.addClip() knob212_base.drawInRect(CGRectMake(10, 10, knob212_base.size.width, knob212_base.size.height)) CGContextRestoreGState(context) //// Picture 2 Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 63, 63) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let picture2Path = UIBezierPath(rect: CGRect(x: -53, y: -53, width: 106, height: 106)) CGContextSaveGState(context) picture2Path.addClip() knob212_indicator.drawInRect(CGRectMake(-53, -53, knob212_indicator.size.width, knob212_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } public class func drawKnobSmall(knobValue knobValue: CGFloat = 0.332) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Image Declarations let knob120_base = UIImage(named: "knob120_base.png")! let knob120_indicator = UIImage(named: "knob120_indicator.png")! //// Variable Declarations let knobAngle: CGFloat = -240 * knobValue //// Picture Drawing let picturePath = UIBezierPath(rect: CGRect(x: 5, y: 5, width: 60, height: 60)) CGContextSaveGState(context) picturePath.addClip() knob120_base.drawInRect(CGRectMake(5, 5, knob120_base.size.width, knob120_base.size.height)) CGContextRestoreGState(context) //// Indicator Drawing CGContextSaveGState(context) CGContextTranslateCTM(context, 35, 35) CGContextRotateCTM(context, -(knobAngle + 120) * CGFloat(M_PI) / 180) let indicatorPath = UIBezierPath(rect: CGRect(x: -30, y: -30, width: 60, height: 60)) CGContextSaveGState(context) indicatorPath.addClip() knob120_indicator.drawInRect(CGRectMake(-30, -30, knob120_indicator.size.width, knob120_indicator.size.height)) CGContextRestoreGState(context) CGContextRestoreGState(context) } }
37.504505
119
0.67043
71d63eb429fee459e9b72991d942119f303f7294
26,974
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /// A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts. /// /// Its behavior differs subtly from the `URL` struct, which conforms to older RFCs. However, you can easily obtain a `URL` based on the contents of a `URLComponents` or vice versa. public struct URLComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing { public typealias ReferenceType = NSURLComponents internal var _handle: _MutableHandle<NSURLComponents> /// Initialize with all components undefined. public init() { _handle = _MutableHandle(adoptingReference: NSURLComponents()) } /// Initialize with the components of a URL. /// /// If resolvingAgainstBaseURL is `true` and url is a relative URL, the components of url.absoluteURL are used. If the url string from the URL is malformed, nil is returned. public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) { guard let result = NSURLComponents(url: url, resolvingAgainstBaseURL: resolve) else { return nil } _handle = _MutableHandle(adoptingReference: result) } /// Initialize with a URL string. /// /// If the URLString is malformed, nil is returned. public init?(string: String) { guard let result = NSURLComponents(string: string) else { return nil } _handle = _MutableHandle(adoptingReference: result) } /// Returns a URL created from the URLComponents. /// /// If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var url: URL? { return _handle.map { $0.url } } /// Returns a URL created from the URLComponents relative to a base URL. /// /// If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public func url(relativeTo base: URL?) -> URL? { return _handle.map { $0.url(relativeTo: base) } } // Returns a URL string created from the URLComponents. If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var string: String? { return _handle.map { $0.string } } /// The scheme subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// Attempting to set the scheme with an invalid scheme string will cause an exception. public var scheme: String? { get { return _handle.map { $0.scheme } } set { _applyMutation { $0.scheme = newValue } } } /// The user subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// /// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. public var user: String? { get { return _handle.map { $0.user } } set { _applyMutation { $0.user = newValue } } } /// The password subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// /// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. public var password: String? { get { return _handle.map { $0.password } } set { _applyMutation { $0.password = newValue } } } /// The host subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var host: String? { get { return _handle.map { $0.host } } set { _applyMutation { $0.host = newValue } } } /// The port subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// Attempting to set a negative port number will cause a fatal error. public var port: Int? { get { return _handle.map { $0.port?.intValue } } set { _applyMutation { $0.port = newValue != nil ? NSNumber(value: newValue!) : nil as NSNumber?} } } /// The path subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var path: String { get { return _handle.map { $0.path } ?? "" } set { _applyMutation { $0.path = newValue } } } /// The query subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var query: String? { get { return _handle.map { $0.query } } set { _applyMutation { $0.query = newValue } } } /// The fragment subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var fragment: String? { get { return _handle.map { $0.fragment } } set { _applyMutation { $0.fragment = newValue } } } /// The user subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlUserAllowed`). public var percentEncodedUser: String? { get { return _handle.map { $0.percentEncodedUser } } set { _applyMutation { $0.percentEncodedUser = newValue } } } /// The password subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPasswordAllowed`). public var percentEncodedPassword: String? { get { return _handle.map { $0.percentEncodedPassword } } set { _applyMutation { $0.percentEncodedPassword = newValue } } } /// The host subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlHostAllowed`). public var percentEncodedHost: String? { get { return _handle.map { $0.percentEncodedHost } } set { _applyMutation { $0.percentEncodedHost = newValue } } } /// The path subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPathAllowed`). public var percentEncodedPath: String { get { return _handle.map { $0.percentEncodedPath } ?? "" } set { _applyMutation { $0.percentEncodedPath = newValue } } } /// The query subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlQueryAllowed`). public var percentEncodedQuery: String? { get { return _handle.map { $0.percentEncodedQuery } } set { _applyMutation { $0.percentEncodedQuery = newValue } } } /// The fragment subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlFragmentAllowed`). public var percentEncodedFragment: String? { get { return _handle.map { $0.percentEncodedFragment } } set { _applyMutation { $0.percentEncodedFragment = newValue } } } private func _toStringRange(_ r : NSRange) -> Range<String.Index>? { guard r.location != NSNotFound else { return nil } let utf16Start = String.UTF16View.Index(encodedOffset: r.location) let utf16End = String.UTF16View.Index(encodedOffset: r.location + r.length) guard let s = self.string else { return nil } guard let start = String.Index(utf16Start, within: s) else { return nil } guard let end = String.Index(utf16End, within: s) else { return nil } return start..<end } /// Returns the character range of the scheme in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfScheme: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfScheme }) } /// Returns the character range of the user in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfUser: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfUser}) } /// Returns the character range of the password in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPassword: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPassword}) } /// Returns the character range of the host in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfHost: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfHost}) } /// Returns the character range of the port in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPort: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPort}) } /// Returns the character range of the path in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPath: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPath}) } /// Returns the character range of the query in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfQuery: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfQuery}) } /// Returns the character range of the fragment in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfFragment: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfFragment}) } /// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string. /// /// Each `URLQueryItem` represents a single key-value pair, /// /// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the `URLComponents` has an empty query component, returns an empty array. If the `URLComponents` has no query component, returns nil. /// /// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. Passing an empty array sets the query component of the `URLComponents` to an empty string. Passing nil removes the query component of the `URLComponents`. /// /// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value. public var queryItems: [URLQueryItem]? { get { return _handle.map { $0.queryItems } } set { _applyMutation { $0.queryItems = newValue } } } public var hashValue: Int { return _handle.map { $0.hash } } // MARK: - Bridging fileprivate init(reference: NSURLComponents) { _handle = _MutableHandle(reference: reference) } public static func ==(lhs: URLComponents, rhs: URLComponents) -> Bool { // Don't copy references here; no one should be storing anything return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference()) } } extension URLComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { if let u = url { return u.description } else { return self.customMirror.children.reduce("") { $0.appending("\($1.label ?? ""): \($1.value) ") } } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] if let s = self.scheme { c.append((label: "scheme", value: s)) } if let u = self.user { c.append((label: "user", value: u)) } if let pw = self.password { c.append((label: "password", value: pw)) } if let h = self.host { c.append((label: "host", value: h)) } if let p = self.port { c.append((label: "port", value: p)) } c.append((label: "path", value: self.path)) if #available(macOS 10.10, iOS 8.0, *) { if let qi = self.queryItems { c.append((label: "queryItems", value: qi )) } } if let f = self.fragment { c.append((label: "fragment", value: f)) } let m = Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) return m } } /// A single name-value pair, for use with `URLComponents`. public struct URLQueryItem : ReferenceConvertible, Hashable, Equatable { public typealias ReferenceType = NSURLQueryItem fileprivate var _queryItem : NSURLQueryItem public init(name: String, value: String?) { _queryItem = NSURLQueryItem(name: name, value: value) } fileprivate init(reference: NSURLQueryItem) { _queryItem = reference.copy() as! NSURLQueryItem } fileprivate var reference : NSURLQueryItem { return _queryItem } public var name: String { get { return _queryItem.name } set { _queryItem = NSURLQueryItem(name: newValue, value: value) } } public var value: String? { get { return _queryItem.value } set { _queryItem = NSURLQueryItem(name: name, value: newValue) } } public var hashValue: Int { return _queryItem.hash } public static func ==(lhs: URLQueryItem, rhs: URLQueryItem) -> Bool { return lhs._queryItem.isEqual(rhs._queryItem) } } extension URLQueryItem : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { if let v = value { return "\(name)=\(v)" } else { return name } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "name", value: name)) c.append((label: "value", value: value as Any)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } extension NSURLComponents : _SwiftBridgeable { typealias SwiftType = URLComponents internal var _swiftObject: SwiftType { return URLComponents(reference: self) } } extension URLComponents : _NSBridgeable { typealias NSType = NSURLComponents internal var _nsObject: NSType { return _handle._copiedReference() } } extension NSURLQueryItem : _SwiftBridgeable { typealias SwiftType = URLQueryItem internal var _swiftObject: SwiftType { return URLQueryItem(reference: self) } } extension URLQueryItem : _NSBridgeable { typealias NSType = NSURLQueryItem internal var _nsObject: NSType { return _queryItem } } extension URLComponents : _ObjectTypeBridgeable { public typealias _ObjectType = NSURLComponents public static func _getObjectiveCType() -> Any.Type { return NSURLComponents.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSURLComponents { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) -> Bool { result = URLComponents(reference: x) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLComponents?) -> URLComponents { var result: URLComponents? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension URLQueryItem : _ObjectTypeBridgeable { public typealias _ObjectType = NSURLQueryItem public static func _getObjectiveCType() -> Any.Type { return NSURLQueryItem.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSURLQueryItem { return _queryItem } public static func _forceBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) -> Bool { result = URLQueryItem(reference: x) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLQueryItem?) -> URLQueryItem { var result: URLQueryItem? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension URLComponents : Codable { private enum CodingKeys : Int, CodingKey { case scheme case user case password case host case port case path case query case fragment } public init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) self.scheme = try container.decodeIfPresent(String.self, forKey: .scheme) self.user = try container.decodeIfPresent(String.self, forKey: .user) self.password = try container.decodeIfPresent(String.self, forKey: .password) self.host = try container.decodeIfPresent(String.self, forKey: .host) self.port = try container.decodeIfPresent(Int.self, forKey: .port) self.path = try container.decode(String.self, forKey: .path) self.query = try container.decodeIfPresent(String.self, forKey: .query) self.fragment = try container.decodeIfPresent(String.self, forKey: .fragment) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.scheme, forKey: .scheme) try container.encodeIfPresent(self.user, forKey: .user) try container.encodeIfPresent(self.password, forKey: .password) try container.encodeIfPresent(self.host, forKey: .host) try container.encodeIfPresent(self.port, forKey: .port) try container.encode(self.path, forKey: .path) try container.encodeIfPresent(self.query, forKey: .query) try container.encodeIfPresent(self.fragment, forKey: .fragment) } }
54.383065
526
0.69048
87713b76dc0d3d1e69e461f42f1cc33998700d80
224
// // RedditPicsModel+Children.swift // RedditPics // // Created by Banerjee,Subhodip on 28/05/19. // Copyright © 2019 Banerjee,Subhodip. All rights reserved. // struct Children: Decodable{ let data: ChildrenData }
18.666667
60
0.709821
75ad406af410f6198d08172956c59e73ca0562a8
271
// // CircularProgressBarApp.swift // CircularProgressBar // // Created by Aravind Chowdary Kamani on 07/03/22. // import SwiftUI @main struct CircularProgressBarApp: App { var body: some Scene { WindowGroup { ContentView() } } }
15.055556
51
0.627306
39eb0b46f7bdd62a4ad4a5b8de4b40f9e9ff5e17
1,074
// // STTestBridge.swift // SwiftlyReachable // // Created by Rick Windham on 2/4/15. // Copyright (c) 2015 SwiftTime. All rights reserved. // import Foundation import SystemConfiguration typealias changeBlock = ((UInt32) -> Void) func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } class STReachabilityBridge { var monitoring:Bool = false var target:SCNetworkReachability! var block:changeBlock! init(target:SCNetworkReachability, andBlock block:changeBlock) { println("statusFlags \(statusFlags)") self.block = block } deinit { println("*** bridge de-init ***") } func startMonitoring() -> Bool { delay(2.0) {self.block(statusFlags)} return true } func stopMonitoring() { monitoring = false } func getStatus() -> UInt32 { return statusFlags } }
21.48
68
0.602421
d789ebe25cef996c7e052029b0dc3b77ed8148f8
660
// // NSURLTests.swift // MyApp // // Created by iOSTeam on 2/21/18. // Copyright © 2018 Asian Tech Co., Ltd. All rights reserved. // import XCTest import SwiftUtils @testable import MyApp final class NSURLTests: XCTestCase { func testInit() { for code in 100..<600 { guard let status = HTTPStatus(code: code) else { continue } XCTAssertEqual(status.code, code) XCTAssertGreaterThan(status.description.count, 0) let error = NSError(status: status) XCTAssertEqual(error.code, status.code) XCTAssertEqual(error.localizedDescription, status.description) } } }
25.384615
74
0.639394
9bc8ff0f907cce547261a25ff9933173d9ea4be2
10,865
// // ViewController.swift // Trivia Assist // // Created by Fedor Paretsky on 4/2/18. // Copyright © 2018 f3d0r. All rights reserved. // import Cocoa import Alamofire import SwiftyJSON import AppKit let API_KEY = "SOME_API_KEY" let SEARCH_API_KEY = "SOME_OTHER_API_KEY" //Coordinates of parts of screen in format [x, y, width, height] let questionCoords = [40, 170, 305, 150] let optionOneCoords = [35, 325, 330, 57] let optionTwoCoords = [35, 385, 330, 57] let optionThreeCoords = [35, 443, 330, 57] class ViewController: NSViewController { @IBOutlet weak var questionField: NSTextField! @IBOutlet weak var optionOneField: NSTextField! @IBOutlet weak var optionOneResultText: NSTextField! @IBOutlet weak var optionTwoField: NSTextField! @IBOutlet weak var optionTwoResultText: NSTextField! @IBOutlet weak var optionThreeField: NSTextField! @IBOutlet weak var optionThreeResultText: NSTextField! @IBOutlet weak var clearButton: NSButton! @IBOutlet weak var testConnectionButton: NSButton! @IBOutlet weak var saveCurrentButton: NSButton! @IBOutlet weak var statusLabel: NSTextField! @IBOutlet weak var justScanButton: NSButton! @IBOutlet weak var justAnalyzeButton: NSButton! @IBOutlet weak var scanAndAnalyzeButton: NSButton! override func viewDidLoad() { super.viewDidLoad() optionOneResultText.stringValue = "----" optionTwoResultText.stringValue = "----" optionThreeResultText.stringValue = "----" } override var representedObject: Any? { didSet { } } @IBAction func clearFields(_ sender: Any) { clearAll() } func clearAll() { questionField.stringValue = "" optionOneField.stringValue = "" optionTwoField.stringValue = "" optionThreeField.stringValue = "" optionOneResultText.stringValue = "----" optionTwoResultText.stringValue = "----" optionThreeResultText.stringValue = "----" optionOneResultText.textColor = NSColor.gray optionTwoResultText.textColor = NSColor.gray optionThreeResultText.textColor = NSColor.gray } @IBAction func testConnection(_ sender: Any) { Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in switch response.result { case .success: self.testConnectionButton.title = "Status: OK" DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.testConnectionButton.title = "Test Connection (OK)" }) case .failure: self.testConnectionButton.title = "Status: ERROR" DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.testConnectionButton.title = "Test Connection (ERROR)" }) } } } @IBAction func saveCurrent(_ sender: Any) { } @IBAction func justScan(_ sender: Any) { clearAll() fillFields() } @IBAction func scanAndAnalyze(_ sender: Any) { findQuestion(formattedQuestion: questionField.stringValue, optionOne: optionOneField.stringValue, optionTwo: optionTwoField.stringValue, optionThree: optionThreeField.stringValue) { (optionOneCount, optionTwoCount, optionThreeCount) in let one = Int(optionOneCount) let two = Int(optionTwoCount) let three = Int(optionThreeCount) self.optionOneResultText.stringValue = String(one) self.optionTwoResultText.stringValue = String(two) self.optionThreeResultText.stringValue = String(three) var oneGreen = false var twoGreen = false var threeGreen = false if (one < two) { if (one < three) { if (two < three) { threeGreen = true } else { twoGreen = true threeGreen = true } } else { twoGreen = true } } else { if (two < three) { if (one < three) { threeGreen = true } else { oneGreen = true threeGreen = true } } else { } } if (oneGreen) { self.optionOneResultText.textColor = NSColor.green } else { self.optionOneResultText.textColor = NSColor.red } if (twoGreen) { self.optionTwoResultText.textColor = NSColor.green } else { self.optionTwoResultText.textColor = NSColor.red } if (threeGreen) { self.optionThreeResultText.textColor = NSColor.green } else { self.optionThreeResultText.textColor = NSColor.red } } } func findQuestion(formattedQuestion: String, optionOne: String, optionTwo: String, optionThree: String, completionHandler: @escaping (Int, Int, Int) -> ()) { let url = "https://www.google.com/search?q=" + formattedQuestion.replacingOccurrences(of: " ", with: "+") if let finalURL = URL(string: url), NSWorkspace.shared.open(finalURL) { print("default browser was successfully opened") } Alamofire.request(url).responseString { response in let parsedString = (response.result.value!).replacingOccurrences(of: "<[^>]+>", with: "", options: String.CompareOptions.regularExpression, range: nil) completionHandler(self.substringCount(searchString: parsedString, searchTerm: optionOne), self.substringCount(searchString: parsedString, searchTerm: optionTwo), self.substringCount(searchString: parsedString, searchTerm: optionThree)) } } func saveScreenShot(coords: [Int]) -> String { var displayCount: UInt32 = 0; let result = CGGetActiveDisplayList(0, nil, &displayCount) if (result != CGError.success) { print("error: \(result)") } let allocated = Int(displayCount) let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated) if (result != CGError.success) { print("error: \(result)") } let questionRect = CGRect(x: coords[0], y: coords[1], width: coords[2], height: coords[3]) let questionScreenshot:CGImage = CGDisplayCreateImage(activeDisplays[Int(0)],rect: questionRect)! let questionBitmap = NSBitmapImageRep(cgImage: questionScreenshot) let data = questionBitmap.representation(using: NSBitmapImageRep.FileType.png, properties: [:])! return data.base64EncodedString(); } func ocrImage(bitmap: String, completionHandler: @escaping (Bool, String?) -> ()) { var ocrText = String() let url = "https://vision.googleapis.com/v1/images:annotate?key=" + API_KEY let parameters: Parameters = [ "requests": [ "image": [ "content": bitmap ], "features": [ "type": "TEXT_DETECTION", ] ] ] Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in switch response.result { case .success(let value): var json = JSON(value) ocrText = json["responses"][0]["fullTextAnnotation"]["text"].stringValue ocrText = ocrText.replacingOccurrences(of: "\n", with: " ") ocrText = ocrText.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) completionHandler(true, ocrText) case .failure: completionHandler(false, nil) } } } func fillFields() { let questionBitmap = saveScreenShot(coords: questionCoords) ocrImage(bitmap: questionBitmap) { (success, ocrText) in if success { self.questionField.stringValue = self.phraseQuestion(question: String(ocrText!)) } else { self.questionField.stringValue = "error" } } let optionOneBitmap = saveScreenShot(coords: optionOneCoords) ocrImage(bitmap: optionOneBitmap) { (success, ocrText) in if success { self.optionOneField.stringValue = String(ocrText!) } else { self.optionOneField.stringValue = "error" } } let optionTwoBitmap = saveScreenShot(coords: optionTwoCoords) ocrImage(bitmap: optionTwoBitmap) { (success, ocrText) in if success { self.optionTwoField.stringValue = String(ocrText!) } else { self.optionTwoField.stringValue = "error" } } let optionThreeBitmap = saveScreenShot(coords: optionThreeCoords) ocrImage(bitmap: optionThreeBitmap) { (success, ocrText) in if success { self.optionThreeField.stringValue = String(ocrText!) } else { self.optionThreeField.stringValue = "error" } } } func phraseQuestion(question: String) -> String { let stringToArray = question.components(separatedBy: " ") let wordsToRemove = ["what", "which", "is", "the", "a", "of", "these", "has", "are", "in", "for"] var finalString = "" for currentWord in stringToArray { var removed = false for removedWord in wordsToRemove { if(currentWord.caseInsensitiveCompare(removedWord) == ComparisonResult.orderedSame){ removed = true } } if (!removed) { finalString += (currentWord + " ") } } finalString = finalString.replacingOccurrences(of: "\"", with: "") finalString = finalString.replacingOccurrences(of: "?", with: "") return finalString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } func substringCount(searchString: String, searchTerm: String) -> Int { let searchStringMutable = searchString.lowercased() let searchTermMutable = searchTerm.lowercased() let tok = searchStringMutable.components(separatedBy:searchTermMutable) print(tok.count - 1) return tok.count - 1 } }
38.803571
247
0.581592
208beff671b69e4acda4543a7a5e4425cbf7ccf9
2,300
// // zrxkitTests.swift // zrxkitTests // // Created by Abai Abakirov on 12/5/19. // Copyright © 2019 BlocksDecoded. All rights reserved. // import XCTest import zrxkit import Web3 class zrxkitTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testOrderSign() { let privateKey = try! EthereumPrivateKey(hexPrivateKey: "26A5D2061D8D958ADF0B3A0BBD1A58338BC11865BE26B27B56256FE13732E090") XCTAssertEqual("0xe2507b493bef003030f0a053d55af80237a44c64", privateKey.address.hex(eip55: true).lowercased()) let order = Order( chainId: 3, exchangeAddress: "0x35dd2932454449b14cee11a94d3674a936d5d7b2", makerAssetData: "0xf47261b00000000000000000000000002002d3812f58e35f0ea1ffbf80a75a38c32175fa", takerAssetData: "0xf47261b0000000000000000000000000d0a1e359811322d97991e03f863a0c30c2cf029c", makerAssetAmount: "10000000000000000000", takerAssetAmount: "10000000000000000", makerAddress: "0xe2507b493bef003030f0a053d55af80237a44c64", takerAddress: "0x0000000000000000000000000000000000000000", expirationTimeSeconds: "1561628788", senderAddress: "0x0000000000000000000000000000000000000000", feeRecipientAddress: "0xa258b39954cef5cb142fd567a46cddb31a670124", makerFee: "0", makerFeeAssetData: "0x", takerFee: "0", takerFeeAssetData: "0x", salt: "1561542388954" ) let signedOrder = SignUtils().ecSignOrder(order, privateKey) XCTAssertEqual(signedOrder?.signature, "0x1cf1bf46f7b255f15a00100317e60da98da5b2f14e554cc2e28d8393bf7bbbb3f65879afa3337c8f16edb88419f43064d6de8862764f8ede7f2a0f9acc35f140c802") } func testPerformanceExample() { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } }
34.848485
180
0.729565
e9faa2c8c44495463bdf313da3fa99e9ee1df296
412
// // PerformanceViewController.swift // Sirius_Example // // Created by hongru on 2019/6/12. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit class PerformanceViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white // Do any additional setup after loading the view. } }
17.913043
58
0.67233
671be2b5dac13569bf299d5e3c7a96fbf7f9505e
1,228
import ArgumentParser import SwiftFusion import BeeDataset import BeeTracking import TensorFlow import PythonKit import Foundation import PenguinStructures /// Brando11: compute the mean displacement struct Brando11: ParsableCommand { @Option(help: "Run for number of frames") var trackLength: Int = 80 func run() { let np = Python.import("numpy") let plt = Python.import("matplotlib.pyplot") let trainingDatasetSize = 100 // LOAD THE IMAGE AND THE GROUND TRUTH ORIENTED BOUNDING BOX let dataDir = URL(fileURLWithPath: "./OIST_Data") let data = OISTBeeVideo(directory: dataDir, afterIndex: trainingDatasetSize, length: trackLength)! var dX = [Double]() var dY = [Double]() var dTheta = [Double]() for track in data.tracks { var prevObb: OrientedBoundingBox? prevObb = nil for obb in track.boxes { if prevObb == nil { prevObb = obb } else { dX.append(obb.center.t.x - (prevObb)!.center.t.x) dY.append(obb.center.t.y - (prevObb)!.center.t.y) dTheta.append(obb.center.rot.theta - (prevObb)!.center.rot.theta) } } } // Plot histogram. } }
28.55814
102
0.632736
2127eac6a5c9c4f135ea4663dab6f06681fe3169
3,051
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // -------------------------------------------------------------------------- import AzureCore import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length // swiftlint:disable type_body_length public final class AutoRestDateTimeTestClient: PipelineClient { /// API version of the to invoke. Defaults to the latest. public enum ApiVersion: RequestStringConvertible { /// Custom value for unrecognized enum values case custom(String) /// API version "" case v /// The most recent API version of the public static var latest: ApiVersion { return .v } public var requestString: String { switch self { case let .custom(val): return val case .v: return "" } } public init(_ val: String) { switch val.lowercased() { case "": self = .v default: self = .custom(val) } } } /// Options provided to configure this `AutoRestDateTimeTestClient`. public let options: AutoRestDateTimeTestClientOptions // MARK: Initializers /// Create a AutoRestDateTimeTestClient client. /// - Parameters: /// - endpoint: Base URL for the AutoRestDateTimeTestClient. /// - authPolicy: An `Authenticating` policy to use for authenticating client requests. /// - options: Options used to configure the client. public init( url: URL? = nil, authPolicy: Authenticating, withOptions options: AutoRestDateTimeTestClientOptions ) throws { let defaultHost = URL(string: "http://localhost:3000") guard let endpoint = url ?? defaultHost else { fatalError("Unable to determine base URL. ") } self.options = options super.init( endpoint: endpoint, transport: options.transportOptions.transport ?? URLSessionTransport(), policies: [ UserAgentPolicy(for: AutoRestDateTimeTestClient.self, telemetryOptions: options.telemetryOptions), RequestIdPolicy(), AddDatePolicy(), authPolicy, ContentDecodePolicy(), LoggingPolicy(), NormalizeETagPolicy() ], logger: options.logger, options: options ) } public lazy var datetime = Datetime(client: self) // MARK: Public Client Methods }
33.163043
114
0.580793
160de68b7cbea0ecb1e1434318560d6d9db505d3
3,068
// // Splitter.swift // Split // // Created by Natalia Stele on 11/7/17. // import Foundation public protocol SplitterProtocol { func getTreatment(key: Key, seed: Int, attributes:[String:Any]?, partions: [Partition]?, algo: Int) -> String func getBucket(seed: Int,key: String ,algo: Int) -> Int } public class Splitter: SplitterProtocol { public static let ALGO_LEGACY: Int = 1 public static let ALGO_MURMUR: Int = 2 //------------------------------------------------------------------------------------------------------------------ public static let shared: Splitter = { let instance = Splitter(); return instance; }() //------------------------------------------------------------------------------------------------------------------ public func getTreatment(key: Key, seed: Int, attributes: [String : Any]?, partions: [Partition]?, algo: Int) -> String { var accumulatedSize: Int = 0 Logger.d("Splitter evaluating partitions ... \n") let bucket: Int = getBucket(seed: seed, key: key.bucketingKey! ,algo: algo) Logger.d("BUCKET: \(bucket)") if let splitPartitions = partions { for partition in splitPartitions { Logger.d("PARTITION SIZE \(String(describing: partition.size)) PARTITION TREATMENT: \(String(describing: partition.treatment)) \n") accumulatedSize = accumulatedSize + partition.size! if bucket <= accumulatedSize { Logger.d("TREATMENT RETURNED:\(partition.treatment!)") return partition.treatment! } } } return SplitConstants.CONTROL } //------------------------------------------------------------------------------------------------------------------ public func getBucket(seed: Int, key: String ,algo: Int) -> Int { let hashCode: UInt32 = self.hashCode(seed: seed, key: key, algo: algo) let bucket = (hashCode % 100) + 1 return Int(bucket) } //------------------------------------------------------------------------------------------------------------------ private func hashCode(seed: Int, key: String ,algo: Int) -> UInt32 { switch algo { case Splitter.ALGO_LEGACY: return LegacyHash.getHash(key, UInt32(seed)) case Splitter.ALGO_MURMUR: return Murmur3Hash.hashString(key, UInt32(truncatingIfNeeded: seed)) default: return LegacyHash.getHash(key, UInt32(seed)) } } //------------------------------------------------------------------------------------------------------------------ }
32.638298
147
0.414928
1a155647b8eac93d3403012d7bdb4062a693d07a
3,089
// // DayShapeView.swift // OpenWeatherIos // // Created by Marin Ipati on 03/09/2021. // import UIKit class DayShapeView: UIView { var nightColor: UIColor? { didSet { setNeedsDisplay() } } var daylightColor: UIColor? { didSet { setNeedsDisplay() } } var sunColor: UIColor? { didSet { setNeedsDisplay() } } var strokeColor: UIColor? { didSet { setNeedsDisplay() } } var strokeWidth: CGFloat = 1 { didSet { setNeedsDisplay() } } var indicatorsWidth: CGFloat = 0.33 { didSet { setNeedsDisplay() } } var sunRadius: CGFloat = 10 { didSet { setNeedsDisplay() } } var sunrise: Date { didSet { setNeedsDisplay() } } var sunset: Date { didSet { setNeedsDisplay() } } var current: Date { didSet { setNeedsDisplay() } } var nightPhaseLength: CGFloat { return xPoint(in: shapeRect, withY: 0.0).x } var timeZone: TimeZone = .current { didSet { setNeedsDisplay() } } var calendar: Calendar { var calendar = Calendar.current calendar.timeZone = timeZone return calendar } var startOfDay: Date { return calendar.startOfDay(for: current) } var endOfDay: Date { return startOfDay.addingTimeInterval(86340) } var isInSameDay: Bool { let sunsetIsInSameDay = calendar.isDate(current, inSameDayAs: sunset) let sunriseIsInSameDay = calendar.isDate(current, inSameDayAs: sunrise) return sunsetIsInSameDay && sunriseIsInSameDay } var strength: Double { return Double(shapeRect.height) * 0.5 } let frequency: Double = .pi * 2 let phase: Double = .pi / 2 var offset: Double { return Double(shapeRect.height) * 0.18 } var shapeRect: CGRect { return bounds.inset(by: inset) } lazy private(set) var inset: UIEdgeInsets = { return UIEdgeInsets(top: sunRadius, left: 0, bottom: 0, right: 0) }() init(sunrise: Date, sunset: Date, current: Date) { self.sunrise = sunrise self.sunset = sunset self.current = current super.init(frame: .zero) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } drawFirstNightPhase(in: rect, context: context) drawDaylightPhase(in: rect, context: context) drawSecondNightPhase(in: rect, context: context) drawSunMovePath(in: rect, context: context) drawHorizonLine(in: rect, context: context) drawSunsetSunriseIndicators(in: rect, context: context) drawSun(in: rect, context: context) } }
21.013605
79
0.559728
d787e383b1d36495a242ab0a75432c83697fd2a2
492
import Foundation /// The *script* part of the script, e.g. the stuff that /// runs the komodor runner. /// /// If *this* changes then the template should be updated /// public func renderScriptHeader(_: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium let installDate = dateFormatter.string(from: Date()) return """ #!/bin/sh # Komondor v\(KomondorVersion) # Installed: \(installDate) """ }
23.428571
57
0.632114
5bb145589fe1fabc57a001656bd10a4575d10466
4,911
// // ActionViewController.swift // Behavior Tracker // // Created by Chuchu Jiang on 2/19/19. // Copyright © 2019 adajiang. All rights reserved. // import UIKit class ActionViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var myImageView: UIImageView! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var mealTextField: UITextField! @IBOutlet weak var typeTextField: UITextField! var myImageURL: URL? // Callback method to be defined in parent view controller. var didSaveMeal: ((_ meal: Meal) -> ())? override func viewDidLoad() { super.viewDidLoad() createPickerView() dismissPickerView() let datePicker = UIDatePicker() datePicker.datePickerMode = UIDatePicker.Mode.date datePicker.addTarget(self, action: #selector(ActionViewController.datePickerValueChanged(sender:)), for: UIControl.Event.valueChanged) dateTextField.inputView = datePicker } @objc func datePickerValueChanged(sender:UIDatePicker){ let formatter = DateFormatter() formatter.dateStyle = DateFormatter.Style.medium formatter.timeStyle = DateFormatter.Style.none dateTextField.text = formatter.string(from: sender.date) } //import image button to import image from camera roll, need to add privacy -photo library usage in info.plist @IBAction func handleImportImage(_ sender: UIButton) { let image = UIImagePickerController() image.delegate = self image.sourceType = UIImagePickerController.SourceType.photoLibrary image.allowsEditing = false self.present(image, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage self.myImageView.image = image self.myImageURL = info[UIImagePickerController.InfoKey.imageURL] as? URL self.dismiss(animated: true, completion: nil) } @IBAction func handleSaveButton(_ sender: UIButton) { if typeTextField.text == "Own Meal" { myDatabase.savedPerMeal = myDatabase.costBuyMeal - myDatabase.costGroceries/21 myDatabase.saved += myDatabase.savedPerMeal } /* guard let date = dateTextField.text, let bld = mealTextField.text, let type = typeTextField.text else { return } */ // Pass back data. save imageURL, date, bld, type, add to array let meal = Meal( imageURL: self.myImageURL, date: dateTextField.text ?? "", bld: mealTextField.text ?? "", type: typeTextField.text ?? "") didSaveMeal?(meal) self.dismiss(animated: true, completion: nil) } @IBAction func handleCancelButton(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } //doesnt dismiss???no done button func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Dismisses keyboard when done is pressed. view.endEditing(true) return false } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } //type picker view func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return priorityTypes.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return priorityTypes[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedPriority = priorityTypes[row] typeTextField.text = selectedPriority } var selectedPriority: String? var priorityTypes = ["Own Meal", "Bought Meal"] func createPickerView(){ let pickerView = UIPickerView() pickerView.delegate = self typeTextField.inputView = pickerView } func dismissPickerView(){ let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.dismissKeyboard)) toolBar.setItems([doneButton], animated:false) toolBar.isUserInteractionEnabled = true typeTextField.inputAccessoryView = toolBar } @objc func dismissKeyboard(){ view.endEditing(true) } }
34.104167
178
0.656485
28eb513def29e0c48aa801d4e6b62918d80f5b56
1,658
// // TMDBTVService.swift // TMDB // // Created by Tuyen Le on 10.06.20. // Copyright © 2020 Tuyen Le. All rights reserved. // import Foundation protocol TMDBTVService { func getPopularOnTV(page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getTVShowDetail(id: Int, completion: @escaping (Result<TVShow, Error>) -> Void) func getSimilarTVShows(from tvShowId: Int, page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getRecommendTVShows(from tvShowId: Int, page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getTVShowSeasonDetail(from tvShowId: Int, seasonNumber: Int, completion: @escaping (Result<Season, Error>) -> Void) func getTVShowImages(from tvShowId: Int, completion: @escaping (Result<ImageResult, Error>) -> Void) func getTVShowEpisode(from tvShowId: Int, seasonNumber: Int, episodeNumber: Int, completion: @escaping (Result<Episode, Error>) -> Void) func getTVShowSeasonImage(from tvShowId: Int, seasonNumber: Int, completion: @escaping (Result<ImageResult, Error>) -> Void) func getTVShowEpisodeImage(from tvShowId: Int, seasonNumber: Int, episodeNumber: Int, completion: @escaping (Result<ImageResult, Error>) -> Void) func getTVShowOnTheAir(page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getTVShowAiringToday(page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getTopRatedTVShow(page: Int, completion: @escaping (Result<TVShowResult, Error>) -> Void) func getAllTVShow(query: DiscoverQuery, completion: @escaping (Result<TVShowResult, Error>) -> Void) }
63.769231
149
0.737636
9c615ac43251ef34b77d3b4bbf3da16f1f3703e6
1,314
// // Default+CustomStringConvertible.swift // Networking // // Created by Yauheni Klishevich on 16/09/2019. // Copyright © 2019 YKL. All rights reserved. // import Foundation /** Implementation was borrowed from https://medium.com/@YogevSitton/use-auto-describing-objects-with-customstringconvertible-49528b55f446 */ extension CustomStringConvertible { var description : String { var description: String = "" // Warning is bug: https://bugs.swift.org/browse/SR-7394 if self is AnyObject { let address = Unmanaged.passUnretained(self as AnyObject).toOpaque() description = "<\(type(of: self)): \(address)>" } else { description = "<\(type(of: self))>" } let selfMirror = Mirror(reflecting: self) for (index, child) in selfMirror.children.enumerated() { if index == 0 { description += "{" } if let propertyName = child.label { description += "\(propertyName): \(child.value)" if (index != selfMirror.children.count - 1) { description += ", " } else { description += "}" } } } return description } }
30.55814
135
0.54414
5085dc0b72f88f2652a3fdd87a46106471aeeb1c
228
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension A { enum b { let P { { protocol P { class case ,
17.538462
87
0.736842
71cb12a76569d05272c008fc13ef01f8a8140db5
12,104
// // StereoViewController.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // import UIKit import SceneKit open class StereoViewController: UIViewController, SceneLoadable { #if (arch(arm) || arch(arm64)) && os(iOS) open let device: MTLDevice #endif open var scene: SCNScene? { didSet { _stereoView?.scene = scene } } open var stereoParameters: StereoParametersProtocol = StereoParameters() { didSet { _stereoView?.stereoParameters = stereoParameters } } open var stereoView: StereoView { if !isViewLoaded { loadView() } guard let view = _stereoView else { fatalError("Unexpected context to load stereoView") } return view } open var showsCloseButton: Bool = true { didSet { _closeButton?.isHidden = !showsCloseButton } } open var closeButton: UIButton { if _closeButton == nil { loadCloseButton() } guard let button = _closeButton else { fatalError("Unexpected context to load closeButton") } return button } open var closeButtonHandler: ((_ sender: UIButton) -> Void)? open var showsHelpButton: Bool = false { didSet { _helpButton?.isHidden = !showsHelpButton } } open var helpButton: UIButton { if _helpButton == nil { loadHelpButton() } guard let button = _helpButton else { fatalError("Unexpected context to load helpButton") } return button } open var helpButtonHandler: ((_ sender: UIButton) -> Void)? open var introductionView: UIView? { willSet { introductionView?.removeFromSuperview() } didSet { guard isViewLoaded else { return } if let _ = introductionView { showIntroductionView() } else { hideIntroductionView() } } } private weak var _stereoView: StereoView? private weak var _closeButton: UIButton? private weak var _helpButton: UIButton? private weak var introdutionContainerView: UIView? private var introductionViewUpdateTimer: DispatchSourceTimer? #if (arch(arm) || arch(arm64)) && os(iOS) public init(device: MTLDevice) { self.device = device super.init(nibName: nil, bundle: nil) } #else public init() { super.init(nibName: nil, bundle: nil) } #endif public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func loadView() { #if (arch(arm) || arch(arm64)) && os(iOS) let stereoView = StereoView(device: device) #else let stereoView = StereoView() #endif stereoView.backgroundColor = .black stereoView.scene = scene stereoView.stereoParameters = stereoParameters stereoView.translatesAutoresizingMaskIntoConstraints = false stereoView.isPlaying = false _stereoView = stereoView let introductionContainerView = UIView(frame: stereoView.bounds) introductionContainerView.isHidden = true self.introdutionContainerView = introductionContainerView let view = UIView(frame: stereoView.bounds) view.backgroundColor = .black view.addSubview(stereoView) view.addSubview(introductionContainerView) self.view = view NSLayoutConstraint.activate([ stereoView.topAnchor.constraint(equalTo: view.topAnchor), stereoView.bottomAnchor.constraint(equalTo: view.bottomAnchor), stereoView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stereoView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) if showsCloseButton { loadCloseButton() } if showsHelpButton { loadHelpButton() } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() introdutionContainerView!.bounds = view!.bounds introdutionContainerView!.center = CGPoint(x: view!.bounds.midX, y: view!.bounds.midY) introductionView?.frame = introdutionContainerView!.bounds } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if animated { _stereoView?.alpha = 0 } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _stereoView?.isPlaying = true if animated { UIView.animate(withDuration: 0.2) { self._stereoView?.alpha = 1 } } if UIDevice.current.orientation != .unknown { showIntroductionView(animated: animated) startIntroductionViewVisibilityUpdates() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) _stereoView?.isPlaying = false stopIntroductionViewVisibilityUpdates() } open override var prefersStatusBarHidden: Bool { return true } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscapeRight } private func loadCloseButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-close", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let closeButton = UIButton(type: .system) closeButton.setImage(icon, for: .normal) closeButton.isHidden = !showsCloseButton closeButton.contentVerticalAlignment = .top closeButton.contentHorizontalAlignment = .left closeButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 11, bottom: 0, right: 0) closeButton.translatesAutoresizingMaskIntoConstraints = false _closeButton = closeButton view.addSubview(closeButton) NSLayoutConstraint.activate([ closeButton.widthAnchor.constraint(equalToConstant: 88), closeButton.heightAnchor.constraint(equalToConstant: 88), closeButton.topAnchor.constraint(equalTo: view.topAnchor), closeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) closeButton.addTarget(self, action: #selector(handleTapOnCloseButton(_:)), for: .touchUpInside) } @objc private func handleTapOnCloseButton(_ sender: UIButton) { if let handler = closeButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { presentingViewController?.dismiss(animated: true, completion: nil) } } private func loadHelpButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-help", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let helpButton = UIButton(type: .system) helpButton.setImage(icon, for: .normal) helpButton.isHidden = !showsHelpButton helpButton.contentVerticalAlignment = .top helpButton.contentHorizontalAlignment = .right helpButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 0, bottom: 0, right: 11) helpButton.translatesAutoresizingMaskIntoConstraints = false _helpButton = helpButton view.addSubview(helpButton) NSLayoutConstraint.activate([ helpButton.widthAnchor.constraint(equalToConstant: 88), helpButton.heightAnchor.constraint(equalToConstant: 88), helpButton.topAnchor.constraint(equalTo: view.topAnchor), helpButton.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) helpButton.addTarget(self, action: #selector(handleTapOnHelpButton(_:)), for: .touchUpInside) } @objc private func handleTapOnHelpButton(_ sender: UIButton) { if let handler = helpButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { let url = URL(string: "https://support.google.com/cardboard/answer/6383058")! UIApplication.shared.openURL(url) } } private func showIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let introductionView = introductionView, let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if introductionView.superview != containerView { introductionView.frame = containerView.bounds introductionView.autoresizingMask = [] containerView.addSubview(introductionView) } if animated { if containerView.isHidden { containerView.isHidden = false containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) } UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = .identity stereoView.alpha = 0 }, completion: nil) } else { containerView.isHidden = false containerView.transform = .identity stereoView.alpha = 0 } } private func hideIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) stereoView.alpha = 1 }, completion: { isFinished in guard isFinished else { return } containerView.isHidden = true containerView.transform = .identity }) } else { containerView.isHidden = true containerView.transform = .identity stereoView.alpha = 1 } } private func startIntroductionViewVisibilityUpdates(withInterval interval: TimeInterval = 3, afterDelay delay: TimeInterval = 3) { precondition(introductionViewUpdateTimer == nil) let timer = DispatchSource.makeTimerSource(queue: .main) timer.scheduleRepeating(deadline: .now() + delay, interval: interval) timer.setEventHandler { [weak self] in guard self?.isViewLoaded == true, let _ = self?.introductionView else { return } switch UIDevice.current.orientation { case .landscapeLeft where self?.introdutionContainerView?.isHidden == false: self?.hideIntroductionView(animated: true) case .landscapeRight where self?.introdutionContainerView?.isHidden == true: self?.showIntroductionView(animated: true) default: break } } timer.resume() introductionViewUpdateTimer = timer } private func stopIntroductionViewVisibilityUpdates() { introductionViewUpdateTimer?.cancel() introductionViewUpdateTimer = nil } } extension StereoViewController: ImageLoadable {} #if (arch(arm) || arch(arm64)) && os(iOS) extension StereoViewController: VideoLoadable {} #endif
32.106101
136
0.614508
c14f57a90063161bd3b61b0fafa005765183e8da
1,041
// // TitleItemController.swift // SlideController // // Created by Evgeny Dedovets on 4/17/17. // Copyright © 2017 Touchlane LLC. All rights reserved. // import UIKit class TitleItemController<T>: TitleItemControllableObject where T: TitleItemObject, T: UIView { private var item = T() typealias Item = T.Item // MARK: - InitializableImplementation required init() { } // MARK: - ItemViewableImplementation var view: Item { return item.view } // MARK: - SelectableImplementation var isSelected: Bool { get { return item.isSelected } set { item.isSelected = newValue } } var didSelectAction: ((Int) -> ())? { get { return item.didSelectAction } set { item.didSelectAction = newValue } } var index: Int { get { return item.index } set { item.index = newValue } } }
19.277778
95
0.532181
ded7cd132576ec57446841abdc23d6eaccf90ef2
741
// // MainPresenter.swift // SwiftyPick // // Created by Manu Herrera on 09/09/2021. // import UIKit /// MainPresenting protocol used in the VC to communicate with the Presenter. protocol MainPresenting: AnyObject { /// Returns the current palette stored in user defaults func getCurrentPalette() -> UIColor.Palette } /// MainPresenter: presenter to be used by the MainViewController final class MainPresenter: BasePresenter, MainPresenting { /// Method to get the current palette of the app /// - Returns: the palette stored in user defaults as the current one selected func getCurrentPalette() -> UIColor.Palette { // Future Improvement: Grab the palette from user defaults return .flashy } }
29.64
82
0.720648
ddb43b58732dec7cb8ae1b65a666b07c7d6f610e
1,567
// // FileWriter.swift // MEADepthCamera // // Created by Will on 7/23/21. // import Foundation import OSLog // MARK: FileWriter /// Protocol for all file writer types. protocol FileWriter: AnyObject, NameDescribable { /// The output type of the file being written to. var outputType: OutputType { get } /// The URL that the file is written to. var fileURL: URL { get } } extension FileWriter { /// Creates and returns a URL in the specified folder for a file whose name and extension is determined by the specified `OutputType`. static func createFileURL(in folderURL: URL, outputType: OutputType) -> URL { let folderName = folderURL.lastPathComponent let fileName = folderName + "_" + outputType.rawValue let fileURL = folderURL.appendingPathComponent(fileName).appendingPathExtension(outputType.fileExtension) return fileURL } } // MARK: CSVFileWriter /// Protocol for file writers that write comma-delimited `String` data to a CSV file. protocol CSVFileWriter: FileWriter { associatedtype Columns: CaseIterable, RawRepresentable where Columns.RawValue == String } extension CSVFileWriter { /// Writes the columns labels to the first row in the CSV file. func writeColumnLabels(_ columnLabels: String) { do { try columnLabels.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } catch { Logger.Category.fileIO.logger.error("Failed to write to file: \(String(describing: error))") } } }
31.34
138
0.690491
bf4e62cab492dc1368d5d791e0864add2075a8bd
2,270
// // AppDelegate.swift // TwitterBird // // Copyright © 2016 yigu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CAAnimationDelegate { var window: UIWindow? var mask: CALayer? var imageView: UIImageView? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) if let window = window { // add background imageView imageView = UIImageView(frame: window.frame) imageView!.image = UIImage(named: "twitterScreen") window.addSubview(imageView!) // set up mask mask = CALayer() mask?.contents = UIImage(named: "twitterBird")?.cgImage mask?.position = window.center mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 80) imageView!.layer.mask = mask animateMask() // make window visible window.rootViewController = UIViewController() window.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1) window.makeKeyAndVisible() } return true } func animateMask() { // init key frame animation let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 1 keyFrameAnimation.beginTime = CACurrentMediaTime() + 1 // animate zoom in and then zoom out let initalBounds = NSValue(cgRect: mask!.bounds) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 80, height: 64)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 2000, height: 2000)) keyFrameAnimation.values = [initalBounds, secondBounds, finalBounds] // set up time interals keyFrameAnimation.keyTimes = [0, 0.3, 1] // add animation to current view keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut), CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)] mask!.add(keyFrameAnimation, forKey: "bounds") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { imageView?.layer.mask = nil } }
32.428571
174
0.688987
b94222629d9a64ac4d6d54bd2dfdbc129ab4af61
3,224
// // RACExtensions.swift // Owners // // Created by Ankit on 19/05/16. // Copyright © 2016 Fueled. All rights reserved. // import Foundation import ReactiveSwift import Result extension SignalProtocol { func merge(with signal2: Signal<Value, Error>) -> Signal<Value, Error> { return Signal { observer in let disposable = CompositeDisposable() disposable += self.observe(observer) disposable += signal2.observe(observer) return disposable } } } extension SignalProducerProtocol { func ignoreError() -> SignalProducer<Value, NoError> { return self.flatMapError { _ in SignalProducer<Value, NoError>.empty } } func delay(startAfter interval: TimeInterval, onScheduler scheduler: DateSchedulerProtocol) -> ReactiveSwift.SignalProducer<Value, Error> { return SignalProducer<(), Error>(value: ()) .delay(interval, on: scheduler) .flatMap(.latest) { _ in self.producer } } } extension SignalProducerProtocol where Error == NoError { public func chain<U>(_ transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> { return flatMap(.latest, transform: transform) } public func chain<U>(_ transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> { return flatMap(.latest, transform: transform) } func chain<P: PropertyProtocol>( _ transform: @escaping (Value) -> P) -> SignalProducer<P.Value, NoError> { return flatMap(.latest) { transform($0).producer } } func chain<U>( _ transform: @escaping (Value) -> Signal<U, NoError>?) -> SignalProducer<U, NoError> { return flatMap(.latest) { transform($0) ?? Signal<U, NoError>.never } } func chain<U>( _ transform: @escaping (Value) -> SignalProducer<U, NoError>?) -> SignalProducer<U, NoError> { return flatMap(.latest) { transform($0) ?? SignalProducer<U, NoError>.empty } } func chain<P: PropertyProtocol>( _ transform: @escaping (Value) -> P?) -> SignalProducer<P.Value, NoError> { return flatMap(.latest) { transform($0)?.producer ?? SignalProducer<P.Value, NoError>.empty } } public func debounce( _ interval: TimeInterval, onScheduler scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> { return flatMap(.latest, transform: { next in SignalProducer(value: next).delay(interval, on: scheduler) }) } } extension PropertyProtocol { func chain<U>( _ transform: @escaping (Value) -> Signal<U, NoError>) -> SignalProducer<U, NoError> { return producer.chain(transform) } func chain<U>( _ transform: @escaping (Value) -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> { return producer.chain(transform) } func chain<P: PropertyProtocol>( _ transform: @escaping (Value) -> P) -> SignalProducer<P.Value, NoError> { return producer.chain(transform) } func chain<U>( _ transform: @escaping (Value) -> Signal<U, NoError>?) -> SignalProducer<U, NoError> { return producer.chain(transform) } func chain<U>( _ transform: @escaping (Value) -> SignalProducer<U, NoError>?) -> SignalProducer<U, NoError> { return producer.chain(transform) } func chain<P: PropertyProtocol>( _ transform: @escaping (Value) -> P?) -> SignalProducer<P.Value, NoError> { return producer.chain(transform) } }
33.237113
128
0.705955
d6b6edba9277fdee44e2b95cdcf66e22b6d98b7b
965
// // SayHelloTests.swift // SayHelloTests // // Created by 李腾芳 on 2018/1/27. // Copyright © 2018年 CocoaPods. All rights reserved. // import XCTest @testable import SayHello class SayHelloTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.081081
111
0.632124
ab3a3dbf10b541fc97a228a8ff494e414eaee243
1,573
import Foundation import JSONUtilities public struct Content { public let mediaItems: [String: MediaItem] public enum MediaType: String { case json = "application/json" case form = "application/x-www-form-urlencoded" case xml = "application/xml" case multipartForm = "multipart/form-data" case text = "text/plain" } public func getMediaItem(_ type: MediaType) -> MediaItem? { return mediaItems[type.rawValue] } public var jsonSchema: Schema? { return getMediaItem(.json)?.schema ?? mediaItems.first { MediaType.json.rawValue.contains($0.key.replacingOccurrences(of: "*", with: "")) }?.value.schema } public var formSchema: Schema? { return getMediaItem(.form)?.schema } public var multipartFormSchema: Schema? { return getMediaItem(.multipartForm)?.schema } public var xmlSchema: Schema? { return getMediaItem(.xml)?.schema } } extension Content: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { var mediaItems: [String: MediaItem] = [:] for key in jsonDictionary.keys { let mediaItem: MediaItem = try jsonDictionary.json(atKeyPath: .key(key)) mediaItems[key] = mediaItem } self.mediaItems = mediaItems } } public struct MediaItem { public let schema: Schema } extension MediaItem: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { schema = try jsonDictionary.json(atKeyPath: "schema") } }
27.12069
161
0.658614
2675c6622b51d8b017d2dd36156d800f3978b60a
456
/// Represents the outcome of submitting an XRPL transaction. public struct TransactionResult { /// The identifying hash of the transaction. public let hash: TransactionHash /// The TransactionStatus indicating the outcome of this transaction. public let status: TransactionStatus /// Whether this transaction is included in a validated ledger. /// The transactions status is only final if this field is true. public let validated: Bool }
32.571429
71
0.767544
032effc40054ea8ca6e7228dd414941a51b8e767
239
// // BannerButton.swift // TastyImitationKeyboard // // Created by Benjamin Katz on 11/2/16. // Copyright © 2016 Apple. All rights reserved. // import Foundation import UIKit class BannerButton : UIButton { var type: String? }
14.9375
48
0.698745
bbb5ea56c3d8f81f1638a13f4c8c254404611cfd
6,838
// // LoginViewController.swift // V2EX // // Created by xu.shuifeng on 2018/6/26. // Copyright © 2018 shuifeng.me. All rights reserved. // import UIKit import Alamofire import SafariServices class LoginViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var containerView: UIView! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var usernameLineView: UIView! @IBOutlet weak var passwordLabel: UILabel! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var passwordLineView: UIView! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var captchaButton: UIButton! @IBOutlet weak var captchaTextField: UITextField! @IBOutlet weak var captchaLineView: UIView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var privacyCheckButton: UIButton! @IBOutlet weak var privacyPolicyButton: UIButton! private var loginForm: LoginFormData? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Theme.current.backgroundColor closeButton.tintColor = Theme.current.titleColor titleLabel.textColor = Theme.current.titleColor containerView.backgroundColor = Theme.current.cellBackgroundColor containerView.clipsToBounds = true containerView.layer.cornerRadius = 10.0 stackView.clipsToBounds = true stackView.layer.cornerRadius = 10.0 usernameLabel.textColor = Theme.current.subTitleColor usernameTextField.textColor = Theme.current.titleColor passwordLabel.textColor = Theme.current.subTitleColor passwordTextField.textColor = Theme.current.titleColor usernameLineView.backgroundColor = Theme.current.backgroundColor passwordLineView.backgroundColor = Theme.current.backgroundColor captchaTextField.textColor = Theme.current.titleColor captchaLineView.backgroundColor = Theme.current.backgroundColor signInButton.setTitleColor(Theme.current.titleColor, for: .normal) privacyCheckButton.tintColor = Theme.current.subTitleColor privacyPolicyButton.setTitleColor(Theme.current.subTitleColor, for: .normal) privacyPolicyButton.setTitle(Strings.LoginPrivacyPolity, for: .normal) usernameLabel.text = Strings.LoginUsername usernameTextField.placeholder = Strings.LoginUsernamePlaceholder passwordLabel.text = Strings.LoginPassword passwordTextField.placeholder = Strings.LoginPasswordPlaceholder signInButton.setTitle(Strings.LoginButtonTitle, for: .normal) usernameTextField.becomeFirstResponder() loadCaptcha() } private func loadCaptcha() { activityIndicator.isHidden = false captchaButton.setImage(UIImage(), for: .normal) V2SDK.request(EndPoint.onceToken(), parser: OnceTokenParser.self) { [weak self] (response: V2Response<LoginFormData>) in self?.activityIndicator.isHidden = true switch response { case .success(let formData): self?.loginForm = formData let url = V2SDK.captchaURL(once: formData.once) AF.request(url).responseData(completionHandler: { dataResponse in if let data = dataResponse.data { let img = UIImage(data: data) self?.captchaButton.setImage(img, for: .normal) } }) case .error(let error): HUD.show(message: error.description) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return Theme.current.statusBarStyle } private func hideKeyboard() { usernameTextField.resignFirstResponder() passwordLabel.resignFirstResponder() captchaTextField.resignFirstResponder() } @IBAction func closeButtonTapped(_ sender: Any) { hideKeyboard() dismiss(animated: true, completion: nil) } @IBAction func captchaButtonTapped(_ sender: Any) { if !activityIndicator.isHidden { return } loadCaptcha() } @IBAction func signInButtonTapped(_ sender: Any) { guard let formData = loginForm else { HUD.show(message: Strings.LoginRefreshCaptchaAlerts) return } guard let username = usernameTextField.text, !username.isEmpty else { HUD.show(message: Strings.LoginUsernameAlerts) return } guard let password = passwordTextField.text, !password.isEmpty else { HUD.show(message: Strings.LoginPasswordAlerts) return } guard let captcha = captchaTextField.text, !captcha.isEmpty else { HUD.show(message: Strings.LoginCaptchaAlerts) return } hideKeyboard() HUD.showIndicator() let endPoint = EndPoint.signIn(username: username, password: password, captcha: captcha, formData: formData) V2SDK.request(endPoint, parser: SignInParser.self) { (response: V2Response<Account>) in HUD.removeIndicator() switch response { case .success(let account): print(account) V2SDK.once = formData.once AppContext.current.account = account self.postLoginSuccessNotification() self.dismiss(animated: true, completion: nil) case .error(let error): HUD.show(message: error.description) } } } func postLoginSuccessNotification() { NotificationCenter.default.post(name: NSNotification.Name.V2.LoginSuccess, object: nil) } @IBAction func privacyCheckButtonTapped(_ sender: Any) { privacyCheckButton.isSelected = !privacyCheckButton.isSelected signInButton.isEnabled = privacyCheckButton.isSelected } @IBAction func privacyPolicyButtonTapped(_ sender: Any) { usernameTextField.endEditing(true) passwordTextField.endEditing(true) captchaTextField.endEditing(true) let url = URL(string: "https://shuifeng.me/v2ex/privacy.html")! let controller = SFSafariViewController(url: url) controller.modalPresentationStyle = .fullScreen present(controller, animated: true, completion: nil) } }
38.41573
128
0.662474
d9cdfa0c68a10d56c3d9b4af05cbc4d9fc60e6c0
1,243
/** * 本地视频全屏 */ import UIKit import AVKit class THJGLocalVideoFullScreenView: UIView { @IBOutlet weak var containerView: UIView! var avPlayerVC: AVPlayerViewController? var url: String! { didSet { let avPlayer = AVPlayer(url: URL(string: url)!) avPlayerVC = AVPlayerViewController() avPlayerVC?.showsPlaybackControls = false avPlayerVC!.player = avPlayer avPlayerVC!.view.frame = containerView.bounds containerView.addSubview(avPlayerVC!.view) avPlayerVC?.player?.play() } } static func showLocalVideoFullScreen() -> THJGLocalVideoFullScreenView { return Bundle.main.loadNibNamed("THJGLocalVideoFullScreenView", owner: self, options: nil)?.last as! THJGLocalVideoFullScreenView } deinit { avPlayerVC?.player?.pause() avPlayerVC = nil } } extension THJGLocalVideoFullScreenView { //退出全屏事件监听 @IBAction func backBtnDidClicked(_ sender: UIButton) { //发送切换屏通知 NotificationCenter.default.post(name: NSNotification.Name(NOTIFICATION_VIDEO_REC_SMALLSCREEN), object: nil) //移除当前视图 removeFromSuperview() } }
25.895833
137
0.644409
113bd619a561ad4513a893cbe63b204936bbbc2f
208
// // Indexable.swift // DataFramework // // Created by Aliaksandr on 11/14/18. // import Foundation public protocol IndexSupportable { associatedtype IntexType var index: IntexType { get } }
12.235294
38
0.6875
f731497c14c9e261e517e6e9a64851c158162c90
2,539
// // ViewController.swift // Learning Project // // Created by Harry E. Pray IV on 7/15/16. // Copyright © 2016 harryprayiv.com. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { @IBOutlet weak var dateSelected: UIDatePicker! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBAction func segmentedControlAction(_ sender: AnyObject) { let dateFormatter = DateFormatter() let timeFormatter = DateFormatter() // Now we specify the display format, e.g. "27-08-2015 dateFormatter.dateFormat = "MM/dd/yyyy" timeFormatter.dateFormat = "h:mm a" // Now we get the date from the UIDatePicker and convert it to a string let strDate = dateFormatter.string(from: dateSelected.date) let strTime = timeFormatter.string(from: dateSelected.date) // Finally we set the text of the label to our new string with the date if(segmentedControl.selectedSegmentIndex == 0) { //setValue(<#T##value: AnyObject?##AnyObject?#>, forKey: <#T##String#>) datebeginLabel.text = strDate precallstatusLabel.text = strTime } else if(segmentedControl.selectedSegmentIndex == 1) { datebeginLabel.text = strDate callstatusLabel.text = strTime } else if(segmentedControl.selectedSegmentIndex == 2) { mealstatusLabel.text = strTime } else if(segmentedControl.selectedSegmentIndex == 3) { mealendstatusLabel.text = strTime } else if(segmentedControl.selectedSegmentIndex == 4) { wrapstatusLabel.text = strTime } } @IBOutlet weak var datebeginLabel: UILabel! @IBOutlet weak var precallstatusLabel: UILabel! @IBOutlet weak var callstatusLabel: UILabel! @IBOutlet weak var mealstatusLabel: UILabel! @IBOutlet weak var mealendstatusLabel: UILabel! @IBOutlet weak var wrapstatusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() datebeginLabel.text = ""; precallstatusLabel.text = ""; callstatusLabel.text = ""; mealstatusLabel.text = ""; mealendstatusLabel.text = ""; wrapstatusLabel.text = ""; // initializing text in labels } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
32.139241
83
0.637259
0e9b5debd53ff9f4717c25c267f9760229a78969
318
// // ViewController.swift // ApplePayIPS // // Created by IPS on 24/04/20. // Copyright © 2020 IPS. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
15.142857
58
0.650943
188c436f55ef29ccad5e9bf56189b75217d381e3
8,143
// // TokenCardRedemptionViewController.swift // Alpha-Wallet // // Created by Oguzhan Gungor on 3/6/18. // Copyright © 2018 Alpha-Wallet. All rights reserved. // import UIKit protocol TokenCardRedemptionViewControllerDelegate: class, CanOpenURL { } class TokenCardRedemptionViewController: UIViewController, TokenVerifiableStatusViewController { private var viewModel: TokenCardRedemptionViewModel private let scrollView = UIScrollView() private var titleLabel = UILabel() private let imageView = UIImageView() private let tokenRowView: TokenRowView & UIView private var timer: Timer! private var session: WalletSession private let token: TokenObject var contract: AlphaWallet.Address { return token.contractAddress } var server: RPCServer { return token.server } let assetDefinitionStore: AssetDefinitionStore weak var delegate: TokenCardRedemptionViewControllerDelegate? init(session: WalletSession, token: TokenObject, viewModel: TokenCardRedemptionViewModel, assetDefinitionStore: AssetDefinitionStore) { self.session = session self.token = token self.viewModel = viewModel self.assetDefinitionStore = assetDefinitionStore let tokenType = OpenSeaBackedNonFungibleTokenHandling(token: token, assetDefinitionStore: assetDefinitionStore, tokenViewType: .viewIconified) switch tokenType { case .backedByOpenSea: tokenRowView = OpenSeaNonFungibleTokenCardRowView(tokenView: .viewIconified) case .notBackedByOpenSea: tokenRowView = TokenCardRowView(server: token.server, tokenView: .viewIconified, assetDefinitionStore: assetDefinitionStore) } super.init(nibName: nil, bundle: nil) updateNavigationRightBarButtons(withTokenScriptFileStatus: nil) titleLabel.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false let imageHolder = UIView() imageHolder.translatesAutoresizingMaskIntoConstraints = false imageHolder.backgroundColor = Colors.appWhite imageHolder.cornerRadius = Metrics.CornerRadius.box imageHolder.addSubview(imageView) tokenRowView.translatesAutoresizingMaskIntoConstraints = false let stackView = [ .spacer(height: 16), titleLabel, .spacer(height: 8), imageHolder, .spacer(height: 4), tokenRowView, ].asStackView(axis: .vertical, alignment: .center) stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30), titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30), imageView.leadingAnchor.constraint(equalTo: imageHolder.leadingAnchor, constant: 64), imageView.trailingAnchor.constraint(equalTo: imageHolder.trailingAnchor, constant: -64), imageView.topAnchor.constraint(equalTo: imageHolder.topAnchor, constant: 16), imageView.bottomAnchor.constraint(equalTo: imageHolder.bottomAnchor, constant: -16), imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor), imageHolder.leadingAnchor.constraint(equalTo: tokenRowView.background.leadingAnchor), imageHolder.trailingAnchor.constraint(equalTo: tokenRowView.background.trailingAnchor), tokenRowView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tokenRowView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.anchorsConstraint(to: view), stackView.anchorsConstraint(to: scrollView), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func configureUI() { let redeem = CreateRedeem(token: token) let redeemData: (message: String, qrCode: String) switch token.type { case .nativeCryptocurrency, .erc20: return case .erc875: redeemData = redeem.redeemMessage(indices: viewModel.tokenHolder.indices) case .erc721, .erc721ForTickets: redeemData = redeem.redeemMessage(tokenIds: viewModel.tokenHolder.tokens.map({ $0.id })) } switch session.account.type { case .real(let account): do { guard let decimalSignature = try SignatureHelper.signatureAsDecimal(for: redeemData.message, account: account) else { break } let qrCodeInfo = redeemData.qrCode + decimalSignature imageView.image = qrCodeInfo.toQRCode() } catch { break } case .watch: break } } private func showSuccessMessage() { invalidateTimer() let tokenTypeName = XMLHandler(contract: contract, assetDefinitionStore: assetDefinitionStore).getNameInPluralForm() UIAlertController.alert(title: R.string.localizable.aWalletTokenRedeemSuccessfulTitle(), message: R.string.localizable.aWalletTokenRedeemSuccessfulDescription(tokenTypeName), alertButtonTitles: [R.string.localizable.oK()], alertButtonStyles: [.cancel], viewController: self, completion: { [weak self] _ in guard let strongSelf = self else { return } // TODO: let token coordinator handle this as we need to refresh the token list as well strongSelf.dismiss(animated: true, completion: nil) }) } private func invalidateTimer() { if timer.isValid { timer.invalidate() } } func configure(viewModel newViewModel: TokenCardRedemptionViewModel? = nil) { if let newViewModel = newViewModel { viewModel = newViewModel } updateNavigationRightBarButtons(withTokenScriptFileStatus: tokenScriptFileStatus) view.backgroundColor = viewModel.backgroundColor titleLabel.textAlignment = .center titleLabel.textColor = viewModel.headerColor titleLabel.font = viewModel.headerFont titleLabel.numberOfLines = 0 titleLabel.text = viewModel.headerTitle configureUI() tokenRowView.configure(tokenHolder: viewModel.tokenHolder) tokenRowView.stateLabel.isHidden = true } } extension TokenCardRedemptionViewController: VerifiableStatusViewController { func showInfo() { let controller = TokenCardRedemptionInfoViewController(delegate: self) controller.navigationItem.largeTitleDisplayMode = .never navigationController?.pushViewController(controller, animated: true) } func showContractWebPage() { delegate?.didPressViewContractWebPage(forContract: viewModel.token.contractAddress, server: server, in: self) } func open(url: URL) { delegate?.didPressViewContractWebPage(url, in: self) } } extension TokenCardRedemptionViewController: StaticHTMLViewControllerDelegate { } extension TokenCardRedemptionViewController: CanOpenURL { func didPressViewContractWebPage(forContract contract: AlphaWallet.Address, server: RPCServer, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(forContract: contract, server: server, in: viewController) } func didPressViewContractWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(url, in: viewController) } func didPressOpenWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressOpenWebPage(url, in: viewController) } }
39.721951
150
0.68562
7679657eb2464a9a283099cabc64c363b0268fa3
2,946
// // MessageCell.swift // FireChat // // Created by 윤병일 on 2021/07/18. // import UIKit class MessageCell : UICollectionViewCell { //MARK: - Properties static let identifier = "MessageCell" var message : Message? { didSet { configure() } } var bubbleLeftAnchor : NSLayoutConstraint! var bubbleRightAnchor : NSLayoutConstraint! private let profileImageView : UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.backgroundColor = .lightGray return iv }() private let textView : UITextView = { let tv = UITextView() tv.backgroundColor = .clear tv.font = .systemFont(ofSize: 16) tv.isScrollEnabled = false tv.textColor = .white tv.isEditable = false return tv }() private let bubbleContainer : UIView = { let view = UIView() view.backgroundColor = .systemPurple return view }() //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Functions private func configureUI() { backgroundColor = .clear [profileImageView, bubbleContainer].forEach { contentView.addSubview($0) } profileImageView.snp.makeConstraints { $0.leading.equalToSuperview().offset(8) $0.bottom.equalToSuperview().offset(4) $0.width.height.equalTo(32) } profileImageView.layer.cornerRadius = 32 / 2 bubbleContainer.snp.makeConstraints { $0.top.equalToSuperview() $0.bottom.equalToSuperview() $0.width.lessThanOrEqualTo(250) } bubbleLeftAnchor = bubbleContainer.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 12) bubbleLeftAnchor.isActive = false bubbleRightAnchor = bubbleContainer.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -12) bubbleRightAnchor.isActive = false bubbleContainer.layer.cornerRadius = 12 bubbleContainer.addSubview(textView) textView.snp.makeConstraints { $0.top.equalTo(bubbleContainer.snp.top).offset(4) $0.leading.equalTo(bubbleContainer.snp.leading).offset(12) $0.trailing.equalTo(bubbleContainer.snp.trailing).offset(-12) $0.bottom.equalTo(bubbleContainer.snp.bottom).offset(-4) } } func configure() { guard let message = message else {return} let viewModel = MessageViewModel(message: message) bubbleContainer.backgroundColor = viewModel.messageBackgroundColor textView.textColor = viewModel.messageTextColor textView.text = message.text bubbleLeftAnchor.isActive = viewModel.leftAnchorActive bubbleRightAnchor.isActive = viewModel.rightAnchorActive profileImageView.isHidden = viewModel.shouldHideProfileImage profileImageView.sd_setImage(with: viewModel.profileImageUrl) } }
27.277778
113
0.694501
872d3221b1dc74348e97f5a22e226c3c7f57f822
1,186
// // TheDuckyCalendarUITests.swift // TheDuckyCalendarUITests // // Created by Kevin Nguyen on 3/3/19. // Copyright © 2019 Kevin Nguyen. All rights reserved. // import XCTest class TheDuckyCalendarUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.885714
182
0.696459
61e94f91bbf6c28d8ec5e1f700a63cbb9b21f16a
2,122
// // TickerService.swift // sweettrex // // Created by Cassius Pacheco on 24/9/17. // // import Foundation protocol TickerServiceProtocol { func tick(_ market: Market) throws -> Result<Ticker> } struct TickerService: TickerServiceProtocol { private let service: HttpServiceProtocol init() { self.init(httpService: HttpService()) } init(httpService: HttpServiceProtocol) { self.service = httpService } func tick(_ market: Market) throws -> Result<Ticker> { var result: Result<Ticker> = .failed(.unknown) do { print("\nTick \(market.name)...") let requestResult = try service.request(.ticker(market), httpMethod: .GET, bodyData: nil) switch requestResult { case .successful(let json): do { let tick = try self.parse(json, for: market) result = .successful(tick) } catch { // TODO: handle errors print("TickerService 💥 failed to parse Ticker") result = .failed(.parsing) } case .failed(_): // TODO: handle errors print("TickerService response error") result = .failed(.unknown) } } catch { // TODO: handle errors print("TickerService - failed to request ticker") result = .failed(.unknown) } return result } func parse(_ json: JSON, for market: Market) throws -> Ticker { guard let result: JSON = try json.get("result") else { throw Abort.badRequest } guard let price: Double = try result.get("Last") else { throw Abort.badRequest } return Ticker(market: market, lastPrice: price) } }
25.566265
101
0.475966
abad55c4a3fac20bd607d1bc217ae47ac5f518ff
2,133
// // AppDelegate.swift // Strategy // // Created by luzhiyong on 16/5/8. // Copyright © 2016年 2345. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:. } }
45.382979
285
0.753399
08f1dcb6949d731bdcaee6c7e8e1cd9e9995f2bf
589
// // InternalMenuSection.swift // Moments // // Created by Jake Lin on 17/10/20. // import RxDataSources struct InternalMenuSection: SectionModelType { let title: String let items: [InternalMenuItemViewModel] let footer: String? init(title: String, items: [InternalMenuItemViewModel], footer: String? = nil) { self.title = title self.items = items self.footer = footer } init(original: InternalMenuSection, items: [InternalMenuItemViewModel]) { self.init(title: original.title, items: items, footer: original.footer) } }
23.56
84
0.675722
ccf8eda12ea52015947254b9a29a98964c65ae86
992
import Quick import Nimble @testable import StrapiSwift class CountRequestTests: QuickSpec { override func spec() { var request: CountRequest! describe("CountRequest") { context("initialization") { it("should create the request with the right values for a string content type") { request = CountRequest(contentType: "restaurant") expect(request.method) == .get expect(request.contentType) == "restaurants" expect(request.path) == "/count" expect(request.parameters.count) == 0 } it("should create the request with the right values for a static content type") { request = CountRequest(contentType: .restaurant) expect(request.method) == .get expect(request.contentType) == "restaurants" expect(request.path) == "/count" expect(request.parameters.count) == 0 } } } } } // MARK: - Private helpers private extension ContentType { static let restaurant = ContentType(rawValue: "restaurant") }
25.435897
85
0.678427
229a5997ab29cdbdb94776d4cbb260efa593a531
506
// // AppDelegate.swift // WebView // // Created by 白川 博之 on 2016/02/29. // Copyright © 2016年 Hiroyuki Shirakawa. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
18.740741
71
0.715415
8fe4d472e89de8d25e019027f9df2ae3311e0913
3,467
// // CV // // Copyright 2020 - Grzegorz Wikiera - https://github.com/gwikiera // // 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 Quick import Nimble import TestHelpers @testable import CV_UIKit @testable import Networking class ImageInteractorTests: QuickSpec { override func spec() { describe("ImageInteractor when loading image") { beforeSuite { mainScheduler = .immediate } context("started") { it("presents loading") { let presenter = ImagePresentationLogic.Spy() let tested = ImageInteractor(presenter: presenter, imageUrl: .stub, provider: .noop) tested.loadImage() expect(presenter.presentLoadingSpy.wasInvoked) == true } it("asks for image if url is not nil") { var imageProvider = ImageProvider.noop let imagePathPublisherSpy = spy(of: imageProvider.imagePathPublisher) imageProvider.imagePathPublisher = { url in imagePathPublisherSpy.register(with: url) return .noop } let tested = ImageInteractor(presenter: ImagePresentationLogic.Dummy(), imageUrl: .stub, provider: imageProvider) tested.loadImage() expect(imagePathPublisherSpy.wasInvoked(with: .stub)) == true } } context("succeded") { it("presents image") { let presenter = ImagePresentationLogic.Spy() var imageProvider = ImageProvider.noop imageProvider.imagePathPublisher = stubReturn(with: .stubOutput("filePath")) let tested = ImageInteractor(presenter: presenter, imageUrl: .stub, provider: imageProvider) tested.loadImage() expect(presenter.presentImageSpy.wasInvoked(with: "filePath")) == true } } context("failed") { it("presents error") { let error = ErrorStub() let presenter = ImagePresentationLogic.Spy() var imageProvider = ImageProvider.noop imageProvider.imagePathPublisher = stubReturn(with: .stubFailure(error)) let tested = ImageInteractor(presenter: presenter, imageUrl: .stub, provider: imageProvider) tested.loadImage() expect(presenter.presentErrorSpy.wasInvoked) == true expect(presenter.presentErrorSpy.invokedParameters) === error } } } } }
40.313953
133
0.548313
d94de9e5ff2ee8188189dd9170d3b444c1308012
996
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import UIKit import WebKit extension WKWebView { /// Navigates to the first item in the back-forward list. /// /// A new navigation to the requested item, or nil if there is no back item in /// the back-forward list. @discardableResult public func goToFirstItem() -> WKNavigation? { guard let firstItem = backForwardList.backList.at(0) else { return nil } return go(to: firstItem) } /// Navigates to the last item in the back-forward list. /// /// A new navigation to the requested item, or nil if there is no back item in /// the back-forward list. @discardableResult public func goToLastItem() -> WKNavigation? { let forwardList = backForwardList.forwardList guard let lastItem = forwardList.at(forwardList.count - 1) else { return nil } return go(to: lastItem) } }
25.538462
82
0.63253
0a2a19fd3ee8ff5829f9da27cb8db7b052c1539e
10,468
// // CheckError.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // // Print out a more human readable error message /// /// - parameter error: OSStatus flag /// public func CheckError(_ error: OSStatus) { #if os(tvOS) // No CoreMIDI switch error { case noErr: return case kAudio_ParamError: AKLog("kAudio_ParamError", log: OSLog.general, type: .error) case kAUGraphErr_NodeNotFound: AKLog("kAUGraphErr_NodeNotFound", log: OSLog.general, type: .error) case kAUGraphErr_OutputNodeErr: AKLog("kAUGraphErr_OutputNodeErr", log: OSLog.general, type: .error) case kAUGraphErr_InvalidConnection: AKLog("kAUGraphErr_InvalidConnection", log: OSLog.general, type: .error) case kAUGraphErr_CannotDoInCurrentContext: AKLog("kAUGraphErr_CannotDoInCurrentContext", log: OSLog.general, type: .error) case kAUGraphErr_InvalidAudioUnit: AKLog("kAUGraphErr_InvalidAudioUnit", log: OSLog.general, type: .error) case kAudioToolboxErr_InvalidSequenceType: AKLog("kAudioToolboxErr_InvalidSequenceType", log: OSLog.general, type: .error) case kAudioToolboxErr_TrackIndexError: AKLog("kAudioToolboxErr_TrackIndexError", log: OSLog.general, type: .error) case kAudioToolboxErr_TrackNotFound: AKLog("kAudioToolboxErr_TrackNotFound", log: OSLog.general, type: .error) case kAudioToolboxErr_EndOfTrack: AKLog("kAudioToolboxErr_EndOfTrack", log: OSLog.general, type: .error) case kAudioToolboxErr_StartOfTrack: AKLog("kAudioToolboxErr_StartOfTrack", log: OSLog.general, type: .error) case kAudioToolboxErr_IllegalTrackDestination: AKLog("kAudioToolboxErr_IllegalTrackDestination", log: OSLog.general, type: .error) case kAudioToolboxErr_NoSequence: AKLog("kAudioToolboxErr_NoSequence", log: OSLog.general, type: .error) case kAudioToolboxErr_InvalidEventType: AKLog("kAudioToolboxErr_InvalidEventType", log: OSLog.general, type: .error) case kAudioToolboxErr_InvalidPlayerState: AKLog("kAudioToolboxErr_InvalidPlayerState", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidProperty: AKLog("kAudioUnitErr_InvalidProperty", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidParameter: AKLog("kAudioUnitErr_InvalidParameter", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidElement: AKLog("kAudioUnitErr_InvalidElement", log: OSLog.general, type: .error) case kAudioUnitErr_NoConnection: AKLog("kAudioUnitErr_NoConnection", log: OSLog.general, type: .error) case kAudioUnitErr_FailedInitialization: AKLog("kAudioUnitErr_FailedInitialization", log: OSLog.general, type: .error) case kAudioUnitErr_TooManyFramesToProcess: AKLog("kAudioUnitErr_TooManyFramesToProcess", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidFile: AKLog("kAudioUnitErr_InvalidFile", log: OSLog.general, type: .error) case kAudioUnitErr_FormatNotSupported: AKLog("kAudioUnitErr_FormatNotSupported", log: OSLog.general, type: .error) case kAudioUnitErr_Uninitialized: AKLog("kAudioUnitErr_Uninitialized", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidScope: AKLog("kAudioUnitErr_InvalidScope", log: OSLog.general, type: .error) case kAudioUnitErr_PropertyNotWritable: AKLog("kAudioUnitErr_PropertyNotWritable", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidPropertyValue: AKLog("kAudioUnitErr_InvalidPropertyValue", log: OSLog.general, type: .error) case kAudioUnitErr_PropertyNotInUse: AKLog("kAudioUnitErr_PropertyNotInUse", log: OSLog.general, type: .error) case kAudioUnitErr_Initialized: AKLog("kAudioUnitErr_Initialized", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidOfflineRender: AKLog("kAudioUnitErr_InvalidOfflineRender", log: OSLog.general, type: .error) case kAudioUnitErr_Unauthorized: AKLog("kAudioUnitErr_Unauthorized", log: OSLog.general, type: .error) default: AKLog("\(error)", log: OSLog.general, type: .error) } #else switch error { case noErr: return case kAudio_ParamError: AKLog("kAudio_ParamError", log: OSLog.general, type: .error) case kAUGraphErr_NodeNotFound: AKLog("kAUGraphErr_NodeNotFound", log: OSLog.general, type: .error) case kAUGraphErr_OutputNodeErr: AKLog("kAUGraphErr_OutputNodeErr", log: OSLog.general, type: .error) case kAUGraphErr_InvalidConnection: AKLog("kAUGraphErr_InvalidConnection", log: OSLog.general, type: .error) case kAUGraphErr_CannotDoInCurrentContext: AKLog("kAUGraphErr_CannotDoInCurrentContext", log: OSLog.general, type: .error) case kAUGraphErr_InvalidAudioUnit: AKLog("kAUGraphErr_InvalidAudioUnit", log: OSLog.general, type: .error) case kMIDIInvalidClient: AKLog("kMIDIInvalidClient", log: OSLog.midi, type: .error) case kMIDIInvalidPort: AKLog("kMIDIInvalidPort", log: OSLog.midi, type: .error) case kMIDIWrongEndpointType: AKLog("kMIDIWrongEndpointType", log: OSLog.midi, type: .error) case kMIDINoConnection: AKLog("kMIDINoConnection", log: OSLog.midi, type: .error) case kMIDIUnknownEndpoint: AKLog("kMIDIUnknownEndpoint", log: OSLog.midi, type: .error) case kMIDIUnknownProperty: AKLog("kMIDIUnknownProperty", log: OSLog.midi, type: .error) case kMIDIWrongPropertyType: AKLog("kMIDIWrongPropertyType", log: OSLog.midi, type: .error) case kMIDINoCurrentSetup: AKLog("kMIDINoCurrentSetup", log: OSLog.midi, type: .error) case kMIDIMessageSendErr: AKLog("kMIDIMessageSendErr", log: OSLog.midi, type: .error) case kMIDIServerStartErr: AKLog("kMIDIServerStartErr", log: OSLog.midi, type: .error) case kMIDISetupFormatErr: AKLog("kMIDISetupFormatErr", log: OSLog.midi, type: .error) case kMIDIWrongThread: AKLog("kMIDIWrongThread", log: OSLog.midi, type: .error) case kMIDIObjectNotFound: AKLog("kMIDIObjectNotFound", log: OSLog.midi, type: .error) case kMIDIIDNotUnique: AKLog("kMIDIIDNotUnique", log: OSLog.midi, type: .error) case kMIDINotPermitted: AKLog("kMIDINotPermitted: Have you enabled the audio background mode in your ios app?", log: OSLog.midi, type: .error) case kAudioToolboxErr_InvalidSequenceType: AKLog("kAudioToolboxErr_InvalidSequenceType", log: OSLog.general, type: .error) case kAudioToolboxErr_TrackIndexError: AKLog("kAudioToolboxErr_TrackIndexError", log: OSLog.general, type: .error) case kAudioToolboxErr_TrackNotFound: AKLog("kAudioToolboxErr_TrackNotFound", log: OSLog.general, type: .error) case kAudioToolboxErr_EndOfTrack: AKLog("kAudioToolboxErr_EndOfTrack", log: OSLog.general, type: .error) case kAudioToolboxErr_StartOfTrack: AKLog("kAudioToolboxErr_StartOfTrack", log: OSLog.general, type: .error) case kAudioToolboxErr_IllegalTrackDestination: AKLog("kAudioToolboxErr_IllegalTrackDestination", log: OSLog.general, type: .error) case kAudioToolboxErr_NoSequence: AKLog("kAudioToolboxErr_NoSequence", log: OSLog.general, type: .error) case kAudioToolboxErr_InvalidEventType: AKLog("kAudioToolboxErr_InvalidEventType", log: OSLog.general, type: .error) case kAudioToolboxErr_InvalidPlayerState: AKLog("kAudioToolboxErr_InvalidPlayerState", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidProperty: AKLog("kAudioUnitErr_InvalidProperty", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidParameter: AKLog("kAudioUnitErr_InvalidParameter", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidElement: AKLog("kAudioUnitErr_InvalidElement", log: OSLog.general, type: .error) case kAudioUnitErr_NoConnection: AKLog("kAudioUnitErr_NoConnection", log: OSLog.general, type: .error) case kAudioUnitErr_FailedInitialization: AKLog("kAudioUnitErr_FailedInitialization", log: OSLog.general, type: .error) case kAudioUnitErr_TooManyFramesToProcess: AKLog("kAudioUnitErr_TooManyFramesToProcess", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidFile: AKLog("kAudioUnitErr_InvalidFile", log: OSLog.general, type: .error) case kAudioUnitErr_FormatNotSupported: AKLog("kAudioUnitErr_FormatNotSupported", log: OSLog.general, type: .error) case kAudioUnitErr_Uninitialized: AKLog("kAudioUnitErr_Uninitialized", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidScope: AKLog("kAudioUnitErr_InvalidScope", log: OSLog.general, type: .error) case kAudioUnitErr_PropertyNotWritable: AKLog("kAudioUnitErr_PropertyNotWritable", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidPropertyValue: AKLog("kAudioUnitErr_InvalidPropertyValue", log: OSLog.general, type: .error) case kAudioUnitErr_PropertyNotInUse: AKLog("kAudioUnitErr_PropertyNotInUse", log: OSLog.general, type: .error) case kAudioUnitErr_Initialized: AKLog("kAudioUnitErr_Initialized", log: OSLog.general, type: .error) case kAudioUnitErr_InvalidOfflineRender: AKLog("kAudioUnitErr_InvalidOfflineRender", log: OSLog.general, type: .error) case kAudioUnitErr_Unauthorized: AKLog("kAudioUnitErr_Unauthorized", log: OSLog.general, type: .error) default: AKLog("\(error)", log: OSLog.general, type: .error) } #endif }
40.10728
130
0.684276
087acc11894629b903f6f63de43e45d6f5394e7a
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for b:Int class a{ struct S<T where I:a{ typealias f=b
27.875
87
0.762332
fcf8019a40ed0e2f0b9fcbd27dfe5ab4e0d8015e
894
// // XMPPTests.swift // XMPPTests // // Created by Mickaël Rémond on 07/10/2018. // Copyright © 2018 ProcessOne. All rights reserved. // import XCTest @testable import XMPP class XMPPTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.542857
111
0.651007
5ddb823c2b281c4a7d76512da58b6e264cf4a29e
742
// swift-tools-version:4.0 // // Package.swift // Perfect-sqlite3-support // // Created by Kyle Jessup on 3/22/16. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PackageDescription let package = Package( name: "PerfectCSQLite3", pkgConfig: "sqlite3", providers: [.apt(["sqlite3", "libsqlite3-dev"])] )
26.5
80
0.551213
6a4c1bf9de4e83c87477c176490e39eb6ecb188f
2,593
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // NonBlockingFileIOTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension NonBlockingFileIOTest { static var allTests : [(String, (NonBlockingFileIOTest) -> () throws -> Void)] { return [ ("testBasicFileIOWorks", testBasicFileIOWorks), ("testOffsetWorks", testOffsetWorks), ("testOffsetBeyondEOF", testOffsetBeyondEOF), ("testEmptyReadWorks", testEmptyReadWorks), ("testReadingShortWorks", testReadingShortWorks), ("testDoesNotBlockTheThreadOrEventLoop", testDoesNotBlockTheThreadOrEventLoop), ("testGettingErrorWhenEventLoopGroupIsShutdown", testGettingErrorWhenEventLoopGroupIsShutdown), ("testChunkReadingWorks", testChunkReadingWorks), ("testChunkReadingCanBeAborted", testChunkReadingCanBeAborted), ("testFailedIO", testFailedIO), ("testChunkReadingWorksForIncrediblyLongChain", testChunkReadingWorksForIncrediblyLongChain), ("testReadingDifferentChunkSize", testReadingDifferentChunkSize), ("testReadDoesNotReadShort", testReadDoesNotReadShort), ("testChunkReadingWhereByteCountIsNotAChunkSizeMultiplier", testChunkReadingWhereByteCountIsNotAChunkSizeMultiplier), ("testChunkedReadDoesNotReadShort", testChunkedReadDoesNotReadShort), ("testChunkSizeMoreThanTotal", testChunkSizeMoreThanTotal), ("testFileRegionReadFromPipeFails", testFileRegionReadFromPipeFails), ("testReadFromNonBlockingPipeFails", testReadFromNonBlockingPipeFails), ("testSeekPointerIsSetToFront", testSeekPointerIsSetToFront), ("testFileOpenWorks", testFileOpenWorks), ("testFileOpenWorksWithEmptyFile", testFileOpenWorksWithEmptyFile), ("testFileOpenFails", testFileOpenFails), ] } }
47.145455
133
0.65214
5da31267ac0c40f1227406084d4c074fe97594f9
12,135
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ public protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { public var URLString: String { return self } } extension NSURL: URLStringConvertible { public var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { public var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { public var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ public protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { public var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } extension NSMutableURLRequest { public override var URLRequest: NSMutableURLRequest { return self } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(method, URLString, headers: headers, destination: destination) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
33.337912
118
0.711496
50ac63ff52b2b86ee61c73794fb4e1f74be7240c
7,302
// // Bech32.swift // iotex-swift // // Created by ququzone on 2019/7/31. // Copyright © 2019 IoTeX. All rights reserved. // import Foundation public class Bech32 { private let gen: [UInt32] = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] /// Bech32 checksum delimiter private let checksumMarker: String = "1" /// Bech32 character set for encoding private let encCharset: Data = "qpzry9x8gf2tvdw0s3jn54khce6mua7l".data(using: .utf8)! /// Bech32 character set for decoding private let decCharset: [Int8] = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 ] /// Find the polynomial with value coefficients mod the generator as 30-bit. private func polymod(_ values: Data) -> UInt32 { var chk: UInt32 = 1 for v in values { let top = (chk >> 25) chk = (chk & 0x1ffffff) << 5 ^ UInt32(v) for i: UInt8 in 0..<5 { chk ^= ((top >> i) & 1) == 0 ? 0 : gen[Int(i)] } } return chk } /// Expand a HRP for use in checksum computation. private func expandHrp(_ hrp: String) -> Data { guard let hrpBytes = hrp.data(using: .utf8) else { return Data() } var result = Data(repeating: 0x00, count: hrpBytes.count*2+1) for (i, c) in hrpBytes.enumerated() { result[i] = c >> 5 result[i + hrpBytes.count + 1] = c & 0x1f } result[hrp.count] = 0 return result } /// Verify checksum private func verifyChecksum(hrp: String, checksum: Data) -> Bool { var data = expandHrp(hrp) data.append(checksum) return polymod(data) == 1 } /// Create checksum private func createChecksum(hrp: String, values: Data) -> Data { var enc = expandHrp(hrp) enc.append(values) enc.append(Data(repeating: 0x00, count: 6)) let mod: UInt32 = polymod(enc) ^ 1 var ret: Data = Data(repeating: 0x00, count: 6) for i in 0..<6 { ret[i] = UInt8((mod >> (5 * (5 - i))) & 31) } return ret } /// Encode Bech32 string public func encode(_ hrp: String, values: Data) -> String { let checksum = createChecksum(hrp: hrp, values: values) var combined = values combined.append(checksum) guard let hrpBytes = hrp.data(using: .utf8) else { return "" } var ret = hrpBytes ret.append("1".data(using: .utf8)!) for i in combined { ret.append(encCharset[Int(i)]) } return String(data: ret, encoding: .utf8) ?? "" } /// Decode Bech32 string public func decode(_ str: String) throws -> (hrp: String, checksum: Data) { guard let strBytes = str.data(using: .utf8) else { throw DecodingError.nonUTF8String } guard strBytes.count <= 90 else { throw DecodingError.stringLengthExceeded } var lower: Bool = false var upper: Bool = false for c in strBytes { // printable range if c < 33 || c > 126 { throw DecodingError.nonPrintableCharacter } // 'a' to 'z' if c >= 97 && c <= 122 { lower = true } // 'A' to 'Z' if c >= 65 && c <= 90 { upper = true } } if lower && upper { throw DecodingError.invalidCase } guard let pos = str.range(of: checksumMarker, options: .backwards)?.lowerBound else { throw DecodingError.noChecksumMarker } let intPos: Int = str.distance(from: str.startIndex, to: pos) guard intPos >= 1 else { throw DecodingError.incorrectHrpSize } guard intPos + 7 <= str.count else { throw DecodingError.incorrectChecksumSize } let vSize: Int = str.count - 1 - intPos var values: Data = Data(repeating: 0x00, count: vSize) for i in 0..<vSize { let c = strBytes[i + intPos + 1] let decInt = decCharset[Int(c)] if decInt == -1 { throw DecodingError.invalidCharacter } values[i] = UInt8(decInt) } let hrp = String(str[..<pos]).lowercased() guard verifyChecksum(hrp: hrp, checksum: values) else { throw DecodingError.checksumMismatch } return (hrp, Data(values[..<(vSize-6)])) } public func convertBits(from: Int, to: Int, pad: Bool, idata: Data) throws -> Data { var acc: Int = 0 var bits: Int = 0 let maxv: Int = (1 << to) - 1 let maxAcc: Int = (1 << (from + to - 1)) - 1 var odata = Data() for ibyte in idata { acc = ((acc << from) | Int(ibyte)) & maxAcc bits += from while bits >= to { bits -= to odata.append(UInt8((acc >> bits) & maxv)) } } if pad { if bits != 0 { odata.append(UInt8((acc << (to - bits)) & maxv)) } } else if (bits >= from || ((acc << (to - bits)) & maxv) != 0) { throw DecodingError.bitsConversionFailed } return odata } } extension Bech32 { public enum DecodingError: LocalizedError { case nonUTF8String case nonPrintableCharacter case invalidCase case noChecksumMarker case incorrectHrpSize case incorrectChecksumSize case stringLengthExceeded case invalidCharacter case checksumMismatch case bitsConversionFailed public var errorDescription: String? { switch self { case .checksumMismatch: return "Checksum doesn't match" case .incorrectChecksumSize: return "Checksum size too low" case .incorrectHrpSize: return "Human-readable-part is too small or empty" case .invalidCase: return "String contains mixed case characters" case .invalidCharacter: return "Invalid character met on decoding" case .noChecksumMarker: return "Checksum delimiter not found" case .nonPrintableCharacter: return "Non printable character in input string" case .nonUTF8String: return "String cannot be decoded by utf8 decoder" case .stringLengthExceeded: return "Input string is too long" case .bitsConversionFailed: return "Failed to perform bits conversion" } } } }
35.275362
93
0.51616
289645a0f05c2506f91f49e17e2d654591783343
12,114
// // QuicksilverProvider+WebSocket.swift // Quicksilver // // Created by Chun on 2019/1/16. // Copyright © 2019 LLS iOS Team. All rights reserved. // import Foundation import StarscreamPrivate /** Providing Standard WebSocket close codes **/ public struct WebSocketCloseCode { public let rawValue: UInt16 public init(rawValue: UInt16) { self.rawValue = rawValue } public static let normal = WebSocketCloseCode(rawValue: 1000) public static let goingAway = WebSocketCloseCode(rawValue: 1001) public static let protocolError = WebSocketCloseCode(rawValue: 1002) public static let protocolUnhandledType = WebSocketCloseCode(rawValue: 1003) public static let noStatusReceived = WebSocketCloseCode(rawValue: 1005) public static let encoding = WebSocketCloseCode(rawValue: 1007) public static let policyViolated = WebSocketCloseCode(rawValue: 1008) public static let messageTooBig = WebSocketCloseCode(rawValue: 1009) } public enum WebSocketErrorType: Error { case outputStreamWriteError //output stream error during write case compressionError case invalidSSLError //Invalid SSL certificate case writeTimeoutError //The socket timed out waiting to be ready to write case protocolError //There was an error parsing the WebSocket frames case upgradeError //There was an error during the HTTP upgrade case closeError //There was an error during the close (socket probably has been dereferenced) init(errorType: ErrorType) { switch errorType { case .outputStreamWriteError: self = .outputStreamWriteError case .compressionError: self = .compressionError case .invalidSSLError: self = .invalidSSLError case .writeTimeoutError: self = .writeTimeoutError case .protocolError: self = .protocolError case .upgradeError: self = .upgradeError case .closeError: self = .closeError } } } public struct WebSocketError: Error { public let type: WebSocketErrorType public let message: String public let code: Int public init(type: WebSocketErrorType, message: String, code: Int) { self.type = type self.message = message self.code = code } init(error: WSError) { type = WebSocketErrorType(errorType: error.type) message = error.message code = error.code } } /// WebScoket config about sub-protocols, wss certs and httpdns supports. public struct WebSocketConfiguration { /// use http dns to improve dns. Default is `false`. public let useHTTPDNS: Bool public let subProtocols: [String] public let enableCompression: Bool public let eventQueue: DispatchQueue /// init method /// /// - Parameters: /// - subProtocols: a list of protocols, default value is [] /// - useHTTPDNS: default value is false /// - enableCompression: default value is true /// - eventQueue: default value is main queue public init(subProtocols: [String] = [], useHTTPDNS: Bool = false, enableCompression: Bool = true, eventQueue: DispatchQueue = DispatchQueue.main) { self.subProtocols = subProtocols self.useHTTPDNS = useHTTPDNS self.enableCompression = enableCompression self.eventQueue = eventQueue } } /// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection. public struct WebSocketEvents { /// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. public var open: () -> Void = { } /// An event to be called when a pong is received from the server. public var pong: (_ data: Data?) -> Void = { data in } /// An event to be called when the WebSocket disconnected with error or not public var disconnect: (_ error: Error?) -> Void = { error in } /// An event to be called when a data message is received from the server. public var dataMessage: (Data) -> Void = { message in } /// An event to be called when a string message is received from the server. public var stringMessage: (String) -> Void = { message in } } // MARK: - InnerWebSocket class InnerWebSocket { var isConnected: Bool { if let webSocket = webSocket { return webSocket.isConnected } else { return false } } var event: WebSocketEvents { get { lock(); defer { unlock() }; return _event } set { lock(); defer { unlock() }; _event = newValue } } let eventQueue: DispatchQueue let enableCompression: Bool init(request: URLRequest, protocols: [String]?, useHTTPDNS: Bool, eventQueue: DispatchQueue, enableCompression: Bool) { pthread_mutex_init(&mutex, nil) self.eventQueue = eventQueue self.enableCompression = enableCompression originRequest = request taskQueue.async { [weak self] in guard let self = self else { return } if useHTTPDNS { self.initWebSocketWithHTTPDNS(request: request, protocols: protocols) } else { self.initWebSocket(request: request, protocols: protocols) } } } deinit { pthread_mutex_destroy(&mutex) } func connect() { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.connect() } } func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16) { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.disconnect(forceTimeout: forceTimeout, closeCode: closeCode) } } func write(string: String, completion: (() -> Void)?) { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.write(string: string, completion: completion) } } func write(data: Data, completion: (() -> Void)?) { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.write(data: data, completion: completion) } } func write(ping: Data, completion: (() -> Void)?) { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.write(ping: ping, completion: completion) } } func write(pong: Data, completion: (() -> Void)?) { taskQueue.async { [weak self] in guard let self = self else { return } self.webSocket.write(pong: pong, completion: completion) } } // MARK: - Private private let taskQueue = DispatchQueue(label: "webSocket.Quicksilver") private let originRequest: URLRequest private var mutex = pthread_mutex_t() private var webSocket: WebSocket! private var usedHTTPDNS: Bool = false private var _event = WebSocketEvents() private func initWebSocketWithHTTPDNS(request: URLRequest, protocols: [String]?) { if let url = request.url, let host = url.host { let semaphore = DispatchSemaphore(value: 0) var dnsResult: HTTPDNSResult? HTTPDNS.query(host) { (result) in dnsResult = result semaphore.signal() } _ = semaphore.wait(timeout: .distantFuture) if let result = dnsResult, let range = url.absoluteString.range(of: host) { usedHTTPDNS = true let newURLString = url.absoluteString.replacingCharacters(in: range, with: result.ipAddress) let newRequest = generateHTTPDNSRequest(originRequst: request, newURLString: newURLString, host: host) initWebSocket(request: newRequest, protocols: protocols) } else { initWebSocket(request: request, protocols: protocols) } } else { initWebSocket(request: request, protocols: protocols) } } private func generateHTTPDNSRequest(originRequst: URLRequest, newURLString: String, host: String) -> URLRequest { var newRequest = originRequst newRequest.url = URL(string: newURLString) newRequest.setValue(host, forHTTPHeaderField: "Host") newRequest.setValue(host, forHTTPHeaderField: "Origin") return newRequest } private func initWebSocket(request: URLRequest, protocols: [String]?) { let webSocket = WebSocket(request: request, protocols: protocols) webSocket.delegate = self webSocket.pongDelegate = self if usedHTTPDNS { webSocket.overrideTrustHostname = true webSocket.desiredTrustHostname = originRequest.url?.host } webSocket.callbackQueue = eventQueue webSocket.enableCompression = enableCompression self.webSocket = webSocket } @inline(__always) private func lock() { pthread_mutex_lock(&mutex) } @inline(__always) private func unlock() { pthread_mutex_unlock(&mutex) } } extension InnerWebSocket: WebSocketDelegate, WebSocketPongDelegate { func websocketDidConnect(socket: WebSocketClient) { event.open() } func websocketDidReceivePong(socket: WebSocketClient, data: Data?) { event.pong(data) } func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { if let error = error as? WSError { event.disconnect(WebSocketError(error: error)) } else { event.disconnect(error) } } func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { event.stringMessage(text) } func websocketDidReceiveData(socket: WebSocketClient, data: Data) { event.dataMessage(data) } } // MARK: - QuicksilverProvider + WebSocket extension QuicksilverProvider { open class WS { public init(request: URLRequest, configuration: WebSocketConfiguration = WebSocketConfiguration()) { ws = InnerWebSocket(request: request, protocols: configuration.subProtocols, useHTTPDNS: configuration.useHTTPDNS, eventQueue: configuration.eventQueue, enableCompression: configuration.enableCompression) } /// The events of the WebSocket. open var event: WebSocketEvents { get { return ws.event } set { ws.event = newValue } } /// WebSocket on connected status or not open var isConnected: Bool { return ws.isConnected } /** Connect to the WebSocket server on a background thread. */ open func open() { ws.connect() } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my event callback once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my event callback. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ open func close(forceTimeout: TimeInterval? = nil, closeCode: WebSocketCloseCode = .normal) { ws.disconnect(forceTimeout: forceTimeout, closeCode: closeCode.rawValue) } /** Transmits message to the server over the WebSocket connection. - Parameter data: The Data message to be sent to the server. */ open func send(_ data: Data, completion: (() -> Void)? = nil) { ws.write(data: data, completion: completion) } /** Transmits message to the server over the WebSocket connection. - Parameter message: The String message to be sent to the server. */ open func send(_ message: String, completion: (() -> Void)? = nil) { ws.write(string: message, completion: completion) } /** Transmits a ping to the server over the WebSocket connection. - Parameter data: optional message The data to be sent to the server. */ open func ping(_ data: Data = Data(), completion: (() -> Void)? = nil) { ws.write(ping: data, completion: completion) } // MARK: - Private private let ws: InnerWebSocket } }
31.221649
232
0.687882
ed5e0025b1da346814e323d79c64cb9dc353a986
1,386
import Foundation public final class GitCloner: Cloning { @discardableResult public func clone(from source: URL, to destination: URL, branch: String, recurseSubmodules: Bool, publisher: RemoteProgressPublisher) throws -> Repository? { try branch.withCString { (cBranch) in try git_remote_callbacks.withCallbacks(publisher.callbacks) { (gitCallbacks) in var options = git_clone_options.defaultOptions() options.bare = 0 options.checkout_branch = cBranch options.fetch_opts.callbacks = gitCallbacks let gitRepo: OpaquePointer do { gitRepo = try OpaquePointer.from { git_clone(&$0, source.absoluteString, destination.path, &options) } } catch let error as RepoError { publisher.error(error) throw error } catch let error { publisher.error(.unexpected) throw error } guard let repo = try? XTRepository(gitRepo: gitRepo) else { return nil } if recurseSubmodules { for sub in repo.submodules() { try sub.update(callbacks: publisher.callbacks) // recurse } } publisher.finished() return repo } } } }
26.653846
77
0.562049
e58de98d66ad64736d6fc3085a19426efe6e7788
2,126
// // LibreTransmitter.swift // MiaomiaoClient // // Created by Bjørn Inge Berg on 08/01/2020. // Copyright © 2020 Bjørn Inge Berg. All rights reserved. // import CoreBluetooth import Foundation import UIKit public protocol LibreTransmitterProxy: class { static var shortTransmitterName: String { get } static var smallImage: UIImage? { get } static var manufacturerer: String { get } static func canSupportPeripheral(_ peripheral: CBPeripheral) -> Bool static var writeCharacteristic: UUIDContainer? { get set } static var notifyCharacteristic: UUIDContainer? { get set } static var serviceUUID: [UUIDContainer] { get set } var delegate: LibreTransmitterDelegate? { get set } init(delegate: LibreTransmitterDelegate, advertisementData: [String: Any]? ) func requestData(writeCharacteristics: CBCharacteristic, peripheral: CBPeripheral) func updateValueForNotifyCharacteristics(_ value: Data, peripheral: CBPeripheral, writeCharacteristic: CBCharacteristic?) func reset() static func getDeviceDetailsFromAdvertisement(advertisementData: [String: Any]?) -> String? } extension LibreTransmitterProxy { func canSupportPeripheral(_ peripheral: CBPeripheral) -> Bool { Self.canSupportPeripheral(peripheral) } public var staticType: LibreTransmitterProxy.Type { Self.self } } extension Array where Array.Element == LibreTransmitterProxy.Type { func getServicesForDiscovery() -> [CBUUID] { self.flatMap { return $0.serviceUUID.map { $0.value } }.removingDuplicates() } } public enum LibreTransmitters { public static var all: [LibreTransmitterProxy.Type] { [MiaoMiaoTransmitter.self, BubbleTransmitter.self] } public static func isSupported(_ peripheral: CBPeripheral) -> Bool { getSupportedPlugins(peripheral)?.isEmpty == false } public static func getSupportedPlugins(_ peripheral: CBPeripheral) -> [LibreTransmitterProxy.Type]? { all.enumerated().compactMap { $0.element.canSupportPeripheral(peripheral) ? $0.element : nil } } }
33.746032
125
0.718721
4a962e1f4c7250a266c92d9a9a904796659d03a9
11,735
// // FortunesAlgorithm.swift // VoronoiLibSwift // // Created by Wilhelm Oks on 20.04.19. // Copyright © 2019 Wilhelm Oks. All rights reserved. // import simd final class FortunesAlgorithm { static func run(sites: [FortuneSite], borderInfo: BorderInfoAggregator, on clipRect: ClipRect.Double4) -> [VEdge] { let eventQueue = MinHeap<FortuneEvent>(capacity: 5 * sites.count) for s in sites { let _ = eventQueue.insert(FortuneSiteEvent(s)) } //init tree let beachLine = BeachLine() var edges = [VEdge]() let deleted = HashSet<FortuneCircleEvent>() //init edge list while eventQueue.count != 0 { let fEvent = eventQueue.pop() if fEvent is FortuneSiteEvent { beachLine.addBeachSection(siteEvent: fEvent as! FortuneSiteEvent, eventQueue: eventQueue, deleted: deleted, edges: &edges) } else { if deleted.contains(fEvent as! FortuneCircleEvent) { deleted.remove(fEvent as! FortuneCircleEvent) } else { beachLine.removeBeachSection(circle: fEvent as! FortuneCircleEvent, eventQueue: eventQueue, deleted: deleted, edges: &edges) } } } var edgesToRemove: [VEdge] = [] //clip edges for edge in edges { let valid: Bool = clipEdge(edge: edge, clipRect: clipRect) if valid { if borderInfo.enabled { if let border = border(for: edge.start, on: clipRect) { borderInfo.add(point: edge.start, forSite: edge.left, onBorder: border) borderInfo.add(point: edge.start, forSite: edge.right, onBorder: border) } if let edgeEnd = edge.end, let border = border(for: edgeEnd, on: clipRect) { borderInfo.add(point: edgeEnd, forSite: edge.left, onBorder: border) borderInfo.add(point: edgeEnd, forSite: edge.right, onBorder: border) } } } else { edgesToRemove.append(edge) edge.left.removeCellEdge(edge) edge.right.removeCellEdge(edge) } } let n = edges.count for i in 0..<n { let ii = n - 1 - i let edge = edges[ii] for r in 0..<edgesToRemove.count { let rr = edgesToRemove.count - 1 - r let edgeToRemove = edgesToRemove[rr] if edge === edgeToRemove { edgesToRemove.remove(at: rr) edges.remove(at: ii) break } } } return edges } private static func border(for point: VPoint, on clipRect: ClipRect.Double4) -> ClipRect.Border? { if Approx.approxEqual(point.x, clipRect.minX) { return .left } else if Approx.approxEqual(point.x, clipRect.maxX) { return .right } else if Approx.approxEqual(point.y, clipRect.minY) { return .top } else if Approx.approxEqual(point.y, clipRect.maxY) { return .bottom } else { return nil } } //combination of personal ray clipping alg and cohen sutherland private static func clipEdge(edge: VEdge, clipRect: ClipRect.Double4) -> Bool { let (minX, minY, maxX, maxY) = clipRect var accept = false //if its a ray if edge.end == nil { accept = clipRay(edge: edge, clipRect: clipRect) } else { //Cohen–Sutherland var start = computeOutCode(x: edge.start.x, y: edge.start.y, clipRect: clipRect) var end = computeOutCode(x: edge.end!.x, y: edge.end!.y, clipRect: clipRect) while true { if (start | end) == 0 { accept = true break } if (start & end) != 0 { break } var x: Double = -1 var y: Double = -1 let outcode = start != 0 ? start : end if (outcode & 0x8) != 0 { // top x = edge.start.x + (edge.end!.x - edge.start.x)*(maxY - edge.start.y)/(edge.end!.y - edge.start.y) y = maxY } else if (outcode & 0x4) != 0 { // bottom x = edge.start.x + (edge.end!.x - edge.start.x)*(minY - edge.start.y)/(edge.end!.y - edge.start.y) y = minY } else if (outcode & 0x2) != 0 { //right y = edge.start.y + (edge.end!.y - edge.start.y)*(maxX - edge.start.x)/(edge.end!.x - edge.start.x) x = maxX } else if ((outcode & 0x1) != 0) { //left y = edge.start.y + (edge.end!.y - edge.start.y)*(minX - edge.start.x)/(edge.end!.x - edge.start.x) x = minX } let borderPoint = VPoint(x: x, y: y) if outcode == start { edge.start = borderPoint start = computeOutCode(x: x, y: y, clipRect: clipRect) } else { edge.end = borderPoint end = computeOutCode(x: x, y: y, clipRect: clipRect) } } } //if we have a neighbor if let neighbor = edge.neighbor { //check it let valid = clipEdge(edge: neighbor, clipRect: clipRect) //both are valid if accept && valid { if let neighborEnd = neighbor.end { edge.start = neighborEnd } } //this edge isn't valid, but the neighbor is //flip and set if !accept && valid { if let neighborEnd = neighbor.end { edge.start = neighborEnd } edge.end = neighbor.start accept = true } } return accept } private static func computeOutCode(x: Double, y: Double, clipRect: ClipRect.Double4) -> Int { let (minX, minY, maxX, maxY) = clipRect var code: Int = 0 if Approx.approxEqual(x, minX) || Approx.approxEqual(x, maxX) { } else if x < minX { code |= 0x1 } else if x > maxX { code |= 0x2 } if Approx.approxEqual(y, minY) || Approx.approxEqual(y, maxY) { } else if y < minY { code |= 0x4 } else if y > maxY { code |= 0x8 } return code } private static func clipRay(edge: VEdge, clipRect: ClipRect.Double4) -> Bool { let (minX, minY, maxX, maxY) = clipRect let start = edge.start //horizontal ray if Approx.approxZero(edge.slopeRise) { if !Approx.valueIsWithin(value: start.y, lowerBound: minY, upperBound: maxY) { return false } if edge.slopeRun > 0 && start.x > maxX { return false } if edge.slopeRun < 0 && start.x < minX { return false } if Approx.valueIsWithin(value: start.x, lowerBound: minX, upperBound: maxX) { let edgeEnd = edge.slopeRun > 0 ? VPoint(x: maxX, y: start.y) : VPoint(x: minX, y: start.y) edge.end = edgeEnd } else { let edgeStart = edge.slopeRun > 0 ? VPoint(x: minX, y: start.y) : VPoint(x: maxX, y: start.y) let edgeEnd = edge.slopeRun > 0 ? VPoint(x: maxX, y: start.y) : VPoint(x: minX, y: start.y) edge.start = edgeStart edge.end = edgeEnd } return true } //vertical ray if Approx.approxZero(edge.slopeRun) { if start.x < minX || start.x > maxX { return false } if edge.slopeRise > 0 && start.y > maxY { return false } if edge.slopeRise < 0 && start.y < minY { return false } if Approx.valueIsWithin(value: start.y, lowerBound: minY, upperBound: maxY) { let edgeEnd = edge.slopeRise > 0 ? VPoint(x: start.x, y: maxY) : VPoint(x: start.x, y: minY) edge.end = edgeEnd } else { let edgeStart = edge.slopeRise > 0 ? VPoint(x: start.x, y: minY) : VPoint(x: start.x, y: maxY) let edgeEnd = edge.slopeRise > 0 ? VPoint(x: start.x, y: maxY) : VPoint(x: start.x, y: minY) edge.start = edgeStart edge.end = edgeEnd } return true } //works for outside assert(edge.slope != nil, "edge.Slope != nil") assert(edge.intercept != nil, "edge.Intercept != nil") let topX = VPoint(x: calcX(m: edge.slope!, y: maxY, b: edge.intercept!), y: maxY) let bottomX = VPoint(x: calcX(m: edge.slope!, y: minY, b: edge.intercept!), y: minY) let leftY = VPoint(x: minX, y: calcY(m: edge.slope!, x: minX, b: edge.intercept!)) let rightY = VPoint(x: maxX, y: calcY(m: edge.slope!, x: maxX, b: edge.intercept!)) //reject intersections not within bounds var candidates = Array<VPoint>() if Approx.valueIsWithin(value: topX.x, lowerBound: minX, upperBound: maxX) { candidates.append(topX) } if Approx.valueIsWithin(value: bottomX.x, lowerBound: minX, upperBound: maxX) { candidates.append(bottomX) } if Approx.valueIsWithin(value: leftY.y, lowerBound: minY, upperBound: maxY) { candidates.append(leftY) } if Approx.valueIsWithin(value: rightY.y, lowerBound: minY, upperBound: maxY) { candidates.append(rightY) } //reject candidates which don't align with the slope var i = candidates.count - 1 while i > -1 { let candidate = candidates[i] //grab vector representing the edge let ax = candidate.x - start.x let ay = candidate.y - start.y if edge.slopeRun*ax + edge.slopeRise*ay < 0 { candidates.remove(at: i) } i -= 1 } //if there are two candidates we are outside the closer one is start //the further one is the end if candidates.count == 2 { let candidate0 = candidates[0] let candidate1 = candidates[1] let a = candidate0 - start let b = candidate1 - start let aGraterThanB = simd_length_squared(a) > simd_length_squared(b) let edgeStart = aGraterThanB ? candidate1 : candidate0 let edgeEnd = aGraterThanB ? candidate0 : candidate1 edge.start = edgeStart edge.end = edgeEnd } //if there is one candidate we are inside if candidates.count == 1 { let candidate = candidates[0] edge.end = candidate } //there were no candidates return edge.end != nil } private static func calcY(m: Double, x: Double, b: Double) -> Double { return m * x + b } private static func calcX(m: Double, y: Double, b: Double) -> Double { return (y - b) / m } }
38.224756
144
0.498679
87f4168ba57aba9b4aafa07320da94e9a6a93a19
4,020
/*--------------------------------------------------------------------------*/ /* /\/\/\__/\/\/\ MooseFactory Foundation - v2.0 */ /* \/\/\/..\/\/\/ */ /* | | (c)2007-2020 Tristan Leblanc */ /* (oo) [email protected] */ /* MooseFactory Software */ /*--------------------------------------------------------------------------*/ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*--------------------------------------------------------------------------*/ // ObjectsBag.swift // CombineModel // // Created by Tristan Leblanc on 06/12/2020. import Foundation struct Multiple: Equatable, CustomStringConvertible { static func == (lhs: Self, rhs: Self) -> Bool { return false } var description: String { return "<Multiple>" } } class ObjectsBag { var objects: [Any] var objectsKeyPaths: [[String: Any]] var representingKeyPaths: [String: Any]? { guard var out = objectsKeyPaths.first else { return nil } if objectsKeyPaths.count == 1 { return out } let dicts = Array(objectsKeyPaths.dropFirst()) for dict in dicts { deepMerge(dict, to: &out) } return out } func deepMerge(_ dict: [String: Any], to out: inout [String: Any]) { out.merge(dict) { (l, r) in guard type(of: l) == type(of: r) else { return Multiple() } if var lo = l as? [String: Any], let ro = r as? [String: Any] { if lo.count == ro.count { self.deepMerge(ro, to: &lo) return lo } else { return Multiple() } } if let lo = l as? [AnyObject], let ro = r as? [AnyObject] { if lo.count == ro.count { for obj in lo.enumerated() { if !compareBytes(lhs: obj.element, rhs: ro[obj.offset]) { return Multiple() } } return l } else { return Multiple() } } if let lo = l as? AnyObject, let ro = r as? AnyObject { if compareBytes(lhs: lo, rhs: ro) { return l } } return Multiple() } } func compareBytes(lhs: AnyObject, rhs: AnyObject) -> Bool { let lptr = Unmanaged.passUnretained(lhs).toOpaque() let rptr = Unmanaged.passUnretained(rhs).toOpaque() return lptr == rptr } init(_ objects: [Any]) { self.objects = objects self.objectsKeyPaths = objects.map { Mirror.allKeyPaths(for: $0, options: .explode)} } }
36.216216
93
0.502736
762f5ba057373371ea1e3e7ad4e9b71d28959e0e
2,147
// // SendMoneyViewModel.swift // Hugo // // Created by Ali Gutierrez on 3/31/21. // Copyright © 2021 Clever Mobile Apps. All rights reserved. // import UIKit class SendMoneyViewModel: NSObject { var countryData: CountryCodeItem? var userManager = UserManager.shared var isUSingContact = false var phoneNumber = "" var email = "" var fieldsNeedInput: Bool { phoneNumber.isEmpty && email.isEmpty } var textfieldShouldShake: Bool { !email.isEmpty && !isValidEmail(email) } func verifySendMoneyInfo(with amountText: String) -> Bool { let amount = amountText .replacingOccurrences(of: userManager.symbol ?? "$", with: "") .replacingOccurrences(of: ",", with: "") .replacingOccurrences(of: " ", with: "") guard let amountAsDouble = Double(amount) else { return false } if amount.isEmpty { return false } if amountAsDouble <= 0.00 { return false } if fieldsNeedInput { return false } if textfieldShouldShake { return false } return true } func showMessagePrompt(_ error: String) { let alert = UIAlertController(title: "AProblemOcurredTitle".localizedString , message: error, preferredStyle: .alert) let action = UIAlertAction(title: AlertString.OK, style: .default, handler: nil) alert.addAction(action) let vc = getCurrentViewController() vc?.present(alert, animated: true, completion: nil) } func getCurrentViewController() -> UIViewController? { if let rootController = UIApplication.shared.keyWindow?.rootViewController { var currentController: UIViewController! = rootController while( currentController.presentedViewController != nil ) { currentController = currentController.presentedViewController } return currentController } return nil } }
27.883117
126
0.590126
62ada19fcb38ff97e2c76538749a9a3ce3b1ab14
14,638
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Cocoa import SwiftyDropbox class ViewController: NSViewController { @IBOutlet weak var oauthLinkButton: NSButton! @IBOutlet weak var oauthLinkBrowserButton: NSButton! @IBOutlet weak var oauthUnlinkButton: NSButton! @IBOutlet weak var runApiTestsButton: NSButton! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear() { } @IBAction func oauthLinkButtonPressed(_ sender: AnyObject) { if DropboxClientsManager.authorizedClient == nil && DropboxClientsManager.authorizedTeamClient == nil { DropboxClientsManager.authorizeFromController(sharedWorkspace: NSWorkspace.shared(), controller: self, openURL: {(url: URL) -> Void in NSWorkspace.shared().open(url)}) } } @IBAction func oauthLinkBrowserButtonPressed(_ sender: AnyObject) { DropboxClientsManager.unlinkClients() DropboxClientsManager.authorizeFromController(sharedWorkspace: NSWorkspace.shared(), controller: self, openURL: {(url: URL) -> Void in NSWorkspace.shared().open(url)}, browserAuth: true) } @IBAction func oauthUnlinkButtonPressed(_ sender: AnyObject) { DropboxClientsManager.unlinkClients() checkButtons() } @IBAction func runApiTestsButtonPressed(_ sender: AnyObject) { if DropboxClientsManager.authorizedClient != nil || DropboxClientsManager.authorizedTeamClient != nil { let unlink = { DropboxClientsManager.unlinkClients() self.checkButtons() } switch(appPermission) { case .fullDropbox: testAllUserEndpoints(nextTest: unlink) case .teamMemberFileAccess: testTeamMemberFileAcessActions(unlink) case .teamMemberManagement: testTeamMemberManagementActions(unlink) } } } func checkButtons() { if DropboxClientsManager.authorizedClient != nil || DropboxClientsManager.authorizedTeamClient != nil { oauthLinkButton.isHidden = true oauthLinkBrowserButton.isHidden = true oauthUnlinkButton.isHidden = false runApiTestsButton.isHidden = false } else { oauthLinkButton.isHidden = false oauthLinkBrowserButton.isHidden = false oauthUnlinkButton.isHidden = true runApiTestsButton.isHidden = true } } /** To run these unit tests, you will need to do the following: Navigate to TestSwifty/ and run `pod install` to install AlamoFire dependencies. There are three types of unit tests here: 1.) Regular Dropbox User API tests (requires app with 'Full Dropbox' permissions) 2.) Dropbox Business API tests (requires app with 'Team member file access' permissions) 3.) Dropbox Business API tests (requires app with 'Team member management' permissions) To run all of these tests, you will need three apps, one for each of the above permission types. You must test these apps one at a time. Once you have these apps, you will need to do the following: 1.) Fill in user-specific data in `TestData` and `TestTeamData` in TestData.swift 2.) For each of the above apps, you will need to add a user-specific app key. For each test run, you will need to call `DropboxClientsManager.setupWithAppKey` (or `DropboxClientsManager.setupWithTeamAppKey`) and supply the appropriate app key value, in AppDelegate.swift 3.) Depending on which app you are currently testing, you will need to toggle the `appPermission` variable in AppDelegate.swift to the appropriate value. 4.) For each of the above apps, you will need to add a user-specific URL scheme in Info.plist > URL types > Item 0 (Editor) > URL Schemes > click '+'. URL scheme value should be 'db-<APP KEY>' where '<APP KEY>' is value of your particular app's key To create an app or to locate your app's app key, please visit the App Console here: https://www.dropbox.com/developers/apps */ // Test user app with 'Full Dropbox' permission func testAllUserEndpoints(_ asMember: Bool = false, nextTest: (() -> Void)? = nil) { let tester = DropboxTester() let end = { if let nextTest = nextTest { nextTest() } else { TestFormat.printAllTestsEnd() } } let testAuthActions = { self.testAuthActions(tester, nextTest: end) } let testUserActions = { self.testUserActions(tester, nextTest: testAuthActions) } let testSharingActions = { self.testSharingActions(tester, nextTest: testUserActions) } let start = { self.testFilesActions(tester, nextTest: testSharingActions, asMember: asMember) } start() } // Test business app with 'Team member file access' permission func testTeamMemberFileAcessActions(_ nextTest: (() -> Void)? = nil) { let tester = DropboxTeamTester() let end = { if let nextTest = nextTest { nextTest() } else { TestFormat.printAllTestsEnd() } } let testPerformActionAsMember = { self.testAllUserEndpoints(true, nextTest: end) } let start = { self.testTeamMemberFileAcessActions(tester, nextTest: testPerformActionAsMember) } start() } // Test business app with 'Team member management' permission func testTeamMemberManagementActions(_ nextTest: (() -> Void)? = nil) { let tester = DropboxTeamTester() let end = { if let nextTest = nextTest { nextTest() } else { TestFormat.printAllTestsEnd() } } let start = { self.testTeamMemberManagementActions(tester, nextTest: end) } start() } func testFilesActions(_ dropboxTester: DropboxTester, nextTest: @escaping (() -> Void), asMember: Bool = false) { let tester = FilesTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let listFolderLongpollAndTrigger = { // route currently doesn't work with Team app performing 'As Member' tester.listFolderLongpollAndTrigger(end, asMember: asMember) } let uploadFile = { tester.uploadFile(listFolderLongpollAndTrigger) } let downloadToMemory = { tester.downloadToMemory(uploadFile) } let downloadError = { tester.downloadError(downloadToMemory) } let downloadAgain = { tester.downloadAgain(downloadError) } let downloadToFile = { tester.downloadToFile(downloadAgain) } let saveUrl = { // route currently doesn't work with Team app performing 'As Member' tester.saveUrl(downloadToFile, asMember: asMember) } let listRevisions = { tester.listRevisions(saveUrl) } let getTemporaryLink = { tester.getTemporaryLink(listRevisions) } let getMetadataInvalid = { tester.getMetadataInvalid(getTemporaryLink) } let getMetadata = { tester.getMetadata(getMetadataInvalid) } let copyReferenceGet = { tester.copyReferenceGet(getMetadata) } let copy = { tester.copy(copyReferenceGet) } let uploadDataSession = { tester.uploadDataSession(copy) } let uploadData = { tester.uploadData(uploadDataSession) } let listFolder = { tester.listFolder(uploadData) } let createFolder = { tester.createFolder(listFolder) } let delete = { tester.delete(createFolder) } let start = { delete() } TestFormat.printTestBegin(#function) start() } func testSharingActions(_ dropboxTester: DropboxTester, nextTest: @escaping (() -> Void)) { let tester = SharingTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let unshareFolder = { tester.unshareFolder(end) } let updateFolderPolicy = { tester.updateFolderPolicy(unshareFolder) } let mountFolder = { tester.mountFolder(updateFolderPolicy) } let unmountFolder = { tester.unmountFolder(mountFolder) } let revokeSharedLink = { tester.revokeSharedLink(unmountFolder) } let removeFolderMember = { tester.removeFolderMember(revokeSharedLink) } let listSharedLinks = { tester.listSharedLinks(removeFolderMember) } let listFolders = { tester.listFolders(listSharedLinks) } let listFolderMembers = { tester.listFolderMembers(listFolders) } let addFolderMember = { tester.addFolderMember(listFolderMembers) } let getSharedLinkMetadata = { tester.getSharedLinkMetadata(addFolderMember) } let getFolderMetadata = { tester.getFolderMetadata(getSharedLinkMetadata) } let createSharedLinkWithSettings = { tester.createSharedLinkWithSettings(getFolderMetadata) } let shareFolder = { tester.shareFolder(createSharedLinkWithSettings) } let start = { shareFolder() } TestFormat.printTestBegin(#function) start() } func testUserActions(_ dropboxTester: DropboxTester, nextTest: @escaping (() -> Void)) { let tester = UserTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let getSpaceUsage = { tester.getSpaceUsage(end) } let getCurrentAccount = { tester.getCurrentAccount(getSpaceUsage) } let getAccountBatch = { tester.getAccountBatch(getCurrentAccount) } let getAccount = { tester.getAccount(getAccountBatch) } let start = { getAccount() } TestFormat.printTestBegin(#function) start() } func testAuthActions(_ dropboxTester: DropboxTester, nextTest: @escaping (() -> Void)) { let tester = AuthTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let tokenRevoke = { tester.tokenRevoke(end) } let start = { tokenRevoke() } TestFormat.printTestBegin(#function) start() } func testTeamMemberFileAcessActions(_ dropboxTester: DropboxTeamTester, nextTest: @escaping (() -> Void)) { let tester = TeamTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let reportsGetStorage = { tester.reportsGetStorage(end) } let reportsGetMembership = { tester.reportsGetMembership(reportsGetStorage) } let reportsGetDevices = { tester.reportsGetDevices(reportsGetMembership) } let reportsGetActivity = { tester.reportsGetActivity(reportsGetDevices) } let linkedAppsListMembersLinkedApps = { tester.linkedAppsListMembersLinkedApps(reportsGetActivity) } let linkedAppsListMemberLinkedApps = { tester.linkedAppsListMemberLinkedApps(linkedAppsListMembersLinkedApps) } let getInfo = { tester.getInfo(linkedAppsListMemberLinkedApps) } let listMembersDevices = { tester.listMembersDevices(getInfo) } let listMemberDevices = { tester.listMemberDevices(listMembersDevices) } let initMembersGetInfo = { tester.initMembersGetInfo(listMemberDevices) } let start = { initMembersGetInfo() } TestFormat.printTestBegin(#function) start() } func testTeamMemberManagementActions(_ dropboxTester: DropboxTeamTester, nextTest: @escaping (() -> Void)) { let tester = TeamTests(tester: dropboxTester) let end = { TestFormat.printTestEnd() nextTest() } let membersRemove = { tester.membersRemove(end) } let membersSetProfile = { tester.membersSetProfile(membersRemove) } let membersSetAdminPermissions = { tester.membersSetAdminPermissions(membersSetProfile) } let membersSendWelcomeEmail = { tester.membersSendWelcomeEmail(membersSetAdminPermissions) } let membersList = { tester.membersList(membersSendWelcomeEmail) } let membersGetInfo = { tester.membersGetInfo(membersList) } let membersAdd = { tester.membersAdd(membersGetInfo) } let groupsDelete = { tester.groupsDelete(membersAdd) } let groupsUpdate = { tester.groupsUpdate(groupsDelete) } let groupsMembersList = { tester.groupsMembersList(groupsUpdate) } let groupsMembersAdd = { tester.groupsMembersAdd(groupsMembersList) } let groupsList = { tester.groupsList(groupsMembersAdd) } let groupsGetInfo = { tester.groupsGetInfo(groupsList) } let groupsCreate = { tester.groupsCreate(groupsGetInfo) } let initMembersGetInfo = { tester.initMembersGetInfo(groupsCreate) } let start = { initMembersGetInfo() } TestFormat.printTestBegin(#function) start() } }
32.820628
194
0.588195
e4d7508233b604336ce5a2864f84ffa098d536ef
17,772
import KsApi import Prelude import ReactiveSwift public typealias SelectedRewardId = Int public typealias SelectedRewardQuantity = Int public typealias SelectedRewardQuantities = [SelectedRewardId: SelectedRewardQuantity] public enum RewardAddOnSelectionDataSourceItem: Equatable { case rewardAddOn(RewardAddOnCardViewData) case emptyState(EmptyStateViewType) public var rewardAddOnCardViewData: RewardAddOnCardViewData? { switch self { case let .rewardAddOn(data): return data case .emptyState: return nil } } public var emptyStateViewType: EmptyStateViewType? { switch self { case .rewardAddOn: return nil case let .emptyState(viewType): return viewType } } } public protocol RewardAddOnSelectionViewModelInputs { func beginRefresh() func configure(with data: PledgeViewData) func continueButtonTapped() func rewardAddOnCardViewDidSelectQuantity(quantity: Int, rewardId: Int) func shippingLocationViewDidFailToLoad() func shippingRuleSelected(_ shippingRule: ShippingRule) func viewDidLoad() } public protocol RewardAddOnSelectionViewModelOutputs { var configureContinueCTAViewWithData: Signal<RewardAddOnSelectionContinueCTAViewData, Never> { get } var configurePledgeShippingLocationViewControllerWithData: Signal<PledgeShippingLocationViewData, Never> { get } var endRefreshing: Signal<(), Never> { get } var goToPledge: Signal<PledgeViewData, Never> { get } var loadAddOnRewardsIntoDataSource: Signal<[RewardAddOnSelectionDataSourceItem], Never> { get } var loadAddOnRewardsIntoDataSourceAndReloadTableView: Signal<[RewardAddOnSelectionDataSourceItem], Never> { get } var shippingLocationViewIsHidden: Signal<Bool, Never> { get } var startRefreshing: Signal<(), Never> { get } } public protocol RewardAddOnSelectionViewModelType { var inputs: RewardAddOnSelectionViewModelInputs { get } var outputs: RewardAddOnSelectionViewModelOutputs { get } } public final class RewardAddOnSelectionViewModel: RewardAddOnSelectionViewModelType, RewardAddOnSelectionViewModelInputs, RewardAddOnSelectionViewModelOutputs { public init() { let configData = Signal.combineLatest( self.configureWithDataProperty.signal.skipNil(), self.viewDidLoadProperty.signal ) .map(first) let project = configData.map(\.project) let baseReward = configData.map(\.rewards).map(\.first).skipNil() let baseRewardQuantities = configData.map(\.selectedQuantities) let refTag = configData.map(\.refTag) let context = configData.map(\.context) let initialLocationId = configData.map(\.selectedLocationId) let shippingLocationViewConfigData = Signal.zip(project, baseReward, initialLocationId) let fetchShippingLocations = Signal.merge( shippingLocationViewConfigData, shippingLocationViewConfigData.takeWhen(self.beginRefreshSignal) ) .filter { _, reward, _ in reward.shipping.enabled } self.configurePledgeShippingLocationViewControllerWithData = fetchShippingLocations .map { project, reward, initialLocationId in (project, reward, false, initialLocationId) } let slug = project.map(\.slug) let fetchAddOnsWithSlug = Signal.merge( slug, slug.takeWhen(self.beginRefreshSignal) ) let shippingRule = Signal.merge( self.shippingRuleSelectedProperty.signal, baseReward.filter { reward in !reward.shipping.enabled }.mapConst(nil) ) let slugAndShippingRule = Signal.combineLatest(fetchAddOnsWithSlug, shippingRule) let projectEvent = slugAndShippingRule.switchMap { slug, shippingRule in AppEnvironment.current.apiService.fetchRewardAddOnsSelectionViewRewards( query: rewardAddOnSelectionViewAddOnsQuery( withProjectSlug: slug, andGraphId: shippingRule?.location.graphID ) ) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } self.startRefreshing = self.beginRefreshSignal self.endRefreshing = projectEvent.filter { $0.isTerminating }.ignoreValues() let addOns = projectEvent.values().map(\.rewardData.addOns).skipNil() let requestErrored = projectEvent.map(\.error).map(isNotNil) // Quantities updated as the user selects them, merged with an empty initial value. let updatedSelectedQuantities = Signal.merge( self.rewardAddOnCardViewDidSelectQuantityProperty.signal .skipNil() .scan([:]) { current, new -> SelectedRewardQuantities in let (quantity, rewardId) = new var mutableCurrent = current mutableCurrent[rewardId] = quantity return mutableCurrent }, configData.mapConst([:]) ) let backedQuantities = project.map { project -> SelectedRewardQuantities in guard let backing = project.personalization.backing else { return [:] } return selectedRewardQuantities(in: backing) } // Backed quantities overwritten by user-selected quantities. let selectedAddOnQuantities = Signal.combineLatest( updatedSelectedQuantities, backedQuantities ) .map { updatedSelectedQuantities, backedQuantities in backedQuantities.withAllValuesFrom(updatedSelectedQuantities) } // User-selected and backed quantities combined with the base reward selection. let selectedQuantities = Signal.combineLatest( selectedAddOnQuantities, baseRewardQuantities ) .map { selectedAddOnQuantities, baseRewardQuantities in selectedAddOnQuantities.withAllValuesFrom(baseRewardQuantities) } let latestSelectedQuantities = Signal.merge( baseRewardQuantities, selectedQuantities ) let rewardAddOnCardsViewData = Signal.combineLatest( addOns, project, baseReward, context, shippingRule ) let reloadRewardsIntoDataSource = rewardAddOnCardsViewData .withLatest(from: latestSelectedQuantities) .map(unpack) .map(rewardsData) self.loadAddOnRewardsIntoDataSourceAndReloadTableView = Signal.merge( reloadRewardsIntoDataSource, requestErrored.filter(isTrue).mapConst([.emptyState(.errorPullToRefresh)]) ) self.loadAddOnRewardsIntoDataSource = rewardAddOnCardsViewData .takePairWhen(latestSelectedQuantities) .map(unpack) .map(rewardsData) self.shippingLocationViewIsHidden = Signal.merge( baseReward.map(\.shipping.enabled).negate(), self.shippingLocationViewDidFailToLoadProperty.signal.mapConst(true), fetchShippingLocations.mapConst(false) ) .skipRepeats() let dataSourceItems = Signal.merge( self.loadAddOnRewardsIntoDataSourceAndReloadTableView, self.loadAddOnRewardsIntoDataSource ) let allRewards = dataSourceItems.map { items in items.compactMap { item -> Reward? in item.rewardAddOnCardViewData?.reward } } let baseRewardAndAddOnRewards = Signal.combineLatest( baseReward, dataSourceItems.map { items in items.compactMap { item -> Reward? in item.rewardAddOnCardViewData?.reward } } ) let totalSelectedAddOnsQuantity = Signal.combineLatest( latestSelectedQuantities, baseReward.map(\.id), allRewards.map { $0.map(\.id) } ) .map { quantities, baseRewardId, addOnRewardIds in quantities // Filter out the base reward for determining the add-on quantities .filter { key, _ in key != baseRewardId && addOnRewardIds.contains(key) } .reduce(0) { accum, keyValue in let (_, value) = keyValue return accum + value } } let selectionChanged = Signal.combineLatest(project, latestSelectedQuantities, shippingRule) .map(isValid) self.configureContinueCTAViewWithData = Signal.merge( Signal.combineLatest(totalSelectedAddOnsQuantity, selectionChanged) .map { qty, isValid in (qty, isValid, false) }, configData.mapConst((0, true, true)) ) let selectedRewards = baseRewardAndAddOnRewards .combineLatest(with: latestSelectedQuantities) .map(unpack) .map { baseReward, addOnRewards, selectedQuantities -> [Reward] in let selectedRewardIds = selectedQuantities .filter { _, qty in qty > 0 } .keys return [baseReward] + addOnRewards .filter { reward in selectedRewardIds.contains(reward.id) } } let selectedLocationId = Signal.merge( initialLocationId, shippingRule.map { $0?.location.id } ) self.goToPledge = Signal.combineLatest( project, selectedRewards, selectedQuantities, selectedLocationId, refTag, context ) .map(PledgeViewData.init) .takeWhen(self.continueButtonTappedProperty.signal) let shippingTotal = Signal.combineLatest( shippingRule.skipNil(), selectedRewards, selectedQuantities ) .map(calculateShippingTotal) let baseRewardShippingTotal = Signal.zip(project, baseReward, shippingRule) .map(getBaseRewardShippingTotal) let allRewardsShippingTotal = Signal.merge( baseRewardShippingTotal, shippingTotal ) // Additional pledge amount is zero if not backed. let additionalPledgeAmount = Signal.merge( configData.filter { $0.project.personalization.backing == nil }.mapConst(0.0), project.map { $0.personalization.backing }.skipNil().map(\.bonusAmount) ) let allRewardsTotal = Signal.combineLatest( selectedRewards, selectedQuantities ) .map(calculateAllRewardsTotal) let combinedPledgeTotal = Signal.combineLatest( additionalPledgeAmount, allRewardsShippingTotal, allRewardsTotal ) .map(calculatePledgeTotal) let pledgeTotal = Signal.merge( project.map { $0.personalization.backing }.skipNil().map(\.amount), combinedPledgeTotal ) // MARK: - Tracking // shippingRule needs to be set for the event is fired Signal.zip( project, baseReward, selectedRewards, refTag, configData, additionalPledgeAmount, allRewardsShippingTotal, pledgeTotal ) .take(first: 1) .observeForUI() .observeValues { project, baseReward, selectedRewards, refTag, configData, additionalPledgeAmount, shippingTotal, pledgeTotal in let checkoutPropertiesData = checkoutProperties( from: project, baseReward: baseReward, addOnRewards: selectedRewards, selectedQuantities: configData.selectedQuantities, additionalPledgeAmount: additionalPledgeAmount, pledgeTotal: pledgeTotal, shippingTotal: shippingTotal, isApplePay: nil ) AppEnvironment.current.ksrAnalytics.trackAddOnsPageViewed( project: project, reward: baseReward, checkoutData: checkoutPropertiesData, refTag: refTag ) } // Send updated checkout data with add-ons continue event Signal.combineLatest( project, baseReward, selectedRewards, selectedQuantities, additionalPledgeAmount, pledgeTotal, allRewardsShippingTotal, refTag ).takeWhen(self.continueButtonTappedProperty.signal) .observeValues { project, baseReward, selectedRewards, selectedQuantities, additionalPledgeAmount, pledgeTotal, shippingTotal, refTag in let checkoutData = checkoutProperties( from: project, baseReward: baseReward, addOnRewards: selectedRewards, selectedQuantities: selectedQuantities, additionalPledgeAmount: additionalPledgeAmount, pledgeTotal: pledgeTotal, shippingTotal: shippingTotal, isApplePay: nil ) AppEnvironment.current.ksrAnalytics.trackAddOnsContinueButtonClicked( project: project, reward: baseReward, checkoutData: checkoutData, refTag: refTag ) } } private let (beginRefreshSignal, beginRefreshObserver) = Signal<Void, Never>.pipe() public func beginRefresh() { self.beginRefreshObserver.send(value: ()) } private let configureWithDataProperty = MutableProperty<PledgeViewData?>(nil) public func configure(with data: PledgeViewData) { self.configureWithDataProperty.value = data } private let continueButtonTappedProperty = MutableProperty(()) public func continueButtonTapped() { self.continueButtonTappedProperty.value = () } private let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } private let rewardAddOnCardViewDidSelectQuantityProperty = MutableProperty<(SelectedRewardQuantity, SelectedRewardId)?>(nil) public func rewardAddOnCardViewDidSelectQuantity( quantity: SelectedRewardQuantity, rewardId: SelectedRewardId ) { self.rewardAddOnCardViewDidSelectQuantityProperty.value = (quantity, rewardId) } private let shippingLocationViewDidFailToLoadProperty = MutableProperty(()) public func shippingLocationViewDidFailToLoad() { self.shippingLocationViewDidFailToLoadProperty.value = () } private let shippingRuleSelectedProperty = MutableProperty<ShippingRule?>(nil) public func shippingRuleSelected(_ shippingRule: ShippingRule) { self.shippingRuleSelectedProperty.value = shippingRule } public let configureContinueCTAViewWithData: Signal<RewardAddOnSelectionContinueCTAViewData, Never> public let configurePledgeShippingLocationViewControllerWithData: Signal<PledgeShippingLocationViewData, Never> public let endRefreshing: Signal<(), Never> public let goToPledge: Signal<PledgeViewData, Never> public let loadAddOnRewardsIntoDataSource: Signal<[RewardAddOnSelectionDataSourceItem], Never> public let loadAddOnRewardsIntoDataSourceAndReloadTableView: Signal<[RewardAddOnSelectionDataSourceItem], Never> public let shippingLocationViewIsHidden: Signal<Bool, Never> public let startRefreshing: Signal<(), Never> public var inputs: RewardAddOnSelectionViewModelInputs { return self } public var outputs: RewardAddOnSelectionViewModelOutputs { return self } } // MARK: - Functions private func unpack( rewardsData: ([Reward], Project, Reward, PledgeViewContext, ShippingRule?), selectedQuantities: SelectedRewardQuantities ) -> ([Reward], Project, Reward, PledgeViewContext, ShippingRule?, SelectedRewardQuantities) { return (rewardsData.0, rewardsData.1, rewardsData.2, rewardsData.3, rewardsData.4, selectedQuantities) } private func rewardsData( addOns: [Reward], project: Project, baseReward: Reward, context: PledgeViewContext, shippingRule: ShippingRule?, selectedQuantities: SelectedRewardQuantities ) -> [RewardAddOnSelectionDataSourceItem] { let addOnsFilteredByAvailability = addOns.filter { addOnIsAvailable($0, in: project) } let addOnsFilteredByExpandedShippingRule = filteredAddOns( addOnsFilteredByAvailability, filteredBy: shippingRule, baseReward: baseReward ) guard !addOnsFilteredByExpandedShippingRule.isEmpty else { return [.emptyState(.addOnsUnavailable)] } return addOnsFilteredByExpandedShippingRule .map { reward in RewardAddOnCardViewData( project: project, reward: reward, context: context == .pledge ? .pledge : .manage, shippingRule: reward.shipping.enabled ? reward.shippingRule(matching: shippingRule) : nil, selectedQuantities: selectedQuantities ) } .map(RewardAddOnSelectionDataSourceItem.rewardAddOn) } private func addOnIsAvailable(_ addOn: Reward, in project: Project) -> Bool { // If the user is backing this addOn, it's available for editing if let backedAddOns = project.personalization.backing?.addOns, backedAddOns.map(\.id).contains(addOn.id) { return true } let isUnlimitedOrAvailable = addOn.limit == nil || addOn.remaining ?? 0 > 0 // Assuming the user has not backed the addOn, we only display if it's within range of the start and end date let hasNoTimeLimitOrIsWithinRange = isStartDateBeforeToday(for: addOn) && isEndDateAfterToday(for: addOn) return [ project.state == .live, hasNoTimeLimitOrIsWithinRange, isUnlimitedOrAvailable ] .allSatisfy(isTrue) } private func filteredAddOns( _ addOns: [Reward], filteredBy shippingRule: ShippingRule?, baseReward: Reward ) -> [Reward] { return addOns.filter { addOn in // For digital-only base rewards only return add-ons that are also digital-only. if baseReward.shipping.enabled == false { return addOn.shipping.enabled == false } /** For restricted or unrestricted shipping base rewards, unrestricted shipping or digital-only add-ons are available. */ return addOn.shipping.preference .isAny(of: Reward.Shipping.Preference.none) || addOnReward(addOn, shipsTo: shippingRule?.location.id) } } /** For base rewards that have restricted or unrestricted shipping, only return add-ons that can ship to the selected shipping location. */ private func addOnReward( _ addOn: Reward, shipsTo locationId: Int? ) -> Bool { guard let selectedLocationId = locationId else { return false } let addOnShippingLocationIds: Set<Int> = Set( addOn.shippingRulesExpanded?.map(\.location).map(\.id) ?? [] ) return addOnShippingLocationIds.contains(selectedLocationId) } private func isValid( project: Project, latestSelectedQuantities: SelectedRewardQuantities, selectedShippingRule: ShippingRule? ) -> Bool { guard let backing = project.personalization.backing else { return true } return latestSelectedQuantities != selectedRewardQuantities(in: backing) || backing.locationId != selectedShippingRule?.location.id }
33.787072
142
0.730644
71581d4e74a45ebc9aabdccc80107f87a5f1b50d
1,728
// // SharingGroups.swift // SharingExtensionUI // // Created by Christopher G Prince on 10/4/20. // import SwiftUI import iOSSignIn // Adapted from https://stackoverflow.com/questions/59141688/swiftui-change-list-row-highlight-colour-when-tapped struct SharingGroupsView: View { @ObservedObject var viewModel:ShareViewModel @Environment(\.colorScheme) var colorScheme var selectedColor: Color { if colorScheme == .dark { return Color.gray } else { return Color(UIColor.lightGray) } } var body: some View { // Wanted to use a form to get the list background color working, but this makes the header non-sticky https://stackoverflow.com/questions/56517904 List { Section(header: Text("Album")) { ForEach(viewModel.sharingGroups, id: \.self) { group in Button(action: { if self.viewModel.selectedSharingGroupUUID != group.id { self.viewModel.selectedSharingGroupUUID = group.id } }, label: { Text(group.name) }) .listRowBackground( self.viewModel.selectedSharingGroupUUID == group.id ? selectedColor : Color(UIColor.systemGroupedBackground)) } // `textCase` -- a hack to not have the Section title be upper case. See https://developer.apple.com/forums/thread/655524 }.textCase(nil) }.listRowBackground(Color(UIColor.systemBackground)) .background(Color(UIColor.systemBackground)) } }
33.882353
155
0.575231
bfb173c81eaf35f0697e4ae988bce57285e52cd8
1,729
// // ViewController.swift // seaHorse // // Created by Bailey Yingling on 11/2/20. // Copyright © 2020 Bailey Yingling. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBOutlet weak var courtImage: UIView! @IBAction func courtPan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) courtImage.center = CGPoint(x: point.x, y: point.y) } @IBOutlet weak var fearImage: UIView! @IBAction func fearPan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) fearImage.center = CGPoint(x: point.x, y: point.y) } @IBOutlet weak var summerImage: UIView! @IBAction func summerPan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) summerImage.center = CGPoint(x: point.x, y: point.y) } @IBOutlet weak var madvillainyImage: UIView! @IBAction func madvillainyPan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) madvillainyImage.center = CGPoint(x: point.x, y: point.y) } @IBOutlet weak var shipImage: UIView! @IBAction func shipPan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) shipImage.center = CGPoint(x: point.x, y: point.y) } @IBOutlet weak var whiteImage: UIView! @IBAction func whitePan(_ sender: UIPanGestureRecognizer) { let point = sender.location(in: view) whiteImage.center = CGPoint(x: point.x, y: point.y) } }
27.444444
69
0.64199
e9afd1f67364d5628038a7183ec1ecdabadb7a84
2,166
// // RxMoyaProvider+ExceptionRequest.swift // rabbitDoctor // // Created by Mac on 2017/8/2. // Copyright © 2017年 rabbitDoctor. All rights reserved. // import Foundation import RxSwift import Moya import ObjectMapper import Result import SwiftyJSON public extension RxMoyaProvider { func tryExceptionRequest<T: Any>(_ token: Target, _ type: T.Type) -> Observable<T> { return Observable.create { [weak self] observer -> Disposable in let cancelableToken = self?.request(token) { result in switch result { case let .success(response): let json = JSON.init(data: response.data) let templateType = "\(T.self)".lowercased() switch json.type { case .array where templateType.contains("array"): observer.onNext(json.arrayValue as! T) case .dictionary where templateType.contains("dictionary"): observer.onNext(json.dictionaryValue as! T) case .number where (templateType.contains("number") || templateType.contains("int") || templateType.contains("float") || templateType.contains("double")), .bool where templateType.contains("bool"): observer.onNext(json.numberValue as! T) case .string where templateType.contains("string"): observer.onNext(json.stringValue as! T) default: observer.onError(ErrorFactory.createError(code: networkErrorType.paraTypeError.0, errorMessage: networkErrorType.paraTypeError.1)) } observer.onCompleted() case let .failure(error): observer.onError(error) } } return Disposables.create { cancelableToken?.cancel() } } } }
36.711864
154
0.515235
623cc8ba9f6faef4d1203dcb0b3cafc323ca77aa
18,256
// TransactionViewController.swift /* Package MobileWallet Created by Jason van den Berg on 2019/11/07 Using Swift 5.0 Running on macOS 10.15 Copyright 2019 The Tari Project Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit class TransactionViewController: UIViewController, UITextFieldDelegate { let bottomHeadingPadding: CGFloat = 11 let valueViewHeightMultiplierFull: CGFloat = 0.2536 let valueViewHeightMultiplierShortened: CGFloat = 0.18 let defaultNavBarHeight: CGFloat = 90 var contactPublicKey: PublicKey? var contactAlias: String = "" let navigationBar = NavigationBarWithSubtitle() let valueContainerView = UIView() var valueContainerViewHeightConstraintFull = NSLayoutConstraint() var valueContainerViewHeightConstraintShortened = NSLayoutConstraint() var valueCenterYAnchorConstraint = NSLayoutConstraint() let valueLabel = UILabel() let emojiButton = EmoticonView() let fromContainerView = UIView() let fromHeadingLabel = UILabel() let addContactButton = TextButton() let contactNameHeadingLabel = UILabel() let contactNameTextField = UITextField() let editContactNameButton = TextButton() let dividerView = UIView() let noteHeadingLabel = UILabel() let noteLabel = UILabel() var noteHeadingLabelTopAnchorConstraintContactNameShowing = NSLayoutConstraint() var noteHeadingLabelTopAnchorConstraintContactNameMissing = NSLayoutConstraint() var navigationBarHeightAnchor = NSLayoutConstraint() let txStateView = AnimatedRefreshingView() var transaction: TransactionProtocol? private var isShowingStateView = false @IBOutlet weak var transactionIDLabel: UILabel! var isShowingContactAlias: Bool = true { didSet { if isShowingContactAlias { noteHeadingLabelTopAnchorConstraintContactNameMissing.isActive = false noteHeadingLabelTopAnchorConstraintContactNameShowing.isActive = true addContactButton.isHidden = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: { [ weak self] in guard let self = self else { return } self.contactNameTextField.isHidden = false self.contactNameHeadingLabel.isHidden = false self.dividerView.isHidden = false }) } else { noteHeadingLabelTopAnchorConstraintContactNameShowing.isActive = false noteHeadingLabelTopAnchorConstraintContactNameMissing.isActive = true contactNameTextField.isHidden = true contactNameHeadingLabel.isHidden = true dividerView.isHidden = true editContactNameButton.isHidden = true } } } var isEditingContactName: Bool = false { didSet { if isEditingContactName { contactNameTextField.becomeFirstResponder() editContactNameButton.isHidden = true UIView.animate(withDuration: 0.15, delay: 0, options: .curveLinear, animations: { [weak self] () in guard let self = self else { return } self.valueContainerViewHeightConstraintFull.isActive = false self.valueContainerViewHeightConstraintShortened.isActive = true self.view.layoutIfNeeded() }) } else { contactNameTextField.resignFirstResponder() editContactNameButton.isHidden = false UIView.animate(withDuration: 0.15, delay: 0, options: .curveLinear, animations: { [weak self] () in guard let self = self else { return } self.valueContainerViewHeightConstraintShortened.isActive = false self.valueContainerViewHeightConstraintFull.isActive = true self.view.layoutIfNeeded() }) } } } override func viewDidLoad() { super.viewDidLoad() setup() do { try setDetails() } catch { UserFeedback.shared.error( title: NSLocalizedString("Transaction error", comment: "Transaction detail screen"), description: NSLocalizedString("Failed to load transaction details", comment: "Transaction detail screen"), error: error ) } hideKeyboardWhenTappedAroundOrSwipedDown() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) Tracker.shared.track("/home/tx_details", "Transaction Details") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) registerEvents() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) unRegisterEvents() } private func setup() { view.backgroundColor = Theme.shared.colors.appBackground setupNavigationBar() setupValueView() setupFromEmojis() setupAddContactButton() setupContactName() setupEditContactButton() setupDivider() setupNote() view.bringSubviewToFront(emojiButton) //Transaction ID transactionIDLabel.textColor = Theme.shared.colors.transactionScreenSubheadingLabel transactionIDLabel.font = Theme.shared.fonts.transactionScreenTxIDLabel } @objc func keyboardWillHide(notification: NSNotification) { if isEditingContactName { isEditingContactName = false } } @objc func feeButtonPressed(_ sender: UIButton) { UserFeedback.shared.info( title: NSLocalizedString("Where does the fee go?", comment: "Transaction detail view"), description: NSLocalizedString("The transaction fee is distributed to the thousands of computers (also known as “miners”) who ensure that your Tari transactions are fast and secure.", comment: "Transaction detail view") ) } @objc func editContactButtonPressed(_ sender: UIButton) { isEditingContactName = true } @objc func addContactButtonPressed(_ sender: UIButton) { isShowingContactAlias = true isEditingContactName = true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return isEditingContactName } func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard textField.text?.isEmpty == false else { textField.text = contactAlias return false } isEditingContactName = false guard contactPublicKey != nil else { UserFeedback.shared.error( title: NSLocalizedString("Contact error", comment: "Transaction detail screen"), description: NSLocalizedString("Missing public key from transaction.", comment: "Transaction detail screen") ) return true } do { try TariLib.shared.tariWallet!.addUpdateContact(alias: textField.text!, publicKey: contactPublicKey!) DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: { UINotificationFeedbackGenerator().notificationOccurred(.success) //UserFeedback.shared.success(title: NSLocalizedString("Contact Updated!", comment: "Transaction detail screen")) }) } catch { UserFeedback.shared.error( title: NSLocalizedString("Contact error", comment: "Transaction detail screen"), description: NSLocalizedString("Failed to save contact details.", comment: "Transaction detail screen"), error: error ) } return true } private func registerEvents() { updateTxState() let eventTypes: [TariEventTypes] = [ .receievedTransactionReply, .receivedFinalizedTransaction, .transactionBroadcast, .transactionMined ] eventTypes.forEach { (eventType) in TariEventBus.onMainThread(self, eventType: eventType) { [weak self] (result) in guard let self = self else { return } self.didRecieveUpdatedTx(updatedTx: result?.object as? TransactionProtocol) } } } private func unRegisterEvents() { TariEventBus.unregister(self) } func didRecieveUpdatedTx(updatedTx: TransactionProtocol?) { guard let currentTx = transaction else { return } guard let newTx = updatedTx else { TariLogger.warn("Did not get transaction in callback reponse") return } guard currentTx.id.0 == newTx.id.0 else { //Received a tx update but it was for another tx return } transaction = newTx do { try setDetails() updateTxState() } catch { TariLogger.error("Failed to update TX state", error: error) } } private func showStateView(defaultState: AnimatedRefreshingViewState, _ onComplete: @escaping () -> Void) { guard !isShowingStateView else { onComplete() return } UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: { [weak self] in guard let self = self else { return } self.navigationBarHeightAnchor.constant = self.defaultNavBarHeight + AnimatedRefreshingView.containerHeight + 10 self.navigationBar.layoutIfNeeded() self.view.layoutIfNeeded() }) { [weak self] (_) in guard let self = self else { return } self.txStateView.translatesAutoresizingMaskIntoConstraints = false self.navigationBar.addSubview(self.txStateView) self.txStateView.bottomAnchor.constraint(equalTo: self.navigationBar.bottomAnchor, constant: -Theme.shared.sizes.appSidePadding).isActive = true self.txStateView.leadingAnchor.constraint(equalTo: self.navigationBar.leadingAnchor, constant: Theme.shared.sizes.appSidePadding).isActive = true self.txStateView.trailingAnchor.constraint(equalTo: self.navigationBar.trailingAnchor, constant: -Theme.shared.sizes.appSidePadding).isActive = true self.txStateView.setupView(defaultState) self.txStateView.animateIn() self.isShowingStateView = true onComplete() } } private func hideStateView() { guard isShowingStateView else { return } self.txStateView.animateOut { [weak self] in guard let self = self else { return } UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: { [weak self] in guard let self = self else { return } self.navigationBarHeightAnchor.constant = self.defaultNavBarHeight self.navigationBar.layoutIfNeeded() self.view.layoutIfNeeded() }) { [weak self] (_) in guard let self = self else { return } self.isShowingStateView = false } } } private func updateTxState() { guard let tx = transaction else { return } var newState: AnimatedRefreshingViewState? switch tx.status.0 { case .completed: newState = .txWaitingForSender case .pending: if tx.direction == .inbound { newState = .txWaitingForSender } else if tx.direction == .outbound { newState = .txWaitingForRecipient } case .broadcast: newState = .txBroadcasted default: newState = nil } if let state = newState { //Attempt to show it if it's not showing yet, else just update the state showStateView(defaultState: state) { [weak self] in guard let self = self else { return } self.txStateView.updateState(state) } } else { hideStateView() } } private func setDetails() throws { if let tx = transaction { let (microTari, microTariError) = tx.microTari guard microTariError == nil else { throw microTariError! } if tx.direction == .inbound { navigationBar.title = NSLocalizedString("Payment Received", comment: "Navigation bar title on transaction view screen") fromHeadingLabel.text = NSLocalizedString("From", comment: "Transaction detail view") valueLabel.text = microTari!.formatted contactPublicKey = tx.sourcePublicKey.0 } else if tx.direction == .outbound { navigationBar.title = NSLocalizedString("Payment Sent", comment: "Navigation bar title on transaction view screen") fromHeadingLabel.text = NSLocalizedString("To", comment: "Transaction detail view") valueLabel.text = microTari!.formatted contactPublicKey = tx.destinationPublicKey.0 } if let pubKey = contactPublicKey { let (emojis, emojisError) = pubKey.emojis guard emojisError == nil else { throw emojisError! } emojiButton.setUpView(emojiText: emojis, type: .buttonView, textCentered: false, inViewController: self, showContainerViewBlur: false) } let (date, dateError) = tx.date guard dateError == nil else { throw dateError! } navigationBar.subtitle = date!.formattedDisplay() let (contact, contactError) = tx.contact if contactError == nil { let (alias, aliasError) = contact!.alias guard aliasError == nil else { throw aliasError! } contactAlias = alias contactNameTextField.text = contactAlias isShowingContactAlias = true } else { isShowingContactAlias = false } let (message, messageError) = tx.message guard messageError == nil else { throw messageError! } setNoteText(message) let (id, idError) = tx.id guard idError == nil else { throw idError! } let txIdDisplay = NSLocalizedString("Transaction ID:", comment: "Transaction detail view") + " \(String(id))" //Get the fee for outbound transactions only if let completedTx = tx as? CompletedTransaction { if completedTx.direction == .outbound { let (fee, feeError) = completedTx.fee guard feeError == nil else { throw feeError! } setFeeLabel(fee!.formattedPreciseWithOperator) } } else if let pendingOutboundTx = tx as? PendingOutboundTransaction { let (fee, feeError) = pendingOutboundTx.fee guard feeError == nil else { throw feeError! } setFeeLabel(fee!.formattedPreciseWithOperator) } if tx.status.0 != .mined && tx.status.0 != .imported { navigationBar.title = NSLocalizedString("Payment In Progress", comment: "Navigation bar title on transaction view screen") } //Hopefully we can add this back some time var statusEmoji = "" //If the app is in debug mode, show the status if TariSettings.shared.isDebug { switch tx.status.0 { case .completed: statusEmoji = " ✔️" case .broadcast: statusEmoji = " 📡" case .mined: statusEmoji = " ⛏️" case .imported: statusEmoji = " 🤖" case .pending: statusEmoji = " ⏳" case .transactionNullError: statusEmoji = " 🤔" case .unknown: statusEmoji = " 🤷" } } transactionIDLabel.text = "\(txIdDisplay)\(statusEmoji)" } } }
37.719008
231
0.610375
1cafa79821a6aab323b4beebb6f0af23a6cf99a3
496
// Import the SwiftIO library to control input and output. import SwiftIO // Import the SwiftIOFeather to use the id of the pins. import MadBoard import LIS3DH // Initialize the I2C bus and the sensor. let i2c = I2C(Id.I2C0) let acc = LIS3DH(i2c) // Send the command to the sensor to obtain the value and print it every second. while true { let value = acc.readXYZ() print("x: \(value.x)g") print("y: \(value.y)g") print("z: \(value.z)g") print("\n") sleep(ms: 1000) }
23.619048
80
0.671371
87edc8d648df89d0787ed285ac5c6918292bc07a
4,911
import Foundation import ShellCommand import Toolkit public final class DSYMSymbolizer { private let dwarfUUIDProvider: DWARFUUIDProvider private let fileManager: FileManager public init( dwarfUUIDProvider: DWARFUUIDProvider, fileManager: FileManager) { self.dwarfUUIDProvider = dwarfUUIDProvider self.fileManager = fileManager } // LLDB documentation https://jonasdevlieghere.com/static/lldb/use/symbols.html // Some lldb related source https://github.com/llvm-mirror/lldb/blob/master/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp // Post about patching https://medium.com/@maxraskin/background-1b4b6a9c65be public func symbolize( dsymBundlePath: String, sourcePath: String, buildSourcePath: String, binaryPath: String, binaryPathInApp: String) throws { guard try shouldPatchDSYM(dsymBundlePath: dsymBundlePath, sourcePath: sourcePath) == true else { return } let binaryUUIDs = try dwarfUUIDProvider.obtainDwarfUUIDs(path: binaryPath) let dsymUUIDs = try dwarfUUIDProvider.obtainDwarfUUIDs(path: dsymBundlePath) guard try validateUUID(binaryUUIDs: binaryUUIDs, dsymUUIDs: dsymUUIDs) == true else { throw DSYMSymbolizerError.uuidMismatch( dsymPath: dsymBundlePath, binaryPath: binaryPath ) } try generatePlist( dsymBundlePath: dsymBundlePath, binaryPathInApp: binaryPathInApp, localSourcePath: sourcePath, remoteSourcePath: buildSourcePath, binaryUUIDs: binaryUUIDs ) } private func validateUUID( binaryUUIDs: [DWARFUUID], dsymUUIDs: [DWARFUUID]) throws -> Bool { for binaryUUID in binaryUUIDs { if dsymUUIDs.contains(binaryUUID) { continue } return false } return true } public func shouldPatchDSYM(dsymBundlePath: String, sourcePath: String) throws -> Bool { let plistDirectory = dsymBundlePath .appendingPathComponent("Contents") .appendingPathComponent("Resources") let directoryFiles = try fileManager.contentsOfDirectory(atPath: plistDirectory) for fileName in directoryFiles { if fileName.pathExtension() == "plist" { let filePath = plistDirectory.appendingPathComponent(fileName) if fileManager.isReadableFile(atPath: filePath) { if let plistContent = NSDictionary(contentsOfFile: filePath), let plistSourcePath = plistContent["DBGSourcePath"] as? String, plistSourcePath.contains(sourcePath) { return false } } } } return true } private func generatePlist( dsymBundlePath: String, binaryPathInApp: String, localSourcePath: String, remoteSourcePath: String, binaryUUIDs: [DWARFUUID]) throws { for uuid in binaryUUIDs { let plistName = uuid.uuid.uuidString + ".plist" let plistPath = dsymBundlePath .appendingPathComponent("Contents") .appendingPathComponent("Resources") .appendingPathComponent(plistName) let dwarfFilePath = try obtainDSYMBinaryPath(dsymBundlePath: dsymBundlePath) let content: [String: String] = [ "DBGArchitecture": uuid.architecture, "DBGBuildSourcePath": remoteSourcePath, "DBGSourcePath": localSourcePath, "DBGDSYMPath": dwarfFilePath, "DBGSymbolRichExecutable": binaryPathInApp ] try fileManager.write( content, to: plistPath ) } } private func obtainDSYMBinaryPath(dsymBundlePath: String) throws -> String { // Some.framework.dSYM/Contents/Resources/DWARF/Some let dwarfDirectory = dsymBundlePath .appendingPathComponent("Contents") .appendingPathComponent("Resources") .appendingPathComponent("DWARF") let content = try fileManager.contentsOfDirectory(atPath: dwarfDirectory) if content.count > 1 { throw DSYMSymbolizerError.multipleDWARFFileInDSYM( dsymPath: dsymBundlePath ) } if content.isEmpty { throw DSYMSymbolizerError.unableToFindDWARFFileInDSYM( dsymPath: dsymBundlePath ) } let dwarfFilePath = dwarfDirectory.appendingPathComponent(content[0]) return dwarfFilePath } }
36.377778
137
0.605987
384b041b5d37775c2f2d45915188763a8e4f9438
1,430
import UIKit var str = "内嵌类型" // 枚举通常用于实现特定类或结构体的功能。类似的,它也可以在更加复杂的类型环境中方便的定义通用类和结构体。为实现这种功能,Swift 允许你定义内嵌类型,借此在支持类型的定义中嵌套枚举、类、或结构体。 // 若要在一种类型中嵌套另一种类型,在其支持类型的大括号内定义即可。可以根据需求多级嵌套数个类型。 struct BlackjackCard { // nested Suit enumeration enum Suit: Character { case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣" } // nested Rank enumeration enum Rank: Int { case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King, Ace struct Values { let first: Int, second: Int? } var values: Values { switch self { case .Ace: return Values(first: 1, second: 11) case .Jack, .Queen, .King: return Values(first: 10, second: nil) default: return Values(first: self.rawValue, second: nil) } } } // BlackjackCard properties and methods let rank: Rank, suit: Suit var description: String { var output = "suit is \(suit.rawValue)," output += " value is \(rank.values.first)" if let second = rank.values.second { output += " or \(second)" } return output } } let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades) print("theAceOfSpades: \(theAceOfSpades.description)") // Prints "theAceOfSpades: suit is ♠, value is 1 or 11"
29.791667
101
0.574825
7570cf85dc4dc096b96d0c612de09c9c5ec6aa45
298
// // BusinessDeals.swift // WPRK (iOS) // // Created by Mwai Banda on 10/8/21. // import Foundation struct BusinessDeal: Identifiable, Hashable { var id = UUID() let category: String let title: String let description: String let contact: String let address: String }
15.684211
45
0.657718
1e1f7464f528334fe145166baeea05c0ea628679
5,315
// // TurnipsFormView.swift // ACHNBrowserUI // // Created by Thomas Ricouard on 27/04/2020. // Copyright © 2020 Thomas Ricouard. All rights reserved. // import SwiftUI import Backend struct TurnipsFormView: View { @EnvironmentObject private var subscriptionManager: SubcriptionManager @Environment(\.presentationMode) private var presentationMode let turnipsViewModel: TurnipsViewModel @State private var fields = TurnipFields.decode() @State private var enableNotifications = AppUserDefaults.isSubscribed == true @State private var isSubscribePresented = false private let labels = ["Monday AM", "Monday PM", "Tuesday AM", "Tuesday PM", "Wednesday AM", "Wednesday PM", "Thursday AM", "Thursday PM", "Friday AM", "Friday PM", "Saturday AM", "Saturday PM"] private let weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] private var saveButton: some View { Button(action: save) { Text("Save") } } private func save() { fields.save() turnipsViewModel.refreshPrediction() if enableNotifications, let predictions = turnipsViewModel.predictions, subscriptionManager.subscriptionStatus == .subscribed { NotificationManager.shared.registerTurnipsPredictionNotification(prediction: predictions) } else { NotificationManager.shared.removePendingNotifications() } turnipsViewModel.refreshPendingNotifications() presentationMode.wrappedValue.dismiss() } var body: some View { NavigationView { List { Section(header: SectionHeaderView(text: "Configuration")) { Button(action: { self.fields.clear() self.turnipsViewModel.refreshPrediction() }) { Text("Clear all fields").foregroundColor(.secondaryText) } Toggle(isOn: $enableNotifications) { Text("Receive prices predictions notification") } .opacity(subscriptionManager.subscriptionStatus == .subscribed ? 1.0 : 0.5) .disabled(subscriptionManager.subscriptionStatus != .subscribed) if subscriptionManager.subscriptionStatus != .subscribed { Button(action: { self.isSubscribePresented = true }) { Text("You can get daily notifications for your average turnip price by subscribing to AC Helper+") .foregroundColor(.secondaryText) .font(.footnote) } } } Section(header: SectionHeaderView(text: "Your in game prices")) { HStack { Text("Buy price") TextField("... 🔔 ...", text: $fields.buyPrice) .keyboardType(.numberPad) } if fields.fields.filter{ !$0.isEmpty }.count == 0 { Text("The more in game buy prices you'll add the better the predictions will be. Your buy price only won't give your correct averages. Add prices from the game as you get them.") .foregroundColor(.secondaryText) .font(.footnote) } ForEach(weekdays, id: \.self, content: weekdayRow) } } .listStyle(GroupedListStyle()) .modifier(AdaptsToSoftwareKeyboard()) .navigationBarItems(trailing: saveButton) .navigationBarTitle("Add your turnip prices", displayMode: .inline) .sheet(isPresented: $isSubscribePresented, content: { SubscribeView().environmentObject(self.subscriptionManager) }) } .navigationViewStyle(StackNavigationViewStyle()) } private func weekdayRow(_ weekday: String) -> some View { HStack { Text(weekday) Spacer(minLength: 40) TextField("AM", text: morningField(for: weekday)) .keyboardType(.numberPad) .textFieldStyle(RoundedBorderTextFieldStyle()) .multilineTextAlignment(.center) .frame(maxWidth: 60) TextField("PM", text: afternoonField(for: weekday)) .keyboardType(.numberPad) .textFieldStyle(RoundedBorderTextFieldStyle()) .multilineTextAlignment(.center) .frame(maxWidth: 60) } } private func morningField(for weekday: String) -> Binding<String> { let index = weekdays.firstIndex(of: weekday) ?? 0 return $fields.fields[index * 2] } private func afternoonField(for weekday: String) -> Binding<String> { let index = weekdays.firstIndex(of: weekday) ?? 0 return $fields.fields[index * 2 + 1] } } struct TurnipsFormView_Previews: PreviewProvider { static var previews: some View { TurnipsFormView(turnipsViewModel: TurnipsViewModel()) } }
41.523438
202
0.568391
dedd4dc23ffee9804445d71118b9e47ce9ae84b9
774
// // ThanksViewController.swift // DemoCheckoutApp // // Created by Olha Prokopiuk on 5/1/18. // Copyright © 2018 Olha Prokopiuk. All rights reserved. // import UIKit class ThanksViewController: UIViewController { @IBOutlet weak var newOrderButton: UIButton! override func viewDidLoad() { newOrderButton.backgroundColor = UIView.appearance().tintColor } @IBAction func makeNewOrder() { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let initialViewController = storyboard.instantiateInitialViewController() UIView.transition(with: self.view, duration: 0.5, options: .transitionCrossDissolve, animations: { self.view.window!.rootViewController = initialViewController }) } }
28.666667
106
0.706718
0e72a251cab1dd2a7bb903ed6f9db6a121aa8b61
1,014
// // GroupMaker.swift // XcodeProjectCore // // Created by Yudai Hirose on 2019/07/26. // import Foundation public protocol GroupMaker { func make(context: Context, childrenIds: [String], pathName: String) -> PBX.Group } public struct GroupMakerImpl: GroupMaker { private let idGenerator: StringGenerator public init( idGenerator: StringGenerator = PBXObjectHashIDGenerator() ) { self.idGenerator = idGenerator } public func make(context: Context, childrenIds: [String] = [], pathName: String) -> PBX.Group { let isa = ObjectType.PBXGroup.rawValue let pair: PBXRawMapType = [ "isa": isa, "children": childrenIds, "path": pathName, "sourceTree": "<group>" ] let uuid = idGenerator.generate() let group = PBX.Group( id: uuid, dictionary: pair, isa: isa, context: context ) return group } }
24.142857
99
0.575937
09418cbdf1178a5e7574e2bd03e0c46fdc7f8f37
877
// // DetailViewController.swift // AccelDraw2 // // Created by Guo Xiaoyu on 2/16/16. // Copyright © 2016 Xiaoyu Guo. All rights reserved. // import UIKit class DetailViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.361111
106
0.676169
ff6ae3208ba66c6603efc5fced4c319a32189bb6
216
// // PlayerApp.swift // Shared // // Created by liyale on 2021/3/29. // import SwiftUI @main struct PlayerApp: App { var body: some Scene { WindowGroup { ContentView() } } }
12
35
0.541667
e0713a2cbd65cf062a7646728645c5e0c7768eb6
9,342
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers import XCTest internal final class ProjectActivityCommentCellViewModelTests: TestCase { fileprivate let vm: ProjectActivityCommentCellViewModelType = ProjectActivityCommentCellViewModel() fileprivate let authorImage = TestObserver<String?, Never>() fileprivate let body = TestObserver<String, Never>() fileprivate let cellAccessibilityLabel = TestObserver<String, Never>() fileprivate let cellAccessibilityValue = TestObserver<String, Never>() fileprivate let defaultUser = User.template |> \.id .~ 9 fileprivate let notifyDelegateGoToBacking = TestObserver<(Project, User), Never>() fileprivate let notifyDelegateGoToSendReply = TestObserver<(Project, Update?, DeprecatedComment), Never>() fileprivate let pledgeFooterIsHidden = TestObserver<Bool, Never>() fileprivate let title = TestObserver<String, Never>() internal override func setUp() { super.setUp() self.vm.outputs.authorImageURL.map { $0?.absoluteString }.observe(self.authorImage.observer) self.vm.outputs.body.observe(self.body.observer) self.vm.outputs.cellAccessibilityLabel.observe(self.cellAccessibilityLabel.observer) self.vm.outputs.cellAccessibilityValue.observe(self.cellAccessibilityValue.observer) self.vm.outputs.notifyDelegateGoToBacking.observe(self.notifyDelegateGoToBacking.observer) self.vm.outputs.notifyDelegateGoToSendReply .observe(self.notifyDelegateGoToSendReply.observer) self.vm.outputs.pledgeFooterIsHidden.observe(self.pledgeFooterIsHidden.observer) self.vm.outputs.title.observe(self.title.observer) AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: self.defaultUser)) } func testAuthorImage() { let project = Project.template let user = User.template |> \.avatar.medium .~ "http://coolpic.com/cool.jpg" let activity = .template |> Activity.lens.project .~ project |> Activity.lens.user .~ user self.vm.inputs.configureWith(activity: activity, project: project) self.authorImage.assertValues(["http://coolpic.com/cool.jpg"], "Emits author's image URL") } func testBody() { let project = Project.template let body1 = "Thanks for the update!" let commentPostActivity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ body1) |> Activity.lens.project .~ project self.vm.inputs.configureWith(activity: commentPostActivity, project: project) self.body.assertValues([body1], "Emits post comment's body") let body2 = "Aw, the limited bundle is all gone!" let commentProjectActivity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ body2) |> Activity.lens.project .~ project self.vm.inputs.configureWith(activity: commentProjectActivity, project: project) self.body.assertValues([body1, body2], "Emits project comment's body") } func testCellAccessibilityLabel() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Will this ship to Europe?") |> Activity.lens.project .~ project |> Activity.lens.user .~ (.template |> \.name .~ "Christopher") self.vm.inputs.configureWith(activity: activity, project: project) let expected = Strings.dashboard_activity_user_name_commented_on_your_project(user_name: "Christopher") .htmlStripped() ?? "" self.cellAccessibilityLabel.assertValues([expected], "Should emit accessibility label") } func testCellAccessibilityValue() { let project = Project.template let body = "Thanks for the update!" let activity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ body) |> Activity.lens.project .~ project self.vm.inputs.configureWith(activity: activity, project: project) self.cellAccessibilityValue.assertValues([body], "Emits accessibility value") } func testNotifyDelegateGoToBacking() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.project .~ project self.pledgeFooterIsHidden.assertValueCount(0) self.vm.inputs.configureWith(activity: activity, project: project) self.pledgeFooterIsHidden.assertValues([false], "Show the footer to go to pledge info.") self.vm.inputs.backingButtonPressed() self.notifyDelegateGoToBacking.assertValueCount(1, "Should go to backing") } func testNotifyDelegateGoToSendReply_Project() { let project = Project.template let user = User.template |> \.name .~ "Christopher" let activity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.comment .~ .template |> Activity.lens.project .~ project |> Activity.lens.user .~ user self.vm.inputs.configureWith(activity: activity, project: project) self.vm.inputs.replyButtonPressed() self.notifyDelegateGoToSendReply.assertValueCount(1, "Should go to send reply on project") } func testNotifyDelegateGoToSendReply_Update() { let project = Project.template let update = Update.template let user = User.template |> \.name .~ "Christopher" let activity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ .template |> Activity.lens.project .~ project |> Activity.lens.update .~ update |> Activity.lens.user .~ user self.vm.inputs.configureWith(activity: activity, project: project) self.vm.inputs.replyButtonPressed() self.notifyDelegateGoToSendReply.assertValueCount(1, "Should go to send reply on update") } func testTitleProject() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Love this project!") |> Activity.lens.project .~ project |> Activity.lens.user .~ (.template |> \.name .~ "Christopher") self.vm.inputs.configureWith(activity: activity, project: project) let expected = Strings.dashboard_activity_user_name_commented_on_your_project(user_name: "Christopher") self.title.assertValues([expected], "Should emit that author commented on project") } func testTitleProjectAsCurrentUser() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentProject |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Love this project!") |> Activity.lens.project .~ project |> Activity.lens.user .~ self.defaultUser self.vm.inputs.configureWith(activity: activity, project: project) let expected = Strings.dashboard_activity_you_commented_on_your_project() self.title.assertValues([expected], "Should emit 'you' commented on project") } func testTitleUpdate() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Good update!") |> Activity.lens.project .~ project |> Activity.lens.update .~ (.template |> Update.lens.sequence .~ 5) |> Activity.lens.user .~ (.template |> \.name .~ "Christopher") self.vm.inputs.configureWith(activity: activity, project: project) let expected = Strings.dashboard_activity_user_name_commented_on_update_number( user_name: "Christopher", space: "\u{00a0}", update_number: "5" ) self.title.assertValues([expected], "Should emit that author commented on update") } func testTitleUpdateAsCurrentUser() { let project = Project.template let activity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Good update!") |> Activity.lens.project .~ project |> Activity.lens.update .~ (.template |> Update.lens.sequence .~ 5) |> Activity.lens.user .~ self.defaultUser self.vm.inputs.configureWith(activity: activity, project: project) let expected = Strings.dashboard_activity_you_commented_on_update_number( space: "\u{00a0}", update_number: "5" ) self.title.assertValues([expected], "Should emit 'you' commented on update") } func testHideReplyAndPledgeInfoButtons_IfUserIsCreator() { let creator = User.template |> \.name .~ "Benny" let project = .template |> Project.lens.creator .~ creator let activity = .template |> Activity.lens.category .~ .commentPost |> Activity.lens.comment .~ (.template |> DeprecatedComment.lens.body .~ "Good update!") |> Activity.lens.project .~ project |> Activity.lens.user .~ creator withEnvironment(currentUser: creator) { self.pledgeFooterIsHidden.assertValueCount(0) self.vm.inputs.configureWith(activity: activity, project: project) self.pledgeFooterIsHidden.assertValues([true], "Hide the footer for the creator.") } } }
42.463636
108
0.714836
eb4aaa28c4a9b0701fef02eb55d1452730aeecb0
261
import Foundation @testable import TuistEnvKit final class MockCommandRunner: CommandRunning { var runCallCount: UInt = 0 var runStub: Error? func run() throws { runCallCount += 1 if let runStub = runStub { throw runStub } } }
20.076923
50
0.666667