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
e4fbd2ad53da1a4b503069b8a8e6d787611a760d
1,236
//ViewController.swift //MyTasks //Created by Dee Odus. //Copyright Dee Odus (Appkoder.com). All Rights Reserved. import UIKit var tasksArray = [Task]() class ViewController: UIViewController { @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var taskNameTextfield: UITextField! @IBOutlet weak var taskDescTextview: UITextView! @IBAction func saveButtonClicked(_ sender: Any) { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.timeStyle = .short let taskDate = datePicker.date let taskDateInString = dateFormatter.string(from: taskDate) if let taskName = taskNameTextfield.text, let taskDescription = taskDescTextview.text{ let task = Task(name: taskName, description: taskDescription, date: taskDateInString) tasksArray.append(task) } print(tasksArray) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @IBAction func close(_ sender: Any) { dismiss(animated: true, completion: nil) } }
25.22449
97
0.628641
cc89fc04c5726b743e8d745ffa130ce008817750
3,797
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ /// This is an implementation of Zoelzer's parametric equalizer filter. /// open class AKLowShelfParametricEqualizerFilter: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKLowShelfParametricEqualizerFilterAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "peq1") // MARK: - Properties public private(set) var internalAU: AKAudioUnitType? /// Lower and upper bounds for Corner Frequency public static let cornerFrequencyRange: ClosedRange<Double> = 12.0 ... 20_000.0 /// Lower and upper bounds for Gain public static let gainRange: ClosedRange<Double> = 0.0 ... 10.0 /// Lower and upper bounds for Q public static let qRange: ClosedRange<Double> = 0.0 ... 2.0 /// Initial value for Corner Frequency public static let defaultCornerFrequency: Double = 1_000 /// Initial value for Gain public static let defaultGain: Double = 1.0 /// Initial value for Q public static let defaultQ: Double = 0.707 /// Corner frequency. @objc open var cornerFrequency: Double = defaultCornerFrequency { willSet { let clampedValue = AKLowShelfParametricEqualizerFilter.cornerFrequencyRange.clamp(newValue) guard cornerFrequency != clampedValue else { return } internalAU?.cornerFrequency.value = AUValue(clampedValue) } } /// Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. @objc open var gain: Double = defaultGain { willSet { let clampedValue = AKLowShelfParametricEqualizerFilter.gainRange.clamp(newValue) guard gain != clampedValue else { return } internalAU?.gain.value = AUValue(clampedValue) } } /// Q of the filter. sqrt(0.5) is no resonance. @objc open var q: Double = defaultQ { willSet { let clampedValue = AKLowShelfParametricEqualizerFilter.qRange.clamp(newValue) guard q != clampedValue else { return } internalAU?.q.value = AUValue(clampedValue) } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open var isStarted: Bool { return internalAU?.isStarted ?? false } // MARK: - Initialization /// Initialize this equalizer node /// /// - Parameters: /// - input: Input node to process /// - cornerFrequency: Corner frequency. /// - gain: Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. /// - q: Q of the filter. sqrt(0.5) is no resonance. /// public init( _ input: AKNode? = nil, cornerFrequency: Double = defaultCornerFrequency, gain: Double = defaultGain, q: Double = defaultQ ) { super.init(avAudioNode: AVAudioNode()) _Self.register() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self) self.cornerFrequency = cornerFrequency self.gain = gain self.q = q } } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
35.820755
126
0.654201
22415f206cb6e8d55ac1f0c3d9bd1db8b6cc55bb
1,211
// // SideMenuView.swift // twitterclone // // Created by Stephen Wall on 5/20/21. // import SwiftUI struct DrawerView: View { @EnvironmentObject var viewModel: AuthViewModel var body: some View { ZStack(alignment: .topLeading) { LinearGradient(gradient: Gradient(colors: [Color.blue, Color.purple]), startPoint: .top, endPoint: .bottom) .ignoresSafeArea() VStack(alignment: .leading) { if let user = AuthViewModel.shared.user { DrawerHeaderView(user: user) .foregroundColor(.white) } ForEach(DrawerViewModel.allCases, id: \.self) { option in if option == .logout { Button(action: { viewModel.signOut() }, label: { DrawerCell(title: option.title, imageName: option.imageName) }) } else { NavigationLink( destination: Text(option.title), label: { DrawerCell(title: option.title, imageName: option.imageName) }) } } } } } } struct DrawerView_Previews: PreviewProvider { static var previews: some View { DrawerView() } }
24.714286
113
0.563171
c189683fab4e078533abdf0b33b88ce2dd468d2b
294
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let i{{{a:{{a{class d{class A{func A{protocol A{deinit{{}{a{func g{func g{{}={
36.75
87
0.717687
e9ba81ae46f162f57ae7f248aee1409111e4d0b0
808
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "views-wrap", platforms: [ .macOS(SupportedPlatform.MacOSVersion.v10_15), .iOS(SupportedPlatform.IOSVersion.v13) ], products: [ .library( name: "ViewsWrap", targets: ["ViewsWrap"] ), ], dependencies: [ .package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.8.2") ], targets: [ .target( name: "ViewsWrap", dependencies: [] ), .testTarget( name: "ViewsWrapTests", dependencies: [ "ViewsWrap", "SnapshotTesting", ], resources: [.process("__Snapshots__")] ), ] )
22.444444
114
0.62005
226a13bc9acbfe0d6491046b9ca0478364022f2f
2,392
/* * Copyright (c) 2011-2019, Zingaya, Inc. All rights reserved. */ import UIKit import VoxImplant class IncomingCallViewController: UIViewController, VICallDelegate { // MARK: Properties private let callManager: CallManager = sharedCallManager private var call: VICall? { return callManager.managedCall } // MARK: Outlets @IBOutlet weak var endpointDisplayNameLabel: UILabel! //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() call?.add(self) // add call delegate to current call } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) endpointDisplayNameLabel.text = call?.endpoints.first?.userDisplayName } override var preferredStatusBarStyle: UIStatusBarStyle { if #available(iOS 13.0, *) { return .darkContent } else { return .default } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { call?.remove(self) } // MARK: Actions @IBAction func declineTouch(_ sender: UIButton) { Log.d("Rejecting call") call?.reject(with: .decline, headers: nil) // decline call } @IBAction func acceptTouch(_ sender: UIButton) { PermissionsManager.checkAudioPermisson { Log.d("Accepting call") self.callManager.makeIncomingCallActive() // answer call self.call?.remove(self) self.performSegue(withIdentifier: CallViewController.self, sender: self) } } } // MARK: VICall Delegate extension IncomingCallViewController { func call(_ call: VICall, didDisconnectWithHeaders headers: [AnyHashable : Any]?, answeredElsewhere: NSNumber) { self.call?.remove(self) performSegue(withIdentifier: MainViewController.self, sender: self) } func call(_ call: VICall, didFailWithError error: Error, headers: [AnyHashable : Any]?) { self.call?.remove(self) performSegue(withIdentifier: MainViewController.self, sender: self) } } // MARK: CallManagerDelegate default behaviour extension CallManagerDelegate where Self: UIViewController { func notifyIncomingCall(_ descriptor: VICall) { self.performSegueIfPossible(withIdentifier: IncomingCallViewController.self, sender: self) } }
29.9
116
0.663043
2094c820ca46bafa8312e50302665e71d975885e
3,225
// // SubredditView.swift // RedditOs // // Created by Thomas Ricouard on 09/07/2020. // import SwiftUI import Backend struct SubredditView: View { let posts = Array(repeating: 0, count: 20) @EnvironmentObject private var userData: PersistedContent @StateObject private var viewModel: SubredditViewModel @AppStorage("postDisplayMode") private var displayMode = SubredditPostRow.DisplayMode.large @State private var isSearchSheetOpen = false init(name: String) { _viewModel = StateObject(wrappedValue: SubredditViewModel(name: name)) } var isDefaultChannel: Bool { SidebarViewModel.MainSubreddits.allCases.map{ $0.rawValue }.contains(viewModel.name) } var body: some View { NavigationView { List { if let listings = viewModel.listings { ForEach(listings) { listing in SubredditPostRow(listing: listing, displayMode: displayMode) } LoadingRow(text: "Loading next page") .onAppear(perform: viewModel.fetchListings) } else { LoadingRow(text: nil) } } .listStyle(InsetListStyle()) .frame(width: 430) } .navigationTitle(isDefaultChannel ? "\(viewModel.name.capitalized)" : "r/\(viewModel.name)") .toolbar { ToolbarItem(placement: .primaryAction) { Picker(selection: $displayMode, label: Text("Display"), content: { ForEach(SubredditPostRow.DisplayMode.allCases, id: \.self) { mode in HStack { Text(mode.rawValue.capitalized) Image(systemName: mode.iconName()) .tag(mode) } } }).pickerStyle(DefaultPickerStyle()) } ToolbarItem(placement: .primaryAction) { if !isDefaultChannel { Picker(selection: $viewModel.sortOrder, label: Text("Sorting"), content: { ForEach(SubredditViewModel.SortOrder.allCases, id: \.self) { sort in Text(sort.rawValue.capitalized).tag(sort) } }) } else { EmptyView() } } ToolbarItem(placement: .primaryAction) { Button(action: { isSearchSheetOpen = true }) { Image(systemName: "magnifyingglass") }.popover(isPresented: $isSearchSheetOpen) { SearchSubredditsPopover().environmentObject(userData) } } } .onAppear(perform: viewModel.fetchListings) } } struct Listing_Previews: PreviewProvider { static var previews: some View { SubredditView(name: "Best") } }
34.308511
100
0.494884
3a0b7464221083b4e668ff1b7ac5ee496388025b
228
// // MortyUIApp.swift // MortyUI // // Created by Thomas Ricouard on 18/12/2020. // import SwiftUI @main struct MortyUIApp: App { var body: some Scene { WindowGroup { TabbarView() } } }
12.666667
45
0.561404
1633cc93c2637a015b6eb9c009328cd6a0b25b86
797
// // Polygon.swift // FieldTool // // Created by Anatoly Tukhtarov on 2/18/17. // Copyright © 2017 Anatoly Tukhtarov. All rights reserved. // import MapKit struct Polygon: Geometry { var coordinates: [CLLocationCoordinate2D] var interiorPolygons: [Polygon]? var shape: Shape { let polygons = self.interiorPolygons?.map { MKPolygon(coordinates: $0.coordinates, count: $0.coordinates.count, interiorPolygons: nil) } return MKPolygon(coordinates: self.coordinates, count: self.coordinates.count, interiorPolygons: polygons) } var renderer: Renderer? { return MKPolygonRenderer(overlay: self.shape.overlay!) } }
30.653846
114
0.588457
719659044f0971ab4288472853eedfbe53031550
811
// // ZLCollectionCycleCell.swift // zhangyanlfDY // // Created by 张彦林 on 2018/4/2. // Copyright © 2018年 zhangyanlf. All rights reserved. // import UIKit import Kingfisher class ZLCollectionCycleCell: UICollectionViewCell { /// 轮播图片 @IBOutlet weak var cycleImageView: UIImageView! /// 轮播标题 @IBOutlet weak var cycleTitleLabel: UILabel! var cycleModel : ZLCycleModel? { didSet { //0.检验模型是否有值 guard let cycleModel = cycleModel else { return } //1.显示标题 cycleTitleLabel.text = cycleModel.title //2.显示图片 guard let url = URL(string: cycleModel.pic_url) else { return } cycleImageView.kf.setImage(with: url) } } }
21.342105
66
0.563502
4608b2ecdff49e36432e7ac32656187d10787276
3,346
// // ViewController.swift // HitList // // Created by Joshua Adams on 2/22/15. // This project is adapted from the excellent tutorial "Your First Core Data App Using Swift" by Pietro Rea. // // Note: One of the two fixes suggested http://stackoverflow.com/questions/25076276/unable-to-find-specific-subclass-of-nsmanagedobject must be used for this app to run. Without one of the fixes, the warning described in that question is issued. I used the solution of prepending the project name to the entity class name, but I found that the @objc(Person) solution also works. import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let managedContext = CDManager.sharedCDManager.context let fetchRequest = NSFetchRequest(entityName:"Person") var error: NSError? let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]? if let results = fetchedResults { people = results as [Person] } else { println("Could not fetch \(error), \(error!.userInfo)") } } @IBAction func addName(sender: UIBarButtonItem) { var alert = UIAlertController(title: "New name", message: "Add a new name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction!) -> Void in let textField = alert.textFields![0] as UITextField self.saveName(textField.text) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction!) -> Void in } alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } func saveName(name: String) { let managedContext = CDManager.sharedCDManager.context let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext) person.name = name var error: NSError? if !managedContext.save(&error) { println("Could not save \(error), \(error?.userInfo)") } people.append(person) } var people = [Person]() override func viewDidLoad() { super.viewDidLoad() title = "\"The List\"" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell let person = people[indexPath.row] as Person cell.textLabel!.text = person.name return cell } }
38.022727
378
0.658398
ff3fc66076183e38151c8d465925ff4c8ade0c6f
1,253
// // UIScreen+Extension.swift // ZBExtentsionDemo // // Created by 澳蜗科技 on 2017/8/31. // Copyright © 2017年 AnswerXu. All rights reserved. // import UIKit public enum IPhoneType : UInt { case iphone_320x480 = 1000 case iphone_320x568 = 1001 case iphone_375x667 = 1002 case iphone_414x736 = 1003 } extension UIScreen { public class func width() -> CGFloat { return UIScreen.main.bounds.size.width } public class func height() -> CGFloat { return UIScreen.main.bounds.size.height } public class func size() -> CGSize { return UIScreen.main.bounds.size } public class func bounds() -> CGRect { return UIScreen.main.bounds } public class func scale() -> CGFloat { return UIScreen.main.scale } public class func iphoneType() -> IPhoneType { switch size() { case CGSize.init(width: 320, height: 568): return .iphone_320x568 case CGSize.init(width: 375, height: 667): return .iphone_375x667 case CGSize.init(width: 414, height: 736): return .iphone_414x736 default: return .iphone_320x480 } } }
23.641509
54
0.590583
626afd3023066f51634bd61e17633aae6fa1833f
2,826
import XCTest import Combine @testable import iOSEngineerCodeCheck private struct CustomError: Error {} private final class MockClientForRepositorySearch: Client { let result: RepositorySearchResult = PreviewData.get(jsonFileName: "repositories_search_result")! var promise: ((Result<RepositorySearchResult, Error>) -> Void)! func send<RequestType: Request>(_ request: RequestType) -> AnyPublisher<RequestType.Response, Error> { Future { [weak self] promise in self?.promise = promise as? (Result<RepositorySearchResult, Error>) -> Void }.eraseToAnyPublisher() } func fulfillResult() { promise(.success(result)) } func emitError() { promise(.failure(CustomError())) } } class RepositorySearchViewModelTest: XCTestCase { var cancellables: [AnyCancellable] = [] override func setUpWithError() throws { cancellables = [] } func testRepositorySearchViewModel() { let client = MockClientForRepositorySearch() let viewModel = RepositorySearchViewModel(client: client) XCTAssert(viewModel.repositories.value.isEmpty) var repositories: [RepositorySearchResult.Repository] = [] var isLoading = false viewModel.isLoading .sink { isLoading = $0 } .store(in: &cancellables) viewModel.repositories .sink { repositories = $0 } .store(in: &cancellables) viewModel.search(text: "swift") waitForMainQueue() XCTAssertEqual(viewModel.isLoading.value, true) XCTAssertEqual(isLoading, true) client.fulfillResult() waitForMainQueue() XCTAssertEqual(viewModel.isLoading.value, false) XCTAssertEqual(viewModel.repositories.value.count, client.result.repositories.count) XCTAssertEqual(isLoading, false) XCTAssertEqual(repositories.count, client.result.repositories.count) } func testRepositorySearchViewModelError() { let client = MockClientForRepositorySearch() let viewModel = RepositorySearchViewModel(client: client) var isLoading = false var error: Error? viewModel.isLoading .sink { isLoading = $0 } .store(in: &cancellables) viewModel.errorPublisher .sink { error = $0 } .store(in: &cancellables) viewModel.search(text: "swift") waitForMainQueue() XCTAssertEqual(viewModel.isLoading.value, true) XCTAssertEqual(isLoading, true) client.emitError() waitForMainQueue() XCTAssertEqual(viewModel.isLoading.value, false) XCTAssert(viewModel.repositories.value.isEmpty) XCTAssertEqual(isLoading, false) XCTAssert(error != nil && error! is CustomError) } }
30.387097
106
0.660651
4bd290288954123bd7375c6b6eaed03d631c0403
1,477
// // Router.swift // WeChat // // Created by Sun on 2021/12/15. // Copyright © 2021 TheBoring. All rights reserved. // import Foundation public protocol Routable: TenonModule { func delayInit() } extension Routable { public func delayInit() {} } public struct Router { public static var test: Piece? { print("router test") return nil } private(set) static var routerDispatcher: RouterDispatcherProtocol? public static func resolve<T>(_ pieceType: T.Type) -> T? { return Tenon.resolve(pieceType) } /// 自动发现组件 public static func initialize() { for module in Module.allCases.reversed() { let tonen = "\(module.rawValue).\(module.rawValue)Tenon" let piece = "\(module.rawValue)Piece" if let cls = NSClassFromString(tonen) as? TenonModule.Type { let instance = cls.init() if module.hasPiece, let p = instance as? Piece { Tenon.settle(p, piece) } } } } public static func delayInitialize() { for module in Module.allCases.reversed() { let piece = "\(module.rawValue)Piece" if let p = Tenon.resolve(piece) as? Routable { p.delayInit() } } } public static func registerDispatcher(_ routerDispatcher: RouterDispatcherProtocol?) { self.routerDispatcher = routerDispatcher } }
22.044776
90
0.584292
ab8b3cf1467a494b401976335413d866ce443f7b
4,548
import ObjectMapper class HorSysBitcoinProvider: IBitcoinForksProvider { let name = "HorizontalSystems.xyz" private let url: String private let apiUrl: String func url(for hash: String) -> String { return url + hash } func apiUrl(for hash: String) -> String { return apiUrl + hash } init(testMode: Bool) { url = testMode ? "http://btc-testnet.horizontalsystems.xyz/apg/tx/" : "https://btc.horizontalsystems.xyz/apg/tx/" apiUrl = url } func convert(json: [String: Any]) -> IBitcoinResponse? { return try? HorSysBitcoinResponse(JSONObject: json) } } class HorSysBitcoinCashProvider: IBitcoinForksProvider { let name: String = "HorizontalSystems.xyz" private let url: String private let apiUrl: String func url(for hash: String) -> String { return url + hash } func apiUrl(for hash: String) -> String { return apiUrl + hash } init(testMode: Bool) { url = testMode ? "http://bch-testnet.horizontalsystems.xyz/apg/tx/" : "https://bch.horizontalsystems.xyz/apg/tx/" apiUrl = url } func convert(json: [String: Any]) -> IBitcoinResponse? { return try? HorSysBitcoinResponse(JSONObject: json) } } class HorSysEthereumProvider: IEthereumForksProvider { let name: String = "HorizontalSystems.xyz" private let url: String private let apiUrl: String func url(for hash: String) -> String { return url + hash } func apiUrl(for hash: String) -> String { return apiUrl + hash } init(testMode: Bool) { url = testMode ? "http://eth-testnet.horizontalsystems.xyz/apg/tx/" : "https://eth.horizontalsystems.xyz/apg/tx/" apiUrl = url } func convert(json: [String: Any]) -> IEthereumResponse? { return try? HorSysEthereumResponse(JSONObject: json) } } class HorSysBitcoinResponse: IBitcoinResponse, ImmutableMappable { var txId: String? var blockTime: Int? var blockHeight: Int? var confirmations: Int? var size: Int? var fee: Decimal? var feePerByte: Decimal? var inputs = [(value: Decimal, address: String?)]() var outputs = [(value: Decimal, address: String?)]() required init(map: Map) throws { txId = try? map.value("hash") blockTime = try? map.value("time") blockHeight = try? map.value("height") confirmations = try? map.value("confirmations") if let fee: Double = try? map.value("fee"), let rate: Int = try? map.value("rate") { let feePerByte = Decimal(rate) / 1000 self.feePerByte = feePerByte size = NSDecimalNumber(decimal: Decimal(fee) / feePerByte).intValue self.fee = Decimal(fee) / btcRate } if let vInputs: [[String: Any]] = try? map.value("inputs") { vInputs.forEach { input in if let coin = input["coin"] as? [String: Any], let value = coin["value"] as? Int { let address = coin["address"] as? String inputs.append((value: Decimal(value) / btcRate, address: address)) } } } if let vOutputs: [[String: Any]] = try? map.value("outputs") { vOutputs.forEach { output in if let value = output["value"] as? Int { let address = output["address"] as? String outputs.append((value: Decimal(value) / btcRate, address: address)) } } } } } class HorSysEthereumResponse: IEthereumResponse, ImmutableMappable { var txId: String? var blockTime: Int? var blockHeight: Int? var confirmations: Int? var size: Int? var gasPrice: Decimal? var gasUsed: Decimal? var gasLimit: Decimal? var fee: Decimal? var value: Decimal? var nonce: Int? var from: String? var to: String? required init(map: Map) throws { txId = try? map.value("tx.hash") blockHeight = try? map.value("tx.blockNumber") gasLimit = try? map.value("tx.gas") if let priceString: String = try? map.value("tx.gasPrice"), let price = Decimal(string: priceString) { gasPrice = price / gweiRate } gasUsed = try? map.value("tx.gasUsed") if let valueString: String = try? map.value("tx.value"), let value = Decimal(string: valueString) { self.value = value / ethRate } nonce = try? map.value("tx.nonce") to = try? map.value("tx.to") from = try? map.value("tx.from") } }
31.150685
121
0.605321
3378d10c2821cb396aa552e29ecbdc2f8b24f378
16,777
/* file: geometric_tolerance_with_modifiers.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY geometric_tolerance_with_modifiers SUBTYPE OF ( geometric_tolerance ); modifiers : SET [1 : ?] OF geometric_tolerance_modifier; WHERE wr1: ( ( NOT ( geometric_tolerance_modifier.circle_a IN modifiers ) ) OR ( ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.SHAPE_ASPECT' IN TYPEOF( SELF\ geometric_tolerance.toleranced_shape_aspect ) ) AND ( SELF\geometric_tolerance. toleranced_shape_aspect\shape_aspect.product_definitional = TRUE ) ) OR ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.DIMENSIONAL_SIZE' IN TYPEOF( SELF\ geometric_tolerance.toleranced_shape_aspect ) ) ); END_ENTITY; -- geometric_tolerance_with_modifiers (line:17044 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) geometric_tolerance ATTR: name, TYPE: label -- EXPLICIT ATTR: description, TYPE: OPTIONAL text -- EXPLICIT ATTR: magnitude, TYPE: OPTIONAL length_measure_with_unit -- EXPLICIT ATTR: toleranced_shape_aspect, TYPE: geometric_tolerance_target -- EXPLICIT ATTR: controlling_shape, TYPE: product_definition_shape -- DERIVED := sts_get_product_definition_shape( toleranced_shape_aspect ) ATTR: id, TYPE: identifier -- DERIVED := get_id_value( SELF ) ATTR: auxiliary_classification, TYPE: SET [0 : ?] OF geometric_tolerance_auxiliary_classification -- INVERSE FOR described_item; ATTR: tolerance_relationship, TYPE: SET [0 : ?] OF geometric_tolerance_relationship -- INVERSE FOR relating_geometric_tolerance; ENTITY(SELF) geometric_tolerance_with_modifiers ATTR: modifiers, TYPE: SET [1 : ?] OF geometric_tolerance_modifier -- EXPLICIT SUB- ENTITY(3) geometric_tolerance_with_maximum_tolerance ATTR: maximum_upper_tolerance, TYPE: length_measure_with_unit -- EXPLICIT */ //MARK: - Partial Entity public final class _geometric_tolerance_with_modifiers : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.self } //ATTRIBUTES /// EXPLICIT ATTRIBUTE public internal(set) var _modifiers: SDAI.SET<nGEOMETRIC_TOLERANCE_MODIFIER>/*[1:nil]*/ // PLAIN EXPLICIT ATTRIBUTE public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) //SELECT data types (indirectly) referencing the current type as a member of the select list members.insert(SDAI.STRING(sDRAUGHTING_MODEL_ITEM_DEFINITION.typeName)) // -> Self return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) self._modifiers.value.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } if let comp = self._modifiers.value.isValueEqualOptionally(to: rhs._modifiers.value, visited: &comppairs) { if !comp { return false } } else { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } if let comp = self._modifiers.value.isValueEqualOptionally(to: rhs._modifiers.value, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //MARK: WHERE RULES (ENTITY) public static func WHERE_wr1(SELF: eGEOMETRIC_TOLERANCE_WITH_MODIFIERS?) -> SDAI.LOGICAL { guard let SELF = SELF else { return SDAI.UNKNOWN } let _TEMP1 = nGEOMETRIC_TOLERANCE_MODIFIER.CIRCLE_A let _TEMP2 = SDAI.aggregate(SELF.MODIFIERS, contains: _TEMP1) let _TEMP3 = !_TEMP2 let _TEMP4 = SDAI.TYPEOF(SELF.GROUP_REF(eGEOMETRIC_TOLERANCE.self)?.TOLERANCED_SHAPE_ASPECT, IS: eSHAPE_ASPECT.self) let _TEMP5 = SELF.GROUP_REF(eGEOMETRIC_TOLERANCE.self) let _TEMP6 = _TEMP5?.TOLERANCED_SHAPE_ASPECT let _TEMP7 = _TEMP6?.GROUP_REF(eSHAPE_ASPECT.self) let _TEMP8 = _TEMP7?.PRODUCT_DEFINITIONAL let _TEMP9 = _TEMP8 .==. SDAI.FORCE_OPTIONAL(SDAI.LOGICAL(SDAI.TRUE)) let _TEMP10 = _TEMP4 && _TEMP9 let _TEMP11 = SDAI.TYPEOF(SELF.GROUP_REF(eGEOMETRIC_TOLERANCE.self)?.TOLERANCED_SHAPE_ASPECT, IS: eDIMENSIONAL_SIZE.self) let _TEMP12 = _TEMP10 || _TEMP11 let _TEMP13 = _TEMP3 || _TEMP12 return _TEMP13 } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init(MODIFIERS: SDAI.SET<nGEOMETRIC_TOLERANCE_MODIFIER>/*[1:nil]*/ ) { self._modifiers = MODIFIERS super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 1 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } guard case .success(let p0) = exchangeStructure.recoverRequiredParameter(as: SDAI.SET< nGEOMETRIC_TOLERANCE_MODIFIER>.self, from: parameters[0]) else { exchangeStructure.add(errorContext: "while recovering parameter #0 for entity(\(Self.entityName)) constructor"); return nil } self.init( MODIFIERS: p0 ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY geometric_tolerance_with_modifiers SUBTYPE OF ( geometric_tolerance ); modifiers : SET [1 : ?] OF geometric_tolerance_modifier; WHERE wr1: ( ( NOT ( geometric_tolerance_modifier.circle_a IN modifiers ) ) OR ( ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.SHAPE_ASPECT' IN TYPEOF( SELF\ geometric_tolerance.toleranced_shape_aspect ) ) AND ( SELF\geometric_tolerance. toleranced_shape_aspect\shape_aspect.product_definitional = TRUE ) ) OR ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.DIMENSIONAL_SIZE' IN TYPEOF( SELF\ geometric_tolerance.toleranced_shape_aspect ) ) ); END_ENTITY; -- geometric_tolerance_with_modifiers (line:17044 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eGEOMETRIC_TOLERANCE_WITH_MODIFIERS : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _geometric_tolerance_with_modifiers.self } public let partialEntity: _geometric_tolerance_with_modifiers //MARK: SUPERTYPES public let super_eGEOMETRIC_TOLERANCE: eGEOMETRIC_TOLERANCE // [1] public var super_eGEOMETRIC_TOLERANCE_WITH_MODIFIERS: eGEOMETRIC_TOLERANCE_WITH_MODIFIERS { return self } // [2] //MARK: SUBTYPES public var sub_eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE: eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE? { // [3] return self.complexEntity.entityReference(eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE.self) } //MARK: ATTRIBUTES /// __EXPLICIT__ attribute /// - origin: SUB( ``eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE`` ) public var MAXIMUM_UPPER_TOLERANCE: eLENGTH_MEASURE_WITH_UNIT? { get { return sub_eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE?.partialEntity._maximum_upper_tolerance } set(newValue) { guard let partial = sub_eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE?.super_eGEOMETRIC_TOLERANCE_WITH_MAXIMUM_TOLERANCE .partialEntity else { return } partial._maximum_upper_tolerance = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var DESCRIPTION: tTEXT? { get { return super_eGEOMETRIC_TOLERANCE.partialEntity._description } set(newValue) { let partial = super_eGEOMETRIC_TOLERANCE.partialEntity partial._description = newValue } } /// __INVERSE__ attribute /// observing eGEOMETRIC_TOLERANCE_RELATIONSHIP .RELATING_GEOMETRIC_TOLERANCE /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var TOLERANCE_RELATIONSHIP: SDAI.SET<eGEOMETRIC_TOLERANCE_RELATIONSHIP>/*[0:nil]*/ { get { return SDAI.UNWRAP( super_eGEOMETRIC_TOLERANCE.partialEntity._tolerance_relationship ) } } /// __INVERSE__ attribute /// observing eGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION .DESCRIBED_ITEM /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var AUXILIARY_CLASSIFICATION: SDAI.SET<eGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION>/*[0:nil]*/ { get { return SDAI.UNWRAP( super_eGEOMETRIC_TOLERANCE.partialEntity._auxiliary_classification ) } } /// __EXPLICIT__ attribute /// - origin: SELF( ``eGEOMETRIC_TOLERANCE_WITH_MODIFIERS`` ) public var MODIFIERS: SDAI.SET<nGEOMETRIC_TOLERANCE_MODIFIER>/*[1:nil]*/ { get { return SDAI.UNWRAP( self.partialEntity._modifiers ) } set(newValue) { let partial = self.partialEntity partial._modifiers = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var MAGNITUDE: eLENGTH_MEASURE_WITH_UNIT? { get { return super_eGEOMETRIC_TOLERANCE.partialEntity._magnitude } set(newValue) { let partial = super_eGEOMETRIC_TOLERANCE.partialEntity partial._magnitude = newValue } } /// __DERIVE__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var ID: tIDENTIFIER? { get { if let cached = cachedValue(derivedAttributeName:"ID") { return cached.value as! tIDENTIFIER? } let origin = super_eGEOMETRIC_TOLERANCE let value = tIDENTIFIER(origin.partialEntity._id__getter(SELF: origin)) updateCache(derivedAttributeName:"ID", value:value) return value } } /// __DERIVE__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var CONTROLLING_SHAPE: ePRODUCT_DEFINITION_SHAPE? { get { if let cached = cachedValue(derivedAttributeName:"CONTROLLING_SHAPE") { return cached.value as! ePRODUCT_DEFINITION_SHAPE? } let origin = super_eGEOMETRIC_TOLERANCE let value = ePRODUCT_DEFINITION_SHAPE(origin.partialEntity._controlling_shape__getter(SELF: origin)) updateCache(derivedAttributeName:"CONTROLLING_SHAPE", value:value) return value } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var NAME: tLABEL { get { return SDAI.UNWRAP( super_eGEOMETRIC_TOLERANCE.partialEntity._name ) } set(newValue) { let partial = super_eGEOMETRIC_TOLERANCE.partialEntity partial._name = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eGEOMETRIC_TOLERANCE`` ) public var TOLERANCED_SHAPE_ASPECT: sGEOMETRIC_TOLERANCE_TARGET { get { return SDAI.UNWRAP( super_eGEOMETRIC_TOLERANCE.partialEntity._toleranced_shape_aspect ) } set(newValue) { let partial = super_eGEOMETRIC_TOLERANCE.partialEntity partial._toleranced_shape_aspect = SDAI.UNWRAP(newValue) } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_geometric_tolerance_with_modifiers.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eGEOMETRIC_TOLERANCE.self) else { return nil } self.super_eGEOMETRIC_TOLERANCE = super1 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: WHERE RULE VALIDATION (ENTITY) public override class func validateWhereRules(instance:SDAI.EntityReference?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] { guard let instance = instance as? Self else { return [:] } let prefix2 = prefix + " \(instance)" var result = super.validateWhereRules(instance:instance, prefix:prefix2) result[prefix2 + " .WHERE_wr1"] = _geometric_tolerance_with_modifiers.WHERE_wr1(SELF: instance) return result } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "GEOMETRIC_TOLERANCE_WITH_MODIFIERS", type: self, explicitAttributeCount: 1) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eGEOMETRIC_TOLERANCE.self) entityDef.add(supertype: eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "MAXIMUM_UPPER_TOLERANCE", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.MAXIMUM_UPPER_TOLERANCE, kind: .explicit, source: .subEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "DESCRIPTION", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.DESCRIPTION, kind: .explicitOptional, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TOLERANCE_RELATIONSHIP", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.TOLERANCE_RELATIONSHIP, kind: .inverse, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "AUXILIARY_CLASSIFICATION", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.AUXILIARY_CLASSIFICATION, kind: .inverse, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "MODIFIERS", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.MODIFIERS, kind: .explicit, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "MAGNITUDE", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.MAGNITUDE, kind: .explicitOptional, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "ID", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.ID, kind: .derived, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "CONTROLLING_SHAPE", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.CONTROLLING_SHAPE, kind: .derived, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "NAME", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.NAME, kind: .explicit, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TOLERANCED_SHAPE_ASPECT", keyPath: \eGEOMETRIC_TOLERANCE_WITH_MODIFIERS.TOLERANCED_SHAPE_ASPECT, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) return entityDef } } }
42.581218
185
0.720093
8f000b80e481f1b912026a5caa01fd9a5be83761
4,254
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows how operations can be composed together to form new operations. */ import Foundation /** A subclass of `Operation` that executes zero or more operations as part of its own execution. This class of operation is very useful for abstracting several smaller operations into a larger operation. As an example, the `GetEarthquakesOperation` is composed of both a `DownloadEarthquakesOperation` and a `ParseEarthquakesOperation`. Additionally, `GroupOperation`s are useful if you establish a chain of dependencies, but part of the chain may "loop". For example, if you have an operation that requires the user to be authenticated, you may consider putting the "login" operation inside a group operation. That way, the "login" operation may produce subsequent operations (still within the outer `GroupOperation`) that will all be executed before the rest of the operations in the initial chain of operations. */ class GroupOperation: Operation { private let internalQueue = OperationQueue() private let startingOperation = NSBlockOperation(block: {}) private let finishingOperation = NSBlockOperation(block: {}) private var aggregatedErrors = [NSError]() convenience init(operations: NSOperation...) { self.init(operations: operations) } init(operations: [NSOperation]) { super.init() internalQueue.suspended = true internalQueue.delegate = self internalQueue.addOperation(startingOperation) for operation in operations { internalQueue.addOperation(operation) } } override func cancel() { internalQueue.cancelAllOperations() super.cancel() } override func execute() { internalQueue.suspended = false internalQueue.addOperation(finishingOperation) } func addOperation(operation: NSOperation) { internalQueue.addOperation(operation) } /** Note that some part of execution has produced an error. Errors aggregated through this method will be included in the final array of errors reported to observers and to the `finished(_:)` method. */ final func aggregateError(error: NSError) { aggregatedErrors.append(error) } func operationDidFinish(operation: NSOperation, withErrors errors: [NSError]) { // For use by subclassers. } } extension GroupOperation: OperationQueueDelegate { final func operationQueue(operationQueue: OperationQueue, willAddOperation operation: NSOperation) { assert(!finishingOperation.finished && !finishingOperation.executing, "cannot add new operations to a group after the group has completed") /* Some operation in this group has produced a new operation to execute. We want to allow that operation to execute before the group completes, so we'll make the finishing operation dependent on this newly-produced operation. */ if operation !== finishingOperation { finishingOperation.addDependency(operation) } /* All operations should be dependent on the "startingOperation". This way, we can guarantee that the conditions for other operations will not evaluate until just before the operation is about to run. Otherwise, the conditions could be evaluated at any time, even before the internal operation queue is unsuspended. */ if operation !== startingOperation { operation.addDependency(startingOperation) } } final func operationQueue(operationQueue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [NSError]) { aggregatedErrors.extend(errors) if operation === finishingOperation { internalQueue.suspended = true finish(aggregatedErrors) } else if operation !== startingOperation { operationDidFinish(operation, withErrors: errors) } } }
37.982143
147
0.685708
1d641f023fcad13864304ace73471f172ec187ee
6,441
// // Admin.swift // Server // // Created by BluDesign, LLC on 7/2/17. // import Foundation import MongoKitten struct Admin { // MARK: - Parameters static let collectionName = "admin" static var collection: MongoKitten.Collection { return Application.shared.database[collectionName] } var objectId: ObjectId var document: Document static var settings: Admin = { do { if let document = try Admin.collection.findOne(), let objectId = document.objectId { return Admin(objectId: objectId, document: document) } else { let document: Document = [ "registrationEnabled": true ] guard let objectId = try Admin.collection.insert(document) as? ObjectId else { assertionFailure("Could Not Create Admin") return Admin(objectId: ObjectId(), document: Document()) } return Admin(objectId: objectId, document: document) } } catch let error { assertionFailure("Could Not Create Admin: \(error)") return Admin(objectId: ObjectId(), document: Document()) } }() // MARK: - Settings var timeZone: String { get { return document["timeZone"] as? String ?? TimeZone(secondsFromGMT: 0)?.identifier ?? Constants.defaultTimeZone } set { document["timeZone"] = newValue } } var registrationEnabled: Bool { get { return document["registrationEnabled"] as? Bool ?? false } set { document["registrationEnabled"] = newValue } } var nexmoEnabled: Bool { get { return document["nexmoEnabled"] as? Bool ?? true } set { document["nexmoEnabled"] = newValue } } var domain: String? { get { return document["url"] as? String } set { document["url"] = newValue } } var domainHostname: String? { if let domain = domain, let url = URL(string: domain) { return url.host } return nil } var secureCookie: Bool { get { return document["secureCookie"] as? Bool ?? false } set { document["secureCookie"] = newValue } } // MARK: - Mailgun var mailgunApiKey: String? { get { return document["mailgunApiKey"] as? String } set { document["mailgunApiKey"] = newValue } } var mailgunApiUrl: String? { get { return document["mailgunApiUrl"] as? String } set { document["mailgunApiUrl"] = newValue } } var mailgunFromEmail: String { get { return document["mailgunFromEmail"] as? String ?? Constants.defaultEmail } set { document["mailgunFromEmail"] = newValue } } var notificationEmail: String { get { return document["notificationEmail"] as? String ?? Constants.defaultEmail } set { document["notificationEmail"] = newValue } } var messageSendEmail: Bool { get { return document["messageSendEmail"] as? Bool ?? false } set { document["messageSendEmail"] = newValue } } var faxReceivedSendEmail: Bool { get { return document["faxReceivedSendEmail"] as? Bool ?? true } set { document["faxReceivedSendEmail"] = newValue } } var faxStatusSendEmail: Bool { get { return document["faxStatusSendEmail"] as? Bool ?? true } set { document["faxStatusSendEmail"] = newValue } } // MARK: - APNS var apnsBundleId: String? { get { return document["apnsBundleId"] as? String } set { document["apnsBundleId"] = newValue } } var apnsTeamId: String? { get { return document["apnsTeamId"] as? String } set { document["apnsTeamId"] = newValue } } var apnsKeyId: String? { get { return document["apnsKeyId"] as? String } set { document["apnsKeyId"] = newValue } } var apnsKeyPath: String? { get { return document["apnsKeyPath"] as? String } set { document["apnsKeyPath"] = newValue } } var messageSendApns: Bool { get { return document["messageSendApns"] as? Bool ?? true } set { document["messageSendApns"] = newValue } } var faxReceivedSendApns: Bool { get { return document["faxReceivedSendApns"] as? Bool ?? true } set { document["faxReceivedSendApns"] = newValue } } var faxStatusSendApns: Bool { get { return document["faxStatusSendApns"] as? Bool ?? true } set { document["faxStatusSendApns"] = newValue } } // MARK: - Slack var slackWebHookUrl: String? { get { return document["slackWebHookUrl"] as? String } set { document["slackWebHookUrl"] = newValue } } var messageSendSlack: Bool { get { return document["messageSendSlack"] as? Bool ?? true } set { document["messageSendSlack"] = newValue } } var faxReceivedSendSlack: Bool { get { return document["faxReceivedSendSlack"] as? Bool ?? true } set { document["faxReceivedSendSlack"] = newValue } } var faxStatusSendSlack: Bool { get { return document["faxStatusSendSlack"] as? Bool ?? true } set { document["faxStatusSendSlack"] = newValue } } // MARK: - Methods func save() throws { try Admin.collection.update("_id" == objectId, to: document) } }
23.767528
122
0.498836
e2d31205744a06b067870fc6a968033717f32d8e
1,312
// // ArrayTest.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif @objc public class ArrayTest: NSObject, Codable, JSONEncodable { public var arrayOfString: [String]? public var arrayArrayOfInteger: [[Int64]]? public var arrayArrayOfModel: [[ReadOnlyFirst]]? public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) { self.arrayOfString = arrayOfString self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" case arrayArrayOfModel = "array_array_of_model" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } }
32
133
0.724848
8f9ee6d4f242ccc233c520b1698de432a98b0ef8
4,476
// // JCPhotoBar.swift // JChat // // Created by deng on 2017/3/31. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit @objc public protocol JCPhotoBarDelegate: NSObjectProtocol { @objc optional func photoBarDeleteImage(index: Int) @objc optional func photoBarClickImage(index: Int) @objc optional func photoBarAddImage() } class JCPhotoBar: UIView { weak var delegate: JCPhotoBarDelegate? { get { return item1.delegate } set { item1.delegate = newValue item2.delegate = newValue item3.delegate = newValue item4.delegate = newValue } } override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private let offset = (UIScreen.main.bounds.size.width - 30 - 65 * 4) / 3 private lazy var item1: JCPhotoBarItem = JCPhotoBarItem(frame: CGRect(x: 15, y: 0, width: 65, height: 65)) private lazy var item2: JCPhotoBarItem = JCPhotoBarItem(frame: CGRect(x: 15 + 65 + self.offset, y: 0, width: 65, height: 65)) private lazy var item3: JCPhotoBarItem = JCPhotoBarItem(frame: CGRect(x: 16 + (65 + self.offset) * 2, y: 0, width: 65, height: 65)) private lazy var item4: JCPhotoBarItem = JCPhotoBarItem(frame: CGRect(x: 15 + (65 + self.offset) * 3, y: 0, width: 65, height: 65)) func bindData(_ images: [UIImage]) { switch images.count + 1 { case 1: item1.setAddImage() item2.isHidden = true item3.isHidden = true item4.isHidden = true case 2: item1.setImage(images[0]) item2.setAddImage() item3.isHidden = true item4.isHidden = true case 3: item1.setImage(images[0]) item2.setImage(images[1]) item3.setAddImage() item4.isHidden = true case 4: item1.setImage(images[0]) item2.setImage(images[1]) item3.setImage(images[2]) item4.setAddImage() default: item1.setImage(images[0]) item2.setImage(images[1]) item3.setImage(images[2]) item4.setImage(images[3]) } } private func _init() { item1.index = 0 item2.index = 1 item3.index = 2 item4.index = 3 addSubview(item1) addSubview(item2) addSubview(item3) addSubview(item4) } } class JCPhotoBarItem: UIView { weak var delegate: JCPhotoBarDelegate? var index = 0 var isHiddenDelButton: Bool { get { return delButton.isHidden } set { delButton.isHidden = newValue } } override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var iconView: UIImageView = UIImageView() private lazy var delButton: UIButton = UIButton() func setAddImage() { self.isHidden = false iconView.image = UIImage.loadImage("com_icon_add_65") delButton.isHidden = true } func setImage(_ image: UIImage) { self.isHidden = false delButton.isHidden = false iconView.image = image } private func _init() { iconView.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height) let tapGR = UITapGestureRecognizer(target: self, action: #selector(_tapHandler)) iconView.addGestureRecognizer(tapGR) iconView.isUserInteractionEnabled = true addSubview(iconView) let bgImage = UIImage.loadImage("icon_icon_close") delButton.frame = CGRect(x: self.width - 20, y: 0, width: 20, height: 20) delButton.setBackgroundImage(bgImage, for: .normal) delButton.addTarget(self, action: #selector(_delImage(_ :)), for: .touchUpInside) addSubview(delButton) } func _tapHandler() { if isHiddenDelButton { delegate?.photoBarAddImage?() return } delegate?.photoBarClickImage?(index: index) } func _delImage(_ sender: UIButton) { delegate?.photoBarDeleteImage?(index: index) } }
29.064935
135
0.585567
1c4e1f5da0acdd5fbfbd8e93e4e3ab58d4356b23
4,367
class SubscriptionsStyleSheet: IStyleSheet { static func register(theme: Theme, colors: IColors, fonts: IFonts) { theme.add(styleName: "BookmarkSubscriptionScrollBackground") { (s) -> (Void) in s.backgroundColor = colors.bookmarkSubscriptionScrollBackground } theme.add(styleName: "BookmarkSubscriptionBackground") { (s) -> (Void) in s.backgroundColor = colors.bookmarkSubscriptionBackground } theme.add(styleName: "BookmarkSubscriptionFooterBackground") { (s) -> (Void) in s.backgroundColor = colors.bookmarkSubscriptionFooterBackground } theme.add(styleName: "BookmarksSubscriptionMonthlyButton") { (s) -> (Void) in s.font = fonts.medium14 s.fontColor = colors.blackHintText s.borderWidth = 1 s.cornerRadius = 6 s.borderColor = colors.blackHintText s.backgroundColorHighlighted = colors.blackDividers } theme.add(styleName: "BookmarksSubscriptionDiscount", forType: .dark) { (s) -> (Void) in s.backgroundColor = colors.discountBackground s.cornerRadius = 6 s.shadowRadius = 4 s.shadowOffset = CGSize(width: 0, height: 2) s.shadowColor = colors.blackHintText s.shadowOpacity = 0.62 s.fontColor = UIColor.white s.font = fonts.bold17 s.textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } theme.add(styleName: "BookmarksSubscriptionDiscount", forType: .light) { (s) -> (Void) in s.backgroundColor = colors.discountBackground s.cornerRadius = 6 s.fontColor = UIColor.white s.font = fonts.bold17 s.textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } theme.add(styleName: "AllPassSubscriptionYearlyButton") { (s) -> (Void) in s.fontColorHighlighted = colors.white s.font = fonts.semibold14 s.cornerRadius = 6 s.fontColor = colors.allPassSubscriptionDescription s.backgroundColor = colors.allPassSubscriptionYearlyBackground s.backgroundColorHighlighted = colors.linkBlueHighlighted } theme.add(styleName: "AllPassSubscriptionMonthlyButton") { (s) -> (Void) in s.fontColorHighlighted = colors.white s.font = fonts.semibold14 s.fontColor = colors.allPassSubscriptionMonthlyTitle s.cornerRadius = 6 s.borderWidth = 3 s.borderColor = UIColor.white.withAlphaComponent(alpha54) s.backgroundColorHighlighted = colors.blackDividers s.backgroundColor = colors.clear } theme.add(styleName: "AllPassSubscriptionRestoreButton") { (s) -> (Void) in s.font = fonts.medium14 s.fontColor = colors.allPassSubscriptionTermsTitle s.fontColorHighlighted = colors.linkBlueHighlighted } theme.add(styleName: "AllPassSubscriptionTerms") { (s) -> (Void) in s.font = fonts.regular9 s.fontColor = colors.allPassSubscriptionTermsTitle } theme.add(styleName: "AllPassSubscriptionTermsButton") { (s) -> (Void) in s.font = fonts.regular9 s.fontColor = colors.allPassSubscriptionTermsTitle } theme.add(styleName: "AllPassSubscriptionTitleView") { (s) -> (Void) in s.backgroundColor = colors.clear s.cornerRadius = 10 s.clip = true } theme.add(styleName: "AllPassSubscriptionTitle") { (s) -> (Void) in s.font = fonts.regular17 s.fontColor = colors.allPassSubscriptionTitle } theme.add(styleName: "AllPassSubscriptionSubTitle") { (s) -> (Void) in s.font = fonts.heavy20 s.fontColor = colors.allPassSubscriptionSubTitle } theme.add(styleName: "AllPassSubscriptionDescription1") { (s) -> (Void) in s.font = fonts.heavy38 s.fontColor = colors.allPassSubscriptionDescription } theme.add(styleName: "AllPassSubscriptionDescription2") { (s) -> (Void) in s.fontColor = colors.allPassSubscriptionDescription } theme.add(styleName: "AllPassSubscriptionDiscount") { (s) -> (Void) in s.shadowRadius = 4 s.shadowOffset = CGSize(width: 0, height: 2) s.shadowColor = colors.blackHintText s.shadowOpacity = 0.62 s.cornerRadius = 6 s.font = fonts.heavy17 s.fontColor = colors.discountText s.backgroundColor = colors.allPassSubscriptionDiscountBackground s.textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } } }
37.008475
93
0.684681
71830ab536a2f115e684f9bcba9acac06084548b
936
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import audioplayers import connectivity_macos import kraken import kraken_geolocation import kraken_video_player import path_provider_macos import shared_preferences_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { AudioplayersPlugin.register(with: registry.registrar(forPlugin: "AudioplayersPlugin")) ConnectivityPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlugin")) KrakenPlugin.register(with: registry.registrar(forPlugin: "KrakenPlugin")) LocationPlugin.register(with: registry.registrar(forPlugin: "LocationPlugin")) FLTVideoPlayerPlugin.register(with: registry.registrar(forPlugin: "FLTVideoPlayerPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) }
37.44
98
0.836538
89ee75c060d9242dac5be0766ee64047c44dd333
4,049
// // ViewController.swift // rainyshinycloudy // // Created by mudasar on 01/11/2016. // Copyright © 2016 appinvent.uk. All rights reserved. // import UIKit import Alamofire import CoreLocation class WeatherViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate { var cw:CurrentWeather! var forecast:Forecast! var forecasts = [Forecast]() let locationManger = CLLocationManager() var currenctLocation: CLLocation! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.delegate = self tableView.dataSource = self //print(CURRENT_WEATHER_URL) cw = CurrentWeather() locationManger.delegate = self locationManger.desiredAccuracy = kCLLocationAccuracyBest locationManger.requestWhenInUseAuthorization() locationManger.startMonitoringSignificantLocationChanges() locationAuthStatus() cw.downloadWeatherDetails { self.downloadForecast { self.updateMainUI() if self.forecasts.count > 0 { self.forecasts.remove(at: 0) } self.tableView.reloadData() } } } func downloadForecast(completed: @escaping DownloadComplete) { //downlaod forecast data for table view let forecastUrl = URL(string: FORECAST_WEATHER_URL) Alamofire.request(forecastUrl!).responseJSON { (response) in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject> { if let list = dict["list"] as? [Dictionary<String, AnyObject>] { for obj in list { let forecast = Forecast(weatherDict: obj) self.forecasts.append(forecast) } } } completed() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet var dateLabel: UILabel! @IBOutlet var currentTempLabel: UILabel! @IBOutlet var locationLabel: UILabel! @IBOutlet var currentWeatherImage: UIImageView! @IBOutlet var currentTempTypeLabel: UILabel! @IBOutlet var tableView: UITableView! override func viewDidAppear(_ animated: Bool) { } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return forecasts.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? WeatherTableViewCell { cell.updateData(forecast: forecasts[indexPath.row]) return cell }else{ return WeatherTableViewCell() } } func updateMainUI() { dateLabel.text = cw.date currentTempLabel.text = "\(cw.currentTemp)°" locationLabel.text = cw.cityName currentTempTypeLabel.text = cw.weatherType currentWeatherImage.image = UIImage(named: cw.weatherType) } func locationAuthStatus() { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways { currenctLocation = locationManger.location Location.sharedLocation.lattitude = currenctLocation.coordinate.latitude Location.sharedLocation.longitude = currenctLocation.coordinate.longitude }else{ locationManger.requestWhenInUseAuthorization() locationAuthStatus() } } }
30.908397
140
0.623364
50203e5582e01276ad2e6f2a50799b3ed1f40eeb
502
// // ViewController.swift // HelloXCode7 // // Created by mcxiaoke on 15/9/16. // Copyright © 2015年 mcxiaoke. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.307692
80
0.669323
3a029debcf596ab180e32d7304f89a8d6328ef74
720
// // ADHOC_AtomicBool.swift // EonilPco // // Created by Hoon H. on 2017/01/14. // Copyright © 2017 Eonil. All rights reserved. // import Foundation /// /// Slow, but the only sane way to get atomicity for now in Swift 3... /// final class ADHOC_AtomicBool { private let lock = NSLock() private var value = false init() { } init(_ newState: Bool) { state = newState } var state: Bool { get { let returningValue: Bool lock.lock() returningValue = value lock.unlock() return returningValue } set { lock.lock() value = newValue lock.unlock() } } }
19.459459
70
0.527778
2f7a4cf36d04a5e6310b8b64e5694ebd3ac31cd6
969
// // lab2Tests.swift // lab2Tests // // Created by Dawson Botsford on 9/21/15. // Copyright © 2015 Dawson Botsford. All rights reserved. // import XCTest @testable import lab2 class lab2Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.189189
111
0.631579
26cfe92416b29bb88a00f65a0930cbbf0b64889e
297
public enum AnimationEvent { case overlayDismissal case positionCorrection case backgroundColorChange case zoom } public extension AnimationEvent { static var all: [AnimationEvent] { return [.overlayDismissal, .positionCorrection, .backgroundColorChange] } }
21.214286
79
0.723906
3ab7e0ec2659065cb535ec3a2693a526e1eb7752
612
// // HICTTableViewCell.swift // WorkoutClub // // Created by mac on 2016/12/23. // Copyright © 2016年 hackntuios.minithon.teama. All rights reserved. // import UIKit class HICTTableViewCell: UITableViewCell { @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.103448
69
0.676471
db06a861f4846aefbd6559964b792716c184d261
636
// // SocialViewController.swift // Puc Aberta // // Created by Marco Braga on 21/03/18. // Copyright © 2018 Marco Braga. All rights reserved. // import UIKit import MBProgressHUD class TwitterViewController: BaseViewController { // MARK: - IBOutlets @IBOutlet weak var webView: UIWebView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setup() } // MARK: - Private func setup() { let url = URL(string: "https://twitter.com/hashtag/PucAberta") let request = URLRequest.init(url: url!) self.webView.loadRequest(request) } }
19.272727
70
0.636792
f97fac14acb0aed20248e2de3bd9c9bc58bd09c5
697
import Core import Transport private let crlf: Bytes = [.carriageReturn, .newLine] extension SMTPClient { internal func transmit(line: String, terminating: Bool = true) throws { try stream.send(line) if terminating { try stream.send(crlf) } try stream.flush() } internal func transmit(line: String, terminating: Bool = true, expectingReplyCode: Int) throws { try transmit(line: line, terminating: terminating) let (code, replies) = try acceptReply() guard code == expectingReplyCode else { throw SMTPClientError.unexpectedReply(expected: expectingReplyCode, got: code, replies: replies, initiator: line) } } }
33.190476
125
0.675753
5b213b89dfa993f2b4ae9df3e44ca06ba9a9c8f4
4,189
// // GameKit.swift // sudoku // // Created by Дмитрий Папков on 25.05.2021. // import Foundation import GameKit class GameCenter: ObservableObject { static let shared: GameCenter = .init() @Published var scores: [String: Int] = [:] private let localPlayer = GKLocalPlayer.local private init() { GKAccessPoint.shared.location = .topTrailing self.authentificateUser() } var isAuthentificated: Bool { self.localPlayer.isAuthenticated } var gameKitAccessPoint: Bool { get { GKAccessPoint.shared.isActive } set(newValue) { GKAccessPoint.shared.isActive = newValue } } func authentificateUser() { localPlayer.authenticateHandler = {[weak self] vc, err in guard err == nil, let self = self else { print(err?.localizedDescription ?? "other error") return } self.gameKitAccessPoint = true self.getScores() self.objectWillChange.send() } } func getScores() { let leaderboardIds = GridGenerator.Difficulty.allCases.map({ $0.scoreLeaderboardID }) GKLeaderboard.loadLeaderboards(IDs: leaderboardIds) { [weak self] leaderboards, error in guard error == nil, let leaderboards = leaderboards, let self = self else { print(error?.localizedDescription ?? "Не удалось получить доски рекордов") return } leaderboards.forEach { leaderboard in self.scores[leaderboard.baseLeaderboardID] = 0 leaderboard.loadEntries(for: [self.localPlayer], timeScope: .allTime) { entry, _, error in guard error == nil, let entry = entry else { print(error?.localizedDescription ?? "Не удалось получить результат для таблицы \(leaderboard.baseLeaderboardID)") return } self.scores[leaderboard.baseLeaderboardID] = entry.score } } } } func sendScore(_ score: Int, difficulty: GridGenerator.Difficulty) { guard !self.scores.isEmpty, self.scores[difficulty.scoreLeaderboardID] ?? 0 < score else { return } self.saveScore(to: difficulty.scoreLeaderboardID, score: score) } // func sendTime(_ time: TimeInterval, difficulty: GridGenerator.Difficulty) { // // } private func saveScore(to leaderboard: String, score: Int) { GKLeaderboard.loadLeaderboards(IDs: [leaderboard]) { [weak self] leaderboards, err in guard let self = self, let leaderboard = leaderboards?.first else { return } leaderboard.submitScore(score, context: 0, player: self.localPlayer) { error in if let err = err { print(err.localizedDescription) } } } } } extension GridGenerator.Difficulty { var scoreLeaderboardID: String { switch self { case .flash: return "com.nsnow.sudoku.flash.score" case .easy: return "com.nsnow.sudoku.easy.score" case .medium: return "com.nsnow.sudoku.medium.score" case .hard: return "com.nsnow.sudoku.hard.score" case .insane: return "com.nsnow.sudoku.insane.score" } } // timeLeaderboardID - зарезервировано на потом var timeLeaderboardID: String { switch self { case .flash: return "com.nsnow.sudoku.flash.time" case .easy: return "com.nsnow.sudoku.easy.time" case .medium: return "com.nsnow.sudoku.medium.time" case .hard: return "com.nsnow.sudoku.hard.time" case .insane: return "com.nsnow.sudoku.insane.time" } } }
30.355072
138
0.543089
e5f8a65f4f88ce4baf1961412b4a1ae9a1e660ec
494
// // CleanedLinkItem.swift // Clean Links Extension // // Created by Radoslav Vitanov on 14.03.20. // Copyright © 2020 Radoslav Vitanov. All rights reserved. // import Cocoa class CleanedLinkItem: NSCollectionViewItem { @IBOutlet weak var label: NSTextField! @IBOutlet weak var image: NSImageView! override func viewDidLoad() { super.viewDidLoad() label.isEditable = false label.allowsEditingTextAttributes = true } }
19.76
59
0.65587
212ee2ffcdbca748fe00eb094c96b9332c7aecfd
47,348
import Foundation import PathKit import ProjectSpec import XcodeProj import Yams public class PBXProjGenerator { let project: Project let pbxProj: PBXProj let projectDirectory: Path? let carthageResolver: CarthageDependencyResolver var sourceGenerator: SourceGenerator! var targetObjects: [String: PBXTarget] = [:] var targetAggregateObjects: [String: PBXAggregateTarget] = [:] var targetFileReferences: [String: PBXFileReference] = [:] var sdkFileReferences: [String: PBXFileReference] = [:] var packageReferences: [String: XCRemoteSwiftPackageReference] = [:] var carthageFrameworksByPlatform: [String: Set<PBXFileElement>] = [:] var frameworkFiles: [PBXFileElement] = [] var generated = false public init(project: Project, projectDirectory: Path? = nil) { self.project = project carthageResolver = CarthageDependencyResolver(project: project) pbxProj = PBXProj(rootObject: nil, objectVersion: project.objectVersion) self.projectDirectory = projectDirectory sourceGenerator = SourceGenerator(project: project, pbxProj: pbxProj, projectDirectory: projectDirectory) } @discardableResult func addObject<T: PBXObject>(_ object: T, context: String? = nil) -> T { pbxProj.add(object: object) object.context = context return object } public func generate() throws -> PBXProj { if generated { fatalError("Cannot use PBXProjGenerator to generate more than once") } generated = true for group in project.fileGroups { try sourceGenerator.getFileGroups(path: group) } let localPackages = Set(project.localPackages) for package in localPackages { let path = project.basePath + Path(package).normalize() try sourceGenerator.createLocalPackage(path: path) } let buildConfigs: [XCBuildConfiguration] = project.configs.map { config in let buildSettings = project.getProjectBuildSettings(config: config) var baseConfiguration: PBXFileReference? if let configPath = project.configFiles[config.name], let fileReference = sourceGenerator.getContainedFileReference(path: project.basePath + configPath) as? PBXFileReference { baseConfiguration = fileReference } let buildConfig = addObject( XCBuildConfiguration( name: config.name, buildSettings: buildSettings ) ) buildConfig.baseConfiguration = baseConfiguration return buildConfig } let configName = project.options.defaultConfig ?? buildConfigs.first?.name ?? "" let buildConfigList = addObject( XCConfigurationList( buildConfigurations: buildConfigs, defaultConfigurationName: configName ) ) var derivedGroups: [PBXGroup] = [] let mainGroup = addObject( PBXGroup( children: [], sourceTree: .group, usesTabs: project.options.usesTabs, indentWidth: project.options.indentWidth, tabWidth: project.options.tabWidth ) ) let pbxProject = addObject( PBXProject( name: project.name, buildConfigurationList: buildConfigList, compatibilityVersion: project.compatibilityVersion, mainGroup: mainGroup, developmentRegion: project.options.developmentLanguage ?? "en" ) ) pbxProj.rootObject = pbxProject for target in project.targets { let targetObject: PBXTarget if target.isLegacy { targetObject = PBXLegacyTarget( name: target.name, buildToolPath: target.legacy?.toolPath, buildArgumentsString: target.legacy?.arguments, passBuildSettingsInEnvironment: target.legacy?.passSettings ?? false, buildWorkingDirectory: target.legacy?.workingDirectory, buildPhases: [] ) } else { targetObject = PBXNativeTarget(name: target.name, buildPhases: []) } targetObjects[target.name] = addObject(targetObject) var explicitFileType: String? var lastKnownFileType: String? let fileType = Xcode.fileType(path: Path(target.filename)) if target.platform == .macOS || target.platform == .watchOS || target.type == .framework { explicitFileType = fileType } else { lastKnownFileType = fileType } if !target.isLegacy { let fileReference = addObject( PBXFileReference( sourceTree: .buildProductsDir, explicitFileType: explicitFileType, lastKnownFileType: lastKnownFileType, path: target.filename, includeInIndex: false ), context: target.name ) targetFileReferences[target.name] = fileReference } } for target in project.aggregateTargets { let aggregateTarget = addObject( PBXAggregateTarget( name: target.name, productName: target.name ) ) targetAggregateObjects[target.name] = aggregateTarget } for (name, package) in project.packages { let packageReference = XCRemoteSwiftPackageReference(repositoryURL: package.url, versionRequirement: package.versionRequirement) packageReferences[name] = packageReference addObject(packageReference) } try project.targets.forEach(generateTarget) try project.aggregateTargets.forEach(generateAggregateTarget) let productGroup = addObject( PBXGroup( children: targetFileReferences.valueArray, sourceTree: .group, name: "Products" ) ) derivedGroups.append(productGroup) if !carthageFrameworksByPlatform.isEmpty { var platforms: [PBXGroup] = [] for (platform, files) in carthageFrameworksByPlatform { let platformGroup: PBXGroup = addObject( PBXGroup( children: files.sorted { $0.nameOrPath < $1.nameOrPath }, sourceTree: .group, path: platform ) ) platforms.append(platformGroup) } let carthageGroup = addObject( PBXGroup( children: platforms, sourceTree: .group, name: "Carthage", path: carthageResolver.buildPath ) ) frameworkFiles.append(carthageGroup) } if !frameworkFiles.isEmpty { let group = addObject( PBXGroup( children: frameworkFiles, sourceTree: .group, name: "Frameworks" ) ) derivedGroups.append(group) } mainGroup.children = Array(sourceGenerator.rootGroups) sortGroups(group: mainGroup) // add derived groups at the end derivedGroups.forEach(sortGroups) mainGroup.children += derivedGroups .sorted { $0.nameOrPath.localizedStandardCompare($1.nameOrPath) == .orderedAscending } .map { $0 } let projectAttributes: [String: Any] = ["LastUpgradeCheck": project.xcodeVersion] .merged(project.attributes) let knownRegions = sourceGenerator.knownRegions pbxProject.knownRegions = (knownRegions.isEmpty ? ["en"] : knownRegions).union(["Base"]).sorted() pbxProject.packages = packageReferences.sorted { $0.key < $1.key }.map { $1 } let allTargets: [PBXTarget] = targetObjects.valueArray + targetAggregateObjects.valueArray pbxProject.targets = allTargets .sorted { $0.name < $1.name } pbxProject.attributes = projectAttributes pbxProject.targetAttributes = generateTargetAttributes() return pbxProj } func generateAggregateTarget(_ target: AggregateTarget) throws { let aggregateTarget = targetAggregateObjects[target.name]! let configs: [XCBuildConfiguration] = project.configs.map { config in let buildSettings = project.getBuildSettings(settings: target.settings, config: config) var baseConfiguration: PBXFileReference? if let configPath = target.configFiles[config.name] { baseConfiguration = sourceGenerator.getContainedFileReference(path: project.basePath + configPath) as? PBXFileReference } let buildConfig = XCBuildConfiguration( name: config.name, baseConfiguration: baseConfiguration, buildSettings: buildSettings ) return addObject(buildConfig) } let dependencies = target.targets.map { generateTargetDependency(from: target.name, to: $0) } let buildConfigList = addObject(XCConfigurationList( buildConfigurations: configs, defaultConfigurationName: "" )) var buildPhases: [PBXBuildPhase] = [] buildPhases += try target.buildScripts.map { try generateBuildScript(targetName: target.name, buildScript: $0) } aggregateTarget.buildPhases = buildPhases aggregateTarget.buildConfigurationList = buildConfigList aggregateTarget.dependencies = dependencies } func generateTargetDependency(from: String, to target: String) -> PBXTargetDependency { guard let targetObject = targetObjects[target] ?? targetAggregateObjects[target] else { fatalError("target not found") } let targetProxy = addObject( PBXContainerItemProxy( containerPortal: .project(pbxProj.rootObject!), remoteGlobalID: .object(targetObject), proxyType: .nativeTarget, remoteInfo: target ) ) let targetDependency = addObject( PBXTargetDependency( target: targetObject, targetProxy: targetProxy ) ) return targetDependency } func generateBuildScript(targetName: String, buildScript: BuildScript) throws -> PBXShellScriptBuildPhase { let shellScript: String switch buildScript.script { case let .path(path): shellScript = try (project.basePath + path).read() case let .script(script): shellScript = script } let shellScriptPhase = PBXShellScriptBuildPhase( name: buildScript.name ?? "Run Script", inputPaths: buildScript.inputFiles, outputPaths: buildScript.outputFiles, inputFileListPaths: buildScript.inputFileLists, outputFileListPaths: buildScript.outputFileLists, shellPath: buildScript.shell ?? "/bin/sh", shellScript: shellScript, runOnlyForDeploymentPostprocessing: buildScript.runOnlyWhenInstalling, showEnvVarsInLog: buildScript.showEnvVars ) return addObject(shellScriptPhase) } func generateCopyFiles(targetName: String, copyFiles: TargetSource.BuildPhase.CopyFilesSettings, buildPhaseFiles: [PBXBuildFile]) -> PBXCopyFilesBuildPhase { let copyFilesBuildPhase = PBXCopyFilesBuildPhase( dstPath: copyFiles.subpath, dstSubfolderSpec: copyFiles.destination.destination, files: buildPhaseFiles ) return addObject(copyFilesBuildPhase) } func generateTargetAttributes() -> [PBXTarget: [String: Any]] { var targetAttributes: [PBXTarget: [String: Any]] = [:] let testTargets = pbxProj.nativeTargets.filter { $0.productType == .uiTestBundle || $0.productType == .unitTestBundle } for testTarget in testTargets { // look up TEST_TARGET_NAME build setting func testTargetName(_ target: PBXTarget) -> String? { guard let buildConfigurations = target.buildConfigurationList?.buildConfigurations else { return nil } return buildConfigurations .compactMap { $0.buildSettings["TEST_TARGET_NAME"] as? String } .first } guard let name = testTargetName(testTarget) else { continue } guard let target = self.pbxProj.targets(named: name).first else { continue } targetAttributes[testTarget, default: [:]].merge(["TestTargetID": target]) } func generateTargetAttributes(_ target: ProjectTarget, pbxTarget: PBXTarget) { if !target.attributes.isEmpty { targetAttributes[pbxTarget, default: [:]].merge(target.attributes) } func getSingleBuildSetting(_ setting: String) -> String? { let settings = project.configs.compactMap { project.getCombinedBuildSetting(setting, target: target, config: $0) as? String } guard settings.count == project.configs.count, let firstSetting = settings.first, settings.filter({ $0 == firstSetting }).count == settings.count else { return nil } return firstSetting } func setTargetAttribute(attribute: String, buildSetting: String) { if let setting = getSingleBuildSetting(buildSetting) { targetAttributes[pbxTarget, default: [:]].merge([attribute: setting]) } } setTargetAttribute(attribute: "ProvisioningStyle", buildSetting: "CODE_SIGN_STYLE") setTargetAttribute(attribute: "DevelopmentTeam", buildSetting: "DEVELOPMENT_TEAM") } for target in project.aggregateTargets { guard let pbxTarget = targetAggregateObjects[target.name] else { continue } generateTargetAttributes(target, pbxTarget: pbxTarget) } for target in project.targets { guard let pbxTarget = targetObjects[target.name] else { continue } generateTargetAttributes(target, pbxTarget: pbxTarget) } return targetAttributes } func sortGroups(group: PBXGroup) { // sort children let children = group.children .sorted { child1, child2 in let sortOrder1 = child1.getSortOrder(groupSortPosition: project.options.groupSortPosition) let sortOrder2 = child2.getSortOrder(groupSortPosition: project.options.groupSortPosition) if sortOrder1 != sortOrder2 { return sortOrder1 < sortOrder2 } else { if child1.nameOrPath != child2.nameOrPath { return child1.nameOrPath.localizedStandardCompare(child2.nameOrPath) == .orderedAscending } else { return child1.context ?? "" < child2.context ?? "" } } } group.children = children.filter { $0 != group } // sort sub groups let childGroups = group.children.compactMap { $0 as? PBXGroup } childGroups.forEach(sortGroups) } func generateTarget(_ target: Target) throws { let carthageDependencies = carthageResolver.dependencies(for: target) let sourceFiles = try sourceGenerator.getAllSourceFiles(targetType: target.type, sources: target.sources) .sorted { $0.path.lastComponent < $1.path.lastComponent } var plistPath: Path? var searchForPlist = true var anyDependencyRequiresObjCLinking = false var dependencies: [PBXTargetDependency] = [] var targetFrameworkBuildFiles: [PBXBuildFile] = [] var frameworkBuildPaths = Set<String>() var copyFilesBuildPhasesFiles: [TargetSource.BuildPhase.CopyFilesSettings: [PBXBuildFile]] = [:] var copyFrameworksReferences: [PBXBuildFile] = [] var copyResourcesReferences: [PBXBuildFile] = [] var copyWatchReferences: [PBXBuildFile] = [] var packageDependencies: [XCSwiftPackageProductDependency] = [] var extensions: [PBXBuildFile] = [] var carthageFrameworksToEmbed: [String] = [] let targetDependencies = (target.transitivelyLinkDependencies ?? project.options.transitivelyLinkDependencies) ? getAllDependenciesPlusTransitiveNeedingEmbedding(target: target) : target.dependencies let targetSupportsDirectEmbed = !(target.platform.requiresSimulatorStripping && (target.type.isApp || target.type == .watch2Extension)) let directlyEmbedCarthage = target.directlyEmbedCarthageDependencies ?? targetSupportsDirectEmbed func getEmbedSettings(dependency: Dependency, codeSign: Bool) -> [String: Any] { var embedAttributes: [String] = [] if codeSign { embedAttributes.append("CodeSignOnCopy") } if dependency.removeHeaders { embedAttributes.append("RemoveHeadersOnCopy") } return ["ATTRIBUTES": embedAttributes] } func getDependencyFrameworkSettings(dependency: Dependency) -> [String: Any]? { var linkingAttributes: [String] = [] if dependency.weakLink { linkingAttributes.append("Weak") } return !linkingAttributes.isEmpty ? ["ATTRIBUTES": linkingAttributes] : nil } for dependency in targetDependencies { let embed = dependency.embed ?? target.shouldEmbedDependencies switch dependency.type { case .target: let dependencyTargetName = dependency.reference let targetDependency = generateTargetDependency(from: target.name, to: dependencyTargetName) dependencies.append(targetDependency) guard let dependencyTarget = project.getTarget(dependencyTargetName) else { continue } let dependecyLinkage = dependencyTarget.defaultLinkage let link = dependency.link ?? ((dependecyLinkage == .dynamic && target.type != .staticLibrary) || (dependecyLinkage == .static && target.type.isExecutable)) if link { let dependencyFile = targetFileReferences[dependencyTarget.name]! let buildFile = addObject( PBXBuildFile(file: dependencyFile, settings: getDependencyFrameworkSettings(dependency: dependency)) ) targetFrameworkBuildFiles.append(buildFile) if !anyDependencyRequiresObjCLinking && dependencyTarget.requiresObjCLinking ?? (dependencyTarget.type == .staticLibrary) { anyDependencyRequiresObjCLinking = true } } let embed = dependency.embed ?? (!dependencyTarget.type.isLibrary && ( target.type.isApp || (target.type.isTest && (dependencyTarget.type.isFramework || dependencyTarget.type == .bundle)) )) if embed { let embedFile = addObject( PBXBuildFile( file: targetFileReferences[dependencyTarget.name]!, settings: getEmbedSettings(dependency: dependency, codeSign: dependency.codeSign ?? !dependencyTarget.type.isExecutable) ) ) if dependencyTarget.type.isExtension { // embed app extension extensions.append(embedFile) } else if dependencyTarget.type.isFramework { copyFrameworksReferences.append(embedFile) } else if dependencyTarget.type.isApp && dependencyTarget.platform == .watchOS { copyWatchReferences.append(embedFile) } else if dependencyTarget.type == .xpcService { copyFilesBuildPhasesFiles[.xpcServices, default: []].append(embedFile) } else { copyResourcesReferences.append(embedFile) } } case .framework: let buildPath = Path(dependency.reference).parent().string.quoted frameworkBuildPaths.insert(buildPath) let fileReference: PBXFileElement if dependency.implicit { fileReference = sourceGenerator.getFileReference( path: Path(dependency.reference), inPath: project.basePath, sourceTree: .buildProductsDir ) } else { fileReference = sourceGenerator.getFileReference( path: Path(dependency.reference), inPath: project.basePath ) } if dependency.link ?? (target.type != .staticLibrary) { let buildFile = addObject( PBXBuildFile(file: fileReference, settings: getDependencyFrameworkSettings(dependency: dependency)) ) targetFrameworkBuildFiles.append(buildFile) } if !frameworkFiles.contains(fileReference) { frameworkFiles.append(fileReference) } if embed { let embedFile = addObject( PBXBuildFile(file: fileReference, settings: getEmbedSettings(dependency: dependency, codeSign: dependency.codeSign ?? true)) ) copyFrameworksReferences.append(embedFile) } case .sdk(let root): var dependencyPath = Path(dependency.reference) if !dependency.reference.contains("/") { switch dependencyPath.extension ?? "" { case "framework": dependencyPath = Path("System/Library/Frameworks") + dependencyPath case "tbd": dependencyPath = Path("usr/lib") + dependencyPath case "dylib": dependencyPath = Path("usr/lib") + dependencyPath default: break } } let fileReference: PBXFileReference if let existingFileReferences = sdkFileReferences[dependency.reference] { fileReference = existingFileReferences } else { let sourceTree: PBXSourceTree if let root = root { sourceTree = .custom(root) } else { sourceTree = .sdkRoot } fileReference = addObject( PBXFileReference( sourceTree: sourceTree, name: dependencyPath.lastComponent, lastKnownFileType: Xcode.fileType(path: dependencyPath), path: dependencyPath.string ) ) sdkFileReferences[dependency.reference] = fileReference frameworkFiles.append(fileReference) } let buildFile = addObject( PBXBuildFile( file: fileReference, settings: getDependencyFrameworkSettings(dependency: dependency) ) ) targetFrameworkBuildFiles.append(buildFile) case .carthage(let findFrameworks, let linkType): let findFrameworks = findFrameworks ?? project.options.findCarthageFrameworks let allDependencies = findFrameworks ? carthageResolver.relatedDependencies(for: dependency, in: target.platform) : [dependency] allDependencies.forEach { dependency in var platformPath = Path(carthageResolver.buildPath(for: target.platform, linkType: linkType)) var frameworkPath = platformPath + dependency.reference if frameworkPath.extension == nil { frameworkPath = Path(frameworkPath.string + ".framework") } let fileReference = self.sourceGenerator.getFileReference(path: frameworkPath, inPath: platformPath) self.carthageFrameworksByPlatform[target.platform.carthageName, default: []].insert(fileReference) if dependency.link ?? (target.type != .staticLibrary) { let buildFile = self.addObject( PBXBuildFile(file: fileReference, settings: getDependencyFrameworkSettings(dependency: dependency)) ) targetFrameworkBuildFiles.append(buildFile) } } // Embedding handled by iterating over `carthageDependencies` below case .package(let product): guard let packageReference = packageReferences[dependency.reference] else { return } let productName = product ?? dependency.reference let packageDependency = addObject( XCSwiftPackageProductDependency(productName: productName, package: packageReference) ) packageDependencies.append(packageDependency) let link = dependency.link ?? (target.type != .staticLibrary) if link { let buildFile = addObject( PBXBuildFile(product: packageDependency) ) targetFrameworkBuildFiles.append(buildFile) } let targetDependency = addObject( PBXTargetDependency(product: packageDependency) ) dependencies.append(targetDependency) } } for dependency in carthageDependencies { let embed = dependency.embed ?? target.shouldEmbedCarthageDependencies var platformPath = Path(carthageResolver.buildPath(for: target.platform, linkType: dependency.carthageLinkType ?? .default)) var frameworkPath = platformPath + dependency.reference if frameworkPath.extension == nil { frameworkPath = Path(frameworkPath.string + ".framework") } let fileReference = sourceGenerator.getFileReference(path: frameworkPath, inPath: platformPath) if dependency.carthageLinkType == .static { let embedFile = addObject( PBXBuildFile(file: fileReference, settings: getDependencyFrameworkSettings(dependency: dependency)) ) targetFrameworkBuildFiles.append(embedFile) } else if embed { if directlyEmbedCarthage { let embedFile = addObject( PBXBuildFile(file: fileReference, settings: getEmbedSettings(dependency: dependency, codeSign: dependency.codeSign ?? true)) ) copyFrameworksReferences.append(embedFile) } else { carthageFrameworksToEmbed.append(dependency.reference) } } } var buildPhases: [PBXBuildPhase] = [] func getBuildFilesForSourceFiles(_ sourceFiles: [SourceFile]) -> [PBXBuildFile] { sourceFiles .reduce(into: [SourceFile]()) { output, sourceFile in if !output.contains(where: { $0.fileReference === sourceFile.fileReference }) { output.append(sourceFile) } } .map { addObject($0.buildFile) } } func getBuildFilesForPhase(_ buildPhase: BuildPhase) -> [PBXBuildFile] { let filteredSourceFiles = sourceFiles .filter { $0.buildPhase?.buildPhase == buildPhase } return getBuildFilesForSourceFiles(filteredSourceFiles) } func getBuildFilesForCopyFilesPhases() -> [TargetSource.BuildPhase.CopyFilesSettings: [PBXBuildFile]] { var sourceFilesByCopyFiles: [TargetSource.BuildPhase.CopyFilesSettings: [SourceFile]] = [:] for sourceFile in sourceFiles { guard case let .copyFiles(copyFilesSettings)? = sourceFile.buildPhase else { continue } sourceFilesByCopyFiles[copyFilesSettings, default: []].append(sourceFile) } return sourceFilesByCopyFiles.mapValues { getBuildFilesForSourceFiles($0) } } copyFilesBuildPhasesFiles.merge(getBuildFilesForCopyFilesPhases()) { $0 + $1 } buildPhases += try target.preBuildScripts.map { try generateBuildScript(targetName: target.name, buildScript: $0) } buildPhases += copyFilesBuildPhasesFiles .filter { $0.key.phaseOrder == .preCompile } .map { generateCopyFiles(targetName: target.name, copyFiles: $0, buildPhaseFiles: $1) } let headersBuildPhaseFiles = getBuildFilesForPhase(.headers) if !headersBuildPhaseFiles.isEmpty { if target.type.isFramework || target.type == .dynamicLibrary { let headersBuildPhase = addObject(PBXHeadersBuildPhase(files: headersBuildPhaseFiles)) buildPhases.append(headersBuildPhase) } else { headersBuildPhaseFiles.forEach { pbxProj.delete(object: $0) } } } let sourcesBuildPhaseFiles = getBuildFilesForPhase(.sources) // Sticker packs should not include a compile sources build phase as they // are purely based on a set of image files, and nothing else. let shouldSkipSourcesBuildPhase = sourcesBuildPhaseFiles.isEmpty && target.type == .stickerPack if !shouldSkipSourcesBuildPhase { let sourcesBuildPhase = addObject(PBXSourcesBuildPhase(files: sourcesBuildPhaseFiles)) buildPhases.append(sourcesBuildPhase) } buildPhases += try target.postCompileScripts.map { try generateBuildScript(targetName: target.name, buildScript: $0) } let resourcesBuildPhaseFiles = getBuildFilesForPhase(.resources) + copyResourcesReferences if !resourcesBuildPhaseFiles.isEmpty { let resourcesBuildPhase = addObject(PBXResourcesBuildPhase(files: resourcesBuildPhaseFiles)) buildPhases.append(resourcesBuildPhase) } let swiftObjCInterfaceHeader = project.getCombinedBuildSetting("SWIFT_OBJC_INTERFACE_HEADER_NAME", target: target, config: project.configs[0]) as? String if target.type == .staticLibrary && swiftObjCInterfaceHeader != "" && sourceFiles.contains(where: { $0.buildPhase == .sources && $0.path.extension == "swift" }) { let inputPaths = ["$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"] let outputPaths = ["$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"] let script = addObject( PBXShellScriptBuildPhase( name: "Copy Swift Objective-C Interface Header", inputPaths: inputPaths, outputPaths: outputPaths, shellPath: "/bin/sh", shellScript: "ditto \"${SCRIPT_INPUT_FILE_0}\" \"${SCRIPT_OUTPUT_FILE_0}\"\n" ) ) buildPhases.append(script) } buildPhases += copyFilesBuildPhasesFiles .filter { $0.key.phaseOrder == .postCompile } .map { generateCopyFiles(targetName: target.name, copyFiles: $0, buildPhaseFiles: $1) } if !carthageFrameworksToEmbed.isEmpty { let inputPaths = carthageFrameworksToEmbed .map { "$(SRCROOT)/\(carthageResolver.buildPath(for: target.platform, linkType: .dynamic))/\($0)\($0.contains(".") ? "" : ".framework")" } let outputPaths = carthageFrameworksToEmbed .map { "$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\($0)\($0.contains(".") ? "" : ".framework")" } let carthageExecutable = carthageResolver.executable let carthageScript = addObject( PBXShellScriptBuildPhase( name: "Carthage", inputPaths: inputPaths, outputPaths: outputPaths, shellPath: "/bin/sh", shellScript: "\(carthageExecutable) copy-frameworks\n" ) ) buildPhases.append(carthageScript) } if !targetFrameworkBuildFiles.isEmpty { let frameworkBuildPhase = addObject( PBXFrameworksBuildPhase(files: targetFrameworkBuildFiles) ) buildPhases.append(frameworkBuildPhase) } if !extensions.isEmpty { let copyFilesPhase = addObject( PBXCopyFilesBuildPhase( dstPath: "", dstSubfolderSpec: .plugins, name: "Embed App Extensions", files: extensions ) ) buildPhases.append(copyFilesPhase) } copyFrameworksReferences += getBuildFilesForPhase(.frameworks) if !copyFrameworksReferences.isEmpty { let copyFilesPhase = addObject( PBXCopyFilesBuildPhase( dstPath: "", dstSubfolderSpec: .frameworks, name: "Embed Frameworks", files: copyFrameworksReferences ) ) buildPhases.append(copyFilesPhase) } if !copyWatchReferences.isEmpty { let copyFilesPhase = addObject( PBXCopyFilesBuildPhase( dstPath: "$(CONTENTS_FOLDER_PATH)/Watch", dstSubfolderSpec: .productsDirectory, name: "Embed Watch Content", files: copyWatchReferences ) ) buildPhases.append(copyFilesPhase) } let buildRules = target.buildRules.map { buildRule in addObject( PBXBuildRule( compilerSpec: buildRule.action.compilerSpec, fileType: buildRule.fileType.fileType, isEditable: true, filePatterns: buildRule.fileType.pattern, name: buildRule.name ?? "Build Rule", outputFiles: buildRule.outputFiles, outputFilesCompilerFlags: buildRule.outputFilesCompilerFlags, script: buildRule.action.script ) ) } buildPhases += try target.postBuildScripts.map { try generateBuildScript(targetName: target.name, buildScript: $0) } let configs: [XCBuildConfiguration] = project.configs.map { config in var buildSettings = project.getTargetBuildSettings(target: target, config: config) // Set CODE_SIGN_ENTITLEMENTS if let entitlements = target.entitlements { buildSettings["CODE_SIGN_ENTITLEMENTS"] = entitlements.path } // Set INFOPLIST_FILE if not defined in settings if !project.targetHasBuildSetting("INFOPLIST_FILE", target: target, config: config) { if let info = target.info { buildSettings["INFOPLIST_FILE"] = info.path } else if searchForPlist { plistPath = getInfoPlist(target.sources) searchForPlist = false } if let plistPath = plistPath { buildSettings["INFOPLIST_FILE"] = (try? plistPath.relativePath(from: projectDirectory ?? project.basePath)) ?? plistPath } } // automatically calculate bundle id if let bundleIdPrefix = project.options.bundleIdPrefix, !project.targetHasBuildSetting("PRODUCT_BUNDLE_IDENTIFIER", target: target, config: config) { let characterSet = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-.")).inverted let escapedTargetName = target.name .replacingOccurrences(of: "_", with: "-") .components(separatedBy: characterSet) .joined(separator: "") buildSettings["PRODUCT_BUNDLE_IDENTIFIER"] = bundleIdPrefix + "." + escapedTargetName } // automatically set test target name if target.type == .uiTestBundle || target.type == .unitTestBundle, !project.targetHasBuildSetting("TEST_TARGET_NAME", target: target, config: config) { for dependency in target.dependencies { if dependency.type == .target, let dependencyTarget = project.getTarget(dependency.reference), dependencyTarget.type.isApp { buildSettings["TEST_TARGET_NAME"] = dependencyTarget.name break } } } // automatically set TEST_HOST if target.type == .unitTestBundle, !project.targetHasBuildSetting("TEST_HOST", target: target, config: config) { for dependency in target.dependencies { if dependency.type == .target, let dependencyTarget = project.getTarget(dependency.reference), dependencyTarget.type.isApp { if dependencyTarget.platform == .macOS { buildSettings["TEST_HOST"] = "$(BUILT_PRODUCTS_DIR)/\(dependencyTarget.productName).app/Contents/MacOS/\(dependencyTarget.productName)" } else { buildSettings["TEST_HOST"] = "$(BUILT_PRODUCTS_DIR)/\(dependencyTarget.productName).app/\(dependencyTarget.productName)" } break } } } // objc linkage if anyDependencyRequiresObjCLinking { let otherLinkingFlags = "OTHER_LDFLAGS" let objCLinking = "-ObjC" if var array = buildSettings[otherLinkingFlags] as? [String] { array.append(objCLinking) buildSettings[otherLinkingFlags] = array } else if let string = buildSettings[otherLinkingFlags] as? String { buildSettings[otherLinkingFlags] = [string, objCLinking] } else { buildSettings[otherLinkingFlags] = ["$(inherited)", objCLinking] } } // set Carthage search paths let configFrameworkBuildPaths: [String] if !carthageDependencies.isEmpty { var carthagePlatformBuildPaths: [String] = [] if carthageDependencies.contains(where: { $0.carthageLinkType == .static }) { let carthagePlatformBuildPath = "$(PROJECT_DIR)/" + carthageResolver.buildPath(for: target.platform, linkType: .static) carthagePlatformBuildPaths.append(carthagePlatformBuildPath) } if carthageDependencies.contains(where: { $0.carthageLinkType == .dynamic }) { let carthagePlatformBuildPath = "$(PROJECT_DIR)/" + carthageResolver.buildPath(for: target.platform, linkType: .dynamic) carthagePlatformBuildPaths.append(carthagePlatformBuildPath) } configFrameworkBuildPaths = carthagePlatformBuildPaths + frameworkBuildPaths.sorted() } else { configFrameworkBuildPaths = frameworkBuildPaths.sorted() } // set framework search paths if !configFrameworkBuildPaths.isEmpty { let frameworkSearchPaths = "FRAMEWORK_SEARCH_PATHS" if var array = buildSettings[frameworkSearchPaths] as? [String] { array.append(contentsOf: configFrameworkBuildPaths) buildSettings[frameworkSearchPaths] = array } else if let string = buildSettings[frameworkSearchPaths] as? String { buildSettings[frameworkSearchPaths] = [string] + configFrameworkBuildPaths } else { buildSettings[frameworkSearchPaths] = ["$(inherited)"] + configFrameworkBuildPaths } } var baseConfiguration: PBXFileReference? if let configPath = target.configFiles[config.name], let fileReference = sourceGenerator.getContainedFileReference(path: project.basePath + configPath) as? PBXFileReference { baseConfiguration = fileReference } let buildConfig = XCBuildConfiguration( name: config.name, buildSettings: buildSettings ) buildConfig.baseConfiguration = baseConfiguration return addObject(buildConfig) } let buildConfigList = addObject(XCConfigurationList( buildConfigurations: configs, defaultConfigurationName: "" )) let targetObject = targetObjects[target.name]! let targetFileReference = targetFileReferences[target.name] targetObject.name = target.name targetObject.buildConfigurationList = buildConfigList targetObject.buildPhases = buildPhases targetObject.dependencies = dependencies targetObject.productName = target.name targetObject.buildRules = buildRules targetObject.packageProductDependencies = packageDependencies targetObject.product = targetFileReference if !target.isLegacy { targetObject.productType = target.type } } func getInfoPlist(_ sources: [TargetSource]) -> Path? { sources .lazy .map { self.project.basePath + $0.path } .compactMap { (path) -> Path? in if path.isFile { return path.lastComponent == "Info.plist" ? path : nil } else { return path.first(where: { $0.lastComponent == "Info.plist" }) } } .first } func getAllDependenciesPlusTransitiveNeedingEmbedding(target topLevelTarget: Target) -> [Dependency] { // this is used to resolve cyclical target dependencies var visitedTargets: Set<String> = [] var dependencies: [String: Dependency] = [:] var queue: [Target] = [topLevelTarget] while !queue.isEmpty { let target = queue.removeFirst() if visitedTargets.contains(target.name) { continue } let isTopLevel = target == topLevelTarget for dependency in target.dependencies { // don't overwrite dependencies, to allow top level ones to rule if dependencies[dependency.reference] != nil { continue } // don't want a dependency if it's going to be embedded or statically linked in a non-top level target // in .target check we filter out targets that will embed all of their dependencies switch dependency.type { case .sdk: dependencies[dependency.reference] = dependency case .framework, .carthage, .package: if isTopLevel || dependency.embed == nil { dependencies[dependency.reference] = dependency } case .target: if isTopLevel || dependency.embed == nil { if let dependencyTarget = project.getTarget(dependency.reference) { dependencies[dependency.reference] = dependency if !dependencyTarget.shouldEmbedDependencies { // traverse target's dependencies if it doesn't embed them itself queue.append(dependencyTarget) } } else if project.getAggregateTarget(dependency.reference) != nil { // Aggregate targets should be included dependencies[dependency.reference] = dependency } } } } visitedTargets.update(with: target.name) } return dependencies.sorted(by: { $0.key < $1.key }).map { $0.value } } } extension Target { var shouldEmbedDependencies: Bool { type.isApp || type.isTest } var shouldEmbedCarthageDependencies: Bool { (type.isApp && platform != .watchOS) || type == .watch2Extension || type.isTest } } extension Platform { /// - returns: `true` for platforms that the app store requires simulator slices to be stripped. public var requiresSimulatorStripping: Bool { switch self { case .iOS, .tvOS, .watchOS: return true case .macOS: return false } } } extension PBXFileElement { public func getSortOrder(groupSortPosition: SpecOptions.GroupSortPosition) -> Int { if type(of: self).isa == "PBXGroup" { switch groupSortPosition { case .top: return -1 case .bottom: return 1 case .none: return 0 } } else { return 0 } } } private extension Dependency { var carthageLinkType: Dependency.CarthageLinkType? { switch type { case .carthage(_, let linkType): return linkType default: return nil } } }
42.655856
163
0.576244
fe245d20903485e67bf968e3629291c876115548
6,467
import Foundation import Darwin public enum SysctlError: Error { case unknown case malformedUTF8 case invalidSize case posixError(POSIXErrorCode) } /// Wrapper around `sysctl` that preflights and allocates an [Int8] for the result and throws a Swift error if anything goes wrong. public func sysctl(levels: [Int32]) throws -> [Int8] { return try levels.withUnsafeBufferPointer() { levelsPointer throws -> [Int8] in // Preflight the request to get the required data size var requiredSize = 0 let preFlightResult = Darwin.sysctl(UnsafeMutablePointer<Int32>(mutating: levelsPointer.baseAddress), UInt32(levels.count), nil, &requiredSize, nil, 0) if preFlightResult != 0 { throw POSIXErrorCode(rawValue: errno).map { SysctlError.posixError($0) } ?? SysctlError.unknown } // Run the actual request with an appropriately sized array buffer let data = Array<Int8>(repeating: 0, count: requiredSize) let result = data.withUnsafeBufferPointer() { dataBuffer -> Int32 in return Darwin.sysctl(UnsafeMutablePointer<Int32>(mutating: levelsPointer.baseAddress), UInt32(levels.count), UnsafeMutableRawPointer(mutating: dataBuffer.baseAddress), &requiredSize, nil, 0) } if result != 0 { throw POSIXErrorCode(rawValue: errno).map { SysctlError.posixError($0) } ?? SysctlError.unknown } return data } } /// Generate an array of name levels (as can be used with the previous sysctl function) from a sysctl name string. public func sysctlLevels(fromName: String) throws -> [Int32] { var levelsBufferSize = Int(CTL_MAXNAME) var levelsBuffer = Array<Int32>(repeating: 0, count: levelsBufferSize) try levelsBuffer.withUnsafeMutableBufferPointer { (lbp: inout UnsafeMutableBufferPointer<Int32>) throws in try fromName.withCString { (nbp: UnsafePointer<Int8>) throws in guard sysctlnametomib(nbp, lbp.baseAddress, &levelsBufferSize) == 0 else { throw POSIXErrorCode(rawValue: errno).map { SysctlError.posixError($0) } ?? SysctlError.unknown } } } if levelsBuffer.count > levelsBufferSize { levelsBuffer.removeSubrange(levelsBufferSize..<levelsBuffer.count) } return levelsBuffer } // Helper function used by the various int from sysctl functions, below private func intFromSysctl(levels: [Int32]) throws -> Int64 { let buffer = try sysctl(levels: levels) switch buffer.count { case 4: return buffer.withUnsafeBufferPointer() { $0.baseAddress.map { $0.withMemoryRebound(to: Int32.self, capacity: 1) { Int64($0.pointee) } } ?? 0 } case 8: return buffer.withUnsafeBufferPointer() { $0.baseAddress.map {$0.withMemoryRebound(to: Int64.self, capacity: 1) { $0.pointee } } ?? 0 } default: throw SysctlError.invalidSize } } // Helper function used by the string from sysctl functions, below private func stringFromSysctl(levels: [Int32]) throws -> String { let optionalString = try sysctl(levels: levels).withUnsafeBufferPointer() { dataPointer -> String? in dataPointer.baseAddress.flatMap { String(validatingUTF8: $0) } } guard let s = optionalString else { throw SysctlError.malformedUTF8 } return s } /// Get an arbitrary sysctl value and interpret the bytes as a UTF8 string public func sysctlString(levels: Int32...) throws -> String { return try stringFromSysctl(levels: levels) } /// Get an arbitrary sysctl value and interpret the bytes as a UTF8 string public func sysctlString(name: String) throws -> String { return try stringFromSysctl(levels: sysctlLevels(fromName: name)) } /// Get an arbitrary sysctl value and cast it to an Int64 public func sysctlInt(levels: Int32...) throws -> Int64 { return try intFromSysctl(levels: levels) } /// Get an arbitrary sysctl value and cast it to an Int64 public func sysctlInt(name: String) throws -> Int64 { return try intFromSysctl(levels: sysctlLevels(fromName: name)) } public struct Sysctl { /// e.g. "MyComputer.local" (from System Preferences -> Sharing -> Computer Name) or /// "My-Name-iPhone" (from Settings -> General -> About -> Name) public static var hostName: String { return (try? sysctlString(levels: CTL_KERN, KERN_HOSTNAME)) ?? "" } /// e.g. "x86_64" or "N71mAP" /// NOTE: this is *corrected* on iOS devices to fetch hw.model public static var machine: String { #if os(iOS) && !arch(x86_64) && !arch(i386) return (try? sysctlString(levels: CTL_HW, HW_MODEL)) ?? "" #else return (try? sysctlString(levels: CTL_HW, HW_MACHINE)) ?? "" #endif } /// e.g. "MacPro4,1" or "iPhone8,1" /// NOTE: this is *corrected* on iOS devices to fetch hw.machine public static var model: String { #if os(iOS) && !arch(x86_64) && !arch(i386) return (try? sysctlString(levels: CTL_HW, HW_MACHINE)) ?? "" #else return (try? sysctlString(levels: CTL_HW, HW_MODEL)) ?? "" #endif } /// e.g. "8" or "2" public static var activeCPUs: Int64 { return (try? sysctlInt(levels: CTL_HW, HW_AVAILCPU)) ?? 0 } /// e.g. "15.3.0" or "15.0.0" public static var osRelease: String { return (try? sysctlString(levels: CTL_KERN, KERN_OSRELEASE)) ?? "" } /// e.g. 199506 or 199506 public static var osRev: Int64 { return (try? sysctlInt(levels: CTL_KERN, KERN_OSREV)) ?? 0 } /// e.g. "Darwin" or "Darwin" public static var osType: String { return (try? sysctlString(levels: CTL_KERN, KERN_OSTYPE)) ?? "" } /// e.g. "15D21" or "13D20" public static var osVersion: String { return (try? sysctlString(levels: CTL_KERN, KERN_OSVERSION)) ?? "" } /// e.g. "Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64" or /// "Darwin Kernel Version 15.0.0: Wed Dec 9 22:19:38 PST 2015; root:xnu-3248.31.3~2/RELEASE_ARM64_S8000" public static var version: String { return (try? sysctlString(levels: CTL_KERN, KERN_VERSION)) ?? "" } #if os(macOS) /// e.g. 2659000000 (not available on iOS) public static var cpuFreq: Int64 { return (try? sysctlInt(name: "hw.cpufrequency")) ?? 0 } /// e.g. 25769803776 (not available on iOS) public static var memSize: Int64 { return (try? sysctlInt(levels: CTL_HW, HW_MEMSIZE)) ?? 0 } #endif }
44.6
202
0.670636
d61ec5d44ccf8dd4ffbb88f2289667fdedb6771b
1,379
// // RecentDataSource.swift // appStore // // Created by myslab on 2020/09/19. // Copyright © 2020 mys. All rights reserved. // import UIKit final class RecentDataSource: NSObject, Presentable { var viewModel: SearchViewModel init(_ viewModel: SearchViewModel) { self.viewModel = viewModel } } //MARK:- UITableViewDataSource extension RecentDataSource: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.recents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(SearchLinkCell.self, for: indexPath) cell.configure(viewModel.recents[indexPath.row]) return cell } } //MARK:- UITableViewDelegate extension RecentDataSource: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = tableView.dequeueReusableHeaderFooterView(TitleHeaderView.self) view.configure("recent".localized()) return view } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) viewModel.didSelectRecent(viewModel.recents[indexPath.row]) } }
29.978261
100
0.715011
f8f0f9c6ffa07b35f2aa99634fe6f1eebd140da5
1,470
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } }
38.684211
145
0.759864
799277b374f3de64dad402cecf0f6d1a566b6763
824
// // RecipeBookRouterTests.swift // RecipeBookTests // // Created by Andrew Boyd on 30/08/2017. // Copyright © 2017 Andy Boyd. All rights reserved. // import XCTest @testable import RecipeBook class RecipeBookRouterTests: XCTestCase { let validRecipeDetailData = RecipeDetailDataModel(title: "recipe title", ingredients: "recipe ingredients", link: URL(string: "http://someurl.com")!, imagePath: "http://someImagePath") func test_recipeDetailViewController_returnsRecipeDetailViewController() { let testVC = RecipeBookRouter.recipeDetailViewController(for: self.validRecipeDetailData) XCTAssertNotNil(testVC) } }
34.333333
97
0.595874
9c9bcf49312537b93e3906e860ddc17b9f050dc0
6,019
// // SignupViewController.swift // EstateBand // // Created by Minecode on 2017/6/11. // Copyright © 2017年 org.minecode. All rights reserved. // import UIKit import CoreData class SignupViewController: UIViewController { // Widget data @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var accountField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var idField: UITextField! @IBOutlet weak var workNumberField: UITextField! @IBOutlet weak var maleButton: UIButton! @IBOutlet weak var femaleButton: UIButton! @IBOutlet weak var signupView: UIView! // Data var appDelegate: AppDelegate! override func viewDidLoad() { super.viewDidLoad() // 设置背景 self.view.backgroundColor = UIColor.init(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0) self.signupView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.95) self.signupView.layer.cornerRadius = 15 // 初始化数据 self.appDelegate = UIApplication.shared.delegate as! AppDelegate // 注册收回键盘手势 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGesture))) // 设置控件 self.doneButton.layer.cornerRadius = 10 self.backButton.layer.cornerRadius = 8 } @IBAction func doneAction(_ sender: UIButton) { // 保存数据 saveContext() // 弹窗提醒 } @IBAction func sexSelectAction(_ sender: UIButton) { switch sender.tag { case 100: maleButton.isSelected = true femaleButton.isSelected = false case 101: maleButton.isSelected = false femaleButton.isSelected = true default: break } } @IBAction func backAction(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } func saveContext() { // 判断是否填写完毕 let done = (nameField.text != nil) && (accountField.text != nil) && (passwordField.text != nil) && (idField.text != nil) && (workNumberField.text != nil) if(done) { // 保存添加模型 let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user.name = nameField.text user.account = accountField.text user.password = passwordField.text user.id = Int32.init(idField.text!)! user.workNumber = Int32.init(workNumberField.text!)! user.sex = maleButton.state==UIControlState.selected ? true : false user.pic = "Default" // 弹窗提醒 do { try self.appDelegate.managedObjectContext.save() let alert = UIAlertController.init(title: "Success", message: "Registered successfully", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } catch { let alert = UIAlertController(title: "Failed", message: "Something error!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Failed", message: "Please fill all the text field!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } func tapGesture(sender: UITapGestureRecognizer) { if sender.state == .ended { nameField.resignFirstResponder() accountField.resignFirstResponder() passwordField.resignFirstResponder() idField.resignFirstResponder() workNumberField.resignFirstResponder() } sender.cancelsTouchesInView = false } @IBAction func addDefaultData(_ sender: UIButton) { // 添加第一个人 let user_1 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_1.name = "Michael" user_1.account = "micheal123" user_1.password = "password" user_1.id = 10230003 user_1.workNumber = 210002 user_1.sex = true user_1.pic = "Michael" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } // 添加第二个人 let user_2 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_2.name = "Mike" user_2.account = "[email protected]" user_2.password = "password" user_2.id = 20350012 user_2.workNumber = 210003 user_2.sex = true user_2.pic = "Mike" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } // 添加第三个人 let user_3 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_3.name = "Steven" user_3.account = "[email protected]" user_3.password = "password" user_3.id = 43105128 user_3.workNumber = 210004 user_3.sex = true user_3.pic = "Steven" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } } }
36.92638
161
0.603422
679452619a718adef91ba75a674d8c3088e5b15a
1,023
import UIKit class LoginCoordinator: Coordinator, WindowManager { var window: UIWindow? var rootController: UINavigationController? var tab: BaseTab? func inject(window: UIWindow) { self.window = window self.rootController = UINavigationController() window.rootViewController = rootController window.makeKeyAndVisible() } func start() { let welcomeVC = WelcomeViewController() welcomeVC.coordinator = self rootController?.pushViewController(welcomeVC, animated: true) } func continueToLogin() { let loginVC = LoginViewController() loginVC.coordinator = self rootController?.pushViewController(loginVC, animated: true) } func continueToTabNavigation() { guard let window = self.window else { return } AppSingleton.appCoordinator.inject(window: window) AppSingleton.appCoordinator.start() } func reset() { rootController?.viewControllers.removeAll() } }
26.921053
69
0.673509
8a72665858b1ef49c572e2424d1285e952ad7550
435
// // CalendarShow.swift // TraktKit // // Created by Maximilian Litteral on 6/14/17. // Copyright © 2017 Maximilian Litteral. All rights reserved. // import Foundation public struct CalendarShow: Codable, Hashable { let firstAired: Date let episode: TraktEpisode let show: TraktShow enum CodingKeys: String, CodingKey { case firstAired = "first_aired" case episode case show } }
19.772727
62
0.666667
8a1eab011ad37574df885f37f9e5cbfeaea1ec52
97
// // Dummy.swift // example // // Created by Agaweb Dev on 09/12/2020. // import Foundation
10.777778
40
0.628866
6a84a18815a4891584a74a4171559a473cad3f14
1,032
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** An array of values, each being the `id` value of a column header that is applicable to the current cell. */ public struct ColumnHeaderIDs: Codable, Equatable { /** The `id` value of a column header. */ public var id: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case id = "id" } }
29.485714
105
0.707364
14ea8e6dd2add8cf70ecc14fa850045833c95f0d
1,723
// // MBSouthAfricaDocumentProviders.swift // BlinkID-app // // Created by Jura Skrlec on 31/10/2017. // Copyright © 2017 Microblink. All rights reserved. // import Foundation import MicroBlink class MBSouthAfricaDLDocumentProvider: MBDocumentProvider { override var frontRecognizerProvider: MBRecognizerWrapper? { return MBRecognizerWrapper(withRecognizer: MBDocumentFaceRecognizer()) } override var backRecognizerProvider: MBRecognizerWrapper? { return MBRecognizerWrapper(withRecognizer: MBPdf417Recognizer()) } override var type: MBDocumentType { return MBDocumentType.driverLicense } override var aspectRatio: DocumentAspectRatio { return DocumentAspectRatio.id1 } } class MBSouthAfricaIDDocumentProvider: MBDocumentProvider { override var frontRecognizerProvider: MBRecognizerWrapper? { return MBRecognizerWrapper(withRecognizer: MBDocumentFaceRecognizer()) } override var backRecognizerProvider: MBRecognizerWrapper? { return MBRecognizerWrapper(withRecognizer: MBPdf417Recognizer()) } override var type: MBDocumentType { return MBDocumentType.identityCard } override var aspectRatio: DocumentAspectRatio { return DocumentAspectRatio.id1 } } class MBSouthAfricaVisaDocumentProvider: MBDocumentProvider { override var frontRecognizerProvider: MBRecognizerWrapper? { return MBRecognizerWrapper(withDocumentDetector: MBDocumentDetectorD1Recognizer()) } override var type: MBDocumentType { return MBDocumentType.visa } override var aspectRatio: DocumentAspectRatio { return DocumentAspectRatio.id1 } }
25.716418
90
0.737667
8f04ac00200870719c7a125f5faf22215febf4b6
1,403
// // AppDelegate.swift // Ahlong // // Created by Atown on 2019/12/24. // Copyright © 2019 Atown. 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. } }
36.921053
179
0.746258
ab7f3c23871ba8b7391a6dcd51e8ec16e2a523f7
2,619
// // ContentView.swift // ZoomableExample // // Created by jasu on 2022/01/28. // Copyright (c) 2022 jasu All rights reserved. // import SwiftUI import Zoomable struct ContentView: View { private let url = URL(string: "https://images.unsplash.com/photo-1641130663904-d6cb4772fad5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1432&q=80")! @State private var selection: Int = 0 private var content: some View { GeometryReader { proxy in TabView(selection: $selection) { ZoomableView(size: CGSize(width: proxy.size.width, height: proxy.size.width * (2/3)), min: 1.0, max: 6.0, showsIndicators: true) { Image("bany") .resizable() .scaledToFit() .background(Color.black) .clipped() } .frame(width: proxy.size.width, height: proxy.size.width * (2/3)) .overlay( Rectangle() .fill(Color.clear) .border(.black, width: 1) ) .tabItem { Image(systemName: "0.square.fill") Text("ZoomableView") } .tag(0) ZoomableImageView(url: url, min: 1.0, max: 3.0, showsIndicators: true) { Text("ZoomableImageView") .padding() .background(Color.black.opacity(0.5)) .cornerRadius(8) .foregroundColor(Color.white) } .overlay( Rectangle() .fill(Color.clear) .border(.black, width: 1) ) .tabItem { Image(systemName: "1.square.fill") Text("ZoomableImageView") } .tag(1) } } } var body: some View { #if os(iOS) NavigationView { content .navigationTitle(Text(selection == 0 ? "ZoomableView" : "ZoomableImageView")) .navigationBarTitleDisplayMode(.inline) .padding() } .navigationViewStyle(.stack) #else ZStack { content .padding() } #endif } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
30.453488
196
0.462772
1a8841fe2e55d1c7a884eb49432f79ca09a53bd5
5,717
// // Copyright © 2020 Optimize Fitness Inc. // Licensed under the MIT license // https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE // import Foundation import MinervaList import RxSwift import UIKit open class TextInputCellModel: BaseListCellModel { public typealias TextInputAction = (_ textInputCellModel: TextInputCellModel, _ text: String?) -> Void public var textInputAction: TextInputAction? public var directionalLayoutMargins = NSDirectionalEdgeInsets( top: 8, leading: 16, bottom: 8, trailing: 16 ) fileprivate static let bottomBorderHeight: CGFloat = 1.0 fileprivate static let textBottomMargin: CGFloat = 8.0 fileprivate static let textInputIndent: CGFloat = 10.0 fileprivate var attributedPlaceholder: NSAttributedString { NSAttributedString(string: placeholder, font: font, fontColor: placeholderTextColor) } public var bottomBorderColor = BehaviorSubject<UIColor?>(value: nil) public var becomesFirstResponder = false public var text: String? fileprivate let font: UIFont fileprivate let placeholder: String public var cursorColor: UIColor? public var textColor: UIColor? public var textContentType: UITextContentType? public var isSecureTextEntry: Bool = false public var autocorrectionType: UITextAutocorrectionType = .default public var autocapitalizationType: UITextAutocapitalizationType = .none public var keyboardType: UIKeyboardType = .default public var inputTextColor: UIColor = .white public var placeholderTextColor: UIColor = .white public var maxControlWidth: CGFloat = 340 public var textFieldAccessibilityIdentifier: String? public init(identifier: String, placeholder: String, font: UIFont) { self.placeholder = placeholder self.font = font super.init(identifier: identifier) } // MARK: - BaseListCellModel override open func identical(to model: ListCellModel) -> Bool { guard let model = model as? Self, super.identical(to: model) else { return false } return text == model.text && font == model.font && placeholder == model.placeholder && cursorColor == model.cursorColor && textColor == model.textColor && textContentType == model.textContentType && isSecureTextEntry == model.isSecureTextEntry && autocorrectionType == model.autocorrectionType && autocapitalizationType == model.autocapitalizationType && keyboardType == model.keyboardType && inputTextColor == model.inputTextColor && placeholderTextColor == model.placeholderTextColor && maxControlWidth == model.maxControlWidth && directionalLayoutMargins == model.directionalLayoutMargins && textFieldAccessibilityIdentifier == model.textFieldAccessibilityIdentifier } } public final class TextInputCell: BaseReactiveListCell<TextInputCellModel> { private let textField: UITextField = { let textField = UITextField(frame: .zero) textField.borderStyle = .none textField.adjustsFontForContentSizeCategory = true return textField }() private let bottomBorder: UIView = { let bottomBorder = UIView() return bottomBorder }() override public init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(textField) contentView.addSubview(bottomBorder) setupConstraints() textField.addTarget( self, action: #selector(textFieldDidChange(_:)), for: .editingChanged ) } @objc private func textFieldDidChange(_ textField: UITextField) { guard let model = self.model else { return } model.text = textField.text model.textInputAction?(model, textField.text) } override public func bind(model: TextInputCellModel, sizing: Bool) { super.bind(model: model, sizing: sizing) textField.attributedPlaceholder = model.attributedPlaceholder if let initialText = model.text, textField.text == nil || textField.text?.isEmpty == true { textField.text = initialText } textField.font = model.font contentView.directionalLayoutMargins = model.directionalLayoutMargins guard !sizing else { return } textField.accessibilityIdentifier = model.textFieldAccessibilityIdentifier textField.textColor = model.inputTextColor textField.autocapitalizationType = model.autocapitalizationType textField.autocorrectionType = model.autocorrectionType textField.tintColor = model.cursorColor textField.keyboardType = model.keyboardType textField.isSecureTextEntry = model.isSecureTextEntry textField.textContentType = model.textContentType model.bottomBorderColor .observe(on: MainScheduler.instance) .subscribe(onNext: { [weak self] bottomBorderColor -> Void in self?.bottomBorder.backgroundColor = bottomBorderColor }) .disposed(by: disposeBag) if model.becomesFirstResponder { textField.becomeFirstResponder() } } } // MARK: - Constraints extension TextInputCell { private func setupConstraints() { let layoutGuide = contentView.layoutMarginsGuide textField.anchor( toLeading: layoutGuide.leadingAnchor, top: layoutGuide.topAnchor, trailing: layoutGuide.trailingAnchor, bottom: nil ) bottomBorder.anchorHeight(to: TextInputCellModel.bottomBorderHeight) bottomBorder.anchor( toLeading: layoutGuide.leadingAnchor, top: nil, trailing: layoutGuide.trailingAnchor, bottom: layoutGuide.bottomAnchor ) bottomBorder.topAnchor .constraint( equalTo: textField.bottomAnchor, constant: TextInputCellModel.textBottomMargin ) .isActive = true contentView.shouldTranslateAutoresizingMaskIntoConstraints(false) } }
32.482955
99
0.738324
c146b853aea9beb8a8b5e7e1ae7576af07995490
4,489
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Common import UIKit public class ClipItemInformationTransitioningController: NSObject { private var presentationInteractiveAnimator: ClipItemInformationInteractivePresentationAnimator? private var dismissalInteractiveAnimator: ClipItemInformationInteractiveDismissalAnimator? private var transitionMode: ClipItemInformationTransitionType = .initialValue private let lock: TransitionLock private let logger: Loggable // MARK: - Lifecycle public init(lock: TransitionLock, logger: Loggable) { self.lock = lock self.logger = logger } } extension ClipItemInformationTransitioningController: ClipItemInformationTransitioningControllable { // MARK: - ClipItemInformationTransitioningControllable public var isInteractive: Bool { guard case .custom(interactive: true) = self.transitionMode else { return false } return true } public func isLocked(by id: UUID) -> Bool { lock.isLocked(by: id) } @discardableResult public func beginTransition(id: UUID, mode: ClipItemInformationTransitionType) -> Bool { guard lock.takeLock(id) else { return false } transitionMode = mode return true } @discardableResult public func didPanForDismissal(id: UUID, sender: UIPanGestureRecognizer) -> Bool { guard lock.isLocked(by: id) else { return false } self.dismissalInteractiveAnimator?.didPan(sender: sender) return true } @discardableResult public func didPanForPresentation(id: UUID, sender: UIPanGestureRecognizer) -> Bool { guard lock.isLocked(by: id) else { return false } self.presentationInteractiveAnimator?.didPan(sender: sender) return true } } extension ClipItemInformationTransitioningController: AnimatorDelegate { // MARK: - AnimatorDelegate func animator(_ animator: Animator, didComplete: Bool) { lock.releaseLock() self.transitionMode = .initialValue } } extension ClipItemInformationTransitioningController: UIViewControllerTransitioningDelegate { // MARK: - UIViewControllerTransitioningDelegate public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch self.transitionMode { case .custom: let fallback = FadeTransitionAnimator(logger: self.logger) return ClipItemInformationPresentationAnimator(delegate: self, fallbackAnimator: fallback) default: return nil } } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch self.transitionMode { case .custom: let fallback = FadeTransitionAnimator(logger: self.logger) return ClipItemInformationDismissalAnimator(delegate: self, fallbackAnimator: fallback) default: return nil } } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { switch self.transitionMode { case .custom(interactive: true): let fallback = FadeTransitionAnimator(logger: self.logger) self.presentationInteractiveAnimator = ClipItemInformationInteractivePresentationAnimator(logger: self.logger, fallbackAnimator: fallback) return self.presentationInteractiveAnimator default: return nil } } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { switch self.transitionMode { case .custom(interactive: true): let fallback = FadeTransitionAnimator(logger: self.logger) self.dismissalInteractiveAnimator = ClipItemInformationInteractiveDismissalAnimator(logger: self.logger, fallbackAnimator: fallback) return self.dismissalInteractiveAnimator default: return nil } } }
37.408333
154
0.678325
299672345262b722b0af1b0a7e6b46c8c37eb9f8
3,321
//: [Previous](@previous) import UIKit import XCPlayground import PlaygroundSupport fileprivate enum LocalFeature: String { case exampleOfLocalFeature = "eolf" // for testing purposes case disappearingMessages = "dm" } public protocol LocalFeatureSwitcherStorage { var localFeatures: String? { get set } } public final class LocalFeatureSwitcher: NSObject { public static let shared = LocalFeatureSwitcher() public var isExampleOfLocalFeatureEnabled: Bool { get { return isFeatureEnabled(.exampleOfLocalFeature) } set { updateFeature(.exampleOfLocalFeature, isEnabled: newValue)} } public var isDisappearingMessagesEnabled: Bool { get { return isFeatureEnabled(.disappearingMessages) } set { updateFeature(.disappearingMessages, isEnabled: newValue)} } private enum Constants { static let separator: Character = "," } private var storage: LocalFeatureSwitcherStorage? private let queue = DispatchQueue( label: "ViberConfiguration.LocalFeatureSwitcherQueue", attributes: .concurrent) public func initialize(storage: LocalFeatureSwitcherStorage?) { #if !DEBUG_OPTIONS_ENABLED return #endif self.storage = storage } } extension LocalFeatureSwitcher { fileprivate func isFeatureEnabled(_ feature: LocalFeature) -> Bool { guard let localFeatures = readLocalFeatures() else { return false } return localFeatures.contains(feature) } fileprivate func updateFeature(_ feature: LocalFeature, isEnabled: Bool) { let localFeatures = readLocalFeatures() ?? [] guard localFeatures.contains(feature) != isEnabled else { return } if isEnabled { writeLocalFeatures(localFeatures + [feature]) } else { writeLocalFeatures(localFeatures.filter { $0 != feature }) } } private func readLocalFeatures() -> [LocalFeature]? { #if !DEBUG_OPTIONS_ENABLED return nil #endif var features: String? queue.sync { features = self.storage?.localFeatures } guard let localFeatures = features else { return nil } return localFeatures .split(separator: Constants.separator) .compactMap { LocalFeature(rawValue: String($0)) } } private func writeLocalFeatures(_ features: [LocalFeature]) { #if !DEBUG_OPTIONS_ENABLED return #endif let string = features.map { $0.rawValue }.joined(separator: String(Constants.separator)) queue.async(flags: .barrier) { self.storage?.localFeatures = !string.isEmpty ? string : nil } } } @propertyWrapper struct LocalFeatureWrapper { private var feature: LocalFeature private var switcher: LocalFeatureSwitcher { LocalFeatureSwitcher.shared } var wrappedValue: Bool { get { switcher.isFeatureEnabled(feature) } set { switcher.updateFeature(feature, isEnabled: newValue) } } fileprivate init(_ feature: LocalFeature) { self.feature = feature } } struct Test { @LocalFeatureWrapper(.exampleOfLocalFeature) var test: Bool } var test = Test() print(test.test) //: [Next](@next)
28.384615
96
0.657633
03e7b6ffd14179a45b86dacd7de7f151d7185f26
3,993
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // Version: 1.3.0.0 import Foundation import ChronoxorFbe import ChronoxorProto // Fast Binary Encoding String->OptionalEnumSimple map final model class FinalModelMapStringOptionalEnumSimple: FinalModel { var _buffer: Buffer = Buffer() var _offset: Int = 0 private var _modelKey: ChronoxorFbe.FinalModelString private var _modelValue: FinalModelOptionalEnumSimple init(buffer: Buffer, offset: Int) { _buffer = buffer _offset = offset _modelKey = ChronoxorFbe.FinalModelString(buffer: buffer, offset: offset) _modelValue = FinalModelOptionalEnumSimple(buffer: buffer, offset: offset) } // Get the allocation size func fbeAllocationSize(value values: Dictionary<String, ChronoxorTest.EnumSimple?>) -> Int { var size: Int = 4 for (key, value) in values { size += _modelKey.fbeAllocationSize(value: key) size += _modelValue.fbeAllocationSize(value: value) } return size } // Check if the vector is valid public func verify() -> Int { if _buffer.offset + fbeOffset + 4 > _buffer.size { return Int.max } let fbeMapSize = Int(readUInt32(offset: fbeOffset)) var size: Int = 4 _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 var i = fbeMapSize while i > 0 { let offsetKey = _modelKey.verify() if offsetKey == Int.max { return Int.max } _modelKey.fbeShift(size: offsetKey) _modelValue.fbeShift(size: offsetKey) size += offsetKey let offsetValue = _modelValue.verify() if offsetValue == Int.max { return Int.max } _modelKey.fbeShift(size: offsetValue) _modelValue.fbeShift(size: offsetValue) size += offsetValue i -= 1 } return size } public func get(values: inout Dictionary<String, ChronoxorTest.EnumSimple?>) -> Int { values.removeAll() if _buffer.offset + fbeOffset + 4 > _buffer.size { assertionFailure("Model is broken!") return 0 } let fbeMapSize = Int(readUInt32(offset: fbeOffset)) if fbeMapSize == 0 { return 4 } var size: Int = 4 var offset = Size() _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 for _ in 1...fbeMapSize { offset.value = 0 let key = _modelKey.get(size: &offset) _modelKey.fbeShift(size: offset.value) _modelValue.fbeShift(size: offset.value) size += offset.value offset.value = 0 let value = _modelValue.get(size: &offset) _modelKey.fbeShift(size: offset.value) _modelValue.fbeShift(size: offset.value) size += offset.value values[key] = value } return size } public func set(value values: Dictionary<String, ChronoxorTest.EnumSimple?>) throws -> Int { if _buffer.offset + fbeOffset + 4 > _buffer.size { assertionFailure("Model is broken!") return 0 } write(offset: fbeOffset, value: UInt32(values.count)) var size: Int = 4 _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 for (key, value) in values { let offsetKey = try _modelKey.set(value: key) _modelKey.fbeShift(size: offsetKey) _modelValue.fbeShift(size: offsetKey) let offsetValue = try _modelValue.set(value: value) _modelKey.fbeShift(size: offsetValue) _modelValue.fbeShift(size: offsetValue) size += offsetKey + offsetValue } return size } }
33
96
0.604308
9c47fc6a302be13956c3a2c0da103ff3e9555fc8
4,448
import Foundation import Atomics public class FairSelector: Selector { public enum FairSelectorError: Error { case duplicateId(msg: String) } let state = ManagedAtomic<Int>(0) let stateLock = NonFairLock(10) let condition : Condition let selectables = CircularDoubleLinkedList<Selectable>() var idealNext: CDLLNode<Selectable>? = nil private static let INACTIVE = 0 private static let ENABLING = 1 private static let WAITING = 2 private static let READY = 3 private var hasTimeout = false private var timeoutAt: timespec? = nil private var mutex = Mutex() public init(_ selectables: [Selectable]) throws { state.store(FairSelector.INACTIVE, ordering: .relaxed) hasTimeout = false condition = stateLock.createCondition() for s in selectables { try addSelectable(s) } } public func addSelectable(_ selectable: Selectable) throws { mutex.lock() defer { mutex.unlock() } if let node = selectables.find(finder: { (n) -> CDLLNode<Selectable>? in if n.value!.getId() == selectable.getId() { return n } return nil }) { throw FairSelectorError.duplicateId(msg: "oops, duplicate id detected, each must be unique") } selectable.setSelector(self) selectable.setEnableable(true) let node = selectables.add(selectable) if idealNext == nil { idealNext = node } } public func removeSelectable(_ id: String) -> Bool { mutex.lock() defer { mutex.unlock() } if let node = selectables.find(finder: { (n) -> CDLLNode<Selectable>? in if n.value!.getId() == id { return n } return nil }) { if idealNext === node { if selectables.size == 1 { idealNext = nil } else { idealNext = idealNext?.next } } selectables.remove(node) return true } return false } public func select() -> Selectable { var selected: Selectable? = nil repeat { state.store(FairSelector.ENABLING, ordering: .relaxed) selected = checkEnabled() do { stateLock.lock() defer { stateLock.unlock() } if state.compareExchange(expected: FairSelector.ENABLING, desired: FairSelector.WAITING, ordering: .relaxed).exchanged { if hasTimeout && !TimeoutState.expired(timeoutAt!) { condition.doWait(&timeoutAt!) } else { condition.doWait() } } } state.store(FairSelector.INACTIVE, ordering: .relaxed) } while selected == nil hasTimeout = false return selected! } func hasData(node: CDLLNode<Selectable>) -> CDLLNode<Selectable>? { if let selectable = node.value { if selectable.hasData() { return node } } return nil } private func checkEnabled() -> Selectable? { if let node = selectables.find(beginAt: idealNext, finder: hasData) { if node === idealNext { idealNext = idealNext?.next } state.store(FairSelector.READY, ordering: .relaxed) return node.value } return nil } public func schedule() -> Void { if state.exchange(FairSelector.READY, ordering: .relaxed) == FairSelector.WAITING { stateLock.lock() defer { stateLock.unlock() } condition.doNotify() } } public func setTimeoutAt(_ at: timespec) { if hasTimeout { if earlier(at, timeoutAt!) { timeoutAt = at } } else { hasTimeout = true timeoutAt = at } } func earlier(_ t1: timespec, _ t2: timespec) -> Bool { if t1.tv_sec < t2.tv_sec { return true } if (t1.tv_sec > t2.tv_sec) { return false } return t1.tv_nsec < t2.tv_nsec } }
28.151899
136
0.519335
8f8fda3b80de6a627ab2cfbbf2aacc61430e6aea
2,283
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import MobileCoreServices let UTTAll = [ kUTTypeItem, ] let AAFileTypes = [ "mp3" :AAFileType.Music, "m4a" :AAFileType.Music, "ogg" :AAFileType.Music, "flac" :AAFileType.Music, "alac" :AAFileType.Music, "wav" :AAFileType.Music, "wma" :AAFileType.Music, "aac" :AAFileType.Music, "doc" :AAFileType.Doc, "docm" :AAFileType.Doc, "dot" :AAFileType.Doc, "dotx" :AAFileType.Doc, "epub" :AAFileType.Doc, "fb2" :AAFileType.Doc, "xml" :AAFileType.Doc, "info" :AAFileType.Doc, "tex" :AAFileType.Doc, "stw" :AAFileType.Doc, "sxw" :AAFileType.Doc, "txt" :AAFileType.Doc, "xlc" :AAFileType.Doc, "odf" :AAFileType.Doc, "odt" :AAFileType.Doc, "ott" :AAFileType.Doc, "rtf" :AAFileType.Doc, "pages":AAFileType.Doc, "ini" :AAFileType.Doc, "xls" :AAFileType.Spreadsheet, "xlsx" :AAFileType.Spreadsheet, "xlsm" :AAFileType.Spreadsheet, "xlsb" :AAFileType.Spreadsheet, "numbers":AAFileType.Spreadsheet, "jpg" :AAFileType.Picture, "jpeg" :AAFileType.Picture, "jp2" :AAFileType.Picture, "jps" :AAFileType.Picture, "gif" :AAFileType.Picture, "tiff" :AAFileType.Picture, "png" :AAFileType.Picture, "psd" :AAFileType.Picture, "webp" :AAFileType.Picture, "ico" :AAFileType.Picture, "pcx" :AAFileType.Picture, "tga" :AAFileType.Picture, "raw" :AAFileType.Picture, "svg" :AAFileType.Picture, "mp4" :AAFileType.Video, "3gp" :AAFileType.Video, "m4v" :AAFileType.Video, "webm" :AAFileType.Video, "ppt" :AAFileType.Presentation, "key" :AAFileType.Presentation, "keynote" :AAFileType.Presentation, "pdf" :AAFileType.PDF, "apk" :AAFileType.APK, "rar" :AAFileType.RAR, "zip" :AAFileType.ZIP, "csv" :AAFileType.CSV, "xhtm" :AAFileType.HTML, "htm" :AAFileType.HTML, "html" :AAFileType.HTML, ] enum AAFileType { case Music case Doc case Spreadsheet case Picture case Video case Presentation case PDF case APK case RAR case ZIP case CSV case HTML case UNKNOWN }
23.536082
57
0.612352
0eb79a010e033b1318030ad71848436238cc5d75
2,939
import Foundation import RxSwift public protocol ChainTransaction { func chainApi() -> ChainApi } public extension ChainTransaction { func push( actions: [ActionAbi], transactionContext: TransactionContext ) -> Single<ChainResponse<TransactionCommitted>> { return chainApi().getInfo().flatMap { info in if (info.success) { let transactionAbi = self.createTransactionAbi( expirationDate: transactionContext.expirationDate, blockIdDetails: BlockIdDetails(blockId: info.body!.head_block_id), actions: actions) let signedTransactionAbi = SignedTransactionAbi( chainId: ChainIdWriterValue(chainId: info.body!.chain_id), transaction: transactionAbi, context_free_data: HexCollectionWriterValue(value: [])) let signature = PrivateKeySigning().sign( digest: signedTransactionAbi.toData(transactionContext.abiEncoder()), eosPrivateKey: transactionContext.authorizingPrivateKey) return self.chainApi().pushTransaction(body: PushTransaction( signatures: [signature], compression: "none", packed_context_free_data: "", packed_trx: transactionAbi.toHex(transactionContext.abiEncoder()) )).map { response in ChainResponse<TransactionCommitted>( success: response.success, statusCode: response.statusCode, body: response.body) }.catchError { error in let errorResponse = (error as! HttpErrorResponse<ChainError>) return Single.just(ChainResponse<TransactionCommitted>( success: false, statusCode: errorResponse.statusCode, errorBody: errorResponse.bodyString!)) }.catchErrorJustReturn(ChainResponse.errorResponse()) } else { return Single.just(ChainResponse.errorResponse()) } } } public func createTransactionAbi(expirationDate: Date, blockIdDetails: BlockIdDetails, actions: Array<ActionAbi>) -> TransactionAbi { return TransactionAbi( expiration: TimestampWriterValue(date: expirationDate), ref_block_num: BlockNumWriterValue(value: blockIdDetails.blockNum), ref_block_prefix: BlockPrefixWriterValue(value: blockIdDetails.blockPrefix), max_net_usage_words: 0, max_cpu_usage_ms: 0, delay_sec: 0, context_free_actions: [], actions: actions, transaction_extensions: StringCollectionWriterValue(value: [])) } }
43.865672
89
0.586934
e4a98492b7b875720e05d0b6e6bb1f11ef78b335
4,219
// // PageViewController.swift // Compiler Explorer // // Created by Robert Widmann on 7/27/19. // Copyright © 2019 CodaFi. All rights reserved. // import SwiftUI import UIKit private func pageViewControllerOptions(for idiom: UIUserInterfaceIdiom) -> UIPageViewController { switch idiom { case .pad: return UIPageViewController( transitionStyle: .pageCurl, navigationOrientation: .horizontal, // OK, this one's the worst API now. options: [ .spineLocation : NSNumber(value: UIPageViewController.SpineLocation.mid.rawValue) ]) case .phone: return UIPageViewController( transitionStyle: .scroll, navigationOrientation: .horizontal) default: fatalError() } } struct PageViewController: UIViewControllerRepresentable { let controllers: [UIViewController] @Binding var currentPage: Int init(controllers: [UIViewController], currentPage: Binding<Int>) { self.controllers = controllers self._currentPage = currentPage } func makeCoordinator() -> Coordinator { return Coordinator(controllers: self.controllers, currentPage: self.$currentPage) } func makeUIViewController(context: Context) -> UIPageViewController { let pageViewController = pageViewControllerOptions(for: UIDevice.current.userInterfaceIdiom) pageViewController.dataSource = context.coordinator pageViewController.delegate = context.coordinator pageViewController.isDoubleSided = UIDevice.current.userInterfaceIdiom == .pad return pageViewController } func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) { switch UIDevice.current.userInterfaceIdiom { case .pad: pageViewController.setViewControllers(self.controllers, direction: .forward, animated: false) case .phone: pageViewController.setViewControllers([self.controllers[self.currentPage]], direction: .forward, animated: true) default: fatalError() } } class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate { let controllers: [UIViewController] @Binding var currentPage: Int init(controllers: [UIViewController], currentPage: Binding<Int>) { self.controllers = controllers self._currentPage = currentPage } func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation { switch UIDevice.current.userInterfaceIdiom { case .pad: return .mid case .phone: return .min default: fatalError() } } func pageViewController( _ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = self.controllers.firstIndex(of: viewController) else { return nil } if index == 0 { return nil } return self.controllers[index - 1] } func pageViewController( _ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = self.controllers.firstIndex(of: viewController) else { return nil } if index + 1 == self.controllers.count { return nil } return self.controllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed, let visibleViewController = pageViewController.viewControllers?.first, let index = self.controllers.firstIndex(of: visibleViewController) { self.currentPage = index } } func presentationCount(for pageViewController: UIPageViewController) -> Int { return self.controllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return 0 } } } #if DEBUG struct PageViewController_Previews: PreviewProvider { static var previews: some View { PageViewController(controllers: [ ], currentPage: .constant(0)) } } #endif
32.453846
190
0.722683
6978be968d76233bdd5b745917b127d36fe56266
1,037
// // SelfSizingExampleViewController.swift // FittedSheets // // Created by Gordon Tucker on 2/1/19. // Copyright © 2019 Gordon Tucker. All rights reserved. // import UIKit import FittedSheetsPod class ResizingExampleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func resizeTo150(_ sender: Any) { self.sheetViewController?.resize(to: .fixed(150)) } @IBAction func resizeTo300(_ sender: Any) { self.sheetViewController?.resize(to: .fixed(300)) } @IBAction func resizeTo450(_ sender: Any) { self.sheetViewController?.resize(to: .fixed(450)) } @IBAction func resizeToMargin50(_ sender: Any) { self.sheetViewController?.resize(to: .marginFromTop(50)) } static func instantiate() -> ResizingExampleViewController { return UIStoryboard(name: "ResizingDemo", bundle: nil).instantiateViewController(withIdentifier: "resizing") as! ResizingExampleViewController } }
27.289474
150
0.683703
20b552cd32320ea8ff2f067398a00afaeb955ba4
12,527
// // AppDelegate.swift // TestBed-Swift // // Created by David Westgate on 8/29/16. // Copyright © 2016 Branch Metrics. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var waitingForBranch = false func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { initBranch(launchOptions) return true } // Respond to URL scheme links func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let branchHandled = Branch.getInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation ) if (!branchHandled) { // If not handled by Branch, do other deep link routing for the Facebook SDK, Pinterest SDK, etc } return true } // Respond to Universal Links func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { // pass the url to the handle deep link call return Branch.getInstance().continue(userActivity); //return true } var branchInitialized = false var openingFromBranchLink = false func consumeDeepLink(_ params: [AnyHashable: Any]) { guard !self.branchInitialized else { return } self.branchInitialized = true var feature:String? if let channel = params["~channel"] as? String { var sharingIncident = false if let intent = params["intent"] as? String, intent == "incident-share" { sharingIncident = true } let shouldProcessLink = channel == "spotlight" || sharingIncident if shouldProcessLink { if let incidentId = params["incidentId"] as? String, let username = params["username"] as? String, let uid = params["uid"] as? String { self.openingFromBranchLink = true // let sud = UserDefaults.standard // if sud.object(forKey: Constants.UserInfoKeys.InviterUserName) == nil { // sud.set(username, forKey: Constants.UserInfoKeys.InviterUserName) // sud.set(uid, forKey: Constants.UserInfoKeys.InviterUserId) // } feature = params["~feature"] == nil ? "spotlight" : params["~feature"] as! String // sud.set(feature, forKey: Constants.UserInfoKeys.BranchFeature) // sud.synchronize() // if SessionUser.instance.isAuthenticated() { // let userInfo:[AnyHashable : Any] = [ // "IncidentId":incidentId, // "inviterId":uid, // "feature":feature! // ] // let notification = Notification(name: Notification.Name(rawValue: Constants.Notifications.ShareOnboarding), object: nil, userInfo: userInfo) // OnBoardingContext.sharedInstance.inviterId = uid // NotificationCenter.default.post(notification) // } else { // self.waitingForBranch = false // OnBoardingContext.sharedInstance.phoneNumber = nil // OnBoardingContext.sharedInstance.invitationCode = nil // OnBoardingContext.sharedInstance.incidentId = incidentId // OnBoardingContext.sharedInstance.invitedBy = username // OnBoardingContext.sharedInstance.inviterId = uid // OnBoardingContext.sharedInstance.flow = .tease // // NotificationCenter.default.post(name: Notification.Name(rawValue: Constants.Notifications.BranchSignInFromSharing), object: nil) // } } } // if channel == "Testers" { // if let btts = params["beta-tester-class"] as? String, let btt = BetaTesterType(rawValue: btts) { // SessionUser.instance.shouldOverrideBetaStatusWithBranch = true // SessionUser.instance.betaTesterType = btt // } // if let bc = params["beta-tester-city"] as? String { // CityManager.instance.bypassLocation = true // CityManager.instance.currentCityCode = bc // } // // CityManager.instance.filterCities() // } // if let enableGeorestrictionsAsString = params["enableGeorestrictions"] as? String, channel == "disable-georestrictions" { // let enableGeorestrictions = enableGeorestrictionsAsString == "true" // if !SessionUser.instance.isAuthenticated() { // OnBoardingContext.sharedInstance.overrideGeorestrictions = !enableGeorestrictions // // if OnBoardingContext.sharedInstance.overrideGeorestrictions { // let mainWindow = self.window! // let masterController = mainWindow.rootViewController as! MasterController // if let onboardingViewController = masterController.presentedViewController as? OnBoardingViewController { // let viewControllers = onboardingViewController.viewControllers // if let launch = viewControllers.first as? OnBoardingLaunch { // let currentViewController = viewControllers.last! // if currentViewController is NotInAreaViewController { // launch.loadNextScreen() // } // } // } // } // } // } } if self.openingFromBranchLink { let isFirstTimeSession = params["+is_first_session"] as! Bool let clickedBranchLink = params["+clicked_branch_link"] as! Bool var attrs:[String:AnyObject] = [ "~channel":params["~channel"]! as AnyObject, "~feature":feature! as AnyObject, "+is_first_session":isFirstTimeSession as AnyObject, "+clicked_branch_link":clickedBranchLink as AnyObject, "Open from Deep Link": true as AnyObject, ] if let username = params["username"] as? String { attrs["Referring User"] = username as AnyObject } if let tags = params["~tags"] as? [String] { var ts = "" for t in tags { ts += t } attrs["~tags"] = ts as AnyObject } if let c = params["~campaign"] { attrs["~campaign"] = c as AnyObject } if let s = params["~stage"] { attrs["~stage"] = s as AnyObject } if let cs = params["~creation_source"] { attrs["~creation_source"] = cs as AnyObject } if let mg = params["+match_guaranteed"] { attrs["+match_guaranteed"] = mg as AnyObject } if let r = params["+referrer"] { attrs["+referrer"] = r as AnyObject } if let pn = params["+phone_number"] { attrs["+phone_number"] = pn as AnyObject } if let pn = params["+is_first_session"] { attrs["+is_first_session"] = pn as AnyObject } if let ct = params["+click_timestamp"] { attrs["+click_timestamp"] = ct as AnyObject } // if clickedBranchLink && isFirstTimeSession { // Analytics.trackInstalledFromBranchLink(attrs) // } else if clickedBranchLink { // Analytics.trackClickedBranchLink(attrs) // } // // Analytics.trackOpenApp(attrs) } else { self.waitingForBranch = false // let customAttributes:[String : AnyObject] = [ // "Open from Deep Link": false as AnyObject // ] // Analytics.trackOpenApp(customAttributes) } } func initBranch(_ launchOptions: [AnyHashable: Any]?) { self.waitingForBranch = true let defaultBranchKey = Bundle.main.object(forInfoDictionaryKey: "branch_key") as! String var branchKey = defaultBranchKey if let pendingBranchKey = DataStore.getPendingBranchKey() as String? { if pendingBranchKey != "" { branchKey = pendingBranchKey } DataStore.setActiveBranchKey(branchKey) } else { branchKey = defaultBranchKey DataStore.setActiveBranchKey(defaultBranchKey) } if let branch = Branch.getInstance(branchKey) { branch.setDebug(); if DataStore.getPendingSetDebugEnabled()! { branch.setDebug() DataStore.setActivePendingSetDebugEnabled(true) } else { DataStore.setActivePendingSetDebugEnabled(false) } branch.initSession(launchOptions: launchOptions, andRegisterDeepLinkHandler: { (params, error) in if (error == nil) { // Deeplinking logic for use when automaticallyDisplayDeepLinkController = false if let clickedBranchLink = params?[BRANCH_INIT_KEY_CLICKED_BRANCH_LINK] as! Bool? { if clickedBranchLink { // let nc = self.window!.rootViewController as! UINavigationController // let storyboard = UIStoryboard(name: "Main", bundle: nil) // let contentViewController = storyboard.instantiateViewController(withIdentifier: "Content") as! ContentViewController // nc.pushViewController(contentViewController, animated: true) // contentViewController.contentType = "Content" self.consumeDeepLink(params!) } } else { self.waitingForBranch = false print(String(format: "Branch TestBed: Finished init with params\n%@", (params?.description)!)) } } else { print("Branch TestBed: Initialization failed: " + error!.localizedDescription) } let notificationName = Notification.Name("BranchCallbackCompleted") NotificationCenter.default.post(name: notificationName, object: nil) }) } else { print("Branch TestBed: Invalid Key\n") DataStore.setActiveBranchKey("") DataStore.setPendingBranchKey("") } } func application(_ application: UIApplication, didReceiveRemoteNotification launchOptions: [AnyHashable: Any]) -> Void { Branch.getInstance().handlePushNotification(launchOptions) } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
42.754266
166
0.52766
283f3b7c18e04aefb0f6422fa5cdb37e374f3f3e
1,165
import UIKit public struct ViewStyle { let color: UIColor let cornerRadius: CGFloat? let shadow: ShadowStyle? let border: BorderStyle? public init(color: UIColor, cornerRadius: CGFloat? = nil, shadow: ShadowStyle? = nil, border: BorderStyle? = nil ) { self.color = color self.cornerRadius = cornerRadius self.shadow = shadow self.border = border } } public extension UIView { convenience init(style: ViewStyle) { self.init(frame: .zero) setup(with: style) } private func setup(with style: ViewStyle) { backgroundColor = style.color if let cornerRadius = style.cornerRadius { layer.cornerRadius = cornerRadius layer.masksToBounds = true } if let shadow = style.shadow { layer.shadowColor = shadow.color.cgColor layer.shadowRadius = shadow.radius layer.shadowOpacity = shadow.opacity } if let border = style.border { layer.borderColor = border.color.cgColor layer.borderWidth = border.width } } }
24.787234
52
0.593133
56e22084341ec853db2a83279bfd2f7ba505f62a
2,248
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @IBDesignable public class DesignableButton: SpringButton { @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable public var shadowColor: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColor.cgColor } } @IBInspectable public var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable public var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable public var shadowOffsetY: CGFloat = 0 { didSet { layer.shadowOffset.height = shadowOffsetY } } }
32.114286
81
0.677046
335c8ee11869d334110be59719ac0de33f824bce
602
// // UIGestureRecognizerExtensions.swift // // Created by Rok Gregorič // Copyright © 2018 Rok Gregorič. All rights reserved. // import UIKit extension UIGestureRecognizer { func cancel() { isEnabled = false isEnabled = true } } extension UIGestureRecognizer.State { var name: String { switch self { case .possible: return "possible" case .began: return "began" case .changed: return "changed" case .ended: return "ended" case .cancelled: return "cancelled" case .failed: return "failed" @unknown default: return "unknown" } } }
20.066667
55
0.654485
8ff6dbd658d58724d24522b05949f5c44bde2436
3,403
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-module -o %t %S/Inputs/accessibility_vtables_helper.swift // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -primary-file %s %S/Inputs/accessibility_vtables_other.swift -I %t -module-name accessibility_vtables | %FileCheck %s import accessibility_vtables_helper class Sub : Base { func internalMethod() {} override var prop: Int { get { return 42 } set {} } } // CHECK-LABEL: sil hidden @_TFC21accessibility_vtables3SubcfT_S0_ : $@convention(method) (@owned Sub) -> @owned Sub // CHECK: bb0(%0 : $Sub): // CHECK: function_ref @_TFs25_unimplementedInitializerFT9classNameVs12StaticString8initNameS_4fileS_4lineSu6columnSu_Os5Never // CHECK-LABEL: sil_vtable Sub { // CHECK-NEXT: #Base.internalMethod!1: {{.*}} : _TFC28accessibility_vtables_helper4Base14internalMethod // CHECK-NEXT: #Base.prop!getter.1: {{.*}} : _TFC21accessibility_vtables3Subg4propSi // accessibility_vtables.Sub.prop.getter : Swift.Int // CHECK-NEXT: #Base.prop!setter.1: {{.*}} : _TFC28accessibility_vtables_helper4Bases4propSi // accessibility_vtables_helper.Base.prop.setter : Swift.Int // CHECK-NEXT: #Base.prop!materializeForSet.1: {{.*}} : _TFC28accessibility_vtables_helper4Basem4propSi // accessibility_vtables_helper.Base.prop.materializeForSet : Swift.Int // CHECK-NEXT: #Base.init!initializer.1: {{.*}} : _TFC21accessibility_vtables3SubcfT_S0_ // accessibility_vtables.Sub.init () -> accessibility_vtables.Sub // CHECK-NEXT: #Sub.internalMethod!1: {{.*}} : _TFC21accessibility_vtables3Sub14internalMethod // CHECK-NEXT: #Sub.prop!setter.1: {{.*}} : _TFC21accessibility_vtables3Subs4propSi // accessibility_vtables.Sub.prop.setter : Swift.Int // CHECK-NEXT: #Sub.prop!materializeForSet.1: {{.*}} : _TFC21accessibility_vtables3Subm4propSi // accessibility_vtables.Sub.prop.materializeForSet : Swift.Int // CHECK-NEXT: #Sub.deinit // CHECK-NEXT: } class InternalSub : InternalBase { func method() {} override var prop: Int { get { return 42 } set {} } } // CHECK-LABEL: sil_vtable InternalSub { // CHECK-NEXT: #InternalBase.method!1: {{.*}} : _TFC21accessibility_vtables12InternalBaseP{{[0-9]+}}[[DISCRIMINATOR:_.+]]6method // CHECK-NEXT: #InternalBase.prop!getter.1: {{.*}} : _TFC21accessibility_vtables11InternalSubg4propSi // accessibility_vtables.InternalSub.prop.getter : Swift.Int // CHECK-NEXT: #InternalBase.prop!setter.1: {{.*}} : _TFC21accessibility_vtables12InternalBases4propSi // accessibility_vtables.InternalBase.prop.setter : Swift.Int // CHECK-NEXT: #InternalBase.prop!materializeForSet.1: {{.*}} : _TFC21accessibility_vtables12InternalBasem4propSi // accessibility_vtables.InternalBase.prop.materializeForSet : Swift.Int // CHECK-NEXT: #InternalBase.init!initializer.1: {{.*}} : _TFC21accessibility_vtables11InternalSubc // CHECK-NEXT: #InternalSub.method!1: {{.*}} : _TFC21accessibility_vtables11InternalSub6method // CHECK-NEXT: #InternalSub.prop!setter.1: {{.*}} : _TFC21accessibility_vtables11InternalSubs4propSi // accessibility_vtables.InternalSub.prop.setter : Swift.Int // CHECK-NEXT: #InternalSub.prop!materializeForSet.1: {{.*}} : _TFC21accessibility_vtables11InternalSubm4propSi // accessibility_vtables.InternalSub.prop.materializeForSet : Swift.Int // CHECK-NEXT: #InternalSub.deinit // CHECK-NEXT: }
66.72549
187
0.756098
1eaadfd66df3f0d77dd87b708037ab42e27ef2b6
2,486
/** * Copyright (c) 2017 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. * * 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 MasterViewController: UITableViewController { private let authorizeHealthKitSection = 2 private func authorizeHealthKit() { HealthKitSetupAssistant.authorizeHealthKit { (authorized, error) in guard authorized else { let baseMessage = "HealthKit Authorization Failed" if let error = error { print("\(baseMessage). Reason: \(error.localizedDescription)") } else { print(baseMessage) } return } print("HealthKit Successfully Authorized.") } } // MARK: - UITableView Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == authorizeHealthKitSection { authorizeHealthKit() } } }
36.028986
90
0.717216
9c208abb76c6e7299314b29b014ebdc29f13b448
1,645
// // PlaceCellDataModelTests.swift // DemoTestTests // // Created by Abhisek on 6/10/18. // Copyright © 2018 Abhisek. All rights reserved. // import XCTest @testable import DemoProject class PlaceCellDataModelTests: XCTestCase { var sut: AreaCellDataModel! var place: Area! override func setUp() { super.setUp() let attributes: [String : Any] = ["name": "Cafe De Latina", "vicinity": "Bengaluru", "rating": 4.8, "opening_hours": ["open_now": false]] place = Area(attributes: attributes) sut = AreaCellDataModel(area: place) } override func tearDown() { super.tearDown() sut = nil place = nil } func testAttributes() { // Attributes should not be nil. XCTAssertNotNil(sut.name, "Name is nil in PlaceCellDataModel") XCTAssertNotNil(sut.address, "Address is nil in PlaceCellDataModel") XCTAssertNotNil(sut.openStatusText, "OpenStatus is nil in PlaceCellDataModel") XCTAssertNotNil(sut.rating, "Rating is nil in PlaceCellDataModel") // Test if the attributes have the same desired value as they should have. XCTAssertEqual(sut.name, place.name) XCTAssertEqual(sut.address, place.address) XCTAssertEqual(sut.rating, place.rating?.description) guard let isOpen = place.openStatus else { XCTFail("OpenStatus is nil in PlaceCellDataModel") return } let openStatusText = isOpen ? "We are open. Hop in now!!" : "Sorry we are closed." XCTAssertEqual(sut.openStatusText, openStatusText) } }
32.254902
145
0.641337
62f4604a64bb3e129b1bb35d766a194ea8b8ceec
589
// // alertViewX.swift // alertViewX // // Created by Mohammed Altoobi on 4/15/18. // Copyright © 2018 Mohammed Altoobi. All rights reserved. // import UIKit extension UIViewController{ func alertXMessage(title: String, message: String, `on` controller: UIViewController) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) controller.present(alert, animated: true, completion: nil) } }
29.45
115
0.713073
f9b4ef95f08de89249ad2616f5454a148e682088
5,788
/* MIT License Copyright (c) 2019 Thales DIS 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. IMPORTANT: This source code is intended to serve training information purposes only. Please make sure to review our IdCloud documentation, including security guidelines. */ import UIKit import CoreLocation // RiskEngine backend URL let riskEngineURL = "// PLACEHOLDER: Server URL" class ViewController: UIViewController { var locationManager: CLLocationManager? = nil @IBOutlet weak var labelSDKVersion: UILabel! @IBOutlet weak var labelStatus: UILabel! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // Ask for location permissions. self.getUserAccessPermissionToUseLocationService() // Setup core config, set other optional params, if required let coreConfig = GAHCoreConfig.sharedConfiguration(withUrl: riskEngineURL)! // Gemalto Signal collection is mandatory. let signalConfig = GAHGemaltoSignalConfig.sharedConfiguration()! // Pass configuration to core. GAHCore.initialize([coreConfig, signalConfig]) // Start Signal prefetch GAHCore.startPrefetchSignals() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Display SDK version information. let sdkInfo = GAHCore.getSDKVersionInfo() let formattedVersion = String.init(format: "%@\n%@\n%@\n%@", sdkInfo!.getName(), sdkInfo!.getVersion(), sdkInfo!.getBuild(), sdkInfo!.isDebugMode() ? "Debug" : "Release") self.labelSDKVersion.text = formattedVersion self.labelStatus.text = nil } deinit { // It is recommended to call this method during a transaction screen exit // where startPrefetchSignals() was called previously. GAHCore.stopPrefetchSignals() } // MARK: - Private Helpers /* This triggers the popup to give permission to access location while using the app Location is one of the signal category which is collected and used for risk calcualation */ func getUserAccessPermissionToUseLocationService() { self.locationManager = CLLocationManager.init() self.locationManager!.delegate = self self.locationManager!.requestWhenInUseAuthorization() } private func processPrefetchStatusResponse(_ statusCode: Int, _ statusMsg: String?) { // Log return value status. print("Request prefetch finished with status code: \(statusCode) and message: \(statusMsg ?? "<No Message>")") // Make sure that we have all signals prefetched. if (statusCode == PREFETCH_STATUS_OK) { // With all signals in place. Request Visit ID. GAHCore.requestVisitID({ (visitId: String?) in self.processVisitIDResponse(true, visitId) }) { (errorCode: Int, errorMessage: String?) in self.processVisitIDResponse(false, errorMessage) } } } private func processVisitIDResponse(_ success: Bool, _ value: String?) { // ClearTransactionResources needs to be triggered from ui thread if BehavioSec is used. // In this Lab we want to simple display some visual result, so UI thread is also handy. DispatchQueue.main.sync { // Display result on screen. self.labelStatus.setTextAnimated(value) if (success) { // Do something with Visit ID. // ... // ... } // Clear transaction resources GAHCore.clearTransactionResources() } } // MARK: - User Interface @IBAction func onButtonPressedSampleAction(_ sender: UIButton) { // Show direct response to UI. // Full application will have some sort of dialog fragment / loading indicator. self.labelStatus.setTextAnimated("Processing...") // Listen to prefetch status GAHCore.requestPrefetchStatus { (statusCode: Int, statusMessage: String?) in self.processPrefetchStatusResponse(statusCode, statusMessage) } } } // MARK: - CLLocationManagerDelegate extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { // Handle permission status change. // This method must be implemented (can be empty) in order to get system permission dialog. } }
39.917241
118
0.659295
26ef4dcdd9d5725b94691926de2c38ae69705025
1,009
// // Message.swift // ScaledroneChatTest // // Created by Marin Benčević on 08/09/2018. // Copyright © 2018 Scaledrone. All rights reserved. // import Foundation import UIKit import MessageKit struct Message { let member: Member let text: String let messageId: String } extension Message: MessageType { var sender: Sender { return Sender(id: member.name, displayName: member.name) } var sentDate: Date { return Date() } var kind: MessageKind { return .text(text) } } struct Member { let name: String let color: UIColor } extension Member { var toJSON: Any { return [ "name": name, "color": color.hexString ] } init?(fromJSON json: Any) { guard let data = json as? [String: Any], let name = data["name"] as? String, let hexColor = data["color"] as? String else { print("Couldn't parse Member") return nil } self.name = name self.color = UIColor(hex: hexColor) } }
16.274194
60
0.61447
de5f8d37a6444ae7bc0338247c53b976aad186ba
32,605
import MXLCalendarManagerSwift import XCTest final class MXLCalendarManagerTests: XCTestCase { private let manager = MXLCalendarManager() private var parsedCalendar: MXLCalendar! private let dateFormatter = DateFormatter() override func setUp() { super.setUp() dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") } func parseCalendarWithEvent(eventString: String) { let calendarString = """ BEGIN:VCALENDAR PRODID:-//Google Inc//Google Calendar 70.9054//EN VERSION:2.0 CALSCALE:GREGORIAN METHOD:PUBLISH X-WR-CALNAME:[email protected] X-WR-TIMEZONE:Atlantic/Reykjavik BEGIN:VTIMEZONE TZID:America/Los_Angeles X-LIC-LOCATION:America/Los_Angeles BEGIN:DAYLIGHT TZOFFSETFROM:-0800 TZOFFSETTO:-0700 TZNAME:PDT DTSTART:19700308T020000 RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU END:DAYLIGHT BEGIN:STANDARD TZOFFSETFROM:-0700 TZOFFSETTO:-0800 TZNAME:PST DTSTART:19701101T020000 RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU END:STANDARD END:VTIMEZONE BEGIN:VTIMEZONE TZID:Atlantic/Reykjavik X-LIC-LOCATION:Atlantic/Reykjavik BEGIN:STANDARD TZOFFSETFROM:+0000 TZOFFSETTO:+0000 TZNAME:GMT DTSTART:19700101T000000 END:STANDARD END:VTIMEZONE """ + eventString + """ END:VCALENDAR """ manager.parse(icsString: calendarString) { (calendar: MXLCalendar?, error: Error?) in XCTAssertNil(error) XCTAssert(calendar?.events.count ?? 0 > 0) self.parsedCalendar = calendar } } // MARK: - Daily Tests func testSingleOccurrence() { let eventString = """ BEGIN:VEVENT DTSTART:20181213T150000Z DTEND:20181213T160000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T163823Z DESCRIPTION: LAST-MODIFIED:20190619T163823Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Single occurrence test TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2018-12-13 15:11:52", begin: "2018-12-13 15:00:01", end: "2018-12-13 16:00:00", after: "2018-12-13 16:00:01") testHelper(trueOccurrences: [firstOccurrence], falseOccurrences: []) } func testOnceDailyNoEndTest() { let eventString = """ BEGIN:VEVENT DTSTART:20190617T010000Z DTEND:20190617T020000Z RRULE:FREQ=DAILY DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T002440Z DESCRIPTION: LAST-MODIFIED:20190619T002440Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Every Day Event TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let occurrence = createDatePack(middle: "2020-06-17 01:11:52", begin: "2020-06-17 01:00:01", end: "2020-06-17 02:00:00", after: "2020-06-17 02:00:01") let nextOccurrence = createDatePack(middle: "2020-06-18 01:11:52", begin: "2020-06-18 01:00:01", end: "2020-06-18 02:00:00", after: "2020-06-18 02:00:01") testHelper(trueOccurrences: [occurrence, nextOccurrence], falseOccurrences: []) } func testAllDayOnce() { let eventString = """ BEGIN:VEVENT DTSTART;VALUE=DATE:20190406 DTEND;VALUE=DATE:20190407 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T012159Z DESCRIPTION: LAST-MODIFIED:20190619T031600Z LOCATION: SEQUENCE:1 STATUS:CONFIRMED SUMMARY:All Day Event TRANSP:TRANSPARENT END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let occurrence = createDatePack(middle: "2019-04-06 00:11:52", begin: "2019-04-06 00:00:01", end: "2019-04-07 00:00:00", after: "2019-04-07 00:00:01") testHelper(trueOccurrences: [occurrence], falseOccurrences: []) } func testSpanDayOnce() { let eventString = """ BEGIN:VEVENT DTSTART:20190401T000000Z DTEND:20190402T120000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T003248Z DESCRIPTION: LAST-MODIFIED:20190619T003248Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Multi Day Event TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let occurrence = createDatePack(middle: "2019-04-01 00:11:52", begin: "2019-04-01 00:00:01", end: "2019-04-02 12:00:00", after: "2019-04-02 12:00:01") testHelper(trueOccurrences: [occurrence], falseOccurrences: []) } func testEveryOtherDayNoEnd() { let eventString = """ BEGIN:VEVENT DTSTART;TZID=America/Los_Angeles:20190618T100000 DTEND;TZID=America/Los_Angeles:20190618T110000 RRULE:FREQ=DAILY;INTERVAL=2 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190617T160100Z DESCRIPTION: LAST-MODIFIED:20190617T160100Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Every Other Day Event TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let occurrence = createDatePack(middle: "2019-06-18 17:11:52", begin: "2019-06-18 17:00:01", end: "2019-06-18 18:00:00", after: "2019-06-18 18:00:01") let occurrence2 = createDatePack(middle: "2019-06-24 17:11:52", begin: "2019-06-24 17:00:01", end: "2019-06-24 18:00:00", after: "2019-06-24 18:00:01") let nonOccurrence = createDatePack(middle: "2019-06-19 17:11:52", begin: "2019-06-19 17:00:01", end: "2019-06-19 18:00:00", after: "2019-06-19 18:00:01") testHelper(trueOccurrences: [occurrence, occurrence2], falseOccurrences: [nonOccurrence]) } func testDailyThatFallsOffAfterDate() { let eventString = """ BEGIN:VEVENT DTSTART:20190303T060000Z DTEND:20190303T070000Z RRULE:FREQ=DAILY;UNTIL=20190310 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T012607Z DESCRIPTION: LAST-MODIFIED:20190619T012710Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Daily that falls off after a date TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-03-03 06:11:52", begin: "2019-03-03 06:00:01", end: "2019-03-03 07:00:00", after: "2019-03-03 07:00:01") let lastOccurrence = createDatePack(middle: "2019-03-09 06:11:52", begin: "2019-03-09 06:00:01", end: "2019-03-09 07:00:00", after: "2019-03-09 07:00:01") let afterLastOccurrence = createDatePack(middle: "2019-03-10 06:11:52", begin: "2019-03-10 06:00:01", end: "2019-03-10 07:00:00", after: "2019-03-10 07:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testDailyThatFallsOffAfterThreeOccurrences() { let eventString = """ BEGIN:VEVENT DTSTART:20190318T180000Z DTEND:20190318T190000Z RRULE:FREQ=DAILY;COUNT=3 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T013032Z DESCRIPTION: LAST-MODIFIED:20190619T013102Z LOCATION: SEQUENCE:1 STATUS:CONFIRMED SUMMARY:Daily Event That falls off after 3 times TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-03-18 18:11:52", begin: "2019-03-18 18:00:00", end: "2019-03-18 19:00:00", after: "2019-03-18 19:00:01") let lastOccurrence = createDatePack(middle: "2019-03-20 18:11:52", begin: "2019-03-20 18:00:00", end: "2019-03-20 19:00:00", after: "2019-03-20 19:00:01") let afterLastOccurrence = createDatePack(middle: "2019-03-21 18:11:52", begin: "2019-03-21 18:00:00", end: "2019-03-21 19:00:00", after: "2019-03-21 19:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testDailySpanWithABreak() { let eventString = """ BEGIN:VEVENT DTSTART:20180708T150000Z DTEND:20180708T160000Z RRULE:FREQ=DAILY;UNTIL=20180807 EXDATE:20180712T150000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T165437Z DESCRIPTION: LAST-MODIFIED:20190619T165437Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Daily Span With Break TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2018-07-08 15:11:52", begin: "2018-07-08 15:00:52", end: "2018-07-08 15:59:59", after: "2018-07-08 16:00:01") let lastOccurrence = createDatePack(middle: "2018-08-06 15:11:52", begin: "2018-08-06 15:00:52", end: "2018-08-06 15:59:59", after: "2018-08-06 16:00:01") let breakOccurrence = createDatePack(middle: "2018-07-12 15:11:52", begin: "2018-07-12 15:00:52", end: "2018-07-12 15:59:59", after: "2018-07-12 16:00:01") let afterLastOccurrence = createDatePack(middle: "2018-08-07 15:11:52", begin: "2018-08-07 15:00:52", end: "2018-08-07 15:59:59", after: "2018-08-07 16:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [breakOccurrence, afterLastOccurrence]) } // MARK: - Week Tests func testOnceWeeklyNoEnd() { let eventString = """ BEGIN:VEVENT DTSTART;TZID=America/Los_Angeles:20190617T080000 DTEND;TZID=America/Los_Angeles:20190617T090000 RRULE:FREQ=WEEKLY;BYDAY=MO DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190617T142703Z DESCRIPTION: LAST-MODIFIED:20190617T142703Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Morning Monday 8PST recurrance TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-06-17 15:11:52", begin: "2019-06-17 15:00:01", end: "2019-06-17 16:00:00", after: "2019-06-17 16:00:01") let nextOccurrence = createDatePack(middle: "2019-06-24 15:11:52", begin: "2019-06-24 15:00:01", end: "2019-06-24 16:00:00", after: "2019-04-05 16:00:01") testHelper(trueOccurrences: [firstOccurrence, nextOccurrence], falseOccurrences: []) } func testOnceWeeklySpans2Days() { let eventString = """ BEGIN:VEVENT DTSTART:20190322T230000Z DTEND:20190323T010000Z RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=FR DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T021140Z DESCRIPTION: LAST-MODIFIED:20190619T021140Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Weekly Event That spans 2 days TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-03-22 23:11:52", begin: "2019-03-22 23:00:00", end: "2019-03-23 01:00:00", after: "2019-03-23 01:00:01") let lastOccurrence = createDatePack(middle: "2019-04-05 23:11:52", begin: "2019-04-05 23:00:00", end: "2019-04-06 01:00:00", after: "2019-04-06 01:00:01") let afterLastOccurrence = createDatePack(middle: "2019-04-12 23:11:52", begin: "2019-04-12 23:00:00", end: "2019-04-13 01:00:00", after: "2019-04-13 01:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testOnceWeeklyThatFallsOffAfterThreeOccurances() { let eventString = """ BEGIN:VEVENT DTSTART:20190322T150000Z DTEND:20190322T160000Z RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=FR DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T021140Z DESCRIPTION: LAST-MODIFIED:20190619T021140Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Weekly Event That Falls Off after 3 times TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-03-22 15:11:52", begin: "2019-03-22 15:00:00", end: "2019-03-22 16:00:00", after: "2019-03-22 16:00:01") let lastOccurrence = createDatePack(middle: "2019-04-05 15:11:52", begin: "2019-04-05 15:00:00", end: "2019-04-05 16:00:00", after: "2019-04-05 16:00:01") let afterLastOccurrence = createDatePack(middle: "2019-04-12 15:11:52", begin: "2019-04-12 15:00:00", end: "2019-04-12 16:00:00", after: "2019-04-12 16:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testOnceWeeklyThatFallsOffAfterDate() { let eventString = """ BEGIN:VEVENT DTSTART:20190322T120000Z DTEND:20190322T130000Z RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20190330;BYDAY=FR DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T021304Z DESCRIPTION: LAST-MODIFIED:20190619T021304Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Weekly Event that falls off after a date TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-03-22 12:11:52", begin: "2019-03-22 12:00:01", end: "2019-03-22 13:00:00", after: "2019-03-22 13:00:01") let nextOccurrence = createDatePack(middle: "2019-03-29 12:11:52", begin: "2019-03-29 12:00:01", end: "2019-03-29 13:00:00", after: "2019-03-29 13:00:01") let afterLastOccurrence = createDatePack(middle: "2019-04-05 12:11:52", begin: "2019-04-05 12:00:01", end: "2019-04-05 13:00:00", after: "2019-04-05 13:00:01") let afterLastOccurrence2 = createDatePack(middle: "2019-04-12 12:11:52", begin: "2019-04-12 12:00:01", end: "2019-04-12 13:00:00", after: "2019-04-12 13:00:01") testHelper(trueOccurrences: [firstOccurrence, nextOccurrence], falseOccurrences: [afterLastOccurrence, afterLastOccurrence2]) } func testWeeklySpanWithABreak() { let eventString = """ BEGIN:VEVENT DTSTART:20170708T150000Z DTEND:20170708T160000Z RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20170909;BYDAY=SA EXDATE:20170722T150000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T171652Z DESCRIPTION: LAST-MODIFIED:20190619T171652Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Weekly Event With Break TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2017-07-08 15:11:52", begin: "2017-07-08 15:00:52", end: "2017-07-08 15:59:59", after: "2017-07-08 16:00:01") let lastOccurrence = createDatePack(middle: "2017-09-02 15:11:52", begin: "2017-09-02 15:00:01", end: "2017-09-02 15:59:59", after: "2017-09-02 16:00:01") let breakOccurrence = createDatePack(middle: "2017-07-22 15:11:52", begin: "2017-07-22 15:00:00", end: "2017-07-22 15:59:59", after: "2017-07-22 16:00:01") let afterLastOccurrence = createDatePack(middle: "2017-09-15 15:11:52", begin: "2017-09-15 15:00:00", end: "2017-09-15 15:59:59", after: "2017-09-15 16:01:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [breakOccurrence, afterLastOccurrence]) } // MARK - Month Tests func testOnceMonthlyNoEnd() { let eventString = """ BEGIN:VEVENT DTSTART;TZID=America/Los_Angeles:20190619T210000 DTEND;TZID=America/Los_Angeles:20190620T080000 RRULE:FREQ=MONTHLY;BYMONTHDAY=19 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190617T161604Z DESCRIPTION: LAST-MODIFIED:20190617T161604Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Span days Monthly TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-06-20 4:11:52", begin: "2019-06-20 4:00:01", end: "2019-06-20 15:00:00", after: "2019-06-20 15:00:01") let nextOccurrence = createDatePack(middle: "2019-07-20 4:11:52", begin: "2019-07-20 4:00:01", end: "2019-07-20 15:00:00", after: "2019-07-20 15:00:01") testHelper(trueOccurrences: [firstOccurrence, nextOccurrence], falseOccurrences: []) } func testOnceMonthlyFallsOffAfterThreeTimes() { let eventString = """ BEGIN:VEVENT DTSTART:20190103T010000Z DTEND:20190103T020000Z RRULE:FREQ=MONTHLY;COUNT=3;BYMONTHDAY=3 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T022740Z DESCRIPTION: LAST-MODIFIED:20190619T022740Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Monthly Event Falls Off After 3 Times TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-01-03 01:11:52", begin: "2019-01-03 01:00:52", end: "2019-01-03 02:00:00", after: "2019-01-03 02:00:01") let nextOccurrence = createDatePack(middle: "2019-02-03 01:11:52", begin: "2019-02-03 01:00:01", end: "2019-02-03 02:00:00", after: "2019-02-03 02:00:01") let lastOccurrence = createDatePack(middle: "2019-03-03 01:11:52", begin: "2019-03-03 01:00:01", end: "2019-03-03 02:00:00", after: "2019-03-03 02:00:01") let afterLastOccurrence = createDatePack(middle: "2019-04-03 01:11:52", begin: "2019-04-03 01:00:01", end: "2019-03-04 02:00:00", after: "2019-04-03 02:00:01") testHelper(trueOccurrences: [firstOccurrence, nextOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testOnceMonthlyFallsOffAfterDate() { let eventString = """ BEGIN:VEVENT DTSTART:20190103T150000Z DTEND:20190103T160000Z RRULE:FREQ=MONTHLY;COUNT=3;BYMONTHDAY=3 EXDATE:20190303T150000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T024539Z DESCRIPTION: LAST-MODIFIED:20190619T024617Z LOCATION: SEQUENCE:1 STATUS:CONFIRMED SUMMARY:Montly Event Falls Off After Feb 4 TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-01-03 15:11:52", begin: "2019-01-03 15:00:01", end: "2019-01-03 16:00:00", after: "2019-01-03 16:00:01") let lastOccurrence = createDatePack(middle: "2019-02-03 15:11:52", begin: "2019-02-03 15:00:01", end: "2019-02-03 16:00:00", after: "2019-02-03 16:00:01") let afterLastOccurrence = createDatePack(middle: "2019-03-03 15:11:52", begin: "2019-03-03 15:00:01", end: "2019-03-03 16:00:00", after: "2019-03-03 16:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testMonthlySpanWithBreak() { let eventString = """ BEGIN:VEVENT DTSTART:20170108T160000Z DTEND:20170108T170000Z RRULE:FREQ=MONTHLY;COUNT=5;BYMONTHDAY=8 EXDATE:20170408T160000Z DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T172058Z DESCRIPTION: LAST-MODIFIED:20190619T172058Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Monthly Span With Break TRANSP:OPAQUE END:VEVENT END:VCALENDAR """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2017-01-08 16:11:52", begin: "2017-01-08 16:00:00", end: "2017-01-08 16:59:59", after: "2017-01-08 17:00:01") let lastOccurrence = createDatePack(middle: "2017-05-08 16:11:52", begin: "2017-05-08 16:00:00", end: "2017-05-08 16:59:59", after: "2017-06-08 16:00:01") let breakOccurrence = createDatePack(middle: "2017-04-08 16:11:52", begin: "2017-04-08 16:00:00", end: "2017-04-08 16:59:59", after: "2017-04-08 17:00:01") let afterLastOccurrence = createDatePack(middle: "2017-06-08 16:11:52", begin: "2017-06-08 16:00:00", end: "2017-06-08 16:59:59", after: "2017-06-08 17:01:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [breakOccurrence, afterLastOccurrence]) } // MARK - Year Tests func testOnceYearlyNoEnd() { let eventString = """ BEGIN:VEVENT DTSTART;TZID=America/Los_Angeles:20191225T120000 DTEND;TZID=America/Los_Angeles:20191225T130000 RRULE:FREQ=YEARLY DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190617T161221Z DESCRIPTION: LAST-MODIFIED:20190619T003936Z LOCATION: SEQUENCE:2 STATUS:CONFIRMED SUMMARY:Christmas event TRANSP:TRANSPARENT BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:This is an event reminder TRIGGER:-P0DT0H30M0S END:VALARM END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let occurrence = createDatePack(middle: "2021-12-25 20:11:52", begin: "2021-12-25 20:00:01", end: "2021-12-25 21:00:00", after: "2021-12-25 21:00:01") let occurrence2 = createDatePack(middle: "2022-12-25 20:11:52", begin: "2022-12-25 20:00:01", end: "2022-12-25 21:00:00", after: "2022-12-25 21:00:01") let farFuture = createDatePack(middle: "3022-12-25 20:11:52", begin: "3022-12-25 20:00:01", end: "3022-12-25 21:00:00", after: "3022-12-25 21:00:01") testHelper(trueOccurrences: [occurrence, occurrence2, farFuture], falseOccurrences: []) } func testOnceYearlyFallsOffAfter2Times() { let eventString = """ BEGIN:VEVENT DTSTART:20191224T200000Z DTEND:20191224T210000Z RRULE:FREQ=YEARLY;WKST=SU;COUNT=2 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T030415Z DESCRIPTION: LAST-MODIFIED:20190619T030415Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Christmas eve event drops off after 2 times TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-12-24 20:11:52", begin: "2019-12-24 20:00:00", end: "2019-12-24 21:00:00", after: "2019-12-24 21:00:01") let lastOccurrence = createDatePack(middle: "2020-12-24 20:11:52", begin: "2020-12-24 20:00:00", end: "2020-12-24 21:00:00", after: "2020-12-24 21:00:01") let afterLastOccurrence = createDatePack(middle: "2021-12-24 20:11:52", begin: "2021-12-24 20:00:00", end: "2021-12-24 21:00:00", after: "2021-12-24 21:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } func testOnceYearlyFallsOffAfterDate() { let eventString = """ BEGIN:VEVENT DTSTART:20191223T200000Z DTEND:20191223T210000Z RRULE:FREQ=YEARLY;UNTIL=20201224 DTSTAMP:20190619T173900Z UID:[email protected] CREATED:20190619T030651Z DESCRIPTION: LAST-MODIFIED:20190619T030651Z LOCATION: SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Two days before chrismas drops off after 2020 TRANSP:OPAQUE END:VEVENT """ parseCalendarWithEvent(eventString: eventString) let firstOccurrence = createDatePack(middle: "2019-12-23 20:11:52", begin: "2019-12-23 20:00:01", end: "2019-12-23 21:00:00", after: "2019-12-23 21:00:01") let lastOccurrence = createDatePack(middle: "2020-12-23 20:11:52", begin: "2020-12-23 20:00:01", end: "2020-12-23 21:00:00", after: "2020-12-23 21:00:01") let afterLastOccurrence = createDatePack(middle: "2021-12-23 20:11:52", begin: "2021-12-23 20:00:01", end: "2021-12-23 21:00:00", after: "2021-12-23 21:00:01") testHelper(trueOccurrences: [firstOccurrence, lastOccurrence], falseOccurrences: [afterLastOccurrence]) } // MARK - Helpers struct DatePack { let middle: Date! let begin: Date! let end: Date! let after: Date! } func createDatePack(middle: String, begin: String, end: String, after: String) -> DatePack { return DatePack(middle: dateFormatter.date(from: middle), begin: dateFormatter.date(from: begin), end: dateFormatter.date(from: end), after: dateFormatter.date(from: after)) } private func testHelper(trueOccurrences: [DatePack], falseOccurrences: [DatePack]) { for occurrence in trueOccurrences { // Test middle XCTAssert(parsedCalendar.containsEvent(at: occurrence.middle), String(describing: occurrence.middle)) // Test boundaries XCTAssert(parsedCalendar.containsEvent(at: occurrence.begin), String(describing: occurrence.begin)) XCTAssert(parsedCalendar.containsEvent(at: occurrence.end), String(describing: occurrence.end)) XCTAssertFalse(parsedCalendar.containsEvent(at: occurrence.after), String(describing: occurrence.after)) } for occurrence in falseOccurrences { XCTAssertFalse(parsedCalendar.containsEvent(at: occurrence.middle), String(describing: occurrence.middle)) XCTAssertFalse(parsedCalendar.containsEvent(at: occurrence.begin), String(describing: occurrence.begin)) XCTAssertFalse(parsedCalendar.containsEvent(at: occurrence.end), String(describing: occurrence.end)) XCTAssertFalse(parsedCalendar.containsEvent(at: occurrence.after), String(describing: occurrence.after)) } } }
39.908201
118
0.545867
2f734ee11f18863cff583bfee02bb62ac1992916
446
// // ChartAxisValuesGeneratorYFixedNonOverlapping.swift // SwiftCharts // // Created by ischuetz on 21/07/16. // Copyright © 2016 ivanschuetz. All rights reserved. // import UIKit open class ChartAxisValuesGeneratorYFixedNonOverlapping: ChartAxisValuesGeneratorFixedNonOverlapping { public init(axisValues: [ChartAxisValue], spacing: CGFloat = 4) { super.init(axisValues: axisValues, spacing: spacing, isX: false) } }
26.235294
102
0.746637
1a61f562f597462a8fa8953d9c78799bb48ac2d3
891
// // PhysicsComponent.swift // Book_Sources // // Created by Mateus Rodrigues on 19/03/19. // import SpriteKit import GameplayKit public class PhysicsComponent: GKComponent { var body: SKPhysicsBody init(for node: SKNode) { self.body = SKPhysicsBody(circleOfRadius: node.frame.width/2) self.body.categoryBitMask = CategoryMask.human.rawValue self.body.contactTestBitMask = CategoryMask.zombie.rawValue self.body.collisionBitMask = ~CategoryMask.zombie.rawValue self.body.affectedByGravity = false super.init() } public override func didAddToEntity() { if let node = entity?.component(ofType: SpriteComponent.self)?.node { node.physicsBody = body } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
25.457143
77
0.65881
915f8aa2cae2256ff5c60a064514105052a096e1
740
// // DataManager.swift // MVVMCombine // // Created by Van Le H. on 5/22/21. // Copyright © 2021 Monstar Lab VietNam Co., Ltd. All rights reserved. // import Foundation final class DataManager { enum FileExtension: String { case json case png case propertyList = "plist" case text = "txt" } static func getItemList<T: Decodable>(fileName: String, fileExtension: FileExtension) -> [T] { guard let url = Bundle.main.url(forResource: fileName, withExtension: fileExtension.rawValue), let data = try? Data(contentsOf: url), let itemList = try? PropertyListDecoder().decode([T].self, from: data) else { return [] } return itemList } }
26.428571
102
0.621622
39ac8c1310129e9411bb6c80b53c9949169e94d4
996
// // Example_OSXTests.swift // Example-OSXTests // // Created by Jesse Curry on 10/20/15. // Copyright © 2015 Bout Fitness, LLC. All rights reserved. // import XCTest @testable import Example_OSX class Example_OSXTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.918919
111
0.638554
0ad708ac35898b80c8c5f522fd680a8c4f4f26a6
414
// // JSON.swift // Tyro // // Created by Matthew Purland on 11/16/15. // Copyright © 2015 TypeLift. All rights reserved. // import Foundation import Swiftz public protocol FromJSON { associatedtype T = Self static func fromJSON(_ value : JSONValue) -> Either<JSONError, T> } public protocol ToJSON { associatedtype T = Self static func toJSON(_ value : T) -> Either<JSONError, JSONValue> }
19.714286
69
0.690821
3a063ba0530c9dbfb5cd9cebd92054b546e444fb
1,008
// // TweetsViewController.swift // Twitter // // Created by Senyang Zhuang on 2/17/16. // Copyright © 2016 codepath. All rights reserved. // import UIKit class TweetsViewController: 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. } @IBAction func onLogout(sender: AnyObject) { //Clear and fire the notification User.currentUser?.logout() } /* // 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. } */ }
25.2
106
0.670635
8a428714d5921a3718bd8b4a5a222bc7161e8516
351
// // NotificationView.swift // Pomodoro WatchKit Extension // // Created by Kamaal M Farah on 05/12/2021. // import SwiftUI struct NotificationView: View { var body: some View { Text("Hello, World!") } } struct NotificationView_Previews: PreviewProvider { static var previews: some View { NotificationView() } }
16.714286
51
0.660969
14a0f5fc3ee512fc9aed9cd0af030a30ff11072f
7,926
// // Copyright (c) SRG SSR. All rights reserved. // // License information is available from the LICENSE file. // import SwiftUI // MARK: View /// Behavior: h-hug, v-hug struct ShowHeaderView: View { @Binding private(set) var show: SRGShow @StateObject private var model = ShowHeaderViewModel() fileprivate static let verticalSpacing: CGFloat = constant(iOS: 18, tvOS: 24) init(show: SRGShow) { _show = .constant(show) } var body: some View { MainView(model: model) .onAppear { model.show = show } .onChange(of: show) { newValue in model.show = newValue } } /// Behavior: h-hug, v-hug. fileprivate struct MainView: View { @ObservedObject var model: ShowHeaderViewModel #if os(iOS) @Environment(\.horizontalSizeClass) var horizontalSizeClass #endif var uiHorizontalSizeClass: UIUserInterfaceSizeClass { #if os(iOS) return UIUserInterfaceSizeClass(horizontalSizeClass) #else return .regular #endif } private var direction: StackDirection { #if os(iOS) return (horizontalSizeClass == .compact) ? .vertical : .horizontal #else return .horizontal #endif } private var alignment: StackAlignment { #if os(iOS) return (horizontalSizeClass == .compact) ? .center : .leading #else return .leading #endif } var body: some View { Stack(direction: direction, alignment: alignment, spacing: 0) { ImageView(url: model.imageUrl) .aspectRatio(16 / 9, contentMode: .fit) .background(Color.white.opacity(0.1)) .overlay(ImageOverlay(uiHorizontalSizeClass: uiHorizontalSizeClass)) .adaptiveMainFrame(for: uiHorizontalSizeClass) .layoutPriority(1) DescriptionView(model: model) .padding(.horizontal, constant(iOS: 16, tvOS: 80)) .padding(.vertical) .frame(maxWidth: .infinity) } .padding(.bottom, constant(iOS: 20, tvOS: 50)) .focusable() } } /// Behavior: h-exp, v-exp private struct ImageOverlay: View { let uiHorizontalSizeClass: UIUserInterfaceSizeClass var body: some View { if uiHorizontalSizeClass == .regular { LinearGradient(gradient: Gradient(colors: [.clear, .srgGray16]), startPoint: .center, endPoint: .trailing) } } } /// Behavior: h-hug, v-hug private struct DescriptionView: View { @ObservedObject var model: ShowHeaderViewModel var body: some View { VStack(spacing: ShowHeaderView.verticalSpacing) { if let broadcastInformation = model.broadcastInformation { Badge(text: broadcastInformation, color: Color(.play_green)) } Text(model.title ?? "") .srgFont(.H2) .lineLimit(2) // Fix sizing issue, see https://swiftui-lab.com/bug-linelimit-ignored/. The size is correct // when calculated with a `UIHostingController`, but without this the text does not occupy // all lines it could. .fixedSize(horizontal: false, vertical: true) .multilineTextAlignment(.center) .foregroundColor(.srgGrayC7) if let lead = model.lead { Text(lead) .srgFont(.body) .lineLimit(6) // See above .fixedSize(horizontal: false, vertical: true) .multilineTextAlignment(.center) .foregroundColor(.srgGray96) } HStack(spacing: 20) { SimpleButton(icon: model.favoriteIcon, label: model.favoriteLabel, accessibilityLabel: model.favoriteAccessibilityLabel, action: favoriteAction) #if os(iOS) if model.isFavorite { SimpleButton(icon: model.subscriptionIcon, label: model.subscriptionLabel, accessibilityLabel: model.subscriptionAccessibilityLabel, action: subscriptionAction) } #endif } .alert(isPresented: $model.isFavoriteRemovalAlertDisplayed, content: favoriteRemovalAlert) } } private func favoriteAction() { if model.shouldDisplayFavoriteRemovalAlert { model.isFavoriteRemovalAlertDisplayed = true } else { model.toggleFavorite() } } private func favoriteRemovalAlert() -> Alert { let primaryButton = Alert.Button.cancel(Text(NSLocalizedString("Cancel", comment: "Title of a cancel button"))) {} let secondaryButton = Alert.Button.destructive(Text(NSLocalizedString("Delete", comment: "Title of a delete button"))) { model.toggleFavorite() } return Alert(title: Text(NSLocalizedString("Delete from favorites", comment: "Title of the confirmation pop-up displayed when the user is about to delete a favorite")), message: Text(NSLocalizedString("The favorite and notification subscription will be deleted on all devices connected to your account.", comment: "Confirmation message displayed when a logged in user is about to delete a favorite")), primaryButton: primaryButton, secondaryButton: secondaryButton) } #if os(iOS) private func subscriptionAction() { model.toggleSubscription() } #endif } } // MARK: Helpers private extension View { func adaptiveMainFrame(for horizontalSizeClass: UIUserInterfaceSizeClass?) -> some View { return Group { if horizontalSizeClass == .compact { self } else { frame(height: constant(iOS: 200, tvOS: 400), alignment: .top) } } } } // MARK: Size final class ShowHeaderViewSize: NSObject { static func recommended(for show: SRGShow, layoutWidth: CGFloat, horizontalSizeClass: UIUserInterfaceSizeClass) -> NSCollectionLayoutSize { let fittingSize = CGSize(width: layoutWidth, height: UIView.layoutFittingExpandedSize.height) let model = ShowHeaderViewModel() model.show = show let size = ShowHeaderView.MainView(model: model).adaptiveSizeThatFits(in: fittingSize, for: horizontalSizeClass) return NSCollectionLayoutSize(widthDimension: .absolute(layoutWidth), heightDimension: .absolute(size.height)) } } struct ShowHeaderView_Previews: PreviewProvider { private static let model: ShowHeaderViewModel = { let model = ShowHeaderViewModel() model.show = Mock.show() return model }() static var previews: some View { #if os(tvOS) ShowHeaderView.MainView(model: model) .previewLayout(.sizeThatFits) #else ShowHeaderView.MainView(model: model) .frame(width: 1000) .previewLayout(.sizeThatFits) .environment(\.horizontalSizeClass, .regular) ShowHeaderView.MainView(model: model) .frame(width: 375) .previewLayout(.sizeThatFits) .environment(\.horizontalSizeClass, .compact) #endif } }
37.563981
257
0.568383
dea26374e44da57c078ad6c05a528b2d8910704b
1,566
// // DimmedView.swift // PanModal // // Copyright © 2017 Tiny Speck, Inc. All rights reserved. // import UIKit /** A dim view for use as an overlay over content you want dimmed. */ public class DimmedView: UIView { /** Represents the possible states of the dimmed view. max, off or a percentage of dimAlpha. */ enum DimState { case max case off case percent(CGFloat) } // MARK: - Properties /** The state of the dimmed view */ var dimState: DimState = .off { didSet { switch dimState { case .max: alpha = 1.0 case .off: alpha = 0.0 case .percent(let percentage): alpha = max(0.0, min(1.0, percentage)) } } } /** The closure to be executed when a tap occurs */ var didTap: ((_ recognizer: UIGestureRecognizer) -> Void)? /** Tap gesture recognizer */ private lazy var tapGesture: UIGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(didTapView)) }() // MARK: - Initializers init(dimColor: UIColor = UIColor.black.withAlphaComponent(0.7)) { super.init(frame: .zero) alpha = 0.0 backgroundColor = dimColor addGestureRecognizer(tapGesture) } required public init?(coder aDecoder: NSCoder) { fatalError() } // MARK: - Event Handlers @objc private func didTapView() { didTap?(tapGesture) } }
20.88
82
0.560664
ef2d3e8914e049dfed9871295492cc57f2055842
142
import XCTest import AmpFBAudienceNetworkTests var tests = [XCTestCaseEntry]() tests += AmpFBAudienceNetworkTests.allTests() XCTMain(tests)
17.75
45
0.816901
0ea402f3950ec88a3e43808b40c01a272cce24a7
4,153
// // SKMultipleLineLabel.swift // testing // // Created by Devon Chase on 6/10/16. // Copyright © 2016 Rude Sheep Studios. All rights reserved. // import SpriteKit class SKMultipleLineLabel: SKNode { var text : String var font : String var labels : [SKLabelNode] = [] var fontSize : CGFloat = 20 var fontColor : UIColor = UIColor.blackColor() var parentNode : SKNode init(parent : SKNode, text : String="", font: String="Ariel"){ //wondering if I need to keep. Brought in some of these for ease of modification self.text = text self.font = font self.parentNode = parent super.init() self.createMultiLineLabels() self.displayLabels() } //req init required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* createMultiLineLabels */ func createMultiLineLabels(){ let label = SKLabelNode(fontNamed: font) label.text = text let parWidth = parentNode.frame.size.width if label.frame.width > parWidth { var widthOver = parentNode.frame.size.width - label.frame.size.width if widthOver < 0 { widthOver = widthOver * -1 } var words = label.text?.componentsSeparatedByString(" ") var lineWidth = CGFloat(0) var tempLineList : [String] = [] var tempLine = "" for word in words! { let text = SKLabelNode(text: word) //This if statement generates the line if text.frame.width < parWidth && lineWidth < parWidth{ tempLine = "\(tempLine) \(word)" words?.removeFirst() lineWidth = lineWidth + SKLabelNode(text: tempLine as String).frame.size.width //only call this on the last line since most likely it will fall in this if if words!.count == 0{ tempLineList.append(tempLine) } } else if lineWidth >= parWidth{ //this else if adds the line to the tempLineList //and resets values tempLineList.append(tempLine) lineWidth = 0 tempLine = "" //so the first word in the new line isn't lost //only should run once if text.frame.width < parWidth && lineWidth < parWidth{ tempLine = "\(tempLine) \(word)" words?.removeFirst() lineWidth = lineWidth + SKLabelNode(text: tempLine as String).frame.width } } } for line in tempLineList { let newLine = SKLabelNode(text: line) labels.append(newLine) } } else { label.position = CGPointMake(parentNode.frame.size.width * -0.46, parentNode.frame.size.height * 0.46) labels.append(label) } } func displayLabels(){ var counter = 0 for label in labels { label.horizontalAlignmentMode = .Left label.verticalAlignmentMode = .Top label.fontSize = 30 label.fontColor = UIColor.blackColor() label.zPosition = 2 if counter == 0 { label.position = CGPoint(x: CGRectGetMinX(parentNode.frame) + 10, y: (parentNode.frame.size.height / -2 - 20)) } else { label.position = CGPoint(x: CGRectGetMinX(parentNode.frame) + 10, y: (labels[counter - 1].position.y - label.frame.size.height)) } parentNode.addChild(label) counter += 1 } } }
31.946154
144
0.493619
c17e795b208199f08bf1f83a6bcc35a787360f31
1,121
// // ViewController.swift // tippy2 // // Created by Tony Park on 12/19/19. // Copyright © 2019 Tony Park. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { // Get the bill amount let bill = Double(billField.text!) ?? 0 // Calculate the tip and total let tipPercentages = [0.15, 0.18, 0.2] let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip // Update the tip and total label tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } }
24.911111
72
0.604817
725143c4d17930a8fba31759ec35d1919c883cc2
1,206
/** * (C) Copyright IBM Corp. 2019, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** A query response that contains the matching documents for the preceding aggregations. */ public struct QueryTopHitsAggregationResult: Codable, Equatable { /** Number of matching results. */ public var matchingResults: Int /** An array of the document results. */ public var hits: [[String: JSON]]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case matchingResults = "matching_results" case hits = "hits" } }
28.714286
86
0.706468
2f0b99906d830eff31237d67ad0609f598a7870d
1,357
// // MockAccessTokenService.swift // SpotifyJaime // // Created by Jaime Andres Laino Guerra on 7/18/18. // Copyright © 2018 Jaime Andres Laino Guerra. All rights reserved. // import Foundation struct MockAccessTokenService : AccessTokenService { enum TestOptions { case success(AccessToken) case failure(String) case noInternetConnection } let testOption : TestOptions init(testOption: TestOptions) { self.testOption = testOption } func request(handler: @escaping (Result<AccessToken>) -> Void) { // let result : Result<AccessToken> // // switch testOption { // case .success(let accessToken): // result = Result.Success(accessToken) // case .failure(let error): // result = Result.Failure(ServiceError.failure(error)) // case .noInternetConnection: // result = Result.Failure(ServiceError.noInternetConnection) // } // // handler(result) handler(Result { switch testOption { case .success(let accessToken): return accessToken case .failure(let error): throw ServiceError.failure(error) case .noInternetConnection: throw ServiceError.noInternetConnection } }) } }
27.693878
72
0.601326
db90f90b0c59662068a66f71ba5a3ca44eb13a24
2,100
// // SyncAnswersRequest.swift // KanjiRyokucha // // Created by German Buela on 1/1/17. // Copyright © 2017 German Buela. All rights reserved. // import Foundation extension CardAnswer { var backendRequiresString: Bool { return self == .hard } var srtingForBackend: String? { return self == .hard ? "h" : nil } var intForBackend: Int { return self.rawValue } } struct CardSyncModel { let cardId: Int let answer: CardAnswer } struct SyncAnswer: Encodable { let cardSyncModel: CardSyncModel init(cardSyncModel: CardSyncModel) { self.cardSyncModel = cardSyncModel } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(cardSyncModel.cardId, forKey: .id) if cardSyncModel.answer.backendRequiresString, let stringValue = cardSyncModel.answer.srtingForBackend { try container.encode(stringValue, forKey: .r) } else { try container.encode(cardSyncModel.answer.intForBackend, forKey: .r) } } enum CodingKeys: String, CodingKey { case id case r } } struct SyncAnswersRoot: Encodable { let time: Int let sync: [SyncAnswer] init(answers: [CardSyncModel]) { self.time = 0 self.sync = answers.map { SyncAnswer(cardSyncModel: $0) } } } struct SyncResultModel: Decodable { let putIds: [Int] enum CodingKeys: String, CodingKey { case putIds = "put" } } struct SyncAnswersRequest: KoohiiRequest { let answers: [CardSyncModel] typealias ModelType = SyncResultModel typealias InputType = SyncAnswersRoot let apiMethod = "review/sync" let useEndpoint = true let sendApiKey = true let method = RequestMethod.post let contentType = ContentType.json init(answers: [CardSyncModel]) { self.answers = answers } var jsonObject: SyncAnswersRoot? { return SyncAnswersRoot(answers: answers) } }
23.333333
80
0.636667
f9c81d0521d331933fb574a81c47082966e36893
726
import UIKit import RxSwift import RxCocoa protocol RxViewCell { associatedtype T // NOTE: A single PublishRelay is enough instead of a view model for now. var data: PublishRelay<T> { get set } var bag: DisposeBag { get } func bind() } class RxTableViewCell<T>: UITableViewCell, RxViewCell { internal var data = PublishRelay<T>() internal var bag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() bind() } internal func bind() {} } class RxCollectionViewCell<T>: UICollectionViewCell, RxViewCell { internal var data = PublishRelay<T>() internal var bag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() bind() } internal func bind() {} }
19.621622
75
0.698347
3a85cc348159bb40872744a801cf9931aa93a2ff
1,458
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit import Combine import EssentialFeed import EssentialFeediOS public final class FeedUIComposer { private init() {} private typealias FeedPresentationAdapter = LoadResourcePresentationAdapter<[FeedImage], FeedViewAdapter> public static func feedComposedWith( feedLoader: @escaping () -> AnyPublisher<[FeedImage], Error>, imageLoader: @escaping (URL) -> FeedImageDataLoader.Publisher, selection: @escaping (FeedImage) -> Void = { _ in } ) -> ListViewController { let presentationAdapter = FeedPresentationAdapter(loader: feedLoader) let feedController = makeFeedViewController(title: FeedPresenter.title) feedController.onRefresh = presentationAdapter.loadResource presentationAdapter.presenter = LoadResourcePresenter( resourceView: FeedViewAdapter( controller: feedController, imageLoader: imageLoader, selection: selection), loadingView: WeakRefVirtualProxy(feedController), errorView: WeakRefVirtualProxy(feedController), mapper: FeedPresenter.map) return feedController } private static func makeFeedViewController(title: String) -> ListViewController { let bundle = Bundle(for: ListViewController.self) let storyboard = UIStoryboard(name: "Feed", bundle: bundle) let feedController = storyboard.instantiateInitialViewController() as! ListViewController feedController.title = title return feedController } }
32.4
106
0.786008
622a1699ab68d0d0a8baab7c053550c30fc760b6
471
import XCTest @testable import Slimane class SlimaneTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. //XCTAssertEqual(Slimane().text, "Hello, World!") } static var allTests : [(String, (SlimaneTests) -> () throws -> Void)] { return [ ("testExample", testExample), ] } }
26.166667
96
0.617834
1aa73d98f8b1b21116f47a51d849ec207fd0a2fa
642
// // MenuView.swift // BoardBunnyGame // // Created by Ilya Maslau on 23.02.22. // import SwiftUI struct MenuView: View { // MARK: - variables @StateObject private var gameModel: GameModel = GameModel() // MARK: - gui var body: some View { NavigationView { Group { if gameModel.categoriesModel == nil { ActivityIndicatorView() } else { MainMenuView() } }.navigationBarHidden(true) } .accentColor(ThemeColors.sh.getColorByType(.base)) .environmentObject(gameModel) } }
20.0625
63
0.535826
9ba805ed5931dbce618334e1f66796933236e040
570
// // OBWriteInternationalScheduledConsent2.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct OBWriteInternationalScheduledConsent2: Codable { public var data: OBWriteDataInternationalScheduledConsent2 public var risk: OBRisk1 public init(data: OBWriteDataInternationalScheduledConsent2, risk: OBRisk1) { self.data = data self.risk = risk } public enum CodingKeys: String, CodingKey { case data = "Data" case risk = "Risk" } }
19
81
0.701754
1a428c5568ab66009b7547adc81982c97bb27781
2,325
// // IntegerToRoman.swift // LeetCode // // Created by Nail Sharipov on 10/06/2019. // Copyright © 2019 Nail Sharipov. All rights reserved. // import Foundation class IntegerToRoman { final func intToRoman(_ num: Int) -> String { var a = num var s = String() if a >= 1000 { let q = a / 1000 s.reserveCapacity(q &+ 12) for _ in 0..<q { s.append("M") } a %= 1000 } else { s.reserveCapacity(12) } if a >= 100 { let q = a / 100 a %= 100 switch q { case 1: s.append("C") case 2: s.append("CC") case 3: s.append("CCC") case 4: s.append("CD") case 5: s.append("D") case 6: s.append("DC") case 7: s.append("DCC") case 8: s.append("DCCC") default: s.append("CM") } } if a >= 10 { let q = a / 10 a %= 10 switch q { case 1: s.append("X") case 2: s.append("XX") case 3: s.append("XXX") case 4: s.append("XL") case 5: s.append("L") case 6: s.append("LX") case 7: s.append("LXX") case 8: s.append("LXXX") default: s.append("XC") } } if a > 0 { switch a { case 1: s.append("I") case 2: s.append("II") case 3: s.append("III") case 4: s.append("IV") case 5: s.append("V") case 6: s.append("VI") case 7: s.append("VII") case 8: s.append("VIII") default: s.append("IX") } } return s } }
22.355769
56
0.308387
6962f680e96606e8eb85431ff64da4d68bfaf3d2
386
// // LabelLite.swift // Metal Archives // // Created by Thanh-Nhon Nguyen on 25/02/2019. // Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved. // import Foundation final class LabelLite: ThumbnailableObject { let name: String init?(urlString: String, name: String) { self.name = name super.init(urlString: urlString, imageType: .label) } }
20.315789
60
0.660622
892afb30c80883c9ac9441ba20fed18ec42fedea
2,917
// // IdentifierExtensionsTests.swift // HealthKitOnFhir_Tests // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import Foundation import Quick import Nimble import FHIR class IdentifierExtensionsSpec: QuickSpec { override func spec() { describe("IdentifierExtensions") { context("contains is called") { context("on an identifier with no system") { let test = testObject(system: nil, value: "Test_Value") it("returns false") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beFalse()) } } context("on an identifier with no value") { let test = testObject(system: "Test_System", value: nil) it("returns false") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beFalse()) } } context("on an identifier with a system and value") { context("that contains the provided system and value parameters") { let test = testObject(system: "Test_System", value: "Test_Value") it("returns true") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beTrue()) } } context("that does not contain the provided system") { let test = testObject(system: "Test_Not_System", value: "Test_Value") it("returns false") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beFalse()) } } context("that does not contain the provided value") { let test = testObject(system: "Test_System", value: "Test_Not_Value") it("returns false") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beFalse()) } } context("that does not contain the provided system or value") { let test = testObject(system: "Test_Not_System", value: "Test_Not_Value") it("returns false") { expect(test.contains(system: "Test_System", value: "Test_Value")).to(beFalse()) } } } } } } private func testObject(system: String?, value: String?) -> Identifier { let identifier = Identifier() identifier.system = system != nil ? FHIRURL(system!) : nil identifier.value = value != nil ? FHIRString(value!) : nil return identifier } }
44.19697
107
0.499829
09a16dd8ce8bdb5c8d943a4cdab0bba869e0660a
523
// // Number+Extensions.swift // Lecet // // Created by Y Media Labs on 26/09/18. // Copyright © 2018 Y Media Labs. All rights reserved. // import Foundation extension NumberFormatter { convenience init(with seperator: String) { self.init() self.groupingSeparator = seperator self.numberStyle = .decimal } } extension Int { func format(using seperator: String) -> String { return NumberFormatter(with: seperator).string(from: NSNumber(integerLiteral: self)) ?? "" } }
21.791667
98
0.659656
629d354a4f4f85c22a55d5e5d9df16dec1610489
640
// // String+CreditCardRow.swift // CreditCardRow // // Created by Mathias Claassen on 9/5/16. // // import Foundation public extension String { subscript (i: Int) -> Character { return self[self.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(start, offsetBy: r.upperBound - r.lowerBound) return String(self[start..<end]) } } //"abcde"[0] == "a" //"abcde"[0...2] == "abc" //"abcde"[2..<4] == "cd"
20
69
0.589063
e63d94391f3e8251515d7ec27f65d032f99fbf33
962
// // HairlineView.swift // falcon // // Created by Juan Pablo Civile on 16/12/2020. // Copyright © 2020 muun. All rights reserved. // import Foundation import UIKit class HairlineView: UIView { var color: UIColor = Asset.Colors.cardViewBorder.color { didSet { self.layer.borderColor = color.cgColor } } required init?(coder: NSCoder) { fatalError() } init() { super.init(frame: CGRect.zero) setContentHuggingPriority(.required, for: .vertical) setContentCompressionResistancePriority(.required, for: .vertical) } override func didMoveToSuperview() { self.layer.borderColor = color.cgColor self.layer.borderWidth = (1.0 / UIScreen.main.scale) / 2 self.backgroundColor = UIColor.clear } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: (1.0 / UIScreen.main.scale)) } }
23.463415
91
0.647609
2f91bbc634ddccab57f2de5429bbf7793fd2d4f9
1,394
// // TypeHolderExample.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation internal struct TypeHolderExample: Codable, Hashable { internal var stringItem: String internal var numberItem: Double internal var integerItem: Int internal var boolItem: Bool internal var arrayItem: [Int] internal init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { self.stringItem = stringItem self.numberItem = numberItem self.integerItem = integerItem self.boolItem = boolItem self.arrayItem = arrayItem } internal enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" case integerItem = "integer_item" case boolItem = "bool_item" case arrayItem = "array_item" } // Encodable protocol methods internal func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(stringItem, forKey: .stringItem) try container.encode(numberItem, forKey: .numberItem) try container.encode(integerItem, forKey: .integerItem) try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } }
29.659574
111
0.687231
de1d7bd42a9760c047c61492104ab582ccede524
3,739
import XCTest @testable import Core final class BlogTests: XCTestCase { private var blog: Website.Blog! private var url: URL! override func setUp() { url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString) try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) blog = Website.load(Website.blog("hello", directory: url)) as? Website.Blog try! blog.open() } override func tearDown() { try! FileManager.default.removeItem(at: url) blog.close() } func testAdd() { blog.add(id: "hello") blog.update(blog.model.pages.first { $0.id == "hello" }!.content("lorem")) blog.add(id: "hello") XCTAssertEqual(2, blog.model.pages.count) XCTAssertEqual("", blog.model.pages.first { $0.id == "hello" }!.content) } func testName() { blog.add(id: "hello ") XCTAssertEqual("hello", blog.model.pages.sorted { $0.created > $1.created }.first!.id) blog.add(id: "hello\n") XCTAssertEqual("hello", blog.model.pages.sorted { $0.created > $1.created }.first!.id) blog.add(id: "hello world") XCTAssertEqual("hello-world", blog.model.pages.sorted { $0.created > $1.created }.first!.id) blog.add(id: "hello\\world") XCTAssertEqual("hello%5Cworld", blog.model.pages.sorted { $0.created > $1.created }.first!.id) } func testTitle() { blog.add(id: "hello world") XCTAssertEqual("hello world", blog.model.pages.sorted { $0.created > $1.created }.first!.title) } func testContains() { blog.add(id: "hello world") XCTAssertTrue(blog.contains(id: "hello world")) XCTAssertTrue(blog.contains(id: "hello-world")) } func testRemove() { blog.add(id: "hello") blog.remove(blog.model.pages.filter { $0 != .index }.first!) XCTAssertEqual(1, blog.model.pages.count) XCTAssertTrue(blog.model.pages.contains(.index)) } func testRender() { blog.add(id: "first") blog.add(id: "second") var _index = blog.model.pages.first { $0 == .index }! _index.title = "Start here" blog.update(_index) var _first = blog.model.pages.first { $0.id == "first" }! _first.title = "First page" blog.update(_first) var _second = blog.model.pages.first { $0.id == "second" }! _second.title = "Second page" blog.update(_second) blog.update(blog.model.pages.first { $0 == .index }!.content("welcome")) blog.update(blog.model.pages.first { $0.id == "first" }!.content("hello world")) blog.update(blog.model.pages.first { $0.id == "second" }!.content("lorem ipsum")) let index = try! String(decoding: Data(contentsOf: url.appendingPathComponent("index.html")), as: UTF8.self) XCTAssertTrue(index.contains(""" <p>welcome</p> """)) XCTAssertTrue(index.contains(""" <ul> <li><a href="second.html">Second page</a></li> <li><a href="first.html">First page</a></li> </ul> """)) let item = try! String(decoding: Data(contentsOf: url.appendingPathComponent("first.html")), as: UTF8.self) XCTAssertTrue(item.contains(""" <p>hello world</p> """)) XCTAssertTrue(item.contains(""" <p><a href="index.html">Start here</a></p> """)) } func testNoTitleForIndex() { blog.add(id: "first") let item = try! String(decoding: Data(contentsOf: url.appendingPathComponent("first.html")), as: UTF8.self) XCTAssertTrue(item.contains(""" <p><a href="index.html">Home</a></p> """)) } }
32.513043
116
0.594277
5633c067a1ee33e49cfb8b3c49c2a5c9a8bdd7d7
47,553
// // Created by Krzysztof Zablocki on 11/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation import SourceKittenFramework import PathKit import SourceryRuntime import SourceryUtils protocol Parsable: AnyObject { var __parserData: Any? { get set } } extension Parsable { /// Source structure used by the parser fileprivate var __underlyingSource: [String: SourceKitRepresentable] { return (__parserData as? [String: SourceKitRepresentable]) ?? [:] } /// sets underlying source fileprivate func setSource(_ source: [String: SourceKitRepresentable]) { __parserData = source } } extension Type { public var path: Path? { return __path.map({ Path($0) }) } public func bodyRange(_ contents: String) -> NSRange? { guard let bytesRange = bodyBytesRange else { return nil } return StringView(contents).byteRangeToNSRange(ByteRange(location: ByteCount(bytesRange.offset), length: ByteCount(bytesRange.length))) } } extension Variable: Parsable {} extension Type: Parsable {} extension SourceryMethod: Parsable {} extension MethodParameter: Parsable {} extension EnumCase: Parsable {} extension Subscript: Parsable {} extension Attribute: Parsable {} public final class FileParser: FileParserType { public let path: String? public let module: String? public let modifiedDate: Date? public let initialContents: String fileprivate var contents: String! fileprivate var annotations: AnnotationsParser! fileprivate var inlineRanges: [String: NSRange]! fileprivate var inlineIndentations: [String: String]! fileprivate var logPrefix: String { return path.flatMap { "\($0):" } ?? "" } /// Parses given contents. /// /// - Parameters: /// - verbose: Whether it should log verbose /// - contents: Contents to parse. /// - path: Path to file. /// - Throws: parsing errors. public init(contents: String, path: Path? = nil, module: String? = nil) throws { self.path = path?.string self.modifiedDate = path.flatMap({ (try? FileManager.default.attributesOfItem(atPath: $0.string)[.modificationDate]) as? Date }) self.module = module self.initialContents = contents } // MARK: - Processing public func parseContentsIfNeeded() -> String { guard annotations == nil else { // already loaded return contents } let inline = TemplateAnnotationsParser.parseAnnotations("inline", contents: initialContents) contents = inline.contents inlineRanges = inline.annotatedRanges.mapValues { $0[0].range } inlineIndentations = inline.annotatedRanges.mapValues { $0[0].indentation } annotations = AnnotationsParser(contents: contents) return contents } /// Parses given file context. /// /// - Returns: All types we could find. public func parse() throws -> FileParserResult { _ = parseContentsIfNeeded() if let path = path { Log.verbose("Processing file \(path)") } let file = File(contents: contents) let source = try Structure(file: file).dictionary let (types, functions, typealiases) = try parseTypes(source) let imports = try parseImports(contents).map { Import(path: $0) } types.forEach { $0.imports = imports } return FileParserResult(path: path, module: module, types: types, functions: functions, typealiases: typealiases, inlineRanges: inlineRanges, inlineIndentations: inlineIndentations, modifiedDate: modifiedDate ?? Date(), sourceryVersion: SourceryVersion.current.value) } private func parseImports(_ code: String) throws -> [String] { var unique: Set<String> = [] let regExp = try NSRegularExpression(pattern: "(?:(?:^|;)\\s*)(?:@testable\\s+)?import\\s+([a-zA-Z0-9_]+)", options: [.anchorsMatchLines]) for match in regExp.matches(in: code, options: [], range: NSRange(code.startIndex..., in: code)) { guard let range = Range(match.range(at: 1), in: code) else { continue } unique.insert(String(code[range])) } return Array(unique) } private func parseTypes(_ source: [String: SourceKitRepresentable]) throws -> ([Type], [SourceryMethod], [Typealias]) { var types = [Type]() var functions = [SourceryMethod]() var typealiases = [Typealias]() try walkDeclarations(source: source) { kind, name, access, inheritedTypes, source, definedIn, next in let type: Type switch (kind, name) { case let (.protocol, name?): type = Protocol(name: name, accessLevel: access, isExtension: false, inheritedTypes: inheritedTypes) case let (.class, name?): type = Class(name: name, accessLevel: access, isExtension: false, inheritedTypes: inheritedTypes) case let (.struct, name?): type = Struct(name: name, accessLevel: access, isExtension: false, inheritedTypes: inheritedTypes) case let (.enum, name?): type = Enum(name: name, accessLevel: access, isExtension: false, inheritedTypes: inheritedTypes) case let (.extension, name?), let (.extensionClass, name?), let (.extensionStruct, name?), let (.extensionEnum, name?): type = Type(name: name, accessLevel: access, isExtension: true, inheritedTypes: inheritedTypes) case (.enumelement, _): return parseEnumCase(source) case (.varInstance, _): return parseVariable(source, definedIn: definedIn as? Type) case (.varStatic, _), (.varClass, _): return parseVariable(source, definedIn: definedIn as? Type, isStatic: true) case (.varLocal, _): //! Don't log local / param vars return nil case (.functionMethodClass, _), (.functionMethodInstance, _), (.functionMethodStatic, _): return parseMethod(source, definedIn: definedIn as? Type, nextStructure: next) case (.functionFree, _): guard let function = parseMethod(source, definedIn: definedIn as? Type, nextStructure: next) else { return nil } functions.append(function) return function case (.functionSubscript, _): return parseSubscript(source, definedIn: definedIn as? Type, nextStructure: next) case (.varParameter, _): return parseParameter(source) case (.typealias, _): switch parseTypealias(source, containingType: definedIn as? Type) { case nil: return nil case .typealias(let alias)?: if definedIn == nil { typealiases.append(alias) } return alias case .protocolComposition(let protocolComposition)?: if definedIn == nil { type = protocolComposition } else { return protocolComposition } } case (.associatedtype, _): return parseAssociatedType(source, definedIn: definedIn as? Type) default: let nameSuffix = name.map { " \($0)" } ?? "" Log.astWarning("\(logPrefix) Unsupported entry \"\(access) \(kind)\(nameSuffix)\"") return nil } type.isGeneric = isGeneric(source: source) type.annotations = annotations.from(source) type.attributes = parseDeclarationAttributes(source) type.bodyBytesRange = Substring.body.range(for: source).map { BytesRange(range: $0) } type.setSource(source) type.__path = path types.append(type) return type } return (types, functions, typealiases) } typealias FoundEntry = ( /*kind:*/ SwiftDeclarationKind, /*name:*/ String?, /*accessLevel:*/ AccessLevel, /*inheritedTypes:*/ [String], /*source:*/ [String: SourceKitRepresentable], /*definedIn:*/ Any?, /*next:*/ [String: SourceKitRepresentable]? ) -> Any? /// Walks all declarations in the source private func walkDeclarations(source: [String: SourceKitRepresentable], containingIn: (Any, [String: SourceKitRepresentable])? = nil, foundEntry: FoundEntry) throws { guard let substructures = source[SwiftDocKey.substructure.rawValue] as? [SourceKitRepresentable] else { return } for (index, substructure) in substructures.enumerated() { guard let source = substructure as? [String: SourceKitRepresentable] else { continue } let nextStructure = index < substructures.count - 1 ? substructures[index+1] as? [String: SourceKitRepresentable] : nil try walkDeclaration( source: source, next: nextStructure, containingIn: containingIn, foundEntry: foundEntry ) } } /// Walks single declaration in the source, recursively processing containing types private func walkDeclaration(source: [String: SourceKitRepresentable], next: [String: SourceKitRepresentable]?, containingIn: (Any, [String: SourceKitRepresentable])? = nil, foundEntry: FoundEntry) throws { var declaration = containingIn let inheritedTypes = extractInheritedTypes(source: source) if let requirements = parseTypeRequirements(source) { let foundDeclaration = foundEntry(requirements.kind, requirements.name, requirements.accessibility, inheritedTypes, source, containingIn?.0, next) if let foundDeclaration = foundDeclaration, let containingIn = containingIn { processContainedDeclaration(foundDeclaration, within: containingIn) } declaration = foundDeclaration.map({ ($0, source) }) } try walkDeclarations(source: source, containingIn: declaration, foundEntry: foundEntry) } private func processContainedDeclaration(_ declaration: Any, within containing: (declaration: Any, source: [String: SourceKitRepresentable])) { switch containing.declaration { case let containingType as Type: process(declaration: declaration, containedIn: containingType) case let containingMethod as SourceryMethod: process(declaration: declaration, containedIn: (containingMethod, containing.source)) case let containingSubscript as Subscript: process(declaration: declaration, containedIn: (containingSubscript, containing.source)) default: break } } private func process(declaration: Any, containedIn type: Type) { switch (type, declaration) { case let (_, variable as Variable): type.rawVariables += [variable] case let (_, `subscript` as Subscript): type.rawSubscripts += [`subscript`] case let (_, method as SourceryMethod): if method.isInitializer { method.returnTypeName = TypeName(type.name) } type.rawMethods += [method] case let (_, childType as Type): type.containedTypes += [childType] childType.parent = type case let (enumeration as Enum, enumCase as EnumCase): enumeration.cases += [enumCase] case let (_, `typealias` as Typealias): type.typealiases[`typealias`.aliasName] = `typealias` case let (sourceryProtocol as SourceryProtocol, associatedType as AssociatedType): sourceryProtocol.associatedTypes[associatedType.name] = associatedType default: break } } private func process(declaration: Any, containedIn: (declaration: Any, source: [String: SourceKitRepresentable])) { switch declaration { case let (parameter as MethodParameter): //add only parameters that are in range of method name guard let nameRange = Substring.name.range(for: containedIn.source), let paramKeyRange = Substring.key.range(for: parameter.__underlyingSource), nameRange.offset + nameRange.length >= paramKeyRange.offset + paramKeyRange.length else { return } switch containedIn.declaration { case let (method as SourceryMethod): method.parameters += [parameter] case let (`subscript` as Subscript): `subscript`.parameters += [parameter] default: break } default: break } } } // MARK: - Details parsing extension FileParser { fileprivate func parseTypeRequirements(_ dict: [String: SourceKitRepresentable]) -> (name: String?, kind: SwiftDeclarationKind, accessibility: AccessLevel)? { guard let kind = (dict[SwiftDocKey.kind.rawValue] as? String).flatMap({ SwiftDeclarationKind(rawValue: $0) }) else { return nil } let accessibility = (dict["key.accessibility"] as? String).flatMap({ AccessLevel(rawValue: $0.replacingOccurrences(of: "source.lang.swift.accessibility.", with: "") ) }) ?? .none let name: String? = (dict[SwiftDocKey.name.rawValue] as? String).map { var name: String = $0 if case .enumelement = kind, let openingBrace = name.firstIndex(of: "(") { name = String(name[..<openingBrace]) } if extract(.name, from: dict)?.hasPrefix("`") == true { name = "`\(name)`" } return name } // Some declarations are expected to have name, while others don't. // // Example: // ``` // func method(_: Int) // ``` // // Method is expected to have a name, while argument is not. switch (kind, name) { case (.varParameter, _): // Parameters can have no name break case (_, .some): // Other declarations must have some name break default: // Fail to parse if those requirements aren't met return nil } return (name, kind, accessibility) } private func extractInheritedTypes(source: [String: SourceKitRepresentable]) -> [String] { return (source[SwiftDocKey.inheritedtypes.rawValue] as? [[String: SourceKitRepresentable]])?.compactMap { type in return type[SwiftDocKey.name.rawValue] as? String } ?? [] } fileprivate func isGeneric(source: [String: SourceKitRepresentable]) -> Bool { guard let substring = extract(.nameSuffix, from: source), substring.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("<") == true else { return false } return true } fileprivate func setterAccessibility(source: [String: SourceKitRepresentable]) -> AccessLevel? { if let setter = source["key.setter_accessibility"] as? String { return AccessLevel(rawValue: setter.trimmingPrefix("source.lang.swift.accessibility.")) } else { guard let attributes = source["key.attributes"] as? [[String: SourceKitRepresentable]], let setterAccess = attributes .compactMap({ $0["key.attribute"] as? String }) .first(where: { $0.hasPrefix("source.decl.attribute.setter_access.") }) else { return nil } return AccessLevel(rawValue: setterAccess.trimmingPrefix("source.decl.attribute.setter_access.")) } } } // MARK: - Variables extension FileParserType { internal func inferType(from input: String) -> String? { return Self.inferType(from: input) } internal static func extractComposedTypeNames(from value: String, trimmingCharacterSet: CharacterSet? = nil) -> [TypeName]? { guard case let components = value.components(separatedBy: CharacterSet(charactersIn: "&")), components.count > 1 else { return nil } var characterSet: CharacterSet = .whitespacesAndNewlines if let trimmingCharacterSet = trimmingCharacterSet { characterSet = characterSet.union(trimmingCharacterSet) } let suffixes = components.map { source in source.trimmingCharacters(in: characterSet) } return suffixes.map(TypeName.init(_:)) } internal static func inferType(from input: String) -> String? { let string = input .trimmingCharacters(in: .whitespacesAndNewlines) .strippingComments() .trimmingCharacters(in: .whitespacesAndNewlines) // probably lazy property or default value with closure, // we expect explicit type, as we don't know return type guard !(string.hasPrefix("{") && string.hasSuffix(")")) else { let body = String(string.dropFirst()) guard !body.contains("return") else { return nil } // if there is no return statement it means the return value is the first expression let components = body.components(separatedBy: "(", excludingDelimiterBetween: ("<[(", ")]>")) if let first = components.first { return inferType(from: first + "()") } return nil } var inferredType: String if string == "nil" { return "Optional" } else if string.first == "\"" { return "String" } else if Bool(string) != nil { return "Bool" } else if Int(string) != nil { return "Int" } else if Double(string) != nil { return "Double" } else if string.isValidTupleName() { //tuple let string = string.dropFirstAndLast() let elements = string.commaSeparated() var types = [String]() for element in elements { let nameAndValue = element.colonSeparated() if nameAndValue.count == 1 { guard let type = inferType(from: element) else { return nil } types.append(type) } else { guard let type = inferType(from: nameAndValue[1]) else { return nil } let name = nameAndValue[0] .replacingOccurrences(of: "_", with: "") .trimmingCharacters(in: .whitespaces) if name.isEmpty { types.append(type) } else { types.append("\(name): \(type)") } } } return "(\(types.joined(separator: ", ")))" } else if string.first == "[", string.last == "]" { //collection let string = string.dropFirstAndLast() let items = string .commaSeparated() .map { $0 .trimmingCharacters(in: .whitespacesAndNewlines) .strippingComments() .trimmingCharacters(in: .whitespacesAndNewlines) } func genericType(from itemsTypes: [String]) -> String { let genericType: String var uniqueTypes = Set(itemsTypes) if uniqueTypes.count == 1, let type = uniqueTypes.first { genericType = type } else if uniqueTypes.count == 2, uniqueTypes.remove("Optional") != nil, let type = uniqueTypes.first { genericType = "\(type)?" } else { genericType = "Any" } return genericType } if items[0].colonSeparated().count == 1 { var itemsTypes = [String]() for item in items { guard let type = inferType(from: item) else { return nil } itemsTypes.append(type) } return "[\(genericType(from: itemsTypes))]" } else { var keysTypes = [String]() var valuesTypes = [String]() for items in items { let keyAndValue = items.colonSeparated() guard keyAndValue.count == 2, let keyType = inferType(from: keyAndValue[0]), let valueType = inferType(from: keyAndValue[1]) else { return nil } keysTypes.append(keyType) valuesTypes.append(valueType) } return "[\(genericType(from: keysTypes)): \(genericType(from: valuesTypes))]" } } else { // Enums, i.e. `Optional.some(...)` or `Optional.none` should be inferred to `Optional` // Contained types, i.e. `Foo.Bar()` should be inferred to `Foo.Bar` // This also supports initializers i.e. `MyType.SubType.init()` // But rarely enum cases can also start with capital letters, so we still may wrongly infer them as a type func possibleEnumType(_ string: String) -> String? { let components = string.components(separatedBy: ".", excludingDelimiterBetween: ("<[(", ")]>")) if components.count > 1, let lastComponentFirstLetter = components.last?.first.map(String.init) { if lastComponentFirstLetter.lowercased() == lastComponentFirstLetter { return components .dropLast() .joined(separator: ".") } } return nil } // get everything before `(` let components = string.components(separatedBy: "(", excludingDelimiterBetween: ("<[(", ")]>")) // scenario for '}' is for property settter / getter logic // scenario for ! is for unwrapped optional let unwrappedOptional = string.last == "!" if components.count > 1 && (string.last == ")" || string.last == "}" || unwrappedOptional) { //initializer without `init` inferredType = components[0] let name = possibleEnumType(inferredType) ?? inferredType return name + (unwrappedOptional ? "!" : "") } else { return possibleEnumType(string) } } } } extension FileParser { private func parseVariable(_ source: [String: SourceKitRepresentable], definedIn: Type?, isStatic: Bool = false) -> Variable? { guard let (nameOrNil, _, accessibility) = parseTypeRequirements(source), let name = nameOrNil else { return nil } let definedInProtocol = (definedIn != nil) ? definedIn is SourceryProtocol : false var maybeType: String? = source[SwiftDocKey.typeName.rawValue] as? String if maybeType == nil, let substring = extract(.nameSuffix, from: source)?.trimmingCharacters(in: .whitespaces) { guard substring.hasPrefix("=") else { return nil } var substring = substring.dropFirst().trimmingCharacters(in: .whitespaces) if substring.hasSuffix("{") { substring = String(substring.dropLast()).trimmingCharacters(in: .whitespaces) } maybeType = inferType(from: substring) } let typeName: TypeName if let type = maybeType { typeName = TypeName(type) } else { let declaration = extract(.key, from: source) // swiftlint:disable:next force_unwrapping Log.astWarning("unknown type, please add type attribution to variable\(declaration != nil ? " '\(declaration!)'" : "")") typeName = TypeName("UnknownTypeSoAddTypeAttributionToVariable") } let setterAccessibility = self.setterAccessibility(source: source) let body = extract(Substring.body, from: source) ?? "" let constant = extract(Substring.key, from: source)?.hasPrefix("let") == true let hasPropertyObservers = body.hasPrefix("didSet") || body.hasPrefix("willSet") let computed = !definedInProtocol && ( (setterAccessibility == nil && !constant) || (setterAccessibility != nil && !body.isEmpty && hasPropertyObservers == false) ) let accessLevel = (read: accessibility, write: setterAccessibility ?? (constant ? .none :.internal)) let defaultValue = extractDefaultValue(type: maybeType, from: source) let definedInTypeName = definedIn.map { TypeName($0.name) } let variable = Variable(name: name, typeName: typeName, accessLevel: accessLevel, isComputed: computed, isStatic: isStatic, defaultValue: defaultValue, attributes: parseDeclarationAttributes(source), annotations: annotations.from(source), definedInTypeName: definedInTypeName) variable.setSource(source) return variable } } // MARK: - Subscripts extension FileParser { private func parseSubscript(_ source: [String: SourceKitRepresentable], definedIn: Type? = nil, nextStructure: [String: SourceKitRepresentable]? = nil) -> Subscript? { guard let method = parseMethod(source, definedIn: definedIn, nextStructure: nextStructure) else { return nil } guard let accessibility = AccessLevel(rawValue: method.accessLevel) else { return nil } let setterAccessibility = self.setterAccessibility(source: source) let accessLevel = (read: accessibility, write: setterAccessibility ?? .none) return Subscript(parameters: method.parameters, returnTypeName: method.returnTypeName, accessLevel: accessLevel, attributes: method.attributes, annotations: method.annotations, definedInTypeName: method.definedInTypeName) } } // MARK: - Methods extension FileParser { private func parseMethod(_ source: [String: SourceKitRepresentable], definedIn: Type? = nil, nextStructure: [String: SourceKitRepresentable]? = nil) -> SourceryMethod? { let requirements = parseTypeRequirements(source) guard let kind = requirements?.kind, let accessibility = requirements?.accessibility, var name = requirements?.name, var fullName = extract(.name, from: source) else { return nil } fullName = fullName.strippingComments() name = name.strippingComments() let isStatic = kind == .functionMethodStatic let isClass = kind == .functionMethodClass let isFailableInitializer: Bool if let name = extract(Substring.name, from: source), name.hasPrefix("init?") { isFailableInitializer = true } else { isFailableInitializer = false } var returnTypeName: String = "Void" var `throws` = false var `rethrows` = false var nameSuffix: String? // if declaration has body then get everything up to body start if source.keys.contains(SwiftDocKey.bodyOffset.rawValue) { if let suffix = extract(.nameSuffixUpToBody, from: source) { nameSuffix = suffix.trimmingCharacters(in: .whitespacesAndNewlines) } else { nameSuffix = "" } } else if let nameSuffixRange = Substring.nameSuffix.range(for: source) { // if declaration has no body, usually in protocols, parse it manually // The problem is that generic constraint and throws/rethrows with Void return type is not part of the key... // so we have to scan manully until next structure, but also should drop any comments in between var upperBound: Int? if let nextStructure = nextStructure, let range = Substring.key.range(for: nextStructure) { // if there is next declaration, parse until its start let nextAttributesOffests = parseDeclarationAttributes(nextStructure) .values.compactMap { Substring.key.range(for: $0.__underlyingSource)?.offset } if let firstNextAttributeOffset = nextAttributesOffests.min() { upperBound = min(Int(range.offset), Int(firstNextAttributeOffset)) } else { upperBound = Int(range.offset) } } else if let definedInSource = definedIn?.__underlyingSource, let range = Substring.key.range(for: definedInSource) { // if there are no fiurther declarations, parse until end of containing declaration upperBound = Int(range.offset) + Int(range.length) - 1 } if let upperBound = upperBound { let start = Int(nameSuffixRange.offset) let length = upperBound - Int(nameSuffixRange.offset) let nameSuffixUpToNextStruct = StringView(contents) .substringWithByteRange(ByteRange(location: ByteCount(start), length: ByteCount(length)))? .trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)) if let nameSuffixUpToNextStruct = nameSuffixUpToNextStruct { let tokens = try? SyntaxMap(file: File(contents: nameSuffixUpToNextStruct)).tokens let firstDocToken = tokens?.first(where: { $0.type.hasPrefix("source.lang.swift.syntaxtype.comment") || $0.type.hasPrefix("source.lang.swift.syntaxtype.doccomment") }) if let firstDocToken = firstDocToken { nameSuffix = StringView(nameSuffixUpToNextStruct) .substringWithByteRange(ByteRange(location: ByteCount(0), length: firstDocToken.offset))? .trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)) } else { nameSuffix = nameSuffixUpToNextStruct } } } } if var nameSuffix = nameSuffix { `throws` = nameSuffix.trimPrefix("throws") `rethrows` = nameSuffix.trimPrefix("rethrows") nameSuffix = nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) if nameSuffix.trimPrefix("->") { returnTypeName = nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) } else if !nameSuffix.isEmpty { returnTypeName = nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) } } let definedInTypeName = definedIn.map { TypeName($0.name) } let method = Method(name: fullName, selectorName: name.trimmingSuffix("()"), returnTypeName: TypeName(returnTypeName), throws: `throws`, rethrows: `rethrows`, accessLevel: accessibility, isStatic: isStatic, isClass: isClass, isFailableInitializer: isFailableInitializer, attributes: parseDeclarationAttributes(source), annotations: annotations.from(source), definedInTypeName: definedInTypeName) method.setSource(source) return method } private func parseParameter(_ source: [String: SourceKitRepresentable]) -> MethodParameter? { guard let (name, _, _) = parseTypeRequirements(source), let type = source[SwiftDocKey.typeName.rawValue] as? String else { return nil } let argumentLabel = extract(.name, from: source) let `inout` = type.hasPrefix("inout ") let typeName = TypeName(type, attributes: parseTypeAttributes(type)) let defaultValue = extractDefaultValue(type: type, from: source) let parameter = MethodParameter(argumentLabel: argumentLabel, name: name ?? "", typeName: typeName, defaultValue: defaultValue, annotations: annotations.from(source), isInout: `inout`) parameter.setSource(source) return parameter } } // MARK: - Enums extension FileParser { fileprivate func parseEnumCase(_ source: [String: SourceKitRepresentable]) -> EnumCase? { guard let (nameOrNil, _, _) = parseTypeRequirements(source), let name = nameOrNil else { return nil } var associatedValues: [AssociatedValue] = [] var rawValue: String? guard let keyString = extract(.key, from: source), let nameRange = keyString.range(of: name) else { Log.astWarning("\(logPrefix)parseEnumCase: Unable to extract enum body from \(source)") return nil } var isIndirect: Bool = false if let attributes = source["key.attributes"] as? [[String: SourceKitRepresentable]], let attribute = attributes.first?["key.attribute"] as? String, SwiftDeclarationAttributeKind(rawValue: attribute) == .indirect { isIndirect = true } let wrappedBody = keyString[nameRange.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines) switch (wrappedBody.first, wrappedBody.last) { case ("="?, _?): let body = wrappedBody[wrappedBody.index(after: wrappedBody.startIndex)...].trimmingCharacters(in: .whitespacesAndNewlines) rawValue = parseEnumValues(body) case ("("?, ")"?): let body = wrappedBody[wrappedBody.index(after: wrappedBody.startIndex)..<wrappedBody.index(before: wrappedBody.endIndex)].trimmingCharacters(in: .whitespacesAndNewlines) associatedValues = parseEnumAssociatedValues(body) case (nil, nil): break default: Log.astWarning("\(logPrefix)parseEnumCase: Unknown enum case body format \(wrappedBody)") } let enumCase = EnumCase(name: name, rawValue: rawValue, associatedValues: associatedValues, annotations: annotations.from(source), indirect: isIndirect) enumCase.setSource(source) return enumCase } fileprivate func parseEnumValues(_ body: String) -> String { /// = value let body = body.replacingOccurrences(of: "\"", with: "") return body.trimmingCharacters(in: .whitespacesAndNewlines) } fileprivate func parseEnumAssociatedValues(_ body: String) -> [AssociatedValue] { guard !body.isEmpty else { return [AssociatedValue(localName: nil, externalName: nil, typeName: TypeName("()"))] } let items = body.components( separatedBy: ",", excludingDelimiterBetween: (["<", "[", "(", "{", "/*", "//"], ["}", ")", "]", ">", "*/", "\n"]) ) return items .map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) .enumerated() .map { index, rawBody in let annotations = AnnotationsParser(contents: rawBody).all let noCommentsBody = rawBody.strippingComments() let defaultValue = extractAssociatedValueDefaultValue(type: noCommentsBody) let body = noCommentsBody .strippingDefaultValues() let nameAndType = body.colonSeparated().map({ $0.trimmingCharacters(in: .whitespaces) }) let defaultName: String? = index == 0 && items.count == 1 ? nil : "\(index)" guard nameAndType.count == 2 else { let typeName = TypeName(body, attributes: parseTypeAttributes(body)) return AssociatedValue(localName: nil, externalName: defaultName, typeName: typeName, defaultValue: defaultValue, annotations: annotations) } guard nameAndType[0] != "_" else { let typeName = TypeName(nameAndType[1], attributes: parseTypeAttributes(nameAndType[1])) return AssociatedValue(localName: nil, externalName: defaultName, typeName: typeName, defaultValue: defaultValue, annotations: annotations) } let localName = nameAndType[0] let externalName = items.count > 1 ? localName : defaultName let typeName = TypeName(nameAndType[1], attributes: parseTypeAttributes(nameAndType[1])) return AssociatedValue(localName: localName, externalName: externalName, typeName: typeName, defaultValue: defaultValue, annotations: annotations) } } } // MARK: - Typealiases extension FileParser { private enum TypealiasParseOutcome { case `typealias`(Typealias) case protocolComposition(ProtocolComposition) } private func parseTypealias(_ source: [String: SourceKitRepresentable], containingType: Type?) -> TypealiasParseOutcome? { guard let (nameOrNil, _, _) = parseTypeRequirements(source), let name = nameOrNil, let nameSuffix = extract(.nameSuffix, from: source)? .trimmingCharacters(in: CharacterSet.init(charactersIn: "=").union(.whitespacesAndNewlines)) else { return nil } let trimmingCharacterSet = CharacterSet(charactersIn: "=") if let composedTypeNames = Self.extractComposedTypeNames(from: nameSuffix, trimmingCharacterSet: trimmingCharacterSet), composedTypeNames.count > 1 { let inheritedTypes = composedTypeNames.map { $0.name } return .protocolComposition(ProtocolComposition(name: name, parent: containingType, inheritedTypes: inheritedTypes, composedTypeNames: composedTypeNames)) } return .typealias(Typealias(aliasName: name, typeName: TypeName(nameSuffix), parent: containingType)) } } // MARK: - AssociatedTypes extension FileParser { private func parseAssociatedType(_ source: [String: SourceKitRepresentable], definedIn: Type?) -> AssociatedType? { guard let (nameOrNil, _, _) = parseTypeRequirements(source), let name = nameOrNil else { return nil } guard let nameSuffix = extract(.nameSuffix, from: source)? .trimmingCharacters(in: CharacterSet.init(charactersIn: ":").union(.whitespacesAndNewlines)) else { return AssociatedType(name: name) } let type: Type? if let composedTypeNames = Self.extractComposedTypeNames(from: nameSuffix), composedTypeNames.count > 1 { let inheritedTypes = composedTypeNames.map { $0.name } type = ProtocolComposition(parent: definedIn, inheritedTypes: inheritedTypes, composedTypeNames: composedTypeNames) } else { type = nil } return AssociatedType(name: name, typeName: TypeName(nameSuffix), type: type) } } // MARK: - Attributes extension FileParser { // used to parse attributes of declarations (type, variable, method, subscript) from sourcekit response private func parseDeclarationAttributes(_ source: [String: SourceKitRepresentable]) -> [String: Attribute] { if let attributes = source["key.attributes"] as? [[String: SourceKitRepresentable]] { let parsedAttributes = attributes.compactMap { (attributeDict) -> Attribute? in guard let key = extract(.key, from: attributeDict) else { return nil } guard let identifier = (attributeDict["key.attribute"] as? String).flatMap(Attribute.Identifier.init(identifier:)) else { return nil } let attribute = parseAttribute(key.trimmingPrefix("@"), identifier: identifier) attribute?.setSource(attributeDict) return attribute } var attributesByName = [String: Attribute]() parsedAttributes.forEach { attributesByName[$0.name] = $0 } return attributesByName } return [:] } // used to parse attributes from type names of method parameters and enum associated values // (sourcekit does not provide strucutred information for such attributes) internal func parseTypeAttributes(_ typeName: String) -> [String: Attribute] { let items = typeName.components(separatedBy: "@", excludingDelimiterBetween: ("(", ")")) .map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) guard items.count > 1 else { return [:] } let attributes: [Attribute] = items.filter({ !$0.isEmpty }).compactMap({ parseAttribute($0) }) var attributesByName = [String: Attribute]() attributes.forEach { attributesByName[$0.name] = $0 } return attributesByName } private func parseAttribute(_ string: String, identifier: Attribute.Identifier? = nil) -> Attribute? { guard let attributeString = string.trimmingCharacters(in: .whitespaces) .components(separatedBy: " ", excludingDelimiterBetween: ("(", ")")).first else { return nil } if let openIndex = attributeString.firstIndex(of: "(") { let name = String(attributeString.prefix(upTo: openIndex)) guard let identifier = identifier ?? Attribute.Identifier.from(string: name) else { return nil } let chars = attributeString let startIndex = chars.index(openIndex, offsetBy: 1) let endIndex = chars.index(chars.endIndex, offsetBy: -1) let argumentsString = String(chars[startIndex ..< endIndex]) let arguments = parseAttributeArguments(argumentsString, attribute: name) return Attribute(name: name, arguments: arguments, description: "\(identifier.description)(\(argumentsString))") } else { guard let identifier = identifier ?? Attribute.Identifier.from(string: attributeString) else { return nil } return Attribute(name: identifier.name, description: identifier.description) } } private func parseAttributeArguments(_ string: String, attribute: String) -> [String: NSObject] { var arguments = [String: NSObject]() string.components(separatedBy: ",", excludingDelimiterBetween: ("\"", "\"")) .map({ $0.trimmingCharacters(in: .whitespaces) }) .forEach { argument in // TODO: @objc can be used only for getter or settor of computed property if attribute == "objc" { arguments["name"] = argument as NSString return } guard argument.contains("\"") else { if argument != "*" { arguments[argument.replacingOccurrences(of: " ", with: "_")] = NSNumber(value: true) } return } let nameAndValue = argument .components(separatedBy: ":", excludingDelimiterBetween: ("\"", "\"")) .map({ $0.trimmingCharacters(in: CharacterSet(charactersIn: "\"").union(.whitespaces)) }) if nameAndValue.count != 1 { arguments[nameAndValue[0].replacingOccurrences(of: " ", with: "_")] = nameAndValue[1] as NSString } } return arguments } } // MARK: - Helpers extension FileParser { fileprivate func extract(_ substringIdentifier: Substring, from source: [String: SourceKitRepresentable]) -> String? { return substringIdentifier.extract(from: source, contents: self.contents) } fileprivate func extract(_ substringIdentifier: Substring, from source: [String: SourceKitRepresentable], contents: String) -> String? { return substringIdentifier.extract(from: source, contents: contents) } fileprivate func extractLines(_ substringIdentifier: Substring, from source: [String: SourceKitRepresentable], contents: String, trimWhitespacesAndNewlines: Bool = true) -> String? { return substringIdentifier.extractLines(from: source, contents: contents, trimWhitespacesAndNewlines: trimWhitespacesAndNewlines) } fileprivate func extractLinesNumbers(_ substringIdentifier: Substring, from source: [String: SourceKitRepresentable], contents: String) -> (start: Int, end: Int)? { return substringIdentifier.extractLinesNumbers(from: source, contents: contents) } fileprivate func extract(_ token: SyntaxToken) -> String? { return extract(token, contents: self.contents) } fileprivate func extract(_ token: SyntaxToken, contents: String) -> String? { return StringView(contents).substringWithByteRange(ByteRange(location: token.offset, length: token.length)) } fileprivate func extract(from: SyntaxToken, to: SyntaxToken, contents: String) -> String? { return StringView(contents).substringWithByteRange(ByteRange(location: from.offset, length: to.offset + to.length - from.offset)) } fileprivate func extract(after: SyntaxToken, contents: String) -> String? { return StringView(contents).substringWithByteRange(ByteRange(location: after.offset + after.length, length: ByteCount(contents.count) - (after.offset + after.length))) } fileprivate func extractDefaultValue(type: String?, from source: [String: SourceKitRepresentable]) -> String? { guard var nameSuffix = extract(.nameSuffixUpToBody, from: source)?.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil } if nameSuffix.trimPrefix(":") { nameSuffix = nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) guard let type = type, nameSuffix.trimPrefix(type) else { return nil } } nameSuffix = nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) guard nameSuffix.trimPrefix("=") else { return nil } return nameSuffix.trimmingCharacters(in: .whitespacesAndNewlines) } fileprivate func extractAssociatedValueDefaultValue(type: String) -> String? { if let defaultValueRange = type.range(of: "=") { return String(type[defaultValueRange.upperBound ..< type.endIndex]).trimmingCharacters(in: .whitespaces) } else { return nil } } } extension String { func strippingComments() -> String { var finished: Bool var stripped = self repeat { finished = true let lines = StringView(stripped).lines if lines.count > 1 { stripped = lines.lazy .filter({ line in !line.content.hasPrefix("//") }) .map(\.content) .joined(separator: "\n") } if let annotationStart = stripped.range(of: "/*")?.lowerBound, let annotationEnd = stripped.range(of: "*/")?.upperBound { stripped = stripped.replacingCharacters(in: annotationStart ..< annotationEnd, with: "") .trimmingCharacters(in: .whitespacesAndNewlines) finished = false } } while !finished return stripped } func strippingDefaultValues() -> String { if let defaultValueRange = self.range(of: "=") { return String(self[self.startIndex ..< defaultValueRange.lowerBound]).trimmingCharacters(in: .whitespaces) } else { return self } } }
45.856316
403
0.611423
181668570bc38a17d51660f8037abad7ae8505e6
1,839
// // BHWeatherControlTests.swift // BHWeatherControlTests // // Created by Bassem Hatira on 18/01/2021. // import XCTest @testable import BHWeatherControl class BHWeatherControlTests: XCTestCase { let weatherWorker = WeatherWorker() override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testCurrentWeather() { let expectation = self.expectation(description: "Current Weathers Expectation 200") let locations = [Location(lat: "48.8", lon: "2.1833"), Location(lat: "48.8", lon: "2.25")] weatherWorker.fetchCurrentWeathers(locations: locations) { (weathers, error) in guard let error = error else { expectation.fulfill() return } XCTFail("Error: \(error.localizedDescription)") } waitForExpectations(timeout: 5) { (error) in } } func testDetailsWeather() { let expectation = self.expectation(description: "Detail Weather Expectation 200") let location = Location(lat: "48.8", lon: "2.1833") weatherWorker.fetchWeatherDetails(location: location) { (weather) in expectation.fulfill() } onError: { (error) in XCTFail("Error: \(error?.localizedDescription ?? "Error")") } waitForExpectations(timeout: 5) { (error) in } } }
32.263158
111
0.623165
f56d0b28c40b2562038d977d11c2168ec40bcf9b
2,392
// // AppDelegate.swift // SlideKitTestApp // // Created by Kyler Jensen on 7/3/18. // Copyright © 2018 Kyler Jensen. All rights reserved. // import UIKit import GSTouchesShowingWindow_Swift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private lazy var touchesWindow: GSTouchesShowingWindow = GSTouchesShowingWindow(frame: UIScreen.main.bounds) var window: UIWindow? { get { return touchesWindow } set {} } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46
285
0.752508
db42c0de5df9b9c43056a151939577ad20e7c059
5,939
import UIKit protocol HeaderViewDelegate: class { func headerView(_ headerView: HeaderView, didPressDeleteButton deleteButton: UIButton) func headerView(_ headerView: HeaderView, didPressCloseButton closeButton: UIButton) func headerView(_ headerView: HeaderView, didPressDownloadButton downloadButton: UIButton) } public enum HeaderViewChildPosition { case start case center case end } open class HeaderView: UIView { open fileprivate(set) lazy var closeButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.CloseButton.text, attributes: LightboxConfig.CloseButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: UIControl.State()) if let size = LightboxConfig.CloseButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(closeButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.CloseButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.CloseButton.enabled return button }() open fileprivate(set) lazy var downloadButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.DownloadButton.text, attributes: LightboxConfig.DownloadButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: UIControl.State()) if let size = LightboxConfig.DownloadButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(downloadButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.DownloadButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.DownloadButton.enabled return button }() open fileprivate(set) lazy var activityIndicator: UIActivityIndicatorView = { [unowned self] in let activityIndicator = UIActivityIndicatorView(style: .white) if let size = LightboxConfig.DownloadButton.size { activityIndicator.frame.size = size } else { activityIndicator.sizeToFit() } activityIndicator.isHidden = true return activityIndicator }() open fileprivate(set) lazy var deleteButton: UIButton = { [unowned self] in let title = NSAttributedString( string: LightboxConfig.DeleteButton.text, attributes: LightboxConfig.DeleteButton.textAttributes) let button = UIButton(type: .system) button.setAttributedTitle(title, for: .normal) if let size = LightboxConfig.DeleteButton.size { button.frame.size = size } else { button.sizeToFit() } button.addTarget(self, action: #selector(deleteButtonDidPress(_:)), for: .touchUpInside) if let image = LightboxConfig.DeleteButton.image { button.setBackgroundImage(image, for: UIControl.State()) } button.isHidden = !LightboxConfig.DeleteButton.enabled return button }() let gradientColors = LightboxConfig.Header.gradientColors weak var delegate: HeaderViewDelegate? // MARK: - Initializers public init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.clear if LightboxConfig.Header.displayGradient { _ = addGradientLayer(gradientColors) } [closeButton, deleteButton, downloadButton, activityIndicator].forEach { addSubview($0) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() if LightboxConfig.Header.displayGradient { resizeGradientLayer() } } // MARK: - Actions @objc func deleteButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressDeleteButton: button) } @objc func closeButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressCloseButton: button) } @objc func downloadButtonDidPress(_ button: UIButton) { delegate?.headerView(self, didPressDownloadButton: button) } func showActivityIndicator() { activityIndicator.startAnimating() activityIndicator.isHidden = false downloadButton.isHidden = true } func hideActivityIndicator() { activityIndicator.stopAnimating() activityIndicator.isHidden = true downloadButton.isHidden = false } } // MARK: - LayoutConfigurable extension HeaderView: LayoutConfigurable { @objc public func configureLayout() { let topPadding = getTopOrigin().y + LightboxConfig.Header.topPadding closeButton.frame.origin = CGPoint( x: getX(position: LightboxConfig.CloseButton.position, buttonWidth: closeButton.frame.width), y: topPadding ) downloadButton.frame.origin = CGPoint( x: getX(position: LightboxConfig.DownloadButton.position, buttonWidth: downloadButton.frame.width), y: topPadding ) activityIndicator.frame.origin = downloadButton.frame.origin deleteButton.frame.origin = CGPoint( x: getX(position: LightboxConfig.DeleteButton.position, buttonWidth: deleteButton.frame.width), y: topPadding ) } fileprivate func getX(position: HeaderViewChildPosition, buttonWidth: CGFloat) -> CGFloat { // Side padding depending on the layout orientation, iOS version (11 vs lower), and if it's iPhone X or not. let sidePadding = getTopOrigin().x switch position { case .start: return 17 + sidePadding case .center: return (self.frame.width - buttonWidth) / 2 case .end: return bounds.width - buttonWidth - 17 - sidePadding } } }
28.830097
112
0.692878
56e7d6504aa12de61f2697523b5c736cebdcf92c
3,042
// // Quaternions.swift // SwiftMath // // Created by Matteo Battaglio on 21/03/15. // Copyright (c) 2015 Matteo Battaglio. All rights reserved. // import Foundation public struct Quaternion<Real: RealType> : Equatable { public let re: Real public let im: Vector3<Real> public let isReal: Bool public init(_ re: Real, _ im: Vector3<Real>) { self.re = re self.im = im isReal = im == Vector3.zero() } public init(axis: Vector3<Real>, angle: Real) { assert(axis.length == 1.0, "axis is not a unit-length vector") let halfAngle = angle/2.0 self.init(halfAngle.cos(), axis * halfAngle.sin()) } public static func id() -> Quaternion<Real> { return Quaternion(1.0, .zero()) } public var squareLength: Real { return re * re + im * im } public var length: Real { return norm } public var norm: Real { return squareLength.sqrt() } public func unit() -> Quaternion<Real> { return self / length } public func conj() -> Quaternion<Real> { return Quaternion(re, -im) } public func reciprocal() -> Quaternion<Real> { return self.conj() / squareLength } } public func == <Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Bool { return lhs.re == rhs.re && lhs.im == rhs.im } public func + <Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Quaternion<Real> { return Quaternion(lhs.re + rhs.re, lhs.im + rhs.im) } public func - <Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Quaternion<Real> { return Quaternion(lhs.re - rhs.re, lhs.im - rhs.im) } public func * <Real: RealType>(lhs: Real, rhs: Quaternion<Real>) -> Quaternion<Real> { return Quaternion(rhs.re * lhs, rhs.im * lhs) } public func * <Real: RealType>(lhs: Quaternion<Real>, rhs: Real) -> Quaternion<Real> { return rhs * lhs } public func / <Real: RealType>(quaternion: Quaternion<Real>, scalar: Real) -> Quaternion<Real> { return 1.0/scalar * quaternion } /// Dot product public func dotProduct<Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Real { return lhs.re * rhs.re + lhs.im * rhs.im } /// Dot product public func * <Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Real { return dotProduct(lhs, rhs: rhs) } public func multiply<Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Quaternion<Real> { let re = lhs.re * rhs.re - lhs.im * rhs.im let im = lhs.re * rhs.im + rhs.re * lhs.im + lhs.im × rhs.im return Quaternion(re, im) } infix operator × { associativity left precedence 150 } /// Multiplication public func × <Real: RealType>(lhs: Quaternion<Real>, rhs: Quaternion<Real>) -> Quaternion<Real> { return multiply(lhs, rhs: rhs) } extension Quaternion: CustomStringConvertible { public var description: String { return "(re: \(re), im: \(im))" } }
26.920354
104
0.617028
46b5bb1dca30791d6d93ec3339aceee503fd754c
2,534
// // shop.swift // DeepDungeonsOfDoom // // Created by Jesús García on 06/01/2019. // Copyright © 2019 Jesús García. All rights reserved. // import Foundation import UIKit class shop: ViewController { @IBOutlet weak var money: UILabel! @IBOutlet weak var pickerview: UIPickerView! var modelpicker: modelPicker! @IBOutlet weak var buybutton: UIButton! @IBOutlet weak var errormoney: UILabel! @IBOutlet weak var errordisp: UILabel! @IBOutlet weak var buy: UILabel! override func viewDidLoad() { money.text = String(myHeroes[heroinuse].getCoins()) errormoney.isHidden = true errordisp.isHidden = true buy.isHidden = true modelpicker = modelPicker() modelpicker.modelData = myItems pickerview.delegate = modelpicker pickerview.dataSource = modelpicker } @IBAction func buy(_ sender: Any) { if myItems[rowSelected].price > myHeroes[heroinuse].coins { errordisp.isHidden = true errormoney.isHidden = false buy.isHidden = true } else if myItems[rowSelected].type == "unavaiable" { errormoney.isHidden = true errordisp.isHidden = false buy.isHidden = true } else { switch(myItems[rowSelected].type) { case "pechera": myHeroes[heroinuse].setNewItem(position: 1, item: myItems[rowSelected]) break case "casco": myHeroes[heroinuse].setNewItem(position: 0, item: myItems[rowSelected]) break case "botas": myHeroes[heroinuse].setNewItem(position: 2, item: myItems[rowSelected]) break case "escudo": myHeroes[heroinuse].setNewItem(position: 3, item: myItems[rowSelected]) break; case "arma": myHeroes[heroinuse].setNewItem(position: 4, item: myItems[rowSelected]) break case "accesorio": myHeroes[heroinuse].setNewItem(position: 5, item: myItems[rowSelected]) break default: break } myHeroes[heroinuse].coinsChanged(coins: myHeroes[heroinuse].coins - myItems[rowSelected].price) money.text = String(myHeroes[heroinuse].getCoins()) errormoney.isHidden = true errordisp.isHidden = true buy.isHidden = false } } }
33.342105
107
0.582084
509d774b29ebb2ed7e9106e75f3f2fc76c045984
2,308
// // SceneDelegate.swift // SevenWondersStatTracker // // Created by Martin Peshevski on 3.7.21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.54717
147
0.714905