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
1ae7f1e86d276b0c18fd8d6ba7c2a1aa8107e002
387
import files; import string; import io; import sys; @dispatch=coasters app (file out, file err) date () { "/bin/date" @stderr=err @stdout=out; } /** * Test coaster output file location functionality */ main() { argv_accept("d"); string dir = argv("d"); file f_out<strcat(dir, "/test2.out")>; file f_err<strcat(dir, "/test2.err")>; (f_out, f_err) = date(); }
16.826087
50
0.620155
1ca1dbbfface76e0c529e538713fb74a016d2ae2
4,787
// // TimeAgoTests.swift // DateTools // // Created by David Gileadi on 1/24/17. // Copyright © 2017 CodeWise sp. z o.o. Sp. k. All rights reserved. // import XCTest import Nimble @testable import DateTools class TimeAgoTests: XCTestCase { var formatter: DateFormatter! var date0: Date! var date1: Date! override func setUp() { super.setUp() self.formatter = DateFormatter() self.formatter.dateFormat = "yyyy MM dd HH:mm:ss.SSS" self.date0 = self.formatter.date(from: "2014 11 05 18:15:12.000")! self.date1 = self.formatter.date(from: "2014 11 07 18:15:12.000")! } func testBasicLongTimeAgo() { let now = self.date0.timeAgo(since: self.date0) expect(now).toNot(beEmpty(), description: "'Now' is nil or empty.") let ago = self.date1.timeAgo(since: self.date0) expect(ago).toNot(beEmpty(), description: "Ago is nil or empty.") } func testLongTimeAgo2Days() { self.date0 = self.formatter.date(from: "2014 11 05 18:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("2 days ago") } func testLongTimeAgo1DayAndHalf() { self.date0 = self.formatter.date(from: "2014 11 06 9:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("Yesterday") } func testLongTimeAgoExactlyYesterday() { self.date0 = self.formatter.date(from: "2014 11 06 18:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("Yesterday") } func testLongTimeAgoLessThan24hoursButYesterday() { self.date0 = self.formatter.date(from: "2014 11 06 20:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("22 hours ago") } func testLongTimeAgoLessThan24hoursSameDay() { self.date0 = self.formatter.date(from: "2014 11 07 10:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("8 hours ago") } func testLongTimeAgoBetween24And48Hours() { self.date0 = self.formatter.date(from: "2014 11 07 10:15:12.000")! self.date1 = self.formatter.date(from: "2014 11 08 18:15:12.000")! let ago = self.date0.timeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("Yesterday") } func testBasicShortTimeAgo() { let now = self.date0.shortTimeAgo(since: self.date0) expect(now).toNot(beEmpty(), description: "'Now' is nil or empty.") let ago = self.date1.shortTimeAgo(since: self.date0) expect(ago).toNot(beEmpty(), description: "Ago is nil or empty.") } func testShortTimeAgo2Days() { self.date0 = self.formatter.date(from: "2014 11 05 18:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("2d") } func testShortTimeAgo1DayAndHalf() { self.date0 = self.formatter.date(from: "2014 11 06 9:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("1d") } func testShortTimeAgoExactlyYesterday() { self.date0 = self.formatter.date(from: "2014 11 06 18:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("1d") } func testShortTimeAgoLessThan24hoursButYesterday() { self.date0 = self.formatter.date(from: "2014 11 06 20:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("22h") } func testShortTimeAgoLessThan24hoursSameDay() { self.date0 = self.formatter.date(from: "2014 11 07 10:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("8h") } func testShortTimeAgoBetween24And48Hours() { self.date0 = self.formatter.date(from: "2014 11 07 10:15:12.000")! self.date1 = self.formatter.date(from: "2014 11 08 18:15:12.000")! let ago = self.date0.shortTimeAgo(since: self.date1) expect(ago) == DateToolsLocalizedStrings("1d") } func testLongTimeAgoLocalizationsAccessible() { let en_local = "Yesterday" let ja_local = "昨日" let key = en_local let url = Bundle(for: TimePeriodCollection.self).bundleURL.appendingPathComponent("DateTools.bundle/ja.lproj") let bundle = Bundle(url: url) expect(bundle).toNot(beNil()) if (bundle != nil) { let ja_result = NSLocalizedString(key, tableName: "DateTools", bundle: bundle!, comment: key) expect(ja_local) == ja_result } } }
34.941606
112
0.659703
e8a68ea04112ea0d905ea3a4c7160a91806660f0
1,661
/* * Copyright 2017 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public struct CollectionSummary: Codable { public let id: Int public let name: String public var poster: Image? { return Image(path: posterPath, config: config.posterConfig) } public var backdrop: Image? { return Image(path: backdropPath, config: config.backdropConfig) } private let posterPath: String? private let backdropPath: String? private let config: Configuration public init(from decoder: Decoder) throws { guard let config = decoder.userInfo[.configuration] as? Configuration else { fatalError("Missing configuration or invalid configuration") } let values = try decoder.container(keyedBy: CodingKeys.self) id = try values.decode(Int.self, forKey: .id) name = try values.decode(String.self, forKey: .name) posterPath = try? values.decode(String.self, forKey: .posterPath) backdropPath = try? values.decode(String.self, forKey: .backdropPath) self.config = config } }
33.897959
84
0.685731
264e570a2dff52e4401eab115e271c3af25f116c
6,269
// // ChatTitleViewModelSpec.swift // Rocket.ChatTests // // Created by Rafael Kellermann Streit on 11/23/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import XCTest @testable import Rocket_Chat class ChatTitleViewModelSpec: XCTestCase { func testInitialState() { let model = ChatTitleViewModel() XCTAssertNil(model.subscription, "subscription is nil") XCTAssertEqual(model.iconColor, .RCGray(), "default color is gray") XCTAssertEqual(model.imageName, "Channel Small", "default icon is hashtag") XCTAssertEqual(model.title, "", "title is empty string") } func testClearState() { let model = ChatTitleViewModel() model.subscription = nil model.user = nil XCTAssertNil(model.subscription, "subscription is nil") XCTAssertEqual(model.iconColor, .RCGray(), "default color is gray") XCTAssertEqual(model.imageName, "Channel Small", "default icon is hashtag") XCTAssertEqual(model.title, "", "title is empty string") } func testSubscriptionChannel() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNil(model.user, "user is nil") XCTAssertEqual(model.iconColor, .RCGray(), "channel color is gray") XCTAssertEqual(model.imageName, "Channel Small", "channel icon is hashtag") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionGroup() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "p" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNil(model.user, "user is nil") XCTAssertEqual(model.iconColor, .RCGray(), "group color is gray") XCTAssertEqual(model.imageName, "Group Small", "group icon is lock") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionUserOffline() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "d" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription let user = User.testInstance() user.status = .offline model.user = user.unmanaged XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNotNil(model.user, "user isn't nil") XCTAssertEqual(model.iconColor, .RCGray(), "color is gray") XCTAssertEqual(model.imageName, "DM Small", "icon is mention") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionUserOnline() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "d" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription let user = User.testInstance() user.status = .online model.user = user.unmanaged XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNotNil(model.user, "user isn't nil") XCTAssertEqual(model.iconColor, .RCOnline(), "color is online") XCTAssertEqual(model.imageName, "DM Small", "icon is mention") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionUserAway() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "d" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription let user = User.testInstance() user.status = .away model.user = user.unmanaged XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNotNil(model.user, "user isn't nil") XCTAssertEqual(model.iconColor, .RCAway(), "color is online") XCTAssertEqual(model.imageName, "DM Small", "icon is mention") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionUserBusy() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "d" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription let user = User.testInstance() user.status = .busy model.user = user.unmanaged XCTAssertNotNil(model.subscription, "subscription isn't nil") XCTAssertNotNil(model.user, "user isn't nil") XCTAssertEqual(model.iconColor, .RCBusy(), "color is busy") XCTAssertEqual(model.imageName, "DM Small", "icon is mention") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } func testSubscriptionUserNilAfterSubscriptionUpdate() { let model = ChatTitleViewModel() let subscription = Subscription.testInstance() subscription.privateType = "c" let unmanagedSubscription = subscription.unmanaged model.subscription = unmanagedSubscription let user = User.testInstance() user.status = .busy model.user = user.unmanaged model.subscription = subscription.unmanaged XCTAssertNotNil(model.subscription, "subscription is nil") XCTAssertEqual(model.iconColor, .RCGray(), "default color is gray") XCTAssertEqual(model.imageName, "Channel Small", "default icon is hashtag") XCTAssertEqual(model.title, unmanagedSubscription?.displayName, "title is subscription displayName()") } }
39.18125
110
0.688467
f5319242cae24542e8aaa9825a73a3b3fbd4d96b
3,734
// // AppDelegate.swift // CompatibilitySlider-Start // // Created by Jay Strawn on 6/16/20. // Copyright © 2020 Jay Strawn. All rights reserved. // import UIKit import CoreData @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. } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "CompatibilitySlider_Start") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
44.987952
199
0.671398
23255a2ae999d33855e9e545f2550cde51390734
814
// // MockKeyboardInputSetProvider.swift // KeyboardKit // // Created by Daniel Saidi on 2021-02-08. // Copyright © 2021 Daniel Saidi. All rights reserved. // import KeyboardKit import MockingKit class MockKeyboardInputSetProvider: Mock, KeyboardInputSetProvider { var alphabeticInputSetValue: AlphabeticKeyboardInputSet = AlphabeticKeyboardInputSet(rows: []) var numericInputSetValue: NumericKeyboardInputSet = NumericKeyboardInputSet(rows: []) var symbolicInputSetValue: SymbolicKeyboardInputSet = SymbolicKeyboardInputSet(rows: []) func alphabeticInputSet() -> AlphabeticKeyboardInputSet { alphabeticInputSetValue } func numericInputSet() -> NumericKeyboardInputSet { numericInputSetValue } func symbolicInputSet() -> SymbolicKeyboardInputSet { symbolicInputSetValue } }
37
98
0.783784
335f4157013543deaf8d82f4cda979eada350a5d
336
// // Observable+Threading.swift // Persist // // Created by Fatih Şen on 15.02.2020. // Copyright © 2020 Fatih Şen. All rights reserved. // import Foundation import RxSwift extension ObservableType { public func async() -> Observable<E> { return self.subscribeOn(Schedulers.io()) .observeOn(Schedulers.mainThread()) } }
17.684211
52
0.702381
fcfc1e17c770b1280b9a89fbd0bdd84560bee5d2
3,663
// // ViewController.swift // MapKitTutorial // // Created by HungNV on 7/31/18. // Copyright © 2018 HungNV. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! let initialLocation = CLLocation(latitude: 10.783376, longitude: 106.689918) let regionRadius: CLLocationDistance = 500 var artworks: [Artwork] = [] override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self loadInitialData() mapView.addAnnotations(artworks) // centerMapOnLocation(location: initialLocation) // let artwork = Artwork(title: "Vitalify ASIA", locationName: "224A - 224B Dien Bien Phu P.7 Q.3 HCM", discripline: "Sortware development", coordinate: CLLocationCoordinate2D(latitude: 10.783376, longitude: 106.689918)) // mapView.addAnnotation(artwork) } func loadInitialData() { guard let fileName = Bundle.main.path(forResource: "PublicArt", ofType: "json") else { return } let optionalData = try? Data(contentsOf: URL(fileURLWithPath: fileName)) if let data = optionalData { do { let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) if let object = jsonObject as? [NSString: AnyObject]{ if let allDevices = object["data"] as? [[NSString: AnyObject]]{ print("Successfull") print(allDevices) } } } catch { print("Error Eccurred") } } // guard let data = optionalData else { return } // let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) // // let dictionary = json as? [String: Any] // let works = dictionary["data"] as? [[Any]] // let validWorks = works.flatMap { Artwork(json: $0) } // artworks.append(contentsOf: validWorks) } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius) mapView.setRegion(coordinateRegion, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? Artwork else { return nil } let identifier = "marker" var view: MKMarkerAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView { dequeuedView.annotation = annotation view = dequeuedView } else { view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: 0, y: 0) view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } return view } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let location = view.annotation as? Artwork { let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking] location.mapItem().openInMaps(launchOptions: launchOptions) } } }
37.762887
227
0.636637
e20b1a61d676820809eff4a3b068b505251bc32e
911
// // Globals.swift // CucumberSwift // // Created by Tyler Thompson on 8/25/18. // Copyright © 2018 Tyler Thompson. All rights reserved. // import Foundation //MARK: Hooks public func BeforeFeature(closure: @escaping ((Feature) -> Void)) { Cucumber.shared.beforeFeatureHooks.append(closure) } public func AfterFeature(closure: @escaping ((Feature) -> Void)) { Cucumber.shared.afterFeatureHooks.append(closure) } public func BeforeScenario(closure: @escaping ((Scenario) -> Void)) { Cucumber.shared.beforeScenarioHooks.append(closure) } public func AfterScenario(closure: @escaping ((Scenario) -> Void)) { Cucumber.shared.afterScenarioHooks.append(closure) } public func BeforeStep(closure: @escaping ((Step) -> Void)) { Cucumber.shared.beforeStepHooks.append(closure) } public func AfterStep(closure: @escaping ((Step) -> Void)) { Cucumber.shared.afterStepHooks.append(closure) }
30.366667
69
0.73326
9becd4bb0f4a5ea5b3c58bf4d1ed2b920958cd8b
2,806
// // FIRDatabase.swift // Firebase_HelloWorld // // Created by William on 2019/6/11. // Copyright © 2019 William. All rights reserved. // import UIKit import FirebaseDatabase // MARK: - Firebase工具 class FIRDatabase: NSObject { public static let shard = FIRDatabase() public let database = Database.database().reference() private override init() { super.init() } } // MARK: - 主工具 extension FIRDatabase { /// 取值 (單次 / 及時) func childValueFor(type: RealtimeDatabaseType, withPath path: String, result: @escaping ((Any?) -> Void)) { switch type { case .single: childValueForSingle(withPath: path) { (value) in result(value) } case .realtime: childValueForRealtime(withPath: path) { (value) in result(value) } } } /// 設定數據 func setChildValue(withPath path: String, value: Any, result: @escaping ((Any?) -> Void)) { let isOK = true database.child(path).setValue(value) { (error, database) in if error != nil { result(!isOK); return } result(isOK) } } /// 更新數據 func updateChildValue(withPath path: String, values: [String: Any], result: @escaping ((Any?) -> Void)) { let isOK = true database.child(path).updateChildValues(values) { (error, database) in if error != nil { result(!isOK); return } result(isOK) } } /// 移除數據 func removeChildValue(withPath path: String, result: @escaping ((Any?) -> Void)) { let isOK = true database.child(path).removeValue { (error, database) in if error != nil { result(!isOK); return } result(isOK) } } /// 查詢數據 func queryChildValue(withPath path: String, byKey key: String, value: Int, result: @escaping ((Any?) -> Void)) { database.child(path).queryOrdered(byChild: key).queryEqual(toValue: value).observe(.value, with: { (snapshot) in result(snapshot.value) }, withCancel: { error in result(nil) }) } } // MARK: - 小工具 extension FIRDatabase { /// 取值 (單次) private func childValueForSingle(withPath path: String, result: @escaping ((Any?) -> Void)) { database.child(path).observeSingleEvent(of: .value, with: { (snapshot) in result(snapshot.value) }, withCancel: { (error) in result(nil) }) } /// 取值 (及時) private func childValueForRealtime(withPath path: String, result: @escaping ((Any?) -> Void)) { database.child(path).observe(.value, with: { (snapshot) in result(snapshot.value) }, withCancel: { (error) in result(nil) }) } }
28.06
120
0.565574
1a9c3f25a8affe1d922a699329ccbf4e9caa8d4d
7,309
// // Point2D.swift // Geometry // // Created by Eric Ito on 10/26/15. // Copyright © 2015 Eric Ito. All rights reserved. // import Foundation /** Basic 2D point class. Contains only two double fields. */ public final class Point2D { private static let serialVersionUID: Int64 = 1 public private(set) var x: Double = 0 public private(set) var y: Double = 0 public init() {} public init(x: Double, y: Double) { self.x = x self.y = y } public func setCoords(x: Double, y: Double) { self.x = x self.y = y } public func setCoords(other: Point2D) { x = other.x y = other.y } public func isEqual(other: Point2D) -> Bool { return x == other.x && y == other.y } public func isEqual(x: Double, y: Double) -> Bool { return self.x == x && self.y == y } public func isEqual(other: Point2D, tol: Double) -> Bool { return (abs(x - other.x) <= tol) && (abs(y - other.y) <= tol) } public func equals(other: Point2D) -> Bool { return x == other.x && y == other.y } //FIXME: // @Override // public boolean equals(Object other) { // if (other == this) // return true; // // if (!(other instanceof Point2D)) // return false; // // Point2D v = (Point2D)other; // // return x == v.x && y == v.y; // } public func sub(other: Point2D) { x -= other.x y -= other.y } public func sub(p1: Point2D, p2: Point2D) { x = p1.x - p2.x y = p1.y - p2.y } public func add(other: Point2D) { x += other.x y += other.y } public func add(p1: Point2D, p2: Point2D) { x = p1.x + p2.x y = p1.y + p2.y } public func negate() { x = -x y = -y } public func negate(other: Point2D) { x = -other.x y = -other.y } public func interpolate(other: Point2D, alpha: Double) { x = x * (1.0 - alpha) + other.x * alpha y = y * (1.0 - alpha) + other.y * alpha } public func interpolate(p1: Point2D, p2: Point2D, alpha: Double) { x = p1.x * (1.0 - alpha) + p2.x * alpha y = p1.y * (1.0 - alpha) + p2.y * alpha } public func scaleAdd(f: Double, shift: Point2D) { x = x * f + shift.x y = y * f + shift.y } public func scaleAdd(f: Double, other: Point2D, shift: Point2D) { x = other.x * f + shift.x y = other.y * f + shift.y } public func scale(f: Double, other: Point2D) { x = f * other.x y = f * other.y } public func scale(f: Double) { x *= f y *= f } /** Compares two vertices lexicographicaly. */ public func compare(other: Point2D) -> Int { return y < other.y ? -1 : (y > other.y ? 1 : (x < other.x ? -1 : (x > other.x ? 1 : 0))) } public func normalize(other: Point2D) { let len = other.length(); if len == 0 { x = 1.0 y = 0.0 } else { x = other.x / len y = other.y / len } } public func normalize() { let len = length() if len == 0 { x = 1.0 y = 0.0 } x /= len y /= len } public func length() -> Double { return sqrt(x * x + y * y) } public func sqrLength() -> Double { return x * x + y * y } public class func distance(pt1: Point2D, pt2: Point2D) -> Double { return sqrt(sqrDistance(pt1, pt2)) } public func dotProduct(other: Point2D) -> Double { return x * other.x + y * other.y } func dotProductAbs(other: Point2D) -> Double { return abs(x * other.x) + abs(y * other.y) } public func crossProduct(other: Point2D) -> Double { return x * other.y - y * other.x } public func rotateDirect(Cos: Double, Sin: Double) { // corresponds to the // Transformation2D.SetRotate(cos, // sin).Transform(pt) let xx = x * Cos - y * Sin let yy = x * Sin + y * Cos x = xx y = yy } public func rotateReverse(Cos: Double, Sin: Double) { let xx = x * Cos + y * Sin let yy = -x * Sin + y * Cos x = xx y = yy } /** 90 degree rotation, anticlockwise. Equivalent to RotateDirect(cos(pi/2), sin(pi/2)). */ public func leftPerpendicular() { let xx = x x = -y y = xx } /** 90 degree rotation, anticlockwise. Equivalent to RotateDirect(cos(pi/2), sin(pi/2)). */ public func leftPerpendicular(pt: Point2D) { x = -pt.y y = pt.x } /** 270 degree rotation, anticlockwise. Equivalent to RotateDirect(-cos(pi/2), sin(-pi/2)). */ public func rightPerpendicular() { let xx = x x = y y = -xx } /** 270 degree rotation, anticlockwise. Equivalent to RotateDirect(-cos(pi/2), sin(-pi/2)). */ public func rightPerpendicular(pt: Point2D) { x = pt.y y = -pt.x } func setNan() { x = NumberUtils.NaN() y = NumberUtils.NaN() } func isNan() -> Bool { return NumberUtils.isNaN(x) } /** Calculates which quarter of xy plane the vector lies in. First quater is between vectors (1,0) and (0, 1), second between (0, 1) and (-1, 0), etc. The quarters are numbered counterclockwise. Angle intervals corresponding to quarters: 1 : [0 : 90); 2 : [90 : 180); 3 : [180 : 270); 4 : [270 : 360) */ final func quarter() -> Int { if x > 0 { if y >= 0 { return 1 // x > 0 && y <= 0 } else { // y < 0 && x > 0. Should be x >= 0 && y < 0. The x == // 0 case is processed later. return 4 } } else { if y > 0 { return 2 // x <= 0 && y > 0 } else { // 3: x < 0 && y <= 0. The case x == 0 && // y <= 0 is attribute to the case 4. // The point x==0 and y==0 is a bug, but // will be assigned to 4. return x == 0 ? 4 : 3 } } } /** Assume vector v1 and v2 have same origin. The function compares the vectors by angle in the counter clockwise direction from the axis X. For example, V1 makes 30 degree angle counterclockwise from horizontal x axis V2, makes 270, V3 makes 90, then compareVectors(V1, V2) == -1. compareVectors(V1, V3) == -1. compareVectors(V2, V3) == 1. @return Returns 1 if v1 is less than v2, 0 if equal, and 1 if greater. */ public class func compareVectors(v1: Point2D, v2: Point2D) -> Int { let q1 = v1.quarter() let q2 = v2.quarter() if q2 == q1 { let cross = v1.crossProduct(v2) return cross < 0 ? 1 : (cross > 0 ? -1 : 0) } else { return q1 < q2 ? -1 : 1 } } }
24.860544
82
0.478041
fc3399fecec90778837d4a63ff03656fe6e94fab
1,535
// 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: "DangerSwiftEda", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "DangerSwiftEda", targets: ["DangerSwiftEda"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), .package(name: "danger-swift", url: "https://github.com/danger/swift.git", from: "3.0.0"), .package(name: "DangerSwiftHammer", url: "https://github.com/el-hoshino/DangerSwiftHammer", from: "0.2.0"), .package(name: "DangerSwiftShoki", url: "[email protected]:yumemi/danger-swift-shoki.git", from: "0.1.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "DangerSwiftEda", dependencies: [ .product(name: "Danger", package: "danger-swift"), "DangerSwiftHammer", "DangerSwiftShoki", ]), .testTarget( name: "DangerSwiftEdaTests", dependencies: ["DangerSwiftEda"]), ] )
42.638889
122
0.616287
337fd92f9b302b1eb38888d878d6c65e4ed9ef88
3,168
import Foundation import UIKit extension FileManager { func createTemporaryDirectory() throws -> URL { let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString) try createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) return url } } public extension UIView { func getSuperView(typeClass: AnyClass) -> UIView? { weak var view : UIView? = self while view != nil, !view!.isKind(of: typeClass) { view = view!.superview } if view != nil && view!.isKind(of: typeClass) { return view } return nil } } public extension CGRect { func center() -> CGPoint { return CGPoint.init(x: self.origin.x + self.size.width / 2.0, y: self.origin.y + self.size.height / 2.0) } } public extension CGPoint { func applyOffset(x: CGFloat, y: CGFloat) -> CGPoint { return CGPoint.init(x: self.x + x, y: self.y + y) } } public extension NSObject { class func getClassHierarchy() -> [AnyClass] { var hierarcy = [AnyClass]() hierarcy.append(self.classForCoder()) var currentSuper: AnyClass? = class_getSuperclass(self.classForCoder()) while currentSuper != nil { hierarcy.append(currentSuper!) currentSuper = class_getSuperclass(currentSuper) } return hierarcy } class func getAllClasses() -> [AnyClass] { let expectedClassCount = objc_getClassList(nil, 0) let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(expectedClassCount)) let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass>(allClasses) let actualClassCount: Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount) var classes = [AnyClass]() for i in 0 ..< actualClassCount { if let currentClass: AnyClass = allClasses[Int(i)] { classes.append(currentClass) } } allClasses.deallocate() return classes } class func directSubclasses() -> [AnyClass] { var result: Array<AnyClass> = [] let expectedClassCount = objc_getClassList(nil, 0) let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(expectedClassCount)) let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass>(allClasses) let actualClassCount: Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount) for i in 0 ..< actualClassCount { if let currentClass: AnyClass = allClasses[Int(i)] { guard let currentSuper = class_getSuperclass(currentClass) else { continue } if (String(describing: currentSuper) == String(describing: self)) { result.append(currentClass) } } } allClasses.deallocate() return result } }
30.171429
112
0.600379
fe1b3e86c3e0a4289a36939d95eb8c3443572662
892
// // LPCustomInputToolBar.swift // LPInputViewDemo // // Created by pengli on 2018/4/16. // Copyright © 2018年 pengli. All rights reserved. // import UIKit class LPCustomInputToolBar: UIView { @IBOutlet weak var emotionButton: UIButton! @IBOutlet weak var atButton: UIButton! @IBOutlet weak var loationButton: UIButton! class func instance() -> LPCustomInputToolBar? { guard let views = Bundle.main.loadNibNamed("LPCustomInputToolBar", owner: self, options: nil) else { return nil } return views.first as? LPCustomInputToolBar } deinit { print("LPCustomInputToolBar: -> release memory.") } override func awakeFromNib() { super.awakeFromNib() } override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: UIScreen.main.bounds.width, height: size.height) } }
26.235294
121
0.661435
1c0db2b4843edc22848cd041f45cb5e44ed89b60
1,134
// // PhotoCell.swift // EquilateralLayoutDemo // // Created by Kristopher Baker on 11/19/15. // Copyright © 2015 Kris Baker. All rights reserved. // import UIKit import SDWebImage typealias EquilateralPhotoItem = (photoURL: NSURL!, strokeColor: UIColor!) class EquilateralPhotoCell: UICollectionViewCell { static let ReuseIdentifier = "EquilateralPhotoCell" let equilateralPhotoView = EquilateralPhotoView(frame: CGRectZero) override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() self.contentView.backgroundColor = UIColor.clearColor() self.equilateralPhotoView.frame = CGRectMake(0, 0, frame.width, frame.height) self.contentView.addSubview(self.equilateralPhotoView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(item: EquilateralPhotoItem) { self.equilateralPhotoView.strokeColor = item.strokeColor self.equilateralPhotoView.imageView.sd_setImageWithURL(item.photoURL) } }
29.842105
85
0.703704
165aa25056344c4b08dd10e3bd6d8f095c271d81
1,566
import ComposableGameCenter import Foundation import SharedModels import Tagged public struct TurnBasedContext: Equatable { public var localPlayer: LocalPlayer public var match: TurnBasedMatch public var metadata: TurnBasedMatchData.Metadata public init( localPlayer: LocalPlayer, match: TurnBasedMatch, metadata: TurnBasedMatchData.Metadata ) { self.localPlayer = localPlayer self.match = match self.metadata = metadata } public var currentParticipantIsLocalPlayer: Bool { self.match.currentParticipant?.player?.gamePlayerId == self.localPlayer.gamePlayerId } public var lastPlayedAt: Date { self.match.participants.lazy.compactMap(\.lastTurnDate).max() ?? self.match.creationDate } public var localParticipant: TurnBasedParticipant? { self.match.participants .first { $0.player?.gamePlayerId == self.localPlayer.gamePlayerId } } public var localPlayerIndex: Move.PlayerIndex? { self.match.participants .firstIndex(where: { $0.player?.gamePlayerId == self.localPlayer.gamePlayerId }) .map(Tagged.init(rawValue:)) } public var otherParticipant: TurnBasedParticipant? { self.match.participants .first { $0.player?.gamePlayerId != self.localPlayer.gamePlayerId } } public var otherPlayer: ComposableGameCenter.Player? { self.otherParticipant?.player } public var otherPlayerIndex: Move.PlayerIndex? { self.match.participants .firstIndex { $0.player?.gamePlayerId != self.localPlayer.gamePlayerId } .map(Tagged.init(rawValue:)) } }
28.472727
92
0.737548
f7e9b58bba25117b599cdb66971d1872d500a5c9
11,013
// // MBInAppMessageBottomBannerView.swift // MBInAppMessage // // Created by Lorenzo Oliveto on 17/03/2020. // Copyright © 2020 Lorenzo Oliveto. All rights reserved. // import UIKit /// This view is displayed as a banner coming from the bottom when the in app message has the style `MBInAppMessageStyle.bottomBanner` public class MBInAppMessageBottomBannerView: MBInAppMessageView { var bottomConstraintHidden: NSLayoutConstraint? var bottomConstraintNotHidden: NSLayoutConstraint? override func configure() { let padding: CGFloat = 10 layer.shadowColor = UIColor(white: 162.0 / 255, alpha: 1).cgColor layer.shadowOpacity = 0.37 layer.shadowOffset = CGSize.zero layer.shadowRadius = 10 let mainContainer = UIView(frame: .zero) mainContainer.layer.cornerRadius = 10 mainContainer.clipsToBounds = true mainContainer.translatesAutoresizingMaskIntoConstraints = false addSubview(mainContainer) NSLayoutConstraint.activate([ mainContainer.leadingAnchor.constraint(equalTo: leadingAnchor), mainContainer.trailingAnchor.constraint(equalTo: trailingAnchor), mainContainer.topAnchor.constraint(equalTo: topAnchor), mainContainer.bottomAnchor.constraint(equalTo: bottomAnchor) ]) guard let inAppMessage = message.inAppMessage else { return } let backgroundStyle = styleDelegate?.backgroundStyle(forMessage: inAppMessage) ?? MBInAppMessageViewStyle.backgroundStyle(forMessage: inAppMessage) if backgroundStyle == .translucent { let blurEffect = UIBlurEffect(style: .regular) contentView = UIVisualEffectView(effect: blurEffect) contentView.translatesAutoresizingMaskIntoConstraints = false mainContainer.addSubview(contentView) NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: mainContainer.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: mainContainer.trailingAnchor), contentView.topAnchor.constraint(equalTo: mainContainer.topAnchor), contentView.bottomAnchor.constraint(equalTo: mainContainer.bottomAnchor) ]) } else { contentView = UIView(frame: .zero) contentView.translatesAutoresizingMaskIntoConstraints = false mainContainer.addSubview(contentView) NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: mainContainer.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: mainContainer.trailingAnchor), contentView.topAnchor.constraint(equalTo: mainContainer.topAnchor), contentView.bottomAnchor.constraint(equalTo: mainContainer.bottomAnchor) ]) if #available(iOS 13.0, *) { contentView.backgroundColor = UIColor.systemBackground } else { contentView.backgroundColor = UIColor.white } if let backgroundColor = styleDelegate?.backgroundColor(forMessage: inAppMessage) { contentView.backgroundColor = backgroundColor } else { contentView.backgroundColor = MBInAppMessageViewStyle.backgroundColor(forMessage: inAppMessage) } } var targetView = contentView ?? self if let contentView = contentView as? UIVisualEffectView { targetView = contentView.contentView } var gestureHandleView: UIView? if !inAppMessage.isBlocking { let handleHeight: CGFloat = 5 let gestureHandle = UIView(frame: .zero) gestureHandle.translatesAutoresizingMaskIntoConstraints = false gestureHandle.layer.cornerRadius = handleHeight / 2 if #available(iOS 13.0, *) { if traitCollection.userInterfaceStyle == .dark { gestureHandle.backgroundColor = UIColor.white.withAlphaComponent(0.2) } else { gestureHandle.backgroundColor = UIColor.black.withAlphaComponent(0.2) } } else { gestureHandle.backgroundColor = UIColor.black.withAlphaComponent(0.2) } targetView.addSubview(gestureHandle) NSLayoutConstraint.activate([ gestureHandle.centerXAnchor.constraint(equalTo: targetView.centerXAnchor), gestureHandle.topAnchor.constraint(equalTo: targetView.topAnchor, constant: 10), gestureHandle.widthAnchor.constraint(equalToConstant: 80), gestureHandle.heightAnchor.constraint(equalToConstant: handleHeight) ]) gestureHandleView = gestureHandle } let contentView = MBInAppMessageBannerContent(message: inAppMessage, styleDelegate: styleDelegate) contentView.translatesAutoresizingMaskIntoConstraints = false targetView.addSubview(contentView) NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: targetView.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: targetView.trailingAnchor), contentView.topAnchor.constraint(equalTo: gestureHandleView?.bottomAnchor ?? targetView.topAnchor, constant: 10), contentView.bottomAnchor.constraint(equalTo: targetView.bottomAnchor, constant: -padding) ]) self.imageView = contentView.imageView self.titleLabel = contentView.titleLabel self.bodyLabel = contentView.bodyLabel self.button1 = contentView.button1 self.button2 = contentView.button2 button1?.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) button2?.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) if !inAppMessage.isBlocking { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleDismiss(_:))) panGesture.delegate = self addGestureRecognizer(panGesture) } } override func present() { guard let window = UIApplication.shared.windows.first else { return } window.addSubview(self) translatesAutoresizingMaskIntoConstraints = false let bottomConstraintHidden = self.topAnchor.constraint(equalTo: window.bottomAnchor) var bottomConstraintNotHidden: NSLayoutConstraint! if #available(iOS 11.0, *) { bottomConstraintNotHidden = self.bottomAnchor.constraint(equalTo: window.safeAreaLayoutGuide.bottomAnchor, constant: -8) } else { bottomConstraintNotHidden = self.bottomAnchor.constraint(equalTo: window.bottomAnchor, constant: -8) } self.bottomConstraintHidden = bottomConstraintHidden self.bottomConstraintNotHidden = bottomConstraintNotHidden NSLayoutConstraint.activate([ leadingAnchor.constraint(equalTo: window.leadingAnchor, constant: 8), trailingAnchor.constraint(equalTo: window.trailingAnchor, constant: -8), bottomConstraintHidden, heightAnchor.constraint(greaterThanOrEqualToConstant: 60) ]) window.layoutIfNeeded() bottomConstraintHidden.isActive = false bottomConstraintNotHidden.isActive = true delegate?.viewWillAppear(view: self) UIView.animate(withDuration: 0.3, animations: { window.layoutIfNeeded() }, completion: { _ in self.delegate?.viewDidAppear(view: self) }) if let inAppMessage = message.inAppMessage { if inAppMessage.duration != -1 && !inAppMessage.isBlocking { self.perform(#selector(hide), with: nil, afterDelay: inAppMessage.duration) } } } override func performHide(duration: TimeInterval, completionBlock: (() -> Void)? = nil) { bottomConstraintNotHidden?.isActive = false bottomConstraintHidden?.isActive = true delegate?.viewWillDisappear(view: self) UIView.animate(withDuration: duration, animations: { self.superview?.layoutIfNeeded() }, completion: { _ in self.delegate?.viewDidDisappear(view: self) if let completionBlock = completionBlock { completionBlock() } self.removeFromSuperview() }) } // MARK: - Gesture var initialTouchPoint: CGPoint = CGPoint.zero @objc func handleDismiss(_ gesture: UIPanGestureRecognizer) { guard let view = gesture.view?.superview else { return } let touchPoint = gesture.location(in: view) switch gesture.state { case .began: NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hide), object: nil) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideWithoutCallingCompletionBlock), object: nil) initialTouchPoint = touchPoint case .changed: bottomConstraintNotHidden?.constant = max(touchPoint.y - initialTouchPoint.y, -8) self.layoutIfNeeded() case .ended, .cancelled: if touchPoint.y - initialTouchPoint.y > 30 { let height = self.frame.height + 8 let remainingHeight = height - (touchPoint.y - initialTouchPoint.y) let perc = remainingHeight / height hideWithDuration(duration: TimeInterval(max(perc * 0.3, 0))) } else { bottomConstraintNotHidden?.constant = -8 UIView.animate(withDuration: 0.2, animations: { self.layoutIfNeeded() }, completion: { _ in if let inAppMessage = self.message.inAppMessage { if inAppMessage.duration != -1 { self.perform(#selector(self.hide), with: nil, afterDelay: inAppMessage.duration) } } }) } case .failed, .possible: break default: break } } } extension MBInAppMessageBottomBannerView: UIGestureRecognizerDelegate { /// Prevents the user to scroll the view down when the animation is in progress, or the view is not visible. public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard let constraintNotHidden = bottomConstraintNotHidden else { return false } return constraintNotHidden.isActive } }
44.407258
155
0.636884
298d3c950a308f43cbb36a715ce1575f35279944
808
// // MockAPIClient.swift // iOS-BoilerplateTests // // Created by Daniel Vela Angulo on 05/12/2018. // Copyright © 2018 veladan. All rights reserved. // @testable import iOS_Boilerplate import Nimble import Quick import XCTest class MockAPIClient: Http.Client { var objectToReturn: Http.Result<Marvel.ResponseDto>? init() { super.init(baseURL: "http://www.server.com", basePath: "/path") } override func request<ResponseDto>(_ endpoint: Http.Endpoint<ResponseDto>, completion: @escaping (Http.Result<ResponseDto>) -> Void) { guard let object = objectToReturn as? Http.Result<ResponseDto> else { fatalError("Need to set 'objectToReturn' value before calling this method") } completion(object) } }
27.862069
98
0.655941
db2d6d5877a4d8b79e83ef0aadf94e736f53c0b7
298
// // CalibrationsView.swift // LibreDirect // import SwiftUI struct CalibrationsView: View { @EnvironmentObject var store: AppStore var body: some View { VStack { List { CalibrationSettingsView() }.listStyle(.grouped) } } }
15.684211
42
0.563758
ccaa7cb91b372a63e6a7c2fabb346e419423bffe
3,490
// // GameViewController.swift // SCNTechniqueGlow // // Created by cc on 8/16/17. // Copyright © 2017 Laan Labs. All rights reserved. // import UIKit import QuartzCore import SceneKit extension SCNNode { func setHighlighted( _ highlighted : Bool = true, _ highlightedBitMask : Int = 2 ) { categoryBitMask = highlightedBitMask for child in self.childNodes { child.setHighlighted() } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) // place the camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 15) // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = .omni lightNode.position = SCNVector3(x: 0, y: 10, z: 10) scene.rootNode.addChildNode(lightNode) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = .ambient ambientLightNode.light!.color = UIColor.darkGray scene.rootNode.addChildNode(ambientLightNode) // retrieve the ship node let ship = scene.rootNode.childNode(withName: "ship", recursively: true)! // animate the 3d object ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1))) // retrieve the SCNView let scnView = self.view as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = UIColor.gray // Set the bitmask to 2 for glow //ship.childNodes[0].categoryBitMask = 2 ship.setHighlighted() if let path = Bundle.main.path(forResource: "NodeTechnique", ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) { let dict2 = dict as! [String : AnyObject] let technique = SCNTechnique(dictionary:dict2) // set the glow color to yellow let color = SCNVector3(1.0, 1.0, 0.0) technique?.setValue(NSValue(scnVector3: color), forKeyPath: "glowColorSymbol") scnView.technique = technique } } } override var shouldAutorotate: Bool { return true } override var prefersStatusBarHidden: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } }
30.086207
98
0.595415
1cd9b75a163bb8596bb6c57696dee0a09945391a
1,252
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIO import Foundation extension JSONSerialization { /// Attempts to derive a Foundation object from a ByteBuffer and return it as `T`. /// /// - parameters: /// - buffer: The ByteBuffer being used to derive the Foundation type. /// - options: The reading option used when the parser derives the Foundation type from the ByteBuffer. /// - returns: The Foundation value if successful or `nil` if there was an issue creating the Foundation type. @inlinable public static func jsonObject(with buffer: ByteBuffer, options opt: JSONSerialization.ReadingOptions = []) throws -> Any { return try JSONSerialization.jsonObject(with: Data(buffer: buffer), options: opt) } }
40.387097
114
0.603834
6abb18e0c6771716a844f2206f1c462b290bfa13
2,120
// // ViewController+StoreLocator.swift // C4GenericFilter // // Created by rboyer on 06/07/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import C4GenericFilter enum StoreLocatorTID: Int { case carrefour = 2263 case city = 86 case contact = 237 case drive = 2215 case express = 134 case carrefourMarket = 13 case montagne = 1689 case proxy = 2272 case contactMarche = 3347 case market = 2266 case bio = 3764 case unknown = 0 } /* protocol in filterPOD */ protocol FilterSelectableEntry { associatedtype U func value() -> String static func title() -> String static func idFilter() -> String var wsOutput : String { get } static var allValueE : [U] { get } static func convertTypeToFilterItem(entry: U.Type) -> [FilterSelectionableItem] } /* ------ */ /* in StoreLocatorPOD */ enum budgetType { case light case medium case heavy static let allValues = [light, medium, heavy] func wsValue() -> String { switch self { case .light: return "1" case .medium: return "2" case .heavy: return "3" } } } /* ------ */ /* in app */ extension budgetType : FilterSelectableEntry { typealias U = budgetType func value() -> String { switch self { case .light: return "€" case .medium: return "€€" case .heavy: return "€€€" } } static func title() -> String { return "Prix :" } static func idFilter() -> String { return "budget" } var wsOutput: String { return self.wsValue() } static var allValueE: [budgetType] { return self.allValues } var imagesE: UIImage? { return nil } var valueE: String { return self.value() } static var idFilterE: String { return self.idFilter() } static func convertTypeToFilterItem(entry: budgetType.Type) -> [FilterSelectionableItem] { return entry.allValueE.map {caseItem in StaticSelectionableItem.init(text:caseItem.valueE , output: caseItem.wsOutput, idFilter: U.idFilterE, selected: false)} } } /* ----- */
17.520661
125
0.628774
f75319b96ff69da6ecd57b43e6b41ccfb290f230
243
// // BrandDetailSectionHeaderView.swift // Bank // // Created by yang on 16/2/24. // Copyright © 2016年 ChangHongCloudTechService. All rights reserved. // import UIKit class BrandDetailSectionHeaderView: UITableViewHeaderFooterView { }
17.357143
69
0.757202
deb85b0159501ce1c2753cf20c31ace8159f9219
846
// // RoundCornerTf.swift // EGGPLANt // // Created by YiChin Lee on 10/09/2017. // Copyright © 2017 FifthGroup. All rights reserved. // import UIKit class RoundCornerTf: UITextField { override func draw(_ rect: CGRect) { print("haha") self.clipsToBounds = true self.layer.cornerRadius = 12.0 self.layer.borderWidth = 2.0 self.layer.borderColor = UIColor.white.cgColor } override func textRect(forBounds bounds: CGRect) -> CGRect { return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.size.width-10, height: bounds.size.height) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.size.width-10, height: bounds.size.height) } }
26.4375
123
0.644208
6ab07604e5a1ae4a9e09ccf81d55a53daaa61505
6,982
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class SpatialOperationsViewController: UIViewController, OperationsListVCDelegate, UIAdaptivePresentationControllerDelegate { @IBOutlet var mapView: AGSMapView! private var graphicsOverlay = AGSGraphicsOverlay() private var polygon1, polygon2: AGSPolygonBuilder! private var resultGraphic: AGSGraphic! let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: UIColor.black, width: 1) let operations = ["None", "Union", "Difference", "Symmetric Difference", "Intersection"] override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["SpatialOperationsViewController", "OperationsListViewController"] //initialize map with basemap let map = AGSMap(basemap: AGSBasemap.topographic()) //assign map to map view self.mapView.map = map //add graphics overlay to map view self.mapView.graphicsOverlays.add(self.graphicsOverlay) //initial viewpoint let center = AGSPoint(x: -13453, y: 6710127, spatialReference: AGSSpatialReference.webMercator()) self.mapView.setViewpointCenter(center, scale: 30000, completion: nil) //add two polygons to be used in the operations self.addPolygons() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func addPolygons() { //polygon 1 self.polygon1 = AGSPolygonBuilder(spatialReference: AGSSpatialReference.webMercator()) polygon1.addPointWith(x: -13960, y: 6709400) polygon1.addPointWith(x: -14660, y: 6710000) polygon1.addPointWith(x: -13760, y: 6710730) polygon1.addPointWith(x: -13300, y: 6710500) polygon1.addPointWith(x: -13160, y: 6710100) //symbol let fillSymbol1 = AGSSimpleFillSymbol(style: .solid, color: UIColor.blue, outline: lineSymbol) //graphic let polygon1Graphic = AGSGraphic(geometry: polygon1.toGeometry(), symbol: fillSymbol1, attributes: nil) // create green polygon // outer ring let outerRing = AGSMutablePart(spatialReference: AGSSpatialReference.webMercator()) outerRing.addPointWith(x: -13060, y: 6711030) outerRing.addPointWith(x: -12160, y: 6710730) outerRing.addPointWith(x: -13160, y: 6709700) outerRing.addPointWith(x: -14560, y: 6710730) outerRing.addPointWith(x: -13060, y: 6711030) // inner ring let innerRing = AGSMutablePart(spatialReference: AGSSpatialReference.webMercator()) innerRing.addPointWith(x: -13060, y: 6710910) innerRing.addPointWith(x: -14160, y: 6710630) innerRing.addPointWith(x: -13160, y: 6709900) innerRing.addPointWith(x: -12450, y: 6710660) innerRing.addPointWith(x: -13060, y: 6710910) self.polygon2 = AGSPolygonBuilder(spatialReference: AGSSpatialReference.webMercator()) polygon2.parts.add(outerRing) polygon2.parts.add(innerRing) //symbol let fillSymbol2 = AGSSimpleFillSymbol(style: .solid, color: UIColor.green, outline: lineSymbol) //graphic let polygon2Graphic = AGSGraphic(geometry: polygon2.toGeometry(), symbol: fillSymbol2, attributes: nil) //add graphics to graphics overlay self.graphicsOverlay.graphics.addObjects(from: [polygon1Graphic, polygon2Graphic]) } private func performOperation(_ index: Int) { var resultGeometry: AGSGeometry switch index { case 1: //Union resultGeometry = AGSGeometryEngine.union(ofGeometry1: self.polygon1.toGeometry(), geometry2: self.polygon2.toGeometry())! case 2: //Difference resultGeometry = AGSGeometryEngine.difference(ofGeometry1: self.polygon2.toGeometry(), geometry2: self.polygon1.toGeometry())! case 3: //Symmetric difference resultGeometry = AGSGeometryEngine.symmetricDifference(ofGeometry1: self.polygon2.toGeometry(), geometry2: self.polygon1.toGeometry())! default: //Intersection resultGeometry = AGSGeometryEngine.intersection(ofGeometry1: self.polygon1.toGeometry(), geometry2: self.polygon2.toGeometry())! } //using red fill symbol for result with black border let symbol = AGSSimpleFillSymbol(style: .solid, color: UIColor.red, outline: lineSymbol) //create result graphic if not present if self.resultGraphic == nil { self.resultGraphic = AGSGraphic(geometry: resultGeometry, symbol: symbol, attributes: nil) self.graphicsOverlay.graphics.add(self.resultGraphic) } //update the geometry if already present else { self.resultGraphic.geometry = resultGeometry } } //MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "OperationsListSegue" { let controller = segue.destination as! OperationsListViewController controller.delegate = self controller.operations = self.operations controller.presentationController?.delegate = self controller.preferredContentSize = CGSize(width: 200, height: 200) } } //MARK: - OperationsListVCDelegate func operationsListViewController(_ operationsListViewController: OperationsListViewController, didSelectOperation index: Int) { if index == 0 { if self.resultGraphic != nil { self.graphicsOverlay.graphics.remove(self.resultGraphic) self.resultGraphic = nil } } else { self.performOperation(index) } } //MARK: - UIAdaptivePresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } }
40.830409
156
0.664566
fcadb64a141e5c334441e4f5d822700685cb27c8
3,853
// // AboutViewController.swift // Yep // // Created by nixzhu on 15/8/28. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import Ruler final class AboutViewController: SegueViewController { @IBOutlet private weak var appLogoImageView: UIImageView! @IBOutlet private weak var appLogoImageViewTopConstraint: NSLayoutConstraint! @IBOutlet private weak var appNameLabel: UILabel! @IBOutlet private weak var appNameLabelTopConstraint: NSLayoutConstraint! @IBOutlet private weak var appVersionLabel: UILabel! @IBOutlet private weak var aboutTableView: UITableView! { didSet { aboutTableView.registerNibOf(AboutCell) } } @IBOutlet private weak var aboutTableViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var copyrightLabel: UILabel! private let rowHeight: CGFloat = Ruler.iPhoneVertical(50, 60, 60, 60).value private let aboutAnnotations: [String] = [ NSLocalizedString("Open Source of Yep", comment: ""), NSLocalizedString("Review Yep on the App Store", comment: ""), NSLocalizedString("Terms of Service", comment: ""), ] override func viewDidLoad() { super.viewDidLoad() title = String.trans_titleAbout appLogoImageViewTopConstraint.constant = Ruler.iPhoneVertical(0, 20, 40, 60).value appNameLabelTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 20, 20).value let motionEffect = UIMotionEffect.yep_twoAxesShift(Ruler.iPhoneHorizontal(20, 30, 40).value) appLogoImageView.addMotionEffect(motionEffect) appNameLabel.addMotionEffect(motionEffect) appVersionLabel.addMotionEffect(motionEffect) appNameLabel.textColor = UIColor.yepTintColor() if let releaseVersionNumber = NSBundle.releaseVersionNumber, buildVersionNumber = NSBundle.buildVersionNumber { appVersionLabel.text = NSLocalizedString("Version", comment: "") + " " + releaseVersionNumber + " (\(buildVersionNumber))" } aboutTableViewHeightConstraint.constant = rowHeight * CGFloat(aboutAnnotations.count) + 1 } } // MARK: - UITableViewDataSource, UITableViewDelegate extension AboutViewController: UITableViewDataSource, UITableViewDelegate { private enum Row: Int { case Pods = 1 case Review case Terms } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return aboutAnnotations.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.row { case 0: return UITableViewCell() default: let cell: AboutCell = tableView.dequeueReusableCell() let annotation = aboutAnnotations[indexPath.row - 1] cell.annotationLabel.text = annotation return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.row { case 0: return 1 default: return rowHeight } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: true) } switch indexPath.row { case Row.Pods.rawValue: performSegueWithIdentifier("showPodsHelpYep", sender: nil) case Row.Review.rawValue: UIApplication.sharedApplication().yep_reviewOnTheAppStore() case Row.Terms.rawValue: if let URL = NSURL(string: YepConfig.termsURLString) { yep_openURL(URL) } default: break } } }
32.108333
138
0.669868
d9b7f7d286c1ace26b87131d2005374e6f9b6b4d
3,234
// // LXFHomeLiveTopHeader.swift // LXFBiliBili // // Created by 林洵锋 on 2017/10/21. // Copyright © 2017年 LinXunFeng. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources import ReusableKit import TYCyclePagerView import Then import Kingfisher fileprivate enum Reusable { static let categoryCell = ReusableCell<LXFLiveTopCategoryCell>(nibName: "LXFLiveTopCategoryCell") } class LXFHomeLiveTopHeader: UICollectionReusableView { var header: LXFHomeLiveHeader! @IBOutlet weak var bannerView: UIView! @IBOutlet weak var categoryView: UICollectionView! @IBOutlet private weak var headerView: UIView! var bannerArr = Variable<[String]>([]) private var dataSource : RxCollectionViewSectionedReloadDataSource<LXFMenuSection>! override func awakeFromNib() { super.awakeFromNib() initUI() bindUI() } } extension LXFHomeLiveTopHeader { private func bindUI() { dataSource = RxCollectionViewSectionedReloadDataSource<LXFMenuSection>(configureCell: { (ds, cv, indexPath, item) in let cell = cv.dequeue(Reusable.categoryCell, for: indexPath) cell.iconView.image = UIImage(named: item.imageName) cell.titleLabel.text = item.title return cell }, configureSupplementaryView: {(ds, cv, kind, indexPath) in return UICollectionReusableView() }) let sections = [ LXFMenuSection(items: [ LXFMenuModel(imageName: "live_home_follow_anchor", title: "关注"), LXFMenuModel(imageName: "ic_live_home_entertainment", title: "娱乐"), LXFMenuModel(imageName: "ic_live_home_game", title: "游戏"), LXFMenuModel(imageName: "ic_live_home_mobile_game", title: "手游"), LXFMenuModel(imageName: "ic_live_home_painting", title: "绘画") ]) ] Observable.just(sections).bind(to: categoryView.rx.items(dataSource: dataSource)).disposed(by: rx.disposeBag) } private func initUI() { // 常规headerView let header = LXFHomeLiveHeader.loadFromNib() self.header = header headerView.addSubview(header) header.snp.makeConstraints { (make) in make.edges.equalToSuperview() } // collectionView categoryView.register(Reusable.categoryCell) let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kScreenW / 5, height: 60) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 categoryView.collectionViewLayout = layout // 轮播 let banner = LXFBannerView() bannerView.addSubview(banner) banner.snp.makeConstraints { (make) in make.edges.equalToSuperview() } // 刷新轮播图 bannerArr.asObservable().subscribe(onNext: { (banners) in banner.bannerArr.value = banners }).disposed(by: rx.disposeBag) } } extension LXFHomeLiveTopHeader: LXFViewHeightProtocol { static func viewHeight() -> CGFloat { return 220 + LXFHomeLiveHeader.viewHeight() } }
31.096154
124
0.645331
ab4a9f49be3232b23f8ce9c19e4fd108f6156a03
13,137
// // Connection.swift // EnigmaMachine // // Created by Jeremy Pereira on 24/02/2015. // Copyright (c) 2015, 2018 Jeremy Pereira. All rights reserved. // /* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Toolbox private let log = Logger.getLogger("EnigmaMachine.Components.Connection") /** Enumeration of all the letters that Enigma can deal with */ public enum Letter: Character, Comparable, CustomStringConvertible { case A = "A", B = "B", C = "C", D = "D", E = "E", F = "F", G = "G", H = "H", I = "I", J = "J", K = "K", L = "L", M = "M", N = "N", O = "O", P = "P", Q = "Q", R = "R", S = "S", T = "T", U = "U", V = "V", W = "W", X = "X", Y = "Y", Z = "Z", UpperBound = "$" /** The ordinal of the letter. A is assumed to have ordinal 0 and Z ordinal 25. */ public var ordinal: Int { get { var ret: Int switch self { case .A: ret = 0 case .B: ret = 1 case .C: ret = 2 case .D: ret = 3 case .E: ret = 4 case .F: ret = 5 case .G: ret = 6 case .H: ret = 7 case .I: ret = 8 case .J: ret = 9 case .K: ret = 10 case .L: ret = 11 case .M: ret = 12 case .N: ret = 13 case .O: ret = 14 case .P: ret = 15 case .Q: ret = 16 case .R: ret = 17 case .S: ret = 18 case .T: ret = 19 case .U: ret = 20 case .V: ret = 21 case .W: ret = 22 case .X: ret = 23 case .Y: ret = 24 case .Z: ret = 25 case .UpperBound: ret = Int.max } return ret } } /** Get the letter for a particular ordinal. Ordinals < 0 and > 25 are treated as if they are modulo 26. :param: ordinal The ordinal to translate into a letter. :returns: The letter for the given ordinal. */ public static func letter(ordinal: Int) -> Letter { var ret: Letter var normalisedOrdinal = ordinal % 26 if normalisedOrdinal < 0 { normalisedOrdinal = 26 + normalisedOrdinal } switch (normalisedOrdinal) { case 0: ret = Letter.A case 1: ret = Letter.B case 2: ret = Letter.C case 3: ret = Letter.D case 4: ret = Letter.E case 5: ret = Letter.F case 6: ret = Letter.G case 7: ret = Letter.H case 8: ret = Letter.I case 9: ret = Letter.J case 10: ret = Letter.K case 11: ret = Letter.L case 12: ret = Letter.M case 13: ret = Letter.N case 14: ret = Letter.O case 15: ret = Letter.P case 16: ret = Letter.Q case 17: ret = Letter.R case 18: ret = Letter.S case 19: ret = Letter.T case 20: ret = Letter.U case 21: ret = Letter.V case 22: ret = Letter.W case 23: ret = Letter.X case 24: ret = Letter.Y case 25: ret = Letter.Z default: fatalError("Something % 26 is not in the range 0 ..< 26") } return ret } public func successor() -> Letter { return self == Letter.Z ? Letter.UpperBound : Letter.letter(ordinal: self.ordinal + 1) } public var description: String { get { return "\(self.rawValue)" } } } extension Letter: Strideable { public func distance(to other: Letter) -> Int { return other.ordinal - self.ordinal } public func advanced(by n: Int) -> Letter { return Letter.letter(ordinal: self.ordinal + n) } public typealias Stride = Int } public func &+(left: Letter, right: Letter) -> Letter { return Letter.letter(ordinal: left.ordinal + right.ordinal) } public func &+(left: Letter, right: Int) -> Letter { return Letter.letter(ordinal: left.ordinal + right) } public func &-(left: Letter, right: Letter) -> Letter { return Letter.letter(ordinal: left.ordinal - right.ordinal) } public func <(left: Letter, right: Letter) -> Bool { return left.ordinal < right.ordinal } public func ==(left: Letter, right: Letter) -> Bool { return left.ordinal == right.ordinal } /// Protocol defining a connection from a set of 26 input letters to 26 output /// letters. public protocol Connection { /// maps an input letter to an output letter. /// /// - Parameter index: index The input letter func map(_ index: Letter) -> Letter? /// Creates an inverse connection if it is possible to do so (requires 1:1 /// letter mapping). /// /// - Returns: The inverse connection or nil if it couldn't be done. func makeInverse() -> Connection? /// The name of the connection for printing diagnostics var name: String { get } } public extension Connection { /// Maps tthe input letter to the output letter using the `map(_:)` function. /// If you use the subscript, you can turn on debug logging wit the /// `EnigmaMachine.Components.Connection` logger. /// /// - Parameter index: The letter to map. subscript(index: Letter) -> Letter? { get { let ret = map(index) log.debug("\(index) -> \(ret?.description ?? "nil") from \(name):\(connectionString)") return ret } } /// Gewts a string vewrsion of the mapping. The position in the string /// correspondfing to the ordinal of the letter tells you what the letter /// maps to. A `-` means there is no mapping for the letter. var connectionString: String { get { // Turn off logging to avoid infinite regress calling the mapping // subscript. log.pushLevel(.none) defer { log.popLevel() } var ret: String = "" for letter in Letter.A ... Letter.Z { if let aMapping = self.map(letter) { ret.append(aMapping.rawValue) } else { ret.append(Character("-")) } } return ret } } } /// A connection that is the identity connection. It maps any letter onto /// itself. There is only one identiy connection. public struct IdentityConnection: Connection { private init() { } public func map(_ index: Letter) -> Letter? { return index } public func makeInverse() -> Connection? { return self } public var name: String { return "identity" } /// The one and only identity connection. public static let identity = IdentityConnection() } /// Any object that has connections. There's always a forward connection and /// a reverse connection, A connector is basically a set of wires and you can /// treverse the wires in either direction. public protocol Connector { /// The connection in the forward direction var forward: Connection { get } /// The connection in the reverse direction. var reverse: Connection { get } } /// A connection that uses a dictionary to map inputs to outputs. /// /// When you create it supply a dictionary of mappings. By default each letter is /// mapped to itself so the map supplied to init need only contain non identity /// mappings. For example /// /// ``` /// let conn = DictionaryConnection(map: [ Letter.A : Letter.B ]) /// ``` /// maps every letter to itself except A which it maps to B. class DictionaryConnection: Connection { var letterMap: [Letter : Letter] = [:] let name: String init(name: String, map: [Letter: Letter]) { for letter in Letter.A ... Letter.Z { self.letterMap[letter] = letter } for key in map.keys { self.letterMap[key] = map[key] } self.name = name } func map(_ index: Letter) -> Letter? { return letterMap[index] } func makeInverse() -> Connection? { var newMap: [Letter : Letter] = [:] for key in letterMap.keys { /* * If there already exists an entry for the inverse key, it means * two letters map to the same output. Therefore the inverse * would be ambiguous. */ if newMap[letterMap[key]!] != nil { return nil } newMap[letterMap[key]!] = key } return DictionaryConnection(name: self.name + ".inverse", map: newMap) } } /// A connection that maps letters based on a passed in function class ClosureConnection: Connection { /// The mapping function var mappingFunc: (Letter) -> Letter? init(name: String, mappingFunc: @escaping (Letter) -> Letter?) { self.name = name self.mappingFunc = mappingFunc } private(set) var name: String func map(_ letter: Letter) -> Letter? { return mappingFunc(letter) } func makeInverse() -> Connection? { fatalError("Cannot invoke makeInverse in ClosureConnection") } } /// A null connection. There are no mappings public struct NullConnection: Connection { private init() {} public func map(_ index: Letter) -> Letter? { return nil } public func makeInverse() -> Connection? { return nil } public let name = "null" /// There's only one null connection public static let null = NullConnection() } /// A class representing a fixed set of wirings from one letter to another. public class Wiring: Connector { public var forward: Connection public var reverse: Connection /// Initialise a wiring from a map of one set of letters to another. /// /// - Parameter map: The map describing the wiring. Only specifiy letters /// that do not map to themselves. public init(name: String, map: [Letter : Letter]) { let forwardMap = DictionaryConnection(name: name, map: map) forward = forwardMap if let reverseMap = forwardMap.makeInverse() { reverse = reverseMap } else { fatalError("Reverse map for wiring would be ambiguous") } } public convenience init(name: String, string: String) { var stringMap: [Letter : Letter] = [:] for (input, toChar) in zip(Letter.A ... Letter.Z, string) { if let toLetter = Letter(rawValue: toChar) { stringMap[input] = toLetter } else { fatalError("Initialising wiring from string: string has invalid character") } } self.init(name: name, map: stringMap) } /** A standard straight through connection that maps every letter to itself */ public static let identity: Wiring = identityWiring /// true if the wiring is reciprocal, that is a mapping in the forward /// direction followed by a maping backwards yiends the original letter for /// all letters. public lazy var isReciprocal: Bool = { for letter in Letter.A ... Letter.Z { guard let intermediate = self.forward[letter] else { return false } guard self.forward[intermediate] == letter else { return false } } return true }() /// true if any of the letters maps to themselves. public lazy var hasStraightThrough: Bool = { for letter in Letter.A ... Letter.Z { if let intermediate = self.forward[letter] { guard intermediate != letter else { return true } } } return false }() } private let identityWiring = Wiring(name: "identity", map: [:])
25.070611
98
0.539012
23d2a8b7ac3b7418056137baca85e9ebd0810f15
1,571
//: [Previous](@previous) import Foundation /*: --- # Result - Swift 5.0 에서 추가 --- */ enum NetworkError: Error { case badUrl case missingData } /* generic type enum Result<Success, Failure> where Failure : Error { case success(Success) case failure(Failure) // 에러 정보 } */ func downloadImage( from urlString: String, completionHandler: (Result<String, NetworkError>) -> Void ) { guard let url = URL(string: urlString) else { return completionHandler(.failure(.badUrl)) } // 다운로드를 시도했다고 가정 print("Download image from \(url)") let downloadedImage = "Dog" // let downloadedImage = "Missing Data" if downloadedImage == "Missing Data" { return completionHandler(.failure(.missingData)) } else { return completionHandler(.success(downloadedImage)) } } /*: ### Result 활용 예시 */ // 1) success, failure 결과 구분 let url = "https://loremflickr.com/320/240/dog" //let url = "No Image Url" downloadImage(from: url) { result in switch result { case .success(let data): print("\(data) image download complete") case .failure(let error): print(error.localizedDescription) // 에러를 구분해야 할 경우 // case .failure(.badUrl): print("Bad URL") // case .failure(.missingData): print("Missing Data") } } // 2) get()을 통해 성공한 경우에만 데이터를 가져옴. 아니면 nil 반환 downloadImage(from: url) { result in if let data = try? result.get() { print("\(data) image download complete") } } // 3) Result를 직접 사용 let result = Result { try String(contentsOfFile: "ABC") } print(try? result.get()) //: [Next](@next)
18.927711
59
0.649268
f7cfc351b086dffb4b46ca230362cf2cea91c02f
562
import SwiftUI public struct PlaceHolder<T: View>: ViewModifier { var placeHolder: T var show: Bool public func body(content: Content) -> some View { ZStack(alignment: .leading) { if show { placeHolder .foregroundColor(.white) .padding([.bottom], 9) } content } } } extension View { public func placeHolder<T:View>(_ holder: T, show: Bool) -> some View { self.modifier(PlaceHolder(placeHolder: holder, show: show)) } }
23.416667
75
0.544484
0a38ae6a21d1af01e201604a746fd6648a51c6b0
3,646
// // LoginView.swift // task-tracker-swiftui // // Created by Andrew Morgan on 03/11/2020. // import SwiftUI import RealmSwift struct LoginView: View { @EnvironmentObject var state: AppState @State private var username = "alelordelonew1" @State private var password = "test1234" @State private var newUser = false private enum Dimensions { static let padding: CGFloat = 16.0 } var body: some View { VStack(spacing: Dimensions.padding) { Spacer() InputField(title: "Email/Username", text: self.$username) .keyboardType(.emailAddress) .autocapitalization(.none) InputField(title: "Password", text: self.$password, showingSecureField: true) CallToActionButton( title: newUser ? "Register User" : "Log In", action: { self.userAction(username: self.username, password: self.password) }) HStack { CheckBox(title: "Register new user", isChecked: $newUser) Spacer() } Spacer() } .navigationBarTitle("User Login", displayMode: .inline) .padding(.horizontal, Dimensions.padding) } private func userAction(username: String, password: String) { state.shouldIndicateActivity = true if newUser { signup(username: username, password: password) } else { login(username: username, password: password) } } private func signup(username: String, password: String) { if username.isEmpty || password.isEmpty { state.shouldIndicateActivity = false return } self.state.error = nil app.emailPasswordAuth.registerUser(email: username, password: password) .receive(on: DispatchQueue.main) .sink(receiveCompletion: { state.shouldIndicateActivity = false switch $0 { case .finished: break case .failure(let error): self.state.error = error.localizedDescription } }, receiveValue: { self.state.error = nil login(username: username, password: password) }) .store(in: &state.cancellables) } private func login(username: String, password: String) { if username.isEmpty || password.isEmpty { state.shouldIndicateActivity = false return } self.state.error = nil app.login(credentials: .emailPassword(email: username, password: password)) .receive(on: DispatchQueue.main) .sink(receiveCompletion: { state.shouldIndicateActivity = false switch $0 { case .finished: break case .failure(let error): self.state.error = error.localizedDescription } }, receiveValue: { self.state.error = nil state.loginPublisher.send($0) }) .store(in: &state.cancellables) } } struct LoginView_Previews: PreviewProvider { static var previews: some View { AppearancePreviews( Group { LoginView() .environmentObject(AppState()) Landscape( LoginView() .environmentObject(AppState()) ) } ) } }
31.704348
94
0.532364
9114708a24642da290365228ca1bb3a934faa4e9
9,645
import Dispatch /// Provides `catch` and `recover` to your object that conforms to `Thenable` public protocol CatchMixin: Thenable {} public extension CatchMixin { /** The provided closure executes when this promise rejects. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - Returns: A promise finalizer. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func `catch`(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping (Error) -> Void) -> PMKFinalizer { let finalizer = PMKFinalizer() pipe { switch $0 { case let .rejected(error): guard policy == .allErrors || !error.isCancelled else { fallthrough } on.async(flags: flags) { body(error) finalizer.pending.resolve(()) } case .fulfilled: finalizer.pending.resolve(()) } } return finalizer } } public class PMKFinalizer { let pending = Guarantee<Void>.pending() /// `finally` is the same as `ensure`, but it is not chainable public func finally(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) { pending.guarantee.done(on: on, flags: flags) { body() } } } public extension CatchMixin { /** The provided closure executes when this promise rejects. Unlike `catch`, `recover` continues the chain. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: firstly { CLLocationManager.requestLocation() }.recover { error in guard error == CLError.unknownLocation else { throw error } return .value(CLLocation.chicago) } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ func recover<U: Thenable>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping (Error) throws -> U) -> Promise<T> where U.T == T { let rp = Promise<U.T>(.pending) pipe { switch $0 { case let .fulfilled(value): rp.box.seal(.fulfilled(value)) case let .rejected(error): if policy == .allErrors || !error.isCancelled { on.async(flags: flags) { do { let rv = try body(error) guard rv !== rp else { throw PMKError.returnedSelf } rv.pipe(to: rp.box.seal) } catch { rp.box.seal(.rejected(error)) } } } else { rp.box.seal(.rejected(error)) } } } return rp } /** The provided closure executes when this promise rejects. This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`. - Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (Error) -> Guarantee<T>) -> Guarantee<T> { let rg = Guarantee<T>(.pending) pipe { switch $0 { case let .fulfilled(value): rg.box.seal(value) case let .rejected(error): on.async(flags: flags) { body(error).pipe(to: rg.box.seal) } } } return rg } /** The provided closure executes when this promise resolves, whether it rejects or not. firstly { UIApplication.shared.networkActivityIndicatorVisible = true }.done { //… }.ensure { UIApplication.shared.networkActivityIndicatorVisible = false }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ func ensure(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) -> Promise<T> { let rp = Promise<T>(.pending) pipe { result in on.async(flags: flags) { body() rp.box.seal(result) } } return rp } /** The provided closure executes when this promise resolves, whether it rejects or not. The chain waits on the returned `Guarantee<Void>`. firstly { setup() }.done { //… }.ensureThen { teardown() // -> Guarante<Void> }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ func ensureThen(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Guarantee<Void>) -> Promise<T> { let rp = Promise<T>(.pending) pipe { result in on.async(flags: flags) { body().done { rp.box.seal(result) } } } return rp } /** Consumes the Swift unused-result warning. - Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear. */ @discardableResult func cauterize() -> PMKFinalizer { return `catch` { conf.logHandler(.cauterized($0)) } } } public extension CatchMixin where T == Void { /** The provided closure executes when this promise rejects. This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (Error) -> Void) -> Guarantee<Void> { let rg = Guarantee<Void>(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(()) case let .rejected(error): on.async(flags: flags) { body(error) rg.box.seal(()) } } } return rg } /** The provided closure executes when this promise rejects. This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping (Error) throws -> Void) -> Promise<Void> { let rg = Promise<Void>(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(.fulfilled(())) case let .rejected(error): if policy == .allErrors || !error.isCancelled { on.async(flags: flags) { do { rg.box.seal(.fulfilled(try body(error))) } catch { rg.box.seal(.rejected(error)) } } } else { rg.box.seal(.rejected(error)) } } } return rg } }
38.58
209
0.575842
d70a10c3bc4cb335348493620fed1fed7a243cd2
2,148
// // AppDelegate.swift // Sample // // Created by Lasha Efremidze on 3/20/16. // Copyright © 2016 Lasha Efremidze. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.702128
285
0.75419
e67884e414877edd1ce3b055164a733d8055724c
793
// // Data+PrettyPrinted.swift // DropBit // // Created by BJ Miller on 6/26/19. // Copyright © 2019 Coin Ninja, LLC. All rights reserved. // import Foundation extension Data { func prettyPrinted() -> String { do { let dataAsJSON = try JSONSerialization.jsonObject(with: self, options: .allowFragments) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return String(data: prettyData, encoding: .utf8) ?? "-" } catch { return String(data: self, encoding: .utf8) ?? "-" } } func lineCount() -> Int? { guard let string = String(data: self, encoding: .utf8) else { log.error("Failed to create string with data") return nil } return string.count(of: Character("\n")) + 1 } }
26.433333
102
0.645649
797dfcf4951d12337a5edcf0c919549c1a6aeabf
4,818
import CoreData public final class ManagedObjectContext { // MARK: Lifecycle internal init(_ instance: NSManagedObjectContext) { self.instance = instance } // MARK: Public public enum Error: Swift.Error { case unknownEntity(String) } @discardableResult public func insert<PlainObject: ManagedObjectConvertible>(_ value: PlainObject) throws -> ManagedObject<PlainObject> { guard let managedObject = self.instance.insert(entity: PlainObject.entityName) else { throw Self.Error.unknownEntity(PlainObject.entityName) } return ManagedObject(instance: managedObject).encode(value) } public func delete<PlainObject: ManagedObjectConvertible>( _ managedObject: ManagedObject<PlainObject> ) { self.instance.delete(managedObject.instance) } public func delete<PlainObject: ManagedObjectConvertible>( _ request: Request<PlainObject> ) throws { let fetchRequest = request.makeFetchRequest( ofType: (NSManagedObject.self, .managedObjectResultType), attributesToFetch: [] ) try self.instance.fetch(fetchRequest).forEach { self.instance.delete($0) } } @discardableResult public func batchDelete<PlainObject: ManagedObjectConvertible>( _ request: Request<PlainObject> ) throws -> Int where PlainObject.Relations == Void { let fetchRequest = request.makeFetchRequest( ofType: (NSFetchRequestResult.self, .managedObjectIDResultType), attributesToFetch: [] ) let batchRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) batchRequest.resultType = .resultTypeCount let batchResult = try self.instance.execute(batchRequest) as! NSBatchDeleteResult return (batchResult.result as! NSNumber).intValue } @discardableResult public func count<PlainObject: ManagedObjectConvertible>( of request: Request<PlainObject> ) throws -> Int { let fetchRequest = request.makeFetchRequest( ofType: (NSNumber.self, .countResultType), attributesToFetch: [] ) return try self.instance.count(for: fetchRequest) } @discardableResult public func fetch<PlainObject: ManagedObjectConvertible>( _ request: Request<PlainObject> ) throws -> [ManagedObject<PlainObject>] { let fetchRequest = request.makeFetchRequest( ofType: (NSManagedObject.self, .managedObjectResultType) ) return try self.instance.fetch(fetchRequest).map { .init(instance: $0) } } @discardableResult public func fetch<PlainObject: ManagedObjectConvertible, Attribute: SupportedAttributeType>( _ request: Request<PlainObject>, _ keyPath: KeyPath<PlainObject, Attribute> ) throws -> [Attribute] { let attribute = PlainObject.attribute(keyPath) let fetchRequest = request.makeFetchRequest( ofType: (NSDictionary.self, .dictionaryResultType), attributesToFetch: [attribute] ) return try self.instance.fetch(fetchRequest).map { try Attribute.decode($0[attribute.name]) } } @discardableResult public func fetch<PlainObject: ManagedObjectConvertible, Attribute: SupportedAttributeType>( _ request: Request<PlainObject>, _ keyPath: KeyPath<PlainObject, Attribute?> ) throws -> [Attribute?] { let attribute = PlainObject.attribute(keyPath) let fetchRequest = request.makeFetchRequest( ofType: (NSDictionary.self, .dictionaryResultType), attributesToFetch: [attribute] ) return try self.instance.fetch(fetchRequest).map { try Attribute?.decode($0[attribute.name]) } } // MARK: Internal unowned let instance: NSManagedObjectContext } public extension ManagedObjectContext { @discardableResult func fetchOne<PlainObject: ManagedObjectConvertible>( _ request: Request<PlainObject> ) throws -> ManagedObject<PlainObject>? { try self.fetch(request.limit(1)).first } @discardableResult func fetchOne<PlainObject: ManagedObjectConvertible, Attribute: SupportedAttributeType>( _ request: Request<PlainObject>, _ keyPath: KeyPath<PlainObject, Attribute> ) throws -> Attribute? { try self.fetch(request.limit(1), keyPath).first } @discardableResult func fetchOne<PlainObject: ManagedObjectConvertible, Attribute: SupportedAttributeType>( _ request: Request<PlainObject>, _ keyPath: KeyPath<PlainObject, Attribute?> ) throws -> Attribute? { try self.fetch(request.limit(1), keyPath).first ?? nil } }
33.227586
122
0.669988
0a71719e348e7f9422a5cfaec5934c633a95f1ca
1,777
// // Card.swift // Chica // // Created by Marquis Kurt on 7/7/20. // import Foundation /// A class representation of a content card. public class Card: Codable, Identifiable { // MARK: - STORED PROPERTIES /// The ID for this card. // swiftlint:disable:next identifier_name public let id = UUID() /// The title for this card. public let title: String /// The description for this card. public let description: String /// The URL to this card, if applicable. public let image: String? /// The type of content for this card. public let type: CardType /// The content author's name. public let authorName: String? /// The content author's website URL. public let authorURL: String? /// The content provider's name. public let providerName: String? /// The content provider's website URL. public let providerURL: String? /// The content's HTML code. public let html: String? /// The suggested width for this card. public let width: Int? /// The suggested height for this card. public let height: Int? // MARK: - COMPUTED PROPERTIES private enum CodingKeys: String, CodingKey { case title case description case image case type case authorName = "author_name" case authorURL = "author_url" case providerName = "provider_name" case providerURL = "provider_url" case html case width case height } } /// Grants us conformance to `Hashable` for _free_ extension Card: Hashable { public static func == (lhs: Card, rhs: Card) -> Bool { return lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } }
22.493671
58
0.628588
64e718f617eec3b060af9f9f06f4250d32c9f14b
8,664
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseUI import FirebaseFirestore import SDWebImage func priceString(from price: Int) -> String { let priceText: String switch price { case 1: priceText = "$" case 2: priceText = "$$" case 3: priceText = "$$$" case _: fatalError("price must be between one and three") } return priceText } private func imageURL(from string: String) -> URL { let number = (abs(string.hashValue) % 22) + 1 let URLString = "https://storage.googleapis.com/firestorequickstarts.appspot.com/food_\(number).png" return URL(string: URLString)! } class RestaurantsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var activeFiltersStackView: UIStackView! @IBOutlet var stackViewHeightConstraint: NSLayoutConstraint! @IBOutlet var cityFilterLabel: UILabel! @IBOutlet var categoryFilterLabel: UILabel! @IBOutlet var priceFilterLabel: UILabel! let backgroundView = UIImageView() private var restaurants: [Restaurant] = [] private var documents: [DocumentSnapshot] = [] fileprivate var query: Query? { didSet { if let listener = listener { listener.remove() observeQuery() } } } private var listener: ListenerRegistration? fileprivate func observeQuery() { guard let query = query else { return } stopObserving() // Display data from Firestore, part one } fileprivate func stopObserving() { listener?.remove() } fileprivate func baseQuery() -> Query { // Firestore needs to use Timestamp type instead of Date type. // https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/FirestoreSettings let firestore: Firestore = Firestore.firestore() let settings = firestore.settings settings.areTimestampsInSnapshotsEnabled = true firestore.settings = settings return firestore.collection("restaurants").limit(to: 50) } lazy private var filters: (navigationController: UINavigationController, filtersController: FiltersViewController) = { return FiltersViewController.fromStoryboard(delegate: self) }() override func viewDidLoad() { super.viewDidLoad() backgroundView.image = UIImage(named: "pizza-monster")! backgroundView.contentMode = .scaleAspectFit backgroundView.alpha = 0.5 tableView.backgroundView = backgroundView tableView.tableFooterView = UIView() // Blue bar with white color navigationController?.navigationBar.barTintColor = UIColor(red: 0x3d/0xff, green: 0x5a/0xff, blue: 0xfe/0xff, alpha: 1.0) navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white ] tableView.dataSource = self tableView.delegate = self query = baseQuery() stackViewHeightConstraint.constant = 0 activeFiltersStackView.isHidden = true self.navigationController?.navigationBar.barStyle = .black } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setNeedsStatusBarAppearanceUpdate() observeQuery() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let auth = FUIAuth.defaultAuthUI()! if auth.auth?.currentUser == nil { auth.providers = [] present(auth.authViewController(), animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopObserving() } @IBAction func didTapPopulateButton(_ sender: Any) { let words = ["Bar", "Fire", "Grill", "Drive Thru", "Place", "Best", "Spot", "Prime", "Eatin'"] let cities = Restaurant.cities let categories = Restaurant.categories for _ in 0 ..< 20 { let randomIndexes = (Int(arc4random_uniform(UInt32(words.count))), Int(arc4random_uniform(UInt32(words.count)))) let name = words[randomIndexes.0] + " " + words[randomIndexes.1] let category = categories[Int(arc4random_uniform(UInt32(categories.count)))] let city = cities[Int(arc4random_uniform(UInt32(cities.count)))] let price = Int(arc4random_uniform(3)) + 1 // Basic writes let collection = Firestore.firestore().collection("restaurants") } } @IBAction func didTapClearButton(_ sender: Any) { filters.filtersController.clearFilters() controller(filters.filtersController, didSelectCategory: nil, city: nil, price: nil, sortBy: nil) } @IBAction func didTapFilterButton(_ sender: Any) { present(filters.navigationController, animated: true, completion: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { set {} get { return .lightContent } } deinit { listener?.remove() } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantTableViewCell", for: indexPath) as! RestaurantTableViewCell let restaurant = restaurants[indexPath.row] cell.populate(restaurant: restaurant) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurants.count } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let controller = RestaurantDetailViewController.fromStoryboard() controller.titleImageURL = imageURL(from: restaurants[indexPath.row].name) controller.restaurant = restaurants[indexPath.row] controller.restaurantReference = documents[indexPath.row].reference self.navigationController?.pushViewController(controller, animated: true) } } extension RestaurantsTableViewController: FiltersViewControllerDelegate { func query(withCategory category: String?, city: String?, price: Int?, sortBy: String?) -> Query { var filtered = baseQuery() if category == nil && city == nil && price == nil && sortBy == nil { stackViewHeightConstraint.constant = 0 activeFiltersStackView.isHidden = true } else { stackViewHeightConstraint.constant = 44 activeFiltersStackView.isHidden = false } // Advanced queries return filtered } func controller(_ controller: FiltersViewController, didSelectCategory category: String?, city: String?, price: Int?, sortBy: String?) { let filtered = query(withCategory: category, city: city, price: price, sortBy: sortBy) if let category = category, !category.isEmpty { categoryFilterLabel.text = category categoryFilterLabel.isHidden = false } else { categoryFilterLabel.isHidden = true } if let city = city, !city.isEmpty { cityFilterLabel.text = city cityFilterLabel.isHidden = false } else { cityFilterLabel.isHidden = true } if let price = price { priceFilterLabel.text = priceString(from: price) priceFilterLabel.isHidden = false } else { priceFilterLabel.isHidden = true } self.query = filtered observeQuery() } } class RestaurantTableViewCell: UITableViewCell { @IBOutlet private var thumbnailView: UIImageView! @IBOutlet private var nameLabel: UILabel! @IBOutlet var starsView: ImmutableStarsView! @IBOutlet private var cityLabel: UILabel! @IBOutlet private var categoryLabel: UILabel! @IBOutlet private var priceLabel: UILabel! func populate(restaurant: Restaurant) { // Displaying data, part two let image = imageURL(from: restaurant.name) thumbnailView.sd_setImage(with: image) } override func prepareForReuse() { super.prepareForReuse() thumbnailView.sd_cancelCurrentImageLoad() } }
29.671233
113
0.702793
03371e8af990d3b2403fa2b914c80d4fbec236b5
238
// RUN: not %target-swift-frontend -typecheck %s protocol Item { associatedtype Rule func isValide(valid: Rule) -> Bool } protocol PairableItem: Item { associatedtype AssociatedItem: PairableItem where AssociatedItem.Rule: Rule }
21.636364
77
0.760504
6afee0958bc689795a16ea87634fd699447253e5
1,646
// // SupportedPropertyType.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation public protocol SupportedPropertyType { var requiresTheme: Bool { get } func generate(context: SupportedPropertyTypeContext) -> String #if SanAndreas func dematerialize(context: SupportedPropertyTypeContext) -> String #endif #if canImport(UIKit) func runtimeValue(context: SupportedPropertyTypeContext) -> Any? #endif // FIXME Although it's not needed for POC of Themes, it should be implemented so that more things can be themed. // We would then use this to know how is the type called for generating. // static var runtimeType: String { get } // FIXME Has to be put into `AttributeSupportedPropertyType` static var xsdType: XSDType { get } } public extension SupportedPropertyType { var requiresTheme: Bool { return false } } public protocol AttributeSupportedPropertyType: SupportedPropertyType { static func materialize(from value: String) throws -> Self } public protocol ElementSupportedPropertyType: SupportedPropertyType { static func materialize(from element: XMLElement) throws -> Self } public protocol MultipleAttributeSupportedPropertyType: SupportedPropertyType { static func materialize(from attributes: [String: String]) throws -> Self } extension ElementSupportedPropertyType where Self: AttributeSupportedPropertyType { static func materialize(from element: XMLElement) throws -> Self { let text = element.text ?? "" return try materialize(from: text) } }
29.392857
116
0.737546
225c94417e6a0a6dd9751acf5afc47c618a36a79
675
import Foundation /// A convenience function for mutating a value. /// /// This provides a scope in which the value is mutable. It also helps scope any intermediate declarations. /// /// - important: /// This function relies on value sematics and will not make a copy of classes. As such, it should typically be /// used with value types. Otherwise, the behaviour may be surprising. /// /// - Parameters: /// - value: The value to mutate. /// - mutate: The mutating. /// - Returns: The mutated value. public func mutating<Value>(_ value: Value, with mutate: (inout Value) throws -> Void) rethrows -> Value { var copy = value try mutate(&copy) return copy }
33.75
112
0.694815
114eba2c60212a7daad15b329d24f8e19bcc39df
240
// // ControllerManager.swift // Project Starter // // Created by iOS Developer on 1/3/18. // Copyright © 2018 sawanmind. All rights reserved. // import UIKit public enum ControllerType { case tabBarController case drawer }
14.117647
52
0.695833
dbc47b97596b87205fbb342aebf2f39755f15ef7
4,148
// // GeneralPreferencesViewController.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa class GeneralPreferencesViewController: NSViewController { static func loadFromStoryboard() -> GeneralPreferencesViewController { let vc = NSStoryboard(name: NSStoryboard.Name(rawValue: "Preferences"), bundle: nil).instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "GeneralPreferencesViewController")) return vc as! GeneralPreferencesViewController } @IBOutlet weak var searchInTranscriptsSwitch: ITSwitch! @IBOutlet weak var searchInBookmarksSwitch: ITSwitch! @IBOutlet weak var refreshPeriodicallySwitch: ITSwitch! @IBOutlet weak var skipBackAndForwardBy30SecondsSwitch: ITSwitch! @IBOutlet weak var downloadsFolderLabel: NSTextField! @IBOutlet weak var downloadsFolderIntroLabel: NSTextField! @IBOutlet weak var searchIntroLabel: NSTextField! @IBOutlet weak var includeBookmarksLabel: NSTextField! @IBOutlet weak var includeTranscriptsLabel: NSTextField! @IBOutlet weak var refreshAutomaticallyLabel: NSTextField! @IBOutlet weak var skipBackAndForwardBy30SecondsLabel: NSTextField! @IBOutlet weak var dividerA: NSBox! @IBOutlet weak var dividerB: NSBox! @IBOutlet weak var dividerC: NSBox! override func viewDidLoad() { super.viewDidLoad() downloadsFolderIntroLabel.textColor = .prefsPrimaryText searchIntroLabel.textColor = .prefsPrimaryText includeBookmarksLabel.textColor = .prefsPrimaryText includeTranscriptsLabel.textColor = .prefsPrimaryText refreshAutomaticallyLabel.textColor = .prefsPrimaryText skipBackAndForwardBy30SecondsLabel.textColor = .prefsPrimaryText downloadsFolderLabel.textColor = .prefsSecondaryText dividerA.fillColor = .darkGridColor dividerB.fillColor = .darkGridColor dividerC.fillColor = .darkGridColor searchInTranscriptsSwitch.tintColor = .primary searchInBookmarksSwitch.tintColor = .primary refreshPeriodicallySwitch.tintColor = .primary skipBackAndForwardBy30SecondsSwitch.tintColor = .primary searchInTranscriptsSwitch.checked = Preferences.shared.searchInTranscripts searchInBookmarksSwitch.checked = Preferences.shared.searchInBookmarks refreshPeriodicallySwitch.checked = Preferences.shared.refreshPeriodically skipBackAndForwardBy30SecondsSwitch.checked = Preferences.shared.skipBackAndForwardBy30Seconds downloadsFolderLabel.stringValue = Preferences.shared.localVideoStorageURL.path } @IBAction func searchInTranscriptsSwitchAction(_ sender: Any) { Preferences.shared.searchInTranscripts = searchInTranscriptsSwitch.checked } @IBAction func searchInBookmarksSwitchAction(_ sender: Any) { Preferences.shared.searchInBookmarks = searchInBookmarksSwitch.checked } @IBAction func refreshPeriodicallySwitchAction(_ sender: Any) { Preferences.shared.refreshPeriodically = refreshPeriodicallySwitch.checked } @IBAction func skipBackAndForwardBy30SecondsSwitchAction(_ sender: Any) { Preferences.shared.skipBackAndForwardBy30Seconds = skipBackAndForwardBy30SecondsSwitch.checked } @IBAction func revealDownloadsFolderInFinder(_ sender: NSButton) { let url = Preferences.shared.localVideoStorageURL NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: url.path) } @IBAction func selectDownloadsFolder(_ sender: NSButton) { let panel = NSOpenPanel() panel.title = "Change Downloads Folder" panel.prompt = "Select" panel.canChooseDirectories = true panel.canChooseFiles = false panel.runModal() guard let url = panel.url else { return } Preferences.shared.localVideoStorageURL = url downloadsFolderLabel.stringValue = url.path } }
40.271845
206
0.73216
03d4c947d89b3b91c379206f07851ae7118b3293
1,244
// // RKColorSettings.swift // RKCalendar // // Copyright © 2019 Raffi Kian. All rights reserved. // import Foundation import Combine import SwiftUI public class RKColorSettings : ObservableObject { // foreground colors @Published public var textColor: Color = Color.primary @Published public var todayColor: Color = Color.white @Published public var selectedColor: Color = Color.white @Published public var disabledColor: Color = Color.gray @Published public var betweenStartAndEndColor: Color = Color.white // background colors @Published public var textBackColor: Color = Color.clear @Published public var todayBackColor: Color = Color.gray @Published public var selectedBackColor: Color = Color.red @Published public var disabledBackColor: Color = Color.clear @Published public var betweenStartAndEndBackColor: Color = Color.blue // headers foreground colors @Published public var weekdayHeaderColor: Color = Color.primary @Published public var monthHeaderColor: Color = Color.primary // headers background colors @Published public var weekdayHeaderBackColor: Color = Color.clear @Published public var monthBackColor: Color = Color.clear public init() {} }
35.542857
73
0.747588
56c306280a9e31d51d612887fa40db75ee53bb40
46,153
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 extension SPCodeDraw { public class SocialIconPack : NSObject { @objc dynamic public class func drawInstagram(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { let context = UIGraphicsGetCurrentContext()! context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 40, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 40, y: resizedFrame.height / 40) let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 19.9, y: 0.99)) bezierPath.addCurve(to: CGPoint(x: 12.12, y: 1.1), controlPoint1: CGPoint(x: 14.77, y: 0.99), controlPoint2: CGPoint(x: 14.13, y: 1.01)) bezierPath.addCurve(to: CGPoint(x: 7.54, y: 1.98), controlPoint1: CGPoint(x: 10.11, y: 1.19), controlPoint2: CGPoint(x: 8.74, y: 1.51)) bezierPath.addCurve(to: CGPoint(x: 4.19, y: 4.15), controlPoint1: CGPoint(x: 6.29, y: 2.46), controlPoint2: CGPoint(x: 5.24, y: 3.1)) bezierPath.addCurve(to: CGPoint(x: 2.02, y: 7.5), controlPoint1: CGPoint(x: 3.14, y: 5.2), controlPoint2: CGPoint(x: 2.5, y: 6.26)) bezierPath.addCurve(to: CGPoint(x: 1.14, y: 12.08), controlPoint1: CGPoint(x: 1.55, y: 8.7), controlPoint2: CGPoint(x: 1.23, y: 10.07)) bezierPath.addCurve(to: CGPoint(x: 1.03, y: 19.86), controlPoint1: CGPoint(x: 1.05, y: 14.09), controlPoint2: CGPoint(x: 1.03, y: 14.73)) bezierPath.addCurve(to: CGPoint(x: 1.14, y: 27.64), controlPoint1: CGPoint(x: 1.03, y: 24.98), controlPoint2: CGPoint(x: 1.05, y: 25.63)) bezierPath.addCurve(to: CGPoint(x: 2.02, y: 32.22), controlPoint1: CGPoint(x: 1.23, y: 29.65), controlPoint2: CGPoint(x: 1.55, y: 31.02)) bezierPath.addCurve(to: CGPoint(x: 4.19, y: 35.56), controlPoint1: CGPoint(x: 2.5, y: 33.46), controlPoint2: CGPoint(x: 3.14, y: 34.51)) bezierPath.addCurve(to: CGPoint(x: 7.54, y: 37.74), controlPoint1: CGPoint(x: 5.24, y: 36.61), controlPoint2: CGPoint(x: 6.29, y: 37.26)) bezierPath.addCurve(to: CGPoint(x: 12.12, y: 38.62), controlPoint1: CGPoint(x: 8.74, y: 38.21), controlPoint2: CGPoint(x: 10.11, y: 38.52)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 38.73), controlPoint1: CGPoint(x: 14.13, y: 38.71), controlPoint2: CGPoint(x: 14.77, y: 38.73)) bezierPath.addCurve(to: CGPoint(x: 27.68, y: 38.62), controlPoint1: CGPoint(x: 25.02, y: 38.73), controlPoint2: CGPoint(x: 25.67, y: 38.71)) bezierPath.addCurve(to: CGPoint(x: 32.26, y: 37.74), controlPoint1: CGPoint(x: 29.69, y: 38.52), controlPoint2: CGPoint(x: 31.06, y: 38.21)) bezierPath.addCurve(to: CGPoint(x: 35.6, y: 35.56), controlPoint1: CGPoint(x: 33.5, y: 37.26), controlPoint2: CGPoint(x: 34.55, y: 36.61)) bezierPath.addCurve(to: CGPoint(x: 37.78, y: 32.22), controlPoint1: CGPoint(x: 36.65, y: 34.51), controlPoint2: CGPoint(x: 37.3, y: 33.46)) bezierPath.addCurve(to: CGPoint(x: 38.66, y: 27.64), controlPoint1: CGPoint(x: 38.25, y: 31.02), controlPoint2: CGPoint(x: 38.56, y: 29.65)) bezierPath.addCurve(to: CGPoint(x: 38.77, y: 19.86), controlPoint1: CGPoint(x: 38.75, y: 25.63), controlPoint2: CGPoint(x: 38.77, y: 24.98)) bezierPath.addCurve(to: CGPoint(x: 38.66, y: 12.08), controlPoint1: CGPoint(x: 38.77, y: 14.73), controlPoint2: CGPoint(x: 38.75, y: 14.09)) bezierPath.addCurve(to: CGPoint(x: 37.78, y: 7.5), controlPoint1: CGPoint(x: 38.56, y: 10.07), controlPoint2: CGPoint(x: 38.25, y: 8.7)) bezierPath.addCurve(to: CGPoint(x: 35.6, y: 4.15), controlPoint1: CGPoint(x: 37.3, y: 6.26), controlPoint2: CGPoint(x: 36.65, y: 5.2)) bezierPath.addCurve(to: CGPoint(x: 32.26, y: 1.98), controlPoint1: CGPoint(x: 34.55, y: 3.1), controlPoint2: CGPoint(x: 33.5, y: 2.46)) bezierPath.addCurve(to: CGPoint(x: 27.68, y: 1.1), controlPoint1: CGPoint(x: 31.06, y: 1.51), controlPoint2: CGPoint(x: 29.69, y: 1.19)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 0.99), controlPoint1: CGPoint(x: 25.67, y: 1.01), controlPoint2: CGPoint(x: 25.02, y: 0.99)) bezierPath.close() bezierPath.move(to: CGPoint(x: 19.9, y: 4.39)) bezierPath.addCurve(to: CGPoint(x: 27.52, y: 4.5), controlPoint1: CGPoint(x: 24.94, y: 4.39), controlPoint2: CGPoint(x: 25.53, y: 4.41)) bezierPath.addCurve(to: CGPoint(x: 31.03, y: 5.15), controlPoint1: CGPoint(x: 29.36, y: 4.58), controlPoint2: CGPoint(x: 30.36, y: 4.89)) bezierPath.addCurve(to: CGPoint(x: 33.2, y: 6.56), controlPoint1: CGPoint(x: 31.91, y: 5.49), controlPoint2: CGPoint(x: 32.54, y: 5.9)) bezierPath.addCurve(to: CGPoint(x: 34.61, y: 8.73), controlPoint1: CGPoint(x: 33.86, y: 7.22), controlPoint2: CGPoint(x: 34.27, y: 7.85)) bezierPath.addCurve(to: CGPoint(x: 35.26, y: 12.23), controlPoint1: CGPoint(x: 34.87, y: 9.39), controlPoint2: CGPoint(x: 35.18, y: 10.39)) bezierPath.addCurve(to: CGPoint(x: 35.37, y: 19.86), controlPoint1: CGPoint(x: 35.35, y: 14.22), controlPoint2: CGPoint(x: 35.37, y: 14.82)) bezierPath.addCurve(to: CGPoint(x: 35.26, y: 27.48), controlPoint1: CGPoint(x: 35.37, y: 24.9), controlPoint2: CGPoint(x: 35.35, y: 25.49)) bezierPath.addCurve(to: CGPoint(x: 34.61, y: 30.99), controlPoint1: CGPoint(x: 35.18, y: 29.32), controlPoint2: CGPoint(x: 34.87, y: 30.32)) bezierPath.addCurve(to: CGPoint(x: 33.2, y: 33.16), controlPoint1: CGPoint(x: 34.27, y: 31.87), controlPoint2: CGPoint(x: 33.86, y: 32.5)) bezierPath.addCurve(to: CGPoint(x: 31.03, y: 34.57), controlPoint1: CGPoint(x: 32.54, y: 33.82), controlPoint2: CGPoint(x: 31.91, y: 34.23)) bezierPath.addCurve(to: CGPoint(x: 27.52, y: 35.22), controlPoint1: CGPoint(x: 30.36, y: 34.83), controlPoint2: CGPoint(x: 29.36, y: 35.14)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 35.33), controlPoint1: CGPoint(x: 25.53, y: 35.31), controlPoint2: CGPoint(x: 24.94, y: 35.33)) bezierPath.addCurve(to: CGPoint(x: 12.27, y: 35.22), controlPoint1: CGPoint(x: 14.86, y: 35.33), controlPoint2: CGPoint(x: 14.26, y: 35.31)) bezierPath.addCurve(to: CGPoint(x: 8.77, y: 34.57), controlPoint1: CGPoint(x: 10.43, y: 35.14), controlPoint2: CGPoint(x: 9.43, y: 34.83)) bezierPath.addCurve(to: CGPoint(x: 6.6, y: 33.16), controlPoint1: CGPoint(x: 7.89, y: 34.23), controlPoint2: CGPoint(x: 7.26, y: 33.82)) bezierPath.addCurve(to: CGPoint(x: 5.19, y: 30.99), controlPoint1: CGPoint(x: 5.94, y: 32.5), controlPoint2: CGPoint(x: 5.53, y: 31.87)) bezierPath.addCurve(to: CGPoint(x: 4.54, y: 27.48), controlPoint1: CGPoint(x: 4.93, y: 30.32), controlPoint2: CGPoint(x: 4.62, y: 29.32)) bezierPath.addCurve(to: CGPoint(x: 4.43, y: 19.86), controlPoint1: CGPoint(x: 4.45, y: 25.49), controlPoint2: CGPoint(x: 4.43, y: 24.9)) bezierPath.addCurve(to: CGPoint(x: 4.54, y: 12.23), controlPoint1: CGPoint(x: 4.43, y: 14.82), controlPoint2: CGPoint(x: 4.45, y: 14.22)) bezierPath.addCurve(to: CGPoint(x: 5.19, y: 8.73), controlPoint1: CGPoint(x: 4.62, y: 10.39), controlPoint2: CGPoint(x: 4.93, y: 9.39)) bezierPath.addCurve(to: CGPoint(x: 6.6, y: 6.56), controlPoint1: CGPoint(x: 5.53, y: 7.85), controlPoint2: CGPoint(x: 5.94, y: 7.22)) bezierPath.addCurve(to: CGPoint(x: 8.77, y: 5.15), controlPoint1: CGPoint(x: 7.26, y: 5.9), controlPoint2: CGPoint(x: 7.89, y: 5.49)) bezierPath.addCurve(to: CGPoint(x: 12.27, y: 4.5), controlPoint1: CGPoint(x: 9.43, y: 4.89), controlPoint2: CGPoint(x: 10.43, y: 4.58)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 4.39), controlPoint1: CGPoint(x: 14.26, y: 4.41), controlPoint2: CGPoint(x: 14.86, y: 4.39)) bezierPath.addLine(to: CGPoint(x: 19.9, y: 4.39)) bezierPath.close() bezierPath.move(to: CGPoint(x: 19.9, y: 26.15)) bezierPath.addCurve(to: CGPoint(x: 13.61, y: 19.86), controlPoint1: CGPoint(x: 16.42, y: 26.15), controlPoint2: CGPoint(x: 13.61, y: 23.33)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 13.57), controlPoint1: CGPoint(x: 13.61, y: 16.38), controlPoint2: CGPoint(x: 16.42, y: 13.57)) bezierPath.addCurve(to: CGPoint(x: 26.19, y: 19.86), controlPoint1: CGPoint(x: 23.37, y: 13.57), controlPoint2: CGPoint(x: 26.19, y: 16.38)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 26.15), controlPoint1: CGPoint(x: 26.19, y: 23.33), controlPoint2: CGPoint(x: 23.37, y: 26.15)) bezierPath.close() bezierPath.move(to: CGPoint(x: 19.9, y: 10.17)) bezierPath.addCurve(to: CGPoint(x: 10.21, y: 19.86), controlPoint1: CGPoint(x: 14.55, y: 10.17), controlPoint2: CGPoint(x: 10.21, y: 14.51)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 29.55), controlPoint1: CGPoint(x: 10.21, y: 25.21), controlPoint2: CGPoint(x: 14.55, y: 29.55)) bezierPath.addCurve(to: CGPoint(x: 29.59, y: 19.86), controlPoint1: CGPoint(x: 25.25, y: 29.55), controlPoint2: CGPoint(x: 29.59, y: 25.21)) bezierPath.addCurve(to: CGPoint(x: 19.9, y: 10.17), controlPoint1: CGPoint(x: 29.59, y: 14.51), controlPoint2: CGPoint(x: 25.25, y: 10.17)) bezierPath.addLine(to: CGPoint(x: 19.9, y: 10.17)) bezierPath.close() bezierPath.move(to: CGPoint(x: 32.43, y: 9.57)) bezierPath.addCurve(to: CGPoint(x: 30.23, y: 11.77), controlPoint1: CGPoint(x: 32.43, y: 10.79), controlPoint2: CGPoint(x: 31.44, y: 11.77)) bezierPath.addCurve(to: CGPoint(x: 28.03, y: 9.57), controlPoint1: CGPoint(x: 29.01, y: 11.77), controlPoint2: CGPoint(x: 28.03, y: 10.79)) bezierPath.addCurve(to: CGPoint(x: 30.23, y: 7.38), controlPoint1: CGPoint(x: 28.03, y: 8.36), controlPoint2: CGPoint(x: 29.01, y: 7.38)) bezierPath.addCurve(to: CGPoint(x: 32.43, y: 9.57), controlPoint1: CGPoint(x: 31.44, y: 7.38), controlPoint2: CGPoint(x: 32.43, y: 8.36)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawVK(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 40, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 40, y: resizedFrame.height / 40) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 32.57, y: 19.79)) bezierPath.addCurve(to: CGPoint(x: 38.07, y: 10.51), controlPoint1: CGPoint(x: 32.57, y: 19.79), controlPoint2: CGPoint(x: 37.57, y: 12.8)) bezierPath.addCurve(to: CGPoint(x: 37.01, y: 9.23), controlPoint1: CGPoint(x: 38.24, y: 9.69), controlPoint2: CGPoint(x: 37.87, y: 9.23)) bezierPath.addCurve(to: CGPoint(x: 32.67, y: 9.23), controlPoint1: CGPoint(x: 37.01, y: 9.23), controlPoint2: CGPoint(x: 34.13, y: 9.23)) bezierPath.addCurve(to: CGPoint(x: 31.01, y: 10.28), controlPoint1: CGPoint(x: 31.67, y: 9.23), controlPoint2: CGPoint(x: 31.31, y: 9.66)) bezierPath.addCurve(to: CGPoint(x: 25.8, y: 18.34), controlPoint1: CGPoint(x: 31.01, y: 10.28), controlPoint2: CGPoint(x: 28.66, y: 15.23)) bezierPath.addCurve(to: CGPoint(x: 23.91, y: 19.66), controlPoint1: CGPoint(x: 24.89, y: 19.35), controlPoint2: CGPoint(x: 24.42, y: 19.66)) bezierPath.addCurve(to: CGPoint(x: 23.32, y: 18.41), controlPoint1: CGPoint(x: 23.5, y: 19.66), controlPoint2: CGPoint(x: 23.32, y: 19.32)) bezierPath.addLine(to: CGPoint(x: 23.32, y: 10.44)) bezierPath.addCurve(to: CGPoint(x: 22.25, y: 9), controlPoint1: CGPoint(x: 23.32, y: 9.33), controlPoint2: CGPoint(x: 23.18, y: 9)) bezierPath.addLine(to: CGPoint(x: 15.29, y: 9)) bezierPath.addCurve(to: CGPoint(x: 14.43, y: 9.72), controlPoint1: CGPoint(x: 14.76, y: 9), controlPoint2: CGPoint(x: 14.43, y: 9.31)) bezierPath.addCurve(to: CGPoint(x: 16.05, y: 13.85), controlPoint1: CGPoint(x: 14.43, y: 10.77), controlPoint2: CGPoint(x: 16.05, y: 11.01)) bezierPath.addLine(to: CGPoint(x: 16.05, y: 19.72)) bezierPath.addCurve(to: CGPoint(x: 15.42, y: 21.36), controlPoint1: CGPoint(x: 16.05, y: 20.9), controlPoint2: CGPoint(x: 15.99, y: 21.36)) bezierPath.addCurve(to: CGPoint(x: 8.39, y: 10.51), controlPoint1: CGPoint(x: 13.93, y: 21.36), controlPoint2: CGPoint(x: 10.38, y: 16.28)) bezierPath.addCurve(to: CGPoint(x: 6.44, y: 9), controlPoint1: CGPoint(x: 8, y: 9.33), controlPoint2: CGPoint(x: 7.57, y: 9)) bezierPath.addLine(to: CGPoint(x: 2.09, y: 9)) bezierPath.addCurve(to: CGPoint(x: 1, y: 10.05), controlPoint1: CGPoint(x: 1.46, y: 9), controlPoint2: CGPoint(x: 1, y: 9.43)) bezierPath.addCurve(to: CGPoint(x: 7.7, y: 23.62), controlPoint1: CGPoint(x: 1, y: 11.2), controlPoint2: CGPoint(x: 2.36, y: 16.51)) bezierPath.addCurve(to: CGPoint(x: 20.23, y: 31), controlPoint1: CGPoint(x: 11.28, y: 28.41), controlPoint2: CGPoint(x: 15.99, y: 31)) bezierPath.addCurve(to: CGPoint(x: 23.45, y: 29.49), controlPoint1: CGPoint(x: 22.82, y: 31), controlPoint2: CGPoint(x: 23.45, y: 30.57)) bezierPath.addLine(to: CGPoint(x: 23.45, y: 25.82)) bezierPath.addCurve(to: CGPoint(x: 24.34, y: 24.51), controlPoint1: CGPoint(x: 23.45, y: 24.9), controlPoint2: CGPoint(x: 23.81, y: 24.51)) bezierPath.addCurve(to: CGPoint(x: 28.46, y: 27.1), controlPoint1: CGPoint(x: 24.94, y: 24.51), controlPoint2: CGPoint(x: 25.99, y: 24.7)) bezierPath.addCurve(to: CGPoint(x: 33.16, y: 31), controlPoint1: CGPoint(x: 31.37, y: 29.85), controlPoint2: CGPoint(x: 31.57, y: 31)) bezierPath.addLine(to: CGPoint(x: 38.04, y: 31)) bezierPath.addCurve(to: CGPoint(x: 39, y: 29.95), controlPoint1: CGPoint(x: 38.54, y: 31), controlPoint2: CGPoint(x: 39, y: 30.77)) bezierPath.addCurve(to: CGPoint(x: 35.39, y: 24.64), controlPoint1: CGPoint(x: 39, y: 28.87), controlPoint2: CGPoint(x: 37.57, y: 26.93)) bezierPath.addCurve(to: CGPoint(x: 32.57, y: 21.59), controlPoint1: CGPoint(x: 34.49, y: 23.46), controlPoint2: CGPoint(x: 33.03, y: 22.18)) bezierPath.addCurve(to: CGPoint(x: 32.57, y: 19.79), controlPoint1: CGPoint(x: 31.9, y: 20.9), controlPoint2: CGPoint(x: 32.1, y: 20.51)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawWhatsapp(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 40, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 40, y: resizedFrame.height / 40) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 28.52, y: 22.97)) bezierPath.addCurve(to: CGPoint(x: 25.54, y: 21.56), controlPoint1: CGPoint(x: 28.08, y: 22.76), controlPoint2: CGPoint(x: 25.94, y: 21.71)) bezierPath.addCurve(to: CGPoint(x: 24.56, y: 21.78), controlPoint1: CGPoint(x: 25.14, y: 21.42), controlPoint2: CGPoint(x: 24.85, y: 21.35)) bezierPath.addCurve(to: CGPoint(x: 23.18, y: 23.48), controlPoint1: CGPoint(x: 24.27, y: 22.21), controlPoint2: CGPoint(x: 23.44, y: 23.19)) bezierPath.addCurve(to: CGPoint(x: 22.24, y: 23.59), controlPoint1: CGPoint(x: 22.93, y: 23.77), controlPoint2: CGPoint(x: 22.68, y: 23.81)) bezierPath.addCurve(to: CGPoint(x: 18.74, y: 21.44), controlPoint1: CGPoint(x: 21.81, y: 23.37), controlPoint2: CGPoint(x: 20.4, y: 22.91)) bezierPath.addCurve(to: CGPoint(x: 16.32, y: 18.44), controlPoint1: CGPoint(x: 17.44, y: 20.29), controlPoint2: CGPoint(x: 16.57, y: 18.87)) bezierPath.addCurve(to: CGPoint(x: 16.51, y: 17.55), controlPoint1: CGPoint(x: 16.06, y: 18), controlPoint2: CGPoint(x: 16.29, y: 17.77)) bezierPath.addCurve(to: CGPoint(x: 17.16, y: 16.79), controlPoint1: CGPoint(x: 16.7, y: 17.36), controlPoint2: CGPoint(x: 16.94, y: 17.05)) bezierPath.addCurve(to: CGPoint(x: 17.6, y: 16.07), controlPoint1: CGPoint(x: 17.38, y: 16.54), controlPoint2: CGPoint(x: 17.45, y: 16.36)) bezierPath.addCurve(to: CGPoint(x: 17.56, y: 15.31), controlPoint1: CGPoint(x: 17.74, y: 15.78), controlPoint2: CGPoint(x: 17.67, y: 15.53)) bezierPath.addCurve(to: CGPoint(x: 16.22, y: 12.09), controlPoint1: CGPoint(x: 17.45, y: 15.09), controlPoint2: CGPoint(x: 16.58, y: 12.96)) bezierPath.addCurve(to: CGPoint(x: 15.24, y: 11.35), controlPoint1: CGPoint(x: 15.86, y: 11.25), controlPoint2: CGPoint(x: 15.51, y: 11.36)) bezierPath.addCurve(to: CGPoint(x: 14.4, y: 11.33), controlPoint1: CGPoint(x: 14.98, y: 11.34), controlPoint2: CGPoint(x: 14.69, y: 11.33)) bezierPath.addCurve(to: CGPoint(x: 13.24, y: 11.88), controlPoint1: CGPoint(x: 14.11, y: 11.33), controlPoint2: CGPoint(x: 13.64, y: 11.44)) bezierPath.addCurve(to: CGPoint(x: 11.72, y: 15.49), controlPoint1: CGPoint(x: 12.84, y: 12.31), controlPoint2: CGPoint(x: 11.72, y: 13.36)) bezierPath.addCurve(to: CGPoint(x: 13.5, y: 19.97), controlPoint1: CGPoint(x: 11.72, y: 17.62), controlPoint2: CGPoint(x: 13.28, y: 19.68)) bezierPath.addCurve(to: CGPoint(x: 20.93, y: 26.52), controlPoint1: CGPoint(x: 13.71, y: 20.26), controlPoint2: CGPoint(x: 16.57, y: 24.64)) bezierPath.addCurve(to: CGPoint(x: 23.42, y: 27.43), controlPoint1: CGPoint(x: 21.97, y: 26.96), controlPoint2: CGPoint(x: 22.78, y: 27.23)) bezierPath.addCurve(to: CGPoint(x: 26.16, y: 27.6), controlPoint1: CGPoint(x: 24.46, y: 27.76), controlPoint2: CGPoint(x: 25.41, y: 27.71)) bezierPath.addCurve(to: CGPoint(x: 29.1, y: 25.54), controlPoint1: CGPoint(x: 27, y: 27.48), controlPoint2: CGPoint(x: 28.74, y: 26.55)) bezierPath.addCurve(to: CGPoint(x: 29.35, y: 23.48), controlPoint1: CGPoint(x: 29.46, y: 24.53), controlPoint2: CGPoint(x: 29.46, y: 23.66)) bezierPath.addCurve(to: CGPoint(x: 28.52, y: 22.97), controlPoint1: CGPoint(x: 29.24, y: 23.3), controlPoint2: CGPoint(x: 28.95, y: 23.19)) bezierPath.close() bezierPath.move(to: CGPoint(x: 20.57, y: 33.77)) bezierPath.addLine(to: CGPoint(x: 20.57, y: 33.77)) bezierPath.addCurve(to: CGPoint(x: 13.2, y: 31.76), controlPoint1: CGPoint(x: 17.97, y: 33.77), controlPoint2: CGPoint(x: 15.42, y: 33.07)) bezierPath.addLine(to: CGPoint(x: 12.67, y: 31.45)) bezierPath.addLine(to: CGPoint(x: 7.18, y: 32.88)) bezierPath.addLine(to: CGPoint(x: 8.65, y: 27.56)) bezierPath.addLine(to: CGPoint(x: 8.3, y: 27.01)) bezierPath.addCurve(to: CGPoint(x: 6.09, y: 19.34), controlPoint1: CGPoint(x: 6.85, y: 24.72), controlPoint2: CGPoint(x: 6.09, y: 22.07)) bezierPath.addCurve(to: CGPoint(x: 20.58, y: 4.93), controlPoint1: CGPoint(x: 6.09, y: 11.4), controlPoint2: CGPoint(x: 12.59, y: 4.93)) bezierPath.addCurve(to: CGPoint(x: 30.82, y: 9.16), controlPoint1: CGPoint(x: 24.45, y: 4.93), controlPoint2: CGPoint(x: 28.08, y: 6.43)) bezierPath.addCurve(to: CGPoint(x: 35.06, y: 19.35), controlPoint1: CGPoint(x: 33.55, y: 11.88), controlPoint2: CGPoint(x: 35.06, y: 15.5)) bezierPath.addCurve(to: CGPoint(x: 20.57, y: 33.77), controlPoint1: CGPoint(x: 35.05, y: 27.3), controlPoint2: CGPoint(x: 28.56, y: 33.77)) bezierPath.close() bezierPath.move(to: CGPoint(x: 32.9, y: 7.09)) bezierPath.addCurve(to: CGPoint(x: 20.57, y: 2), controlPoint1: CGPoint(x: 29.61, y: 3.81), controlPoint2: CGPoint(x: 25.23, y: 2)) bezierPath.addCurve(to: CGPoint(x: 3.15, y: 19.34), controlPoint1: CGPoint(x: 10.97, y: 2), controlPoint2: CGPoint(x: 3.15, y: 9.78)) bezierPath.addCurve(to: CGPoint(x: 5.47, y: 28.01), controlPoint1: CGPoint(x: 3.14, y: 22.4), controlPoint2: CGPoint(x: 3.95, y: 25.38)) bezierPath.addLine(to: CGPoint(x: 3, y: 37)) bezierPath.addLine(to: CGPoint(x: 12.24, y: 34.59)) bezierPath.addCurve(to: CGPoint(x: 20.57, y: 36.7), controlPoint1: CGPoint(x: 14.78, y: 35.97), controlPoint2: CGPoint(x: 17.65, y: 36.7)) bezierPath.addLine(to: CGPoint(x: 20.57, y: 36.7)) bezierPath.addLine(to: CGPoint(x: 20.57, y: 36.7)) bezierPath.addCurve(to: CGPoint(x: 38, y: 19.36), controlPoint1: CGPoint(x: 30.18, y: 36.7), controlPoint2: CGPoint(x: 38, y: 28.92)) bezierPath.addCurve(to: CGPoint(x: 32.9, y: 7.09), controlPoint1: CGPoint(x: 38, y: 14.72), controlPoint2: CGPoint(x: 36.19, y: 10.36)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawTelegram(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 40, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 40, y: resizedFrame.height / 40) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 35.15, y: 4.5)) bezierPath.addCurve(to: CGPoint(x: 33.94, y: 4.79), controlPoint1: CGPoint(x: 34.74, y: 4.51), controlPoint2: CGPoint(x: 34.32, y: 4.62)) bezierPath.addCurve(to: CGPoint(x: 18.74, y: 10.7), controlPoint1: CGPoint(x: 33.25, y: 5.06), controlPoint2: CGPoint(x: 26, y: 7.88)) bezierPath.addCurve(to: CGPoint(x: 8.69, y: 14.6), controlPoint1: CGPoint(x: 15.11, y: 12.12), controlPoint2: CGPoint(x: 11.49, y: 13.52)) bezierPath.addCurve(to: CGPoint(x: 3.67, y: 16.54), controlPoint1: CGPoint(x: 5.9, y: 15.69), controlPoint2: CGPoint(x: 3.87, y: 16.47)) bezierPath.addCurve(to: CGPoint(x: 1.4, y: 17.91), controlPoint1: CGPoint(x: 3.01, y: 16.77), controlPoint2: CGPoint(x: 2.05, y: 17.15)) bezierPath.addCurve(to: CGPoint(x: 1.12, y: 19.55), controlPoint1: CGPoint(x: 1.08, y: 18.28), controlPoint2: CGPoint(x: 0.84, y: 18.97)) bezierPath.addCurve(to: CGPoint(x: 2.72, y: 20.75), controlPoint1: CGPoint(x: 1.41, y: 20.13), controlPoint2: CGPoint(x: 1.95, y: 20.46)) bezierPath.addLine(to: CGPoint(x: 2.74, y: 20.76)) bezierPath.addLine(to: CGPoint(x: 2.76, y: 20.77)) bezierPath.addCurve(to: CGPoint(x: 10.35, y: 23.15), controlPoint1: CGPoint(x: 5.56, y: 21.64), controlPoint2: CGPoint(x: 9.78, y: 22.97)) bezierPath.addCurve(to: CGPoint(x: 13.25, y: 32.72), controlPoint1: CGPoint(x: 10.5, y: 23.63), controlPoint2: CGPoint(x: 12.28, y: 29.53)) bezierPath.addCurve(to: CGPoint(x: 14.93, y: 33.73), controlPoint1: CGPoint(x: 13.5, y: 33.38), controlPoint2: CGPoint(x: 14.24, y: 33.82)) bezierPath.addCurve(to: CGPoint(x: 15.53, y: 33.67), controlPoint1: CGPoint(x: 15.05, y: 33.73), controlPoint2: CGPoint(x: 15.28, y: 33.73)) bezierPath.addCurve(to: CGPoint(x: 16.83, y: 32.94), controlPoint1: CGPoint(x: 15.9, y: 33.58), controlPoint2: CGPoint(x: 16.38, y: 33.37)) bezierPath.addLine(to: CGPoint(x: 16.83, y: 32.94)) bezierPath.addCurve(to: CGPoint(x: 20.46, y: 29.4), controlPoint1: CGPoint(x: 17.48, y: 32.33), controlPoint2: CGPoint(x: 19.78, y: 30.07)) bezierPath.addLine(to: CGPoint(x: 27.96, y: 34.96)) bezierPath.addLine(to: CGPoint(x: 27.99, y: 34.98)) bezierPath.addCurve(to: CGPoint(x: 29.57, y: 35.49), controlPoint1: CGPoint(x: 27.99, y: 34.98), controlPoint2: CGPoint(x: 28.67, y: 35.43)) bezierPath.addCurve(to: CGPoint(x: 31.04, y: 35.09), controlPoint1: CGPoint(x: 30.01, y: 35.52), controlPoint2: CGPoint(x: 30.56, y: 35.44)) bezierPath.addCurve(to: CGPoint(x: 32.02, y: 33.42), controlPoint1: CGPoint(x: 31.51, y: 34.75), controlPoint2: CGPoint(x: 31.85, y: 34.17)) bezierPath.addCurve(to: CGPoint(x: 37.28, y: 8.61), controlPoint1: CGPoint(x: 32.61, y: 30.86), controlPoint2: CGPoint(x: 36.6, y: 11.79)) bezierPath.addCurve(to: CGPoint(x: 36.71, y: 5.03), controlPoint1: CGPoint(x: 37.71, y: 6.99), controlPoint2: CGPoint(x: 37.51, y: 5.73)) bezierPath.addCurve(to: CGPoint(x: 35.33, y: 4.5), controlPoint1: CGPoint(x: 36.3, y: 4.68), controlPoint2: CGPoint(x: 35.82, y: 4.52)) bezierPath.addCurve(to: CGPoint(x: 35.15, y: 4.5), controlPoint1: CGPoint(x: 35.27, y: 4.5), controlPoint2: CGPoint(x: 35.21, y: 4.5)) bezierPath.addLine(to: CGPoint(x: 35.15, y: 4.5)) bezierPath.close() bezierPath.move(to: CGPoint(x: 35.24, y: 6.07)) bezierPath.addCurve(to: CGPoint(x: 35.68, y: 6.21), controlPoint1: CGPoint(x: 35.43, y: 6.07), controlPoint2: CGPoint(x: 35.59, y: 6.12)) bezierPath.addCurve(to: CGPoint(x: 35.77, y: 8.23), controlPoint1: CGPoint(x: 35.88, y: 6.38), controlPoint2: CGPoint(x: 36.13, y: 6.89)) bezierPath.addCurve(to: CGPoint(x: 30.51, y: 33.07), controlPoint1: CGPoint(x: 33.84, y: 16.86), controlPoint2: CGPoint(x: 32.16, y: 25.68)) bezierPath.addCurve(to: CGPoint(x: 30.12, y: 33.83), controlPoint1: CGPoint(x: 30.4, y: 33.57), controlPoint2: CGPoint(x: 30.24, y: 33.75)) bezierPath.addCurve(to: CGPoint(x: 29.67, y: 33.94), controlPoint1: CGPoint(x: 30, y: 33.92), controlPoint2: CGPoint(x: 29.87, y: 33.95)) bezierPath.addCurve(to: CGPoint(x: 28.82, y: 33.66), controlPoint1: CGPoint(x: 29.28, y: 33.91), controlPoint2: CGPoint(x: 28.84, y: 33.67)) bezierPath.addLine(to: CGPoint(x: 16.66, y: 24.63)) bezierPath.addCurve(to: CGPoint(x: 30.24, y: 11.88), controlPoint1: CGPoint(x: 17.86, y: 23.5), controlPoint2: CGPoint(x: 25.86, y: 15.9)) bezierPath.addCurve(to: CGPoint(x: 29.69, y: 10.6), controlPoint1: CGPoint(x: 30.72, y: 11.42), controlPoint2: CGPoint(x: 30.33, y: 10.59)) bezierPath.addCurve(to: CGPoint(x: 27.45, y: 11.72), controlPoint1: CGPoint(x: 28.87, y: 10.76), controlPoint2: CGPoint(x: 28.19, y: 11.35)) bezierPath.addCurve(to: CGPoint(x: 10.91, y: 21.68), controlPoint1: CGPoint(x: 22.04, y: 14.9), controlPoint2: CGPoint(x: 11.81, y: 21.13)) bezierPath.addCurve(to: CGPoint(x: 3.26, y: 19.29), controlPoint1: CGPoint(x: 10.44, y: 21.53), controlPoint2: CGPoint(x: 6.11, y: 20.17)) bezierPath.addCurve(to: CGPoint(x: 2.59, y: 18.92), controlPoint1: CGPoint(x: 2.81, y: 19.11), controlPoint2: CGPoint(x: 2.65, y: 18.97)) bezierPath.addCurve(to: CGPoint(x: 2.59, y: 18.92), controlPoint1: CGPoint(x: 2.59, y: 18.92), controlPoint2: CGPoint(x: 2.59, y: 18.92)) bezierPath.addCurve(to: CGPoint(x: 4.19, y: 18.01), controlPoint1: CGPoint(x: 2.8, y: 18.67), controlPoint2: CGPoint(x: 3.67, y: 18.19)) bezierPath.addCurve(to: CGPoint(x: 9.25, y: 16.06), controlPoint1: CGPoint(x: 4.57, y: 17.87), controlPoint2: CGPoint(x: 6.46, y: 17.14)) bezierPath.addCurve(to: CGPoint(x: 19.3, y: 12.16), controlPoint1: CGPoint(x: 12.05, y: 14.98), controlPoint2: CGPoint(x: 15.67, y: 13.57)) bezierPath.addCurve(to: CGPoint(x: 34.56, y: 6.23), controlPoint1: CGPoint(x: 24.39, y: 10.19), controlPoint2: CGPoint(x: 29.48, y: 8.21)) bezierPath.addCurve(to: CGPoint(x: 35.24, y: 6.07), controlPoint1: CGPoint(x: 34.81, y: 6.11), controlPoint2: CGPoint(x: 35.04, y: 6.06)) bezierPath.addLine(to: CGPoint(x: 35.24, y: 6.07)) bezierPath.close() bezierPath.move(to: CGPoint(x: 16.15, y: 26.2)) bezierPath.addLine(to: CGPoint(x: 19.19, y: 28.45)) bezierPath.addCurve(to: CGPoint(x: 15.79, y: 31.79), controlPoint1: CGPoint(x: 18.35, y: 29.29), controlPoint2: CGPoint(x: 16.35, y: 31.26)) bezierPath.addLine(to: CGPoint(x: 16.15, y: 26.2)) bezierPath.addLine(to: CGPoint(x: 16.15, y: 26.2)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawFacebook(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 41, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 41, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 41, y: resizedFrame.height / 40) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 22.36, y: 21.49)) bezierPath.addLine(to: CGPoint(x: 27.52, y: 21.49)) bezierPath.addLine(to: CGPoint(x: 28.29, y: 15.45)) bezierPath.addLine(to: CGPoint(x: 22.36, y: 15.45)) bezierPath.addLine(to: CGPoint(x: 22.36, y: 11.59)) bezierPath.addCurve(to: CGPoint(x: 25.33, y: 8.65), controlPoint1: CGPoint(x: 22.36, y: 9.84), controlPoint2: CGPoint(x: 22.84, y: 8.65)) bezierPath.addLine(to: CGPoint(x: 28.5, y: 8.64)) bezierPath.addLine(to: CGPoint(x: 28.5, y: 3.24)) bezierPath.addCurve(to: CGPoint(x: 23.88, y: 3), controlPoint1: CGPoint(x: 27.95, y: 3.16), controlPoint2: CGPoint(x: 26.07, y: 3)) bezierPath.addCurve(to: CGPoint(x: 16.17, y: 10.99), controlPoint1: CGPoint(x: 19.3, y: 3), controlPoint2: CGPoint(x: 16.17, y: 5.82)) bezierPath.addLine(to: CGPoint(x: 16.17, y: 15.45)) bezierPath.addLine(to: CGPoint(x: 11, y: 15.45)) bezierPath.addLine(to: CGPoint(x: 11, y: 21.49)) bezierPath.addLine(to: CGPoint(x: 16.17, y: 21.49)) bezierPath.addLine(to: CGPoint(x: 16.17, y: 37)) bezierPath.addLine(to: CGPoint(x: 22.36, y: 37)) bezierPath.addLine(to: CGPoint(x: 22.36, y: 21.49)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawViber(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 41, height: 40), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 41, height: 40), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 41, y: resizedFrame.height / 40) //// Bezier 5 Drawing let bezier5Path = UIBezierPath() bezier5Path.move(to: CGPoint(x: 34, y: 16.95)) bezier5Path.addCurve(to: CGPoint(x: 23.83, y: 6), controlPoint1: CGPoint(x: 34.05, y: 11.59), controlPoint2: CGPoint(x: 29.49, y: 6.68)) bezier5Path.addCurve(to: CGPoint(x: 23.47, y: 5.94), controlPoint1: CGPoint(x: 23.72, y: 5.98), controlPoint2: CGPoint(x: 23.6, y: 5.96)) bezier5Path.addCurve(to: CGPoint(x: 22.61, y: 5.85), controlPoint1: CGPoint(x: 23.19, y: 5.9), controlPoint2: CGPoint(x: 22.9, y: 5.85)) bezier5Path.addCurve(to: CGPoint(x: 21.06, y: 7.15), controlPoint1: CGPoint(x: 21.45, y: 5.85), controlPoint2: CGPoint(x: 21.14, y: 6.66)) bezier5Path.addCurve(to: CGPoint(x: 21.28, y: 8.33), controlPoint1: CGPoint(x: 20.98, y: 7.62), controlPoint2: CGPoint(x: 21.05, y: 8.02)) bezier5Path.addCurve(to: CGPoint(x: 22.88, y: 9.02), controlPoint1: CGPoint(x: 21.67, y: 8.85), controlPoint2: CGPoint(x: 22.34, y: 8.94)) bezier5Path.addCurve(to: CGPoint(x: 23.32, y: 9.09), controlPoint1: CGPoint(x: 23.04, y: 9.04), controlPoint2: CGPoint(x: 23.19, y: 9.06)) bezier5Path.addCurve(to: CGPoint(x: 30.94, y: 17.04), controlPoint1: CGPoint(x: 28.4, y: 10.22), controlPoint2: CGPoint(x: 30.11, y: 12.01)) bezier5Path.addCurve(to: CGPoint(x: 30.98, y: 17.48), controlPoint1: CGPoint(x: 30.96, y: 17.17), controlPoint2: CGPoint(x: 30.97, y: 17.32)) bezier5Path.addCurve(to: CGPoint(x: 32.44, y: 19.33), controlPoint1: CGPoint(x: 31.02, y: 18.08), controlPoint2: CGPoint(x: 31.1, y: 19.33)) bezier5Path.addLine(to: CGPoint(x: 32.44, y: 19.33)) bezier5Path.addCurve(to: CGPoint(x: 32.8, y: 19.3), controlPoint1: CGPoint(x: 32.55, y: 19.33), controlPoint2: CGPoint(x: 32.68, y: 19.32)) bezier5Path.addCurve(to: CGPoint(x: 34, y: 17.42), controlPoint1: CGPoint(x: 34.05, y: 19.11), controlPoint2: CGPoint(x: 34.02, y: 17.97)) bezier5Path.addCurve(to: CGPoint(x: 34, y: 17.02), controlPoint1: CGPoint(x: 33.99, y: 17.26), controlPoint2: CGPoint(x: 33.99, y: 17.12)) bezier5Path.addCurve(to: CGPoint(x: 34, y: 16.95), controlPoint1: CGPoint(x: 34, y: 17), controlPoint2: CGPoint(x: 34, y: 16.97)) bezier5Path.close() bezier5Path.move(to: CGPoint(x: 22.28, y: 4.03)) bezier5Path.addCurve(to: CGPoint(x: 22.69, y: 4.07), controlPoint1: CGPoint(x: 22.43, y: 4.04), controlPoint2: CGPoint(x: 22.57, y: 4.05)) bezier5Path.addCurve(to: CGPoint(x: 35.93, y: 17.71), controlPoint1: CGPoint(x: 31.03, y: 5.35), controlPoint2: CGPoint(x: 34.87, y: 9.31)) bezier5Path.addCurve(to: CGPoint(x: 35.95, y: 18.22), controlPoint1: CGPoint(x: 35.95, y: 17.86), controlPoint2: CGPoint(x: 35.95, y: 18.03)) bezier5Path.addCurve(to: CGPoint(x: 37.45, y: 20.27), controlPoint1: CGPoint(x: 35.97, y: 18.87), controlPoint2: CGPoint(x: 35.99, y: 20.24)) bezier5Path.addLine(to: CGPoint(x: 37.5, y: 20.27)) bezier5Path.addCurve(to: CGPoint(x: 38.59, y: 19.85), controlPoint1: CGPoint(x: 37.96, y: 20.27), controlPoint2: CGPoint(x: 38.33, y: 20.13)) bezier5Path.addCurve(to: CGPoint(x: 38.99, y: 18.1), controlPoint1: CGPoint(x: 39.04, y: 19.38), controlPoint2: CGPoint(x: 39.01, y: 18.67)) bezier5Path.addCurve(to: CGPoint(x: 38.98, y: 17.71), controlPoint1: CGPoint(x: 38.98, y: 17.96), controlPoint2: CGPoint(x: 38.98, y: 17.82)) bezier5Path.addCurve(to: CGPoint(x: 23.05, y: 1.02), controlPoint1: CGPoint(x: 39.08, y: 9.11), controlPoint2: CGPoint(x: 31.64, y: 1.31)) bezier5Path.addCurve(to: CGPoint(x: 22.95, y: 1.03), controlPoint1: CGPoint(x: 23.01, y: 1.02), controlPoint2: CGPoint(x: 22.98, y: 1.02)) bezier5Path.addCurve(to: CGPoint(x: 22.84, y: 1.03), controlPoint1: CGPoint(x: 22.93, y: 1.03), controlPoint2: CGPoint(x: 22.9, y: 1.03)) bezier5Path.addCurve(to: CGPoint(x: 22.54, y: 1.02), controlPoint1: CGPoint(x: 22.76, y: 1.03), controlPoint2: CGPoint(x: 22.65, y: 1.03)) bezier5Path.addCurve(to: CGPoint(x: 22.1, y: 1), controlPoint1: CGPoint(x: 22.41, y: 1.01), controlPoint2: CGPoint(x: 22.25, y: 1)) bezier5Path.addCurve(to: CGPoint(x: 20.44, y: 2.55), controlPoint1: CGPoint(x: 20.73, y: 1), controlPoint2: CGPoint(x: 20.47, y: 1.97)) bezier5Path.addCurve(to: CGPoint(x: 22.28, y: 4.03), controlPoint1: CGPoint(x: 20.36, y: 3.89), controlPoint2: CGPoint(x: 21.66, y: 3.99)) bezier5Path.close() bezier5Path.move(to: CGPoint(x: 35.53, y: 28.58)) bezier5Path.addCurve(to: CGPoint(x: 35, y: 28.17), controlPoint1: CGPoint(x: 35.35, y: 28.44), controlPoint2: CGPoint(x: 35.17, y: 28.3)) bezier5Path.addCurve(to: CGPoint(x: 32.18, y: 26.1), controlPoint1: CGPoint(x: 34.09, y: 27.43), controlPoint2: CGPoint(x: 33.12, y: 26.76)) bezier5Path.addCurve(to: CGPoint(x: 31.6, y: 25.7), controlPoint1: CGPoint(x: 31.98, y: 25.97), controlPoint2: CGPoint(x: 31.79, y: 25.83)) bezier5Path.addCurve(to: CGPoint(x: 28.3, y: 24.44), controlPoint1: CGPoint(x: 30.4, y: 24.85), controlPoint2: CGPoint(x: 29.32, y: 24.44)) bezier5Path.addCurve(to: CGPoint(x: 24.74, y: 26.7), controlPoint1: CGPoint(x: 26.92, y: 24.44), controlPoint2: CGPoint(x: 25.73, y: 25.2)) bezier5Path.addCurve(to: CGPoint(x: 23.12, y: 27.68), controlPoint1: CGPoint(x: 24.3, y: 27.36), controlPoint2: CGPoint(x: 23.77, y: 27.68)) bezier5Path.addCurve(to: CGPoint(x: 21.81, y: 27.36), controlPoint1: CGPoint(x: 22.73, y: 27.68), controlPoint2: CGPoint(x: 22.29, y: 27.57)) bezier5Path.addCurve(to: CGPoint(x: 13.59, y: 19.35), controlPoint1: CGPoint(x: 17.93, y: 25.6), controlPoint2: CGPoint(x: 15.17, y: 22.91)) bezier5Path.addCurve(to: CGPoint(x: 14.42, y: 15.59), controlPoint1: CGPoint(x: 12.82, y: 17.63), controlPoint2: CGPoint(x: 13.07, y: 16.51)) bezier5Path.addCurve(to: CGPoint(x: 16.5, y: 12.26), controlPoint1: CGPoint(x: 15.18, y: 15.07), controlPoint2: CGPoint(x: 16.6, y: 14.11)) bezier5Path.addCurve(to: CGPoint(x: 9.8, y: 3.12), controlPoint1: CGPoint(x: 16.39, y: 10.16), controlPoint2: CGPoint(x: 11.75, y: 3.84)) bezier5Path.addCurve(to: CGPoint(x: 7.22, y: 3.11), controlPoint1: CGPoint(x: 8.97, y: 2.82), controlPoint2: CGPoint(x: 8.11, y: 2.81)) bezier5Path.addCurve(to: CGPoint(x: 2.56, y: 6.95), controlPoint1: CGPoint(x: 4.97, y: 3.87), controlPoint2: CGPoint(x: 3.36, y: 5.19)) bezier5Path.addCurve(to: CGPoint(x: 2.66, y: 12.7), controlPoint1: CGPoint(x: 1.78, y: 8.64), controlPoint2: CGPoint(x: 1.82, y: 10.63)) bezier5Path.addCurve(to: CGPoint(x: 12.84, y: 28.19), controlPoint1: CGPoint(x: 5.09, y: 18.67), controlPoint2: CGPoint(x: 8.52, y: 23.89)) bezier5Path.addCurve(to: CGPoint(x: 28.27, y: 38.44), controlPoint1: CGPoint(x: 17.06, y: 32.4), controlPoint2: CGPoint(x: 22.26, y: 35.85)) bezier5Path.addCurve(to: CGPoint(x: 29.8, y: 38.9), controlPoint1: CGPoint(x: 28.82, y: 38.68), controlPoint2: CGPoint(x: 29.39, y: 38.8)) bezier5Path.addCurve(to: CGPoint(x: 30.15, y: 38.98), controlPoint1: CGPoint(x: 29.94, y: 38.93), controlPoint2: CGPoint(x: 30.07, y: 38.95)) bezier5Path.addCurve(to: CGPoint(x: 30.3, y: 39), controlPoint1: CGPoint(x: 30.2, y: 38.99), controlPoint2: CGPoint(x: 30.25, y: 39)) bezier5Path.addLine(to: CGPoint(x: 30.35, y: 39)) bezier5Path.addLine(to: CGPoint(x: 30.35, y: 39)) bezier5Path.addCurve(to: CGPoint(x: 37.63, y: 33.46), controlPoint1: CGPoint(x: 33.18, y: 39), controlPoint2: CGPoint(x: 36.58, y: 36.41)) bezier5Path.addCurve(to: CGPoint(x: 35.53, y: 28.58), controlPoint1: CGPoint(x: 38.54, y: 30.88), controlPoint2: CGPoint(x: 36.87, y: 29.61)) bezier5Path.close() bezier5Path.move(to: CGPoint(x: 23.53, y: 10.86)) bezier5Path.addCurve(to: CGPoint(x: 21.68, y: 11.93), controlPoint1: CGPoint(x: 23.05, y: 10.87), controlPoint2: CGPoint(x: 22.04, y: 10.9)) bezier5Path.addCurve(to: CGPoint(x: 21.74, y: 13.16), controlPoint1: CGPoint(x: 21.52, y: 12.41), controlPoint2: CGPoint(x: 21.54, y: 12.82)) bezier5Path.addCurve(to: CGPoint(x: 23.14, y: 13.9), controlPoint1: CGPoint(x: 22.04, y: 13.67), controlPoint2: CGPoint(x: 22.62, y: 13.82)) bezier5Path.addCurve(to: CGPoint(x: 26.21, y: 17.21), controlPoint1: CGPoint(x: 25.04, y: 14.21), controlPoint2: CGPoint(x: 26.02, y: 15.26)) bezier5Path.addCurve(to: CGPoint(x: 27.7, y: 18.75), controlPoint1: CGPoint(x: 26.3, y: 18.12), controlPoint2: CGPoint(x: 26.91, y: 18.75)) bezier5Path.addLine(to: CGPoint(x: 27.7, y: 18.75)) bezier5Path.addCurve(to: CGPoint(x: 27.88, y: 18.74), controlPoint1: CGPoint(x: 27.76, y: 18.75), controlPoint2: CGPoint(x: 27.82, y: 18.75)) bezier5Path.addCurve(to: CGPoint(x: 29.24, y: 16.68), controlPoint1: CGPoint(x: 28.82, y: 18.63), controlPoint2: CGPoint(x: 29.28, y: 17.94)) bezier5Path.addCurve(to: CGPoint(x: 27.4, y: 12.69), controlPoint1: CGPoint(x: 29.25, y: 15.37), controlPoint2: CGPoint(x: 28.57, y: 13.88)) bezier5Path.addCurve(to: CGPoint(x: 23.53, y: 10.86), controlPoint1: CGPoint(x: 26.23, y: 11.5), controlPoint2: CGPoint(x: 24.82, y: 10.83)) bezier5Path.close() fillColor.setFill() bezier5Path.fill() context.restoreGState() } @objc(SocialIconStyleKitResizingBehavior) public enum ResizingBehavior: Int { case aspectFit /// The content is proportionally resized to fit into the target rectangle. case aspectFill /// The content is proportionally resized to completely fill the target rectangle. case stretch /// The content is stretched to match the entire target rectangle. case center /// The content is centered in the target rectangle, but it is NOT resized. public func apply(rect: CGRect, target: CGRect) -> CGRect { if rect == target || target == CGRect.zero { return rect } var scales = CGSize.zero scales.width = abs(target.width / rect.width) scales.height = abs(target.height / rect.height) switch self { case .aspectFit: scales.width = min(scales.width, scales.height) scales.height = scales.width case .aspectFill: scales.width = max(scales.width, scales.height) scales.height = scales.width case .stretch: break case .center: scales.width = 1 scales.height = 1 } var result = rect.standardized result.size.width *= scales.width result.size.height *= scales.height result.origin.x = target.minX + (target.width - result.width) / 2 result.origin.y = target.minY + (target.height - result.height) / 2 return result } } private override init() {} } }
94.770021
250
0.612831
6252839e6ac94473b29efb010de0974a36595164
1,553
// // Copyright © 2018 Essential Developer. All rights reserved. // import Foundation private struct FeedImageListRemote: Decodable { let items: [FeedImageRemote] } private struct FeedImageRemote: Decodable { let imageId: UUID let imageDesc: String? let imageLoc: String? let imageUrl: URL } public final class RemoteFeedLoader: FeedLoader { private let url: URL private let client: HTTPClient public enum Error: Swift.Error { case connectivity case invalidData } public init(url: URL, client: HTTPClient) { self.url = url self.client = client } public func load(completion: @escaping (FeedLoader.Result) -> Void) { client.get(from: url) { [weak self] result in guard let self = self else { return } switch result { case .failure: completion(.failure(Error.connectivity)) case let .success((data, response)): if let items = self.mapFeedImageListRemote(data: data)?.items, response.statusCode == 200 { completion(.success(items.asFeedImages)) } else { completion(.failure(Error.invalidData)) } } } } private func mapFeedImageListRemote(data: Data) -> FeedImageListRemote? { do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return try decoder.decode(FeedImageListRemote.self, from: data) } catch { return nil } } } private extension Array where Element == FeedImageRemote { var asFeedImages: [FeedImage] { return map { FeedImage(id: $0.imageId, description: $0.imageDesc, location: $0.imageLoc, url: $0.imageUrl) } } }
24.265625
110
0.71217
d6be3196b66e0e85410b0d8b1fdb2e3085abc421
2,019
// // ComplimentTableViewController.swift // X-Things-I-Love-About-You // // Created by Thomas Kellough on 1/24/21. // import UIKit class ComplimentTableViewController: UITableViewController { var compliments: [Compliment] { let days = UserDefaults.standard.integer(forKey: "maxDay") let compliments = AllCompliments().compliments return Array(compliments[0...days]) } override func viewDidLoad() { super.viewDidLoad() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let compliment = compliments[indexPath.row] let image = UIImage(named: compliment.image) cell.imageView?.image = image cell.imageView?.contentMode = .scaleAspectFill cell.textLabel?.text = compliment.title let itemSize = CGSize.init(width: 75, height: 75) UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale); let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize) cell.imageView?.image!.draw(in: imageRect) cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!; UIGraphicsEndImageContext(); return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { compliments.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 75 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(withIdentifier: "ComplimentViewController") as? ComplimentViewController { vc.selectedDay = indexPath.row navigationController?.pushViewController(vc, animated: true) } } }
33.65
132
0.67162
f5a3717f0e303d5d31cd3ceee9912816a9ea2b53
6,150
import Foundation /// A Nimble matcher that succeeds when the actual expression raises an /// exception with the specified name, reason, and/or userInfo. /// /// Alternatively, you can pass a closure to do any arbitrary custom matching /// to the raised exception. The closure only gets called when an exception /// is raised. /// /// nil arguments indicates that the matcher should not attempt to match against /// that parameter. public func raiseException( named named: String? = nil, reason: String? = nil, userInfo: NSDictionary? = nil, closure: ((NSException) -> Void)? = nil) -> MatcherFunc<Any> { return MatcherFunc { actualExpression, failureMessage in var exception: NSException? let capture = NMBExceptionCapture(handler: ({ e in exception = e }), finally: nil) capture.tryBlock { actualExpression.evaluate() return } setFailureMessageForException(failureMessage, exception: exception, named: named, reason: reason, userInfo: userInfo, closure: closure) return exceptionMatchesNonNilFieldsOrClosure(exception, named: named, reason: reason, userInfo: userInfo, closure: closure) } } internal func setFailureMessageForException( failureMessage: FailureMessage, exception: NSException?, named: String?, reason: String?, userInfo: NSDictionary?, closure: ((NSException) -> Void)?) { failureMessage.postfixMessage = "raise exception" if let named = named { failureMessage.postfixMessage += " with name <\(named)>" } if let reason = reason { failureMessage.postfixMessage += " with reason <\(reason)>" } if let userInfo = userInfo { failureMessage.postfixMessage += " with userInfo <\(userInfo)>" } if let _ = closure { failureMessage.postfixMessage += " that satisfies block" } if named == nil && reason == nil && userInfo == nil && closure == nil { failureMessage.postfixMessage = "raise any exception" } if let exception = exception { failureMessage.actualValue = "\(NSStringFromClass(exception.dynamicType)) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }" } else { failureMessage.actualValue = "no exception" } } internal func exceptionMatchesNonNilFieldsOrClosure( exception: NSException?, named: String?, reason: String?, userInfo: NSDictionary?, closure: ((NSException) -> Void)?) -> Bool { var matches = false if let exception = exception { matches = true if named != nil && exception.name != named { matches = false } if reason != nil && exception.reason != reason { matches = false } if userInfo != nil && exception.userInfo != userInfo { matches = false } if let closure = closure { let assertions = gatherFailingExpectations { closure(exception) } let messages = assertions.map { $0.message } if messages.count > 0 { matches = false } } } return matches } public class NMBObjCRaiseExceptionMatcher : NSObject, NMBMatcher { internal var _name: String? internal var _reason: String? internal var _userInfo: NSDictionary? internal var _block: ((NSException) -> Void)? internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) { _name = name _reason = reason _userInfo = userInfo _block = block } public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let block: () -> Any? = ({ actualBlock(); return nil }) let expr = Expression(expression: block, location: location) return raiseException( named: _name, reason: _reason, userInfo: _userInfo, closure: _block ).matches(expr, failureMessage: failureMessage) } public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { return !matches(actualBlock, failureMessage: failureMessage, location: location) } public var named: (name: String) -> NMBObjCRaiseExceptionMatcher { return ({ name in return NMBObjCRaiseExceptionMatcher( name: name, reason: self._reason, userInfo: self._userInfo, block: self._block ) }) } public var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher { return ({ reason in return NMBObjCRaiseExceptionMatcher( name: self._name, reason: reason, userInfo: self._userInfo, block: self._block ) }) } public var userInfo: (userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher { return ({ userInfo in return NMBObjCRaiseExceptionMatcher( name: self._name, reason: self._reason, userInfo: userInfo, block: self._block ) }) } public var satisfyingBlock: (block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher { return ({ block in return NMBObjCRaiseExceptionMatcher( name: self._name, reason: self._reason, userInfo: self._userInfo, block: block ) }) } } extension NMBObjCMatcher { public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher { return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil) } }
34.357542
197
0.586829
f85a4dad6905035d664619fb39bfdeaa6690d599
828
// // File.swift // // // Created by Bagus Andinata on 18/08/20. // import UIKit public struct SkeletonConfig { let colors: [CGColor] let gradientDirection: GradientDirection let animationDuration: Double var transitionShow: SkeletonTransitionStyle var transitionHide: SkeletonTransitionStyle init( colors: [CGColor], gradientDirection: GradientDirection, animationDuration: Double, transitionShow: SkeletonTransitionStyle = .none, transitionHide: SkeletonTransitionStyle = .crossDissolve(0.25) ) { self.colors = colors self.gradientDirection = gradientDirection self.animationDuration = animationDuration self.transitionShow = transitionShow self.transitionHide = transitionHide } }
23
70
0.675121
e4c794e76e31c6a4dc4041abf05df21662aa486b
54,362
// RUN: %target-typecheck-verify-swift -enable-objc-interop -disable-objc-attr-requires-foundation-module -swift-version 5 public protocol PublicProto { func publicReq() } // expected-note@+1 * {{type declared here}} internal protocol InternalProto { func internalReq() } fileprivate protocol FilePrivateProto { func filePrivateReq() } // expected-note@+1 * {{type declared here}} private protocol PrivateProto { func privateReq() } public struct PublicStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-10=public}} private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} internal struct InternalStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}} private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} fileprivate struct FilePrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} public var publicVar = 0 } // expected-note@+1 * {{type declared here}} private struct PrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto { private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} public var publicVar = 0 } public struct PublicStructWithInternalExtension: PublicProto, InternalProto, FilePrivateProto, PrivateProto {} // expected-error@-1 {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} // expected-error@-2 {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} // expected-error@-3 {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} // expected-error@-4 {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} internal extension PublicStructWithInternalExtension { private func publicReq() {} // expected-note {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}} private func internalReq() {} // expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-11=}} private func filePrivateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} private func privateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}} } extension PublicStruct { public init(x: Int) { self.init() } } extension InternalStruct { public init(x: Int) { self.init() } } extension FilePrivateStruct { public init(x: Int) { self.init() } } extension PrivateStruct { public init(x: Int) { self.init() } } public extension PublicStruct { public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}} fileprivate func extFuncPublic() {} private func extImplPublic() {} } internal extension PublicStruct { public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}} fileprivate func extFuncInternal() {} private func extImplInternal() {} } fileprivate extension PublicStruct { public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}} fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}} private func extImplFilePrivate() {} } private extension PublicStruct { public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}} fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}} private func extImplPrivate() {} } public extension InternalStruct { // expected-error {{extension of internal struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} fileprivate func extFuncPublic() {} private func extImplPublic() {} } internal extension InternalStruct { public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}} fileprivate func extFuncInternal() {} private func extImplInternal() {} } fileprivate extension InternalStruct { public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}} fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}} private func extImplFilePrivate() {} } private extension InternalStruct { public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}} fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}} private func extImplPrivate() {} } public extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} fileprivate func extFuncPublic() {} private func extImplPublic() {} } internal extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared internal}} {{1-10=}} public func extMemberInternal() {} fileprivate func extFuncInternal() {} private func extImplInternal() {} } fileprivate extension FilePrivateStruct { public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}} fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}} private func extImplFilePrivate() {} } private extension FilePrivateStruct { public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}} fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}} private func extImplPrivate() {} } public extension PrivateStruct { // expected-error {{extension of private struct cannot be declared public}} {{1-8=}} public func extMemberPublic() {} fileprivate func extFuncPublic() {} private func extImplPublic() {} } internal extension PrivateStruct { // expected-error {{extension of private struct cannot be declared internal}} {{1-10=}} public func extMemberInternal() {} fileprivate func extFuncInternal() {} private func extImplInternal() {} } fileprivate extension PrivateStruct { // expected-error {{extension of private struct cannot be declared fileprivate}} {{1-13=}} public func extMemberFilePrivate() {} fileprivate func extFuncFilePrivate() {} private func extImplFilePrivate() {} } private extension PrivateStruct { public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}} fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}} private func extImplPrivate() {} } public struct PublicStructDefaultMethods: PublicProto, InternalProto, PrivateProto { func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }} func internalReq() {} func privateReq() {} } public class Base { required public init() {} // expected-note@+1 * {{overridden declaration is here}} public func foo() {} // expected-note@+1 * {{overridden declaration is here}} public internal(set) var bar: Int = 0 // expected-note@+1 * {{overridden declaration is here}} public subscript () -> () { return () } } public extension Base { open func extMemberPublic() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} } internal extension Base { open func extMemberInternal() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'internal'}} } public class PublicSub: Base { private required init() {} // expected-error {{'required' initializer must be accessible wherever class 'PublicSub' can be subclassed}} {{3-10=internal}} override func foo() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-3=public }} override var bar: Int { // expected-error {{overriding property must be as accessible as the declaration it overrides}} {{3-3=public }} get { return 0 } set {} } override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-3=public }} } public class PublicSubGood: Base { required init() {} // okay } internal class InternalSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'InternalSub' can be subclassed}} {{12-19=internal}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=internal}} private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=internal}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=internal}} } internal class InternalSubGood: Base { required init() {} // no-warning override func foo() {} override var bar: Int { get { return 0 } set {} } override subscript () -> () { return () } } internal class InternalSubPrivateSet: Base { required init() {} private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-16=}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } fileprivate class FilePrivateSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'FilePrivateSub' can be subclassed}} {{12-19=fileprivate}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}} private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}} } fileprivate class FilePrivateSubGood: Base { required init() {} // no-warning override func foo() {} override var bar: Int { get { return 0 } set {} } override subscript () -> () { return () } } fileprivate class FilePrivateSubGood2: Base { fileprivate required init() {} // no-warning fileprivate override func foo() {} fileprivate override var bar: Int { get { return 0 } set {} } fileprivate override subscript () -> () { return () } } fileprivate class FilePrivateSubPrivateSet: Base { required init() {} private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } private class PrivateSub: Base { required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'PrivateSub' can be subclassed}} {{12-19=fileprivate}} private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}} private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}} get { return 0 } set {} } private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}} } private class PrivateSubGood: Base { required fileprivate init() {} fileprivate override func foo() {} fileprivate override var bar: Int { get { return 0 } set {} } fileprivate override subscript () -> () { return () } } private class PrivateSubPrivateSet: Base { required fileprivate init() {} fileprivate override func foo() {} private(set) override var bar: Int { // expected-error {{setter of overriding property must be as accessible as its enclosing type}} get { return 0 } set {} } private(set) override subscript () -> () { // okay; read-only in base class get { return () } set {} } } public typealias PublicTA1 = PublicStruct public typealias PublicTA2 = InternalStruct // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias PublicTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a fileprivate type}} public typealias PublicTA4 = PrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a private type}} // expected-note@+1 {{type declared here}} internal typealias InternalTA1 = PublicStruct internal typealias InternalTA2 = InternalStruct internal typealias InternalTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a fileprivate type}} internal typealias InternalTA4 = PrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a private type}} public typealias PublicFromInternal = InternalTA1 // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} typealias FunctionType1 = (PrivateStruct) -> PublicStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias FunctionType2 = (PublicStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias FunctionType3 = (PrivateStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias ArrayType = [PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias DictType = [String : PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} typealias GenericArgs = Optional<PrivateStruct> // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}} public protocol HasAssocType { associatedtype Inferred func test(input: Inferred) } public struct AssocTypeImpl: HasAssocType { public func test(input: Bool) {} } public let _: AssocTypeImpl.Inferred? public let x: PrivateStruct = PrivateStruct() // expected-error {{constant cannot be declared public because its type uses a private type}} public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{variable cannot be declared public because its type uses a private type}} public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{variable cannot be declared public because its type uses a private type}} var internalVar: PrivateStruct? // expected-error {{variable must be declared private or fileprivate because its type uses a private type}} let internalConstant = PrivateStruct() // expected-error {{constant must be declared private or fileprivate because its type 'PrivateStruct' uses a private type}} public let publicConstant = [InternalStruct]() // expected-error {{constant cannot be declared public because its type '[InternalStruct]' uses an internal type}} public struct Properties { public let x: PrivateStruct = PrivateStruct() // expected-error {{property cannot be declared public because its type uses a private type}} public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{property cannot be declared public because its type uses a private type}} public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{property cannot be declared public because its type uses a private type}} let y = PrivateStruct() // expected-error {{property must be declared fileprivate because its type 'PrivateStruct' uses a private type}} } public struct Subscripts { subscript (a: PrivateStruct) -> Int { return 0 } // expected-error {{subscript must be declared fileprivate because its index uses a private type}} subscript (a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript must be declared fileprivate because its element type uses a private type}} public subscript (a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}} public subscript (a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its element type uses an internal type}} } public struct Methods { func foo(a: PrivateStruct) -> Int { return 0 } // expected-error {{method must be declared fileprivate because its parameter uses a private type}} func bar(a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{method must be declared fileprivate because its result uses a private type}} public func a(a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func b(a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func c(a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func d(a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}} public func e(a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its result uses an internal type}} } func privateParam(a: PrivateStruct) {} // expected-error {{function must be declared private or fileprivate because its parameter uses a private type}} public struct Initializers { init(a: PrivateStruct) {} // expected-error {{initializer must be declared fileprivate because its parameter uses a private type}} public init(a: PrivateStruct, b: Int) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: Int, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: InternalStruct, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}} public init(a: PrivateStruct, b: InternalStruct) { } // expected-error {{initializer cannot be declared public because its parameter uses a private type}} } public class PublicClass {} // expected-note@+2 * {{type declared here}} // expected-note@+1 * {{superclass is declared here}} internal class InternalClass {} // expected-note@+1 * {{type declared here}} private class PrivateClass {} public protocol AssocTypes { associatedtype Foo associatedtype Internal: InternalClass // expected-error {{associated type in a public protocol uses an internal type in its requirement}} associatedtype InternalConformer: InternalProto // expected-error {{associated type in a public protocol uses an internal type in its requirement}} associatedtype PrivateConformer: PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PI: PrivateProto, InternalProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype IP: InternalProto, PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PrivateDefault = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}} associatedtype PublicDefault = PublicStruct associatedtype PrivateDefaultConformer: PublicProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}} associatedtype PublicDefaultConformer: PrivateProto = PublicStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PrivatePrivateDefaultConformer: PrivateProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}} associatedtype PublicPublicDefaultConformer: PublicProto = PublicStruct } public protocol RequirementTypes { var x: PrivateStruct { get } // expected-error {{property cannot be declared public because its type uses a private type}} subscript(x: Int) -> InternalStruct { get set } // expected-error {{subscript cannot be declared public because its element type uses an internal type}} func foo() -> PrivateStruct // expected-error {{method cannot be declared public because its result uses a private type}} init(x: PrivateStruct) // expected-error {{initializer cannot be declared public because its parameter uses a private type}} } protocol DefaultRefinesPrivate : PrivateProto {} // expected-error {{protocol must be declared private or fileprivate because it refines a private protocol}} public protocol PublicRefinesPrivate : PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}} public protocol PublicRefinesInternal : InternalProto {} // expected-error {{public protocol cannot refine an internal protocol}} public protocol PublicRefinesPI : PrivateProto, InternalProto {} // expected-error {{public protocol cannot refine a private protocol}} public protocol PublicRefinesIP : InternalProto, PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}} private typealias PrivateTypeAlias = PublicProto; // expected-note {{type declared here}} private typealias PrivateCompoundTypeAlias = PublicProto & AnyObject // expected-note {{type declared here}} protocol DefaultRefinesPrivateClass: PrivateClass {} // expected-error {{protocol must be declared private or fileprivate because it refines a private class}} public protocol PublicRefinesPrivateClass: PrivateClass {} // expected-error {{public protocol cannot refine a private class}} public protocol PublicRefinesPrivateTypeAlias: PrivateTypeAlias {} // expected-error {{public protocol cannot refine a private type alias}} public protocol PublicRefinesPrivateCompoundTypeAlias: PrivateCompoundTypeAlias {} // expected-error {{public protocol cannot refine a private type alias}} // expected-note@+1 * {{type declared here}} private typealias PrivateInt = Int enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared private or fileprivate because its raw type uses a private type}} case A } // Note: fileprivate is the most visible valid access level for // Outer.DefaultRawPrivate, so the diagnostic should say that. class Outer { enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared fileprivate because its raw type uses a private type}} case A } } public enum PublicRawPrivate : PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} case A } public enum MultipleConformance : PrivateProto, PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} expected-error {{must appear first}} {{35-35=PrivateInt, }} {{47-59=}} case A func privateReq() {} } open class OpenSubclassInternal : InternalClass {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalClass' of open class must be open}} public class PublicSubclassPublic : PublicClass {} public class PublicSubclassInternal : InternalClass {} // expected-error {{class cannot be declared public because its superclass is internal}} public class PublicSubclassPrivate : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}} class DefaultSubclassPublic : PublicClass {} class DefaultSubclassInternal : InternalClass {} class DefaultSubclassPrivate : PrivateClass {} // expected-error {{class must be declared private or fileprivate because its superclass is private}} // expected-note@+1 * {{superclass is declared here}} public class PublicGenericClass<T> {} // expected-note@+2 * {{type declared here}} // expected-note@+1 * {{superclass is declared here}} internal class InternalGenericClass<T> {} // expected-note@+1 * {{type declared here}} private class PrivateGenericClass<T> {} open class OpenConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<Int>' of open class must be open}} public class PublicConcreteSubclassPublic : PublicGenericClass<Int> {} public class PublicConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-error {{class cannot be declared public because its superclass is internal}} public class PublicConcreteSubclassPrivate : PrivateGenericClass<Int> {} // expected-error {{class cannot be declared public because its superclass is private}} public class PublicConcreteSubclassPublicPrivateArg : PublicGenericClass<PrivateStruct> {} // expected-error {{class cannot be declared public because its superclass uses a private type as a generic parameter}} public class PublicConcreteSubclassPublicInternalArg : PublicGenericClass<InternalStruct> {} // expected-error {{class cannot be declared public because its superclass uses an internal type as a generic parameter}} open class OpenConcreteSubclassPublicFilePrivateArg : PublicGenericClass<FilePrivateStruct> {} // expected-error {{class cannot be declared open because its superclass uses a fileprivate type as a generic parameter}} expected-error {{superclass 'PublicGenericClass<FilePrivateStruct>' of open class must be open}} internal class InternalConcreteSubclassPublicFilePrivateArg : InternalGenericClass<PrivateStruct> {} // expected-error {{class cannot be declared internal because its superclass uses a private type as a generic parameter}} open class OpenGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<T>' of open class must be open}} public class PublicGenericSubclassPublic<T> : PublicGenericClass<T> {} public class PublicGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-error {{class cannot be declared public because its superclass is internal}} public class PublicGenericSubclassPrivate<T> : PrivateGenericClass<T> {} // expected-error {{class cannot be declared public because its superclass is private}} public enum PublicEnumPrivate { case A(PrivateStruct) // expected-error {{enum case in a public enum uses a private type}} } enum DefaultEnumPrivate { case A(PrivateStruct) // expected-error {{enum case in an internal enum uses a private type}} } public enum PublicEnumPI { case A(InternalStruct) // expected-error {{enum case in a public enum uses an internal type}} case B(PrivateStruct, InternalStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}} case C(InternalStruct, PrivateStruct) // expected-error {{enum case in a public enum uses an internal type}} expected-error {{enum case in a public enum uses a private type}} } enum DefaultEnumPublic { case A(PublicStruct) // no-warning } struct DefaultGeneric<T> {} struct DefaultGenericPrivate<T: PrivateProto> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}} struct DefaultGenericPrivate2<T: PrivateClass> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}} struct DefaultGenericPrivateReq<T> where T == PrivateClass {} // expected-warning {{same-type requirement makes generic parameter 'T' non-generic}} // expected-error@-1 {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}} struct DefaultGenericPrivateReq2<T> where T: PrivateProto {} // expected-error {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}} public struct PublicGenericInternal<T: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses an internal type}} public struct PublicGenericPI<T: PrivateProto, U: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericIP<T: InternalProto, U: PrivateProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericPIReq<T: PrivateProto> where T: InternalProto {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}} public struct PublicGenericIPReq<T: InternalProto> where T: PrivateProto {} // expected-error {{generic struct cannot be declared public because its generic requirement uses a private type}} public func genericFunc<T: InternalProto>(_: T) {} // expected-error {{function cannot be declared public because its generic parameter uses an internal type}} {} public class GenericClass<T: InternalProto> { // expected-error {{generic class cannot be declared public because its generic parameter uses an internal type}} public init<T: PrivateProto>(_: T) {} // expected-error {{initializer cannot be declared public because its generic parameter uses a private type}} public func genericMethod<T: PrivateProto>(_: T) {} // expected-error {{instance method cannot be declared public because its generic parameter uses a private type}} } public enum GenericEnum<T: InternalProto> { // expected-error {{generic enum cannot be declared public because its generic parameter uses an internal type}} case A } public protocol PublicMutationOperations { var size: Int { get set } subscript (_: Int) -> Int { get set } } internal protocol InternalMutationOperations { var size: Int { get set } subscript (_: Int) -> Int { get set } } public struct AccessorsControl : InternalMutationOperations { private var size = 0 // expected-error {{property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-10=internal}} private subscript (_: Int) -> Int { // expected-error {{subscript must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{3-10=internal}} get { return 42 } set {} } } public struct PrivateSettersPublic : InternalMutationOperations { // Please don't change the formatting here; it's a precise fix-it test. public private(set) var size = 0 // expected-error {{setter for property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{10-17=internal}} public private(set) subscript (_: Int) -> Int { // expected-error {{subscript setter must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{10-17=internal}} get { return 42 } set {} } } internal struct PrivateSettersInternal : PublicMutationOperations { // Please don't change the formatting here; it's a precise fix-it test. private(set)var size = 0 // expected-error {{setter for property 'size' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-15=}} internal private(set)subscript (_: Int) -> Int { // expected-error {{subscript setter must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{12-24=}} get { return 42 } set {} } } public protocol PublicReadOnlyOperations { var size: Int { get } subscript (_: Int) -> Int { get } } internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations { public private(set) var size = 0 internal private(set) subscript (_: Int) -> Int { // no-warning get { return 42 } set {} } } public struct PrivateSettersForReadOnlyPublic : PublicReadOnlyOperations { public private(set) var size = 0 // no-warning internal private(set) subscript (_: Int) -> Int { // expected-error {{subscript must be declared public because it matches a requirement in public protocol 'PublicReadOnlyOperations'}} {{none}} expected-note {{mark the subscript as 'public' to satisfy the requirement}} {{3-11=public}} get { return 42 } set {} } } public protocol PublicOperatorProto { static prefix func !(_: Self) -> Self } internal protocol InternalOperatorProto { static prefix func !(_: Self) -> Self } fileprivate protocol FilePrivateOperatorProto { static prefix func !(_: Self) -> Self } private protocol PrivateOperatorProto { static prefix func !(_: Self) -> Self } public struct PublicOperatorAdopter : PublicOperatorProto { // expected-error@-1 {{method '!' must be declared public because it matches a requirement in public protocol 'PublicOperatorProto'}} fileprivate struct Inner : PublicOperatorProto { } } private prefix func !(input: PublicOperatorAdopter) -> PublicOperatorAdopter { // expected-note {{mark the operator function as 'public' to satisfy the requirement}} {{1-8=public}} return input } private prefix func !(input: PublicOperatorAdopter.Inner) -> PublicOperatorAdopter.Inner { return input } public struct InternalOperatorAdopter : InternalOperatorProto { // expected-error@-1 {{method '!' must be declared internal because it matches a requirement in internal protocol 'InternalOperatorProto'}} fileprivate struct Inner : InternalOperatorProto { } } private prefix func !(input: InternalOperatorAdopter) -> InternalOperatorAdopter { // expected-note {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}} return input } private prefix func !(input: InternalOperatorAdopter.Inner) -> InternalOperatorAdopter.Inner { return input } public struct FilePrivateOperatorAdopter : FilePrivateOperatorProto { fileprivate struct Inner : FilePrivateOperatorProto { } } private prefix func !(input: FilePrivateOperatorAdopter) -> FilePrivateOperatorAdopter { return input } private prefix func !(input: FilePrivateOperatorAdopter.Inner) -> FilePrivateOperatorAdopter.Inner { return input } public struct PrivateOperatorAdopter : PrivateOperatorProto { fileprivate struct Inner : PrivateOperatorProto { } } private prefix func !(input: PrivateOperatorAdopter) -> PrivateOperatorAdopter { return input } private prefix func !(input: PrivateOperatorAdopter.Inner) -> PrivateOperatorAdopter.Inner { return input } public protocol Equatablish { static func ==(lhs: Self, rhs: Self) /* -> bool */ // expected-note {{protocol requires function '=='}} } fileprivate struct EquatablishOuter { internal struct Inner : Equatablish {} } private func ==(lhs: EquatablishOuter.Inner, rhs: EquatablishOuter.Inner) {} fileprivate struct EquatablishOuter2 { internal struct Inner : Equatablish { fileprivate static func ==(lhs: Inner, rhs: Inner) {} } } fileprivate struct EquatablishOuterProblem { internal struct Inner : Equatablish { // expected-error {{type 'EquatablishOuterProblem.Inner' does not conform to protocol 'Equatablish'}} private static func ==(lhs: Inner, rhs: Inner) {} } } internal struct EquatablishOuterProblem2 { public struct Inner : Equatablish { fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}} // expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{5-16=internal}} } } internal struct EquatablishOuterProblem3 { public struct Inner : Equatablish { // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}} } } private func ==(lhs: EquatablishOuterProblem3.Inner, rhs: EquatablishOuterProblem3.Inner) {} // expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}} internal struct EquatablishOuterProblem4 { public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}} } internal extension EquatablishOuterProblem4.Inner { fileprivate static func ==(lhs: EquatablishOuterProblem4.Inner, rhs: EquatablishOuterProblem4.Inner) {} // expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{3-15=}} } internal struct EquatablishOuterProblem5 { public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}} } private extension EquatablishOuterProblem5.Inner { static func ==(lhs: EquatablishOuterProblem5.Inner, rhs: EquatablishOuterProblem5.Inner) {} // expected-note@-1 {{move the operator function to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}} } public protocol AssocTypeProto { associatedtype Assoc } fileprivate struct AssocTypeOuter { internal struct Inner : AssocTypeProto { fileprivate typealias Assoc = Int } } fileprivate struct AssocTypeOuterProblem { internal struct Inner : AssocTypeProto { private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'fileprivate' to satisfy the requirement}} {{5-12=fileprivate}} } } internal struct AssocTypeOuterProblem2 { public struct Inner : AssocTypeProto { fileprivate typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{5-16=internal}} } } internal struct AssocTypeOuterProblem3 { public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} } internal extension AssocTypeOuterProblem3.Inner { fileprivate typealias Assoc = Int // expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{3-15=}} } internal struct AssocTypeOuterProblem4 { public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} } private extension AssocTypeOuterProblem4.Inner { typealias Assoc = Int // expected-note {{move the type alias to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}} } internal typealias InternalComposition = PublicClass & PublicProto // expected-note {{declared here}} public class DerivedFromInternalComposition : InternalComposition { // expected-error {{class cannot be declared public because its superclass is internal}} public func publicReq() {} } internal typealias InternalGenericComposition<T> = PublicGenericClass<T> & PublicProto // expected-note {{declared here}} public class DerivedFromInternalGenericComposition : InternalGenericComposition<Int> { // expected-error {{class cannot be declared public because its superclass is internal}} public func publicReq() {} } internal typealias InternalConcreteGenericComposition = PublicGenericClass<Int> & PublicProto // expected-note {{declared here}} public class DerivedFromInternalConcreteGenericComposition : InternalConcreteGenericComposition { // expected-error {{class cannot be declared public because its superclass is internal}} public func publicReq() {} } public typealias BadPublicComposition1 = InternalClass & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition2 = PublicClass & InternalProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition3<T> = InternalGenericClass<T> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition4 = InternalGenericClass<Int> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} public typealias BadPublicComposition5 = PublicGenericClass<InternalStruct> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}} open class ClassWithProperties { open open(set) var openProp = 0 // expected-warning {{'open(set)' modifier is redundant for an open property}} {{8-18=}} public public(set) var publicProp = 0 // expected-warning {{'public(set)' modifier is redundant for a public property}} {{10-22=}} internal internal(set) var internalProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}} fileprivate fileprivate(set) var fileprivateProp = 0 // expected-warning {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}} private private(set) var privateProp = 0 // expected-warning {{'private(set)' modifier is redundant for a private property}} {{11-24=}} internal(set) var defaultProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}} } extension ClassWithProperties { // expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}} internal internal(set) var defaultExtProp: Int { get { return 42 } set {} } // expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}} internal(set) var defaultExtProp2: Int { get { return 42 } set {} } } public extension ClassWithProperties { // expected-warning@+2 {{'public' modifier is redundant for property declared in a public extension}} {{3-10=}} // expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{10-22=}} public public(set) var publicExtProp: Int { get { return 42 } set {} } // expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{3-15=}} public(set) var publicExtProp2: Int { get { return 42 } set {} } } internal extension ClassWithProperties { // expected-warning@+2 {{'internal' modifier is redundant for property declared in an internal extension}} {{3-12=}} // expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}} internal internal(set) var internalExtProp: Int { get { return 42 } set {} } // expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}} internal(set) var internalExtProp2: Int { get { return 42 } set {} } } fileprivate extension ClassWithProperties { // expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a fileprivate extension}} {{3-15=}} // expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}} fileprivate fileprivate(set) var fileprivateExtProp: Int { get { return 42 } set {} } // expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}} fileprivate(set) var fileprivateExtProp2: Int { get { return 42 } set {} } private(set) var fileprivateExtProp3: Int { get { return 42 } set {} } } private extension ClassWithProperties { // expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a private (equivalent to fileprivate) extension}} {{3-15=}} // expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}} fileprivate fileprivate(set) var privateExtProp: Int { get { return 42 } set {} } // expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}} fileprivate(set) var privateExtProp2: Int { get { return 42 } set {} } private(set) var privateExtProp3: Int { get { return 42 } set {} } } public var inferredType = PrivateStruct() // expected-error {{variable cannot be declared public because its type 'PrivateStruct' uses a private type}} public var inferredGenericParameters: Optional = PrivateStruct() // expected-error {{variable cannot be declared public because its type uses a private type}} public var explicitType: Optional<PrivateStruct> = PrivateStruct() // expected-error {{variable cannot be declared public because its type uses a private type}} // rdar://problem/47557376 @objc open class ObjCBase { init() {} @objc open dynamic func foo() {} @objc open dynamic var bar: Int = 0 } open class ObjCSub: ObjCBase {} public extension ObjCSub { // Don't try to remove the 'open', since it's needed to be a valid 'override'. open override func foo() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} {{none}} open override var bar: Int { // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} {{none}} get { return 0 } set {} } } public struct TestGenericSubscripts { // We'd like these to be errors in a future version of Swift, but they weren't // in Swift 5.0. public subscript<T: PrivateProto>(_: T) -> Int { return 0 } // expected-warning {{subscript should not be declared public because its generic parameter uses a private type}} {{none}} public subscript<T>(where _: T) -> Int where T: PrivateProto { return 0 } // expected-warning {{subscript should not be declared public because its generic requirement uses a private type}} {{none}} } public typealias TestGenericAlias<T: PrivateProto> = T // expected-warning {{type alias should not be declared public because its generic parameter uses a private type}} public typealias TestGenericAliasWhereClause<T> = T where T: PrivateProto // expected-warning {{type alias should not be declared public because its generic requirement uses a private type}}
61.012346
313
0.751462
3a14242a63071a03b098346e43fe3d145f263c2c
2,067
// // KRoundView.swift // // Copyright (c) 2016 Keun young Kim <[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 open class KRoundView: UIView { @IBInspectable open var cornerRadius: CGFloat = 3 { didSet { setupView() } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { setupView() } } @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { setupView() } } public override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } func setupView() { layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor clipsToBounds = true } }
28.315068
81
0.652153
4a4b0e69a9c0b605bd526ab82227c20b56816750
4,926
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // ProductsManager.swift // // Created by Andrés Boedo on 7/14/20. // import Foundation import StoreKit class ProductsManager: NSObject { private let productsRequestFactory: ProductsRequestFactory private var cachedProductsByIdentifier: [String: SKProduct] = [:] private let queue = DispatchQueue(label: "ProductsManager") private var productsByRequests: [SKRequest: Set<String>] = [:] private var completionHandlers: [Set<String>: [(Set<SKProduct>) -> Void]] = [:] init(productsRequestFactory: ProductsRequestFactory = ProductsRequestFactory()) { self.productsRequestFactory = productsRequestFactory } func products(withIdentifiers identifiers: Set<String>, completion: @escaping (Set<SKProduct>) -> Void) { guard identifiers.count > 0 else { completion([]) return } queue.async { [self] in let productsAlreadyCached = self.cachedProductsByIdentifier.filter { key, _ in identifiers.contains(key) } if productsAlreadyCached.count == identifiers.count { let productsAlreadyCachedSet = Set(productsAlreadyCached.values) Logger.debug(Strings.offering.products_already_cached(identifiers: identifiers)) completion(productsAlreadyCachedSet) return } if let existingHandlers = self.completionHandlers[identifiers] { Logger.debug(Strings.offering.found_existing_product_request(identifiers: identifiers)) self.completionHandlers[identifiers] = existingHandlers + [completion] return } Logger.debug( Strings.offering.no_cached_requests_and_products_starting_skproduct_request(identifiers: identifiers) ) let request = self.productsRequestFactory.request(productIdentifiers: identifiers) request.delegate = self self.completionHandlers[identifiers] = [completion] self.productsByRequests[request] = identifiers request.start() } } func cacheProduct(_ product: SKProduct) { queue.async { self.cachedProductsByIdentifier[product.productIdentifier] = product } } } extension ProductsManager: SKProductsRequestDelegate { func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { queue.async { [self] in Logger.rcSuccess(Strings.storeKit.skproductsrequest_received_response) guard let requestProducts = self.productsByRequests[request] else { Logger.error("requested products not found for request: \(request)") return } guard let completionBlocks = self.completionHandlers[requestProducts] else { Logger.error("callback not found for failing request: \(request)") return } self.completionHandlers.removeValue(forKey: requestProducts) self.productsByRequests.removeValue(forKey: request) self.cacheProducts(response.products) for completion in completionBlocks { completion(Set(response.products)) } } } func requestDidFinish(_ request: SKRequest) { Logger.rcSuccess(Strings.storeKit.skproductsrequest_finished) request.cancel() } func request(_ request: SKRequest, didFailWithError error: Error) { queue.async { [self] in Logger.appleError(Strings.storeKit.skproductsrequest_failed(error: error)) guard let products = self.productsByRequests[request] else { Logger.error("requested products not found for request: \(request)") return } guard let completionBlocks = self.completionHandlers[products] else { Logger.error("callback not found for failing request: \(request)") return } self.completionHandlers.removeValue(forKey: products) self.productsByRequests.removeValue(forKey: request) for completion in completionBlocks { completion(Set()) } } request.cancel() } } private extension ProductsManager { func cacheProducts(_ products: [SKProduct]) { let productsByIdentifier = products.reduce(into: [:]) { resultDict, product in resultDict[product.productIdentifier] = product } cachedProductsByIdentifier = cachedProductsByIdentifier.merging(productsByIdentifier) } }
37.037594
118
0.648396
fedc4986e7c61c2418983490650c2ddfa13d53c9
5,549
// #if os(iOS) import UIKit import RxSwift import RxCocoa import RxDataSources import ReactiveObjC public typealias CellForRowBlock = (UITableView, IndexPath, NSObject) -> UITableViewCell public typealias CanEditRowBlock = (IndexPath) -> Bool @objc(SectionedValue) public class SectionedValueObjC: NSObject { @objc public let section: NSObject @objc public let values: [NSObject] @objc(initWithSection:values:) public init(section: NSObject, values: [NSObject]) { self.section = section self.values = values } @objc(packSection:values:) public static func pack(section: NSObject, values: [NSObject]) -> SectionedValueObjC { return SectionedValueObjC(section: section, values: values) } } extension NSObject: IdentifiableType { public var identity: NSObject { return self } public typealias Identity = NSObject } typealias SectionModelImpl = AnimatableSectionModel<NSObject, NSObject> func convertSectionedValues(_ objcSectionedValues: [SectionedValueObjC]) -> [SectionModelImpl] { return objcSectionedValues.map { return SectionModelImpl(model: $0.section, items: $0.values) } } func convertFromSectionedValues(_ sectionedValues: [SectionModelImpl]) -> [SectionedValueObjC] { return sectionedValues.map { return SectionedValueObjC(section: $0.model, values: $0.items) } } @objc(RxTableViewSectionedDataSource) public final class RxTableViewSectionedReloadDataSourceObjC: NSObject { var disposeBag = DisposeBag() @objc public final var tableView: UITableView? { didSet { rebindDataSource() } } @objc public final var cellForRow: CellForRowBlock? { didSet { rebindDataSource() } } @objc public final var canEditRow: CanEditRowBlock? { didSet { rebindDataSource() } } @objc public var insertionAnimation = UITableView.RowAnimation.none { didSet { rebindDataSource() } } @objc public var deletionAnimation = UITableView.RowAnimation.none { didSet { rebindDataSource() } } @objc public var reloadAnimation = UITableView.RowAnimation.none { didSet { rebindDataSource() } } @objc public final var sectionsSignal: RACSignal<AnyObject>? { didSet { rebindDataSource() } } weak var dataSource: TableViewSectionedDataSource<SectionModelImpl>? @objc public var sectionedValues: [SectionedValueObjC]? { guard let dataSource = dataSource else { return nil } return convertFromSectionedValues(dataSource.sectionModels) } func rebindDataSource() { disposeBag = DisposeBag() guard let tableView = tableView else { return } guard let cellforRow = cellForRow else { return } let canEditRowBlock: ((TableViewSectionedDataSource<SectionModelImpl>, IndexPath) -> Bool) if let canEditRow = canEditRow { canEditRowBlock = { canEditRow($1) } } else { canEditRowBlock = { _, _ in false } } let sectionSignalObservable = sectionsSignal.map { return Observable.from(signal: $0) .rxrac_nonNilValues() .map { $0 as? [SectionedValueObjC] } .rxrac_nonNilValues() .map { convertSectionedValues($0) } } let observableSignal = sectionSignalObservable ?? Observable.just([]) if insertionAnimation == .none && deletionAnimation == .none && reloadAnimation == .none { let dataSource = RxTableViewSectionedReloadDataSource<SectionModelImpl>(configureCell: { cellforRow($1, $2, $3) }) self.dataSource = dataSource dataSource.canEditRowAtIndexPath = canEditRowBlock observableSignal .bind(to: tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) } else { let dataSource = RxTableViewSectionedAnimatedDataSource<SectionModelImpl>(configureCell: { cellforRow($1, $2, $3) }) self.dataSource = dataSource dataSource.animationConfiguration = AnimationConfiguration(insertAnimation: insertionAnimation, reloadAnimation: reloadAnimation, deleteAnimation: deletionAnimation) dataSource.canEditRowAtIndexPath = canEditRowBlock observableSignal .bind(to: tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) } } @objc(sectionAtIndex:) public func section(at index: Int) -> NSObject? { guard let sectionedValues = sectionedValues else { return nil } guard sectionedValues.count > index else { return nil } return sectionedValues[index].section } @objc(valueAtIndexPath:) public func value(at indexPath: IndexPath) -> NSObject? { guard indexPath.indices.count > 1 else { return nil } guard let sectionedValues = sectionedValues else { return nil } guard sectionedValues.count > indexPath.section else { return nil } guard sectionedValues[indexPath.section].values.count > indexPath.row else { return nil } return sectionedValues[indexPath.section].values[indexPath.row] } } #endif
31.528409
128
0.636511
5b2dd8746d6795532d6a533bac249fae55f30b27
1,345
// // ProgressView.swift // SteemApp // // Created by Siarhei Suliukou on 6/1/18. // Copyright © 2018 mby4boomapps. All rights reserved. // import UIKit public final class ProgressView: UIView { private var activityIndicator = UIActivityIndicatorView(frame: CGRect.zero) public override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { self.backgroundColor = UIColor.clear self.addSubview(activityIndicator) activityIndicator.activityIndicatorViewStyle = .whiteLarge activityIndicator.hidesWhenStopped = true activityIndicator.flipToBorder() } func appearAnimate(completion: @escaping () -> ()) { self.isHidden = false UIView.animate(withDuration: 0.2, animations: { self.activityIndicator.startAnimating() }) { _ in completion() } } func disappearAnimate(completion: @escaping () -> ()) { UIView.animate(withDuration: 0.2, animations: { self.activityIndicator.stopAnimating() }) { _ in self.isHidden = true completion() } } }
25.377358
79
0.598513
e005e58d2cc079578bbf5e5e33dfb29c3ffd08e7
10,838
// // CouponDetailsViewController.swift // Wuakup // // Created by Guillermo Gutiérrez on 11/12/14. // Copyright (c) 2014 Yellow Pineapple. All rights reserved. // import UIKit import CoreLocation class CouponDetailsViewController: LoadingPresenterViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate, ZoomTransitionDestination, ZoomTransitionOrigin { @IBOutlet var collectionView: UICollectionView! @IBOutlet weak var menuButton: CodeIconButton! var coupons: [Coupon]! var userLocation: CLLocation? var selectedIndex = 0 var selectedCoupon: Coupon? { get { return coupons?[selectedIndex] } } let couponCellId = "CouponDetailCollectionViewCell" let detailsStoryboardId = "couponDetails" var onSelectionChanged: ((Coupon?, Int) -> Void)? func showDescription(forOffer offer: Coupon) { let presenter = self.navigationController ?? self guard let vc = storyboard?.instantiateViewController(withIdentifier: "couponDescription") as? CouponDescriptionViewController else { return } vc.descriptionText = offer.description presenter.modalPresentationStyle = .currentContext; if #available(iOS 8.0, *) { vc.modalPresentationStyle = .overFullScreen } presenter.present(vc, animated: false, completion: nil) } func showCompanyView(forOffer offer: Coupon) { guard let vc = storyboard?.instantiateViewController(withIdentifier: CouponWaterfallViewController.storyboardId) as? CouponWaterfallViewController else { return } vc.forcedLocation = userLocation vc.filterTitle = offer.company.name vc.filterOptions = FilterOptions(searchTerm: nil, tags: nil, companyId: offer.company.id) navigationController?.pushViewController(vc, animated: true) } func showTagView(forTag tag: String) { guard let vc = storyboard?.instantiateViewController(withIdentifier: CouponWaterfallViewController.storyboardId) as? CouponWaterfallViewController else { return } vc.forcedLocation = userLocation vc.filterTitle = "#" + tag vc.filterOptions = FilterOptions(searchTerm: nil, tags: [tag], companyId: nil) navigationController?.pushViewController(vc, animated: true) } func showRedemptionCode(_ code: RedemptionCode, forOffer offer: Coupon) { guard let vc = storyboard?.instantiateViewController(withIdentifier: "redemptionCode") as? RedemptionCodeViewController else { return } vc.offer = offer vc.redemptionCode = code let presenter = self.navigationController ?? self presenter.modalPresentationStyle = .currentContext; if #available(iOS 8.0, *) { vc.modalPresentationStyle = .overFullScreen } presenter.present(vc, animated: true, completion: nil) } @objc func dismissAction(_ sender: AnyObject) { self.navigationController?.dismiss(animated: true, completion: nil) } // MARK: View lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionView?.layoutIfNeeded() for cell in collectionView?.visibleCells ?? [] { guard let cell = cell as? CouponDetailCollectionViewCell else { continue } cell.couponCollectionHandler?.refreshControl.endRefreshing() } if let navBarTintColor = navigationController?.navigationBar.tintColor { menuButton.iconColor = navBarTintColor menuButton.highlightedIconColor = navBarTintColor.withAlpha(0.5) } if let navigationController = navigationController , navigationController.presentingViewController != nil && navigationController.viewControllers.first == self && navigationItem.leftBarButtonItem == nil { let closeButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(CouponDetailsViewController.dismissAction(_:))) navigationItem.leftBarButtonItem = closeButton } } override func viewDidLoad() { super.viewDidLoad() collectionView?.register(UINib(nibName: "CouponDetailCollectionViewCell", bundle: CurrentBundle.currentBundle()), forCellWithReuseIdentifier: couponCellId) view.backgroundColor = collectionView?.backgroundColor } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView?.scrollToIndexPathIfNotVisible(selectedIndexPath()) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard let segueIdentifier = segue.identifier, let offer = selectedCoupon else { return } switch segueIdentifier { case "reportError": let vc = segue.destination as! WebViewController vc.url = URL(string: OffersService.sharedInstance.reportErrorUrl(forOffer: offer)) default: break } } // MARK: UICollectionView @objc func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { return collectionView.bounds.size } @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return coupons?.count ?? 0 } @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: couponCellId, for: indexPath) as! CouponDetailCollectionViewCell cell.userLocation = userLocation cell.coupon = coupons[(indexPath as NSIndexPath).row] cell.showDetailsDelegate = { cell, couponList, selectedIndex in let detailsVC = self.storyboard?.instantiateViewController(withIdentifier: self.detailsStoryboardId) as! CouponDetailsViewController detailsVC.userLocation = self.userLocation detailsVC.coupons = couponList detailsVC.selectedIndex = selectedIndex detailsVC.onSelectionChanged = { coupon, index in self.getSelectedCell().selectionChanged(couponIndex: index) } self.navigationController?.pushViewController(detailsVC, animated: true) } cell.showMapDelegate = { cell, offer in self.showMap(forOffer: offer) } cell.shareDelegate = { cell, offer in self.shareCoupon(offer) } cell.showDescriptionDelegate = { cell, offer in self.showDescription(forOffer: offer) } cell.showCompanyDelegate = { cell, offer in self.showCompanyView(forOffer: offer) } cell.showRedemptionCodeDelegate = { [unowned self] cell, offer in self.showLoadingView(animated: true) OffersService.sharedInstance.getRedemptionCode(forOffer: offer) { (code, error) in self.dismissLoadingView(animated: false) if let code = code { self.showRedemptionCode(code, forOffer: offer) // If limited offer, update UI with new values if let code = offer.redemptionCode , code.limited && !code.alreadyAssigned { let newCode = RedemptionCodeInfo(limited: code.limited, totalCodes: code.totalCodes, availableCodes: code.availableCodes.map{$0-1}, alreadyAssigned: true) offer.redemptionCode = newCode cell.refreshUI() } } else { let msg = (error as NSError?)?.localizedDescription ?? "ErrorGettingRedemptionCodeMsg".i18n() let alert = UIAlertController(title: "ErrorGettingRedemptionCodeTitle".i18n(), message: msg, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "CloseDialogButton".i18n(), style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } } cell.showTagDelegate = { [unowned self] cell, tag in self.showTagView(forTag: tag) } return cell; } @objc func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? CouponDetailCollectionViewCell else { return } delay(0) { if collectionView.indexPathsForVisibleItems.contains(indexPath) { cell.reloadRelatedCoupons() } } } // MARK: UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if let visibleIndexPath = self.collectionView?.indexPathsForVisibleItems.first { let newSelectedItem = (visibleIndexPath as NSIndexPath).row if newSelectedItem != self.selectedIndex { self.selectedIndex = newSelectedItem if let listener = onSelectionChanged { listener(selectedCoupon, newSelectedItem) } } } } // MARK: IBActions @IBAction func menuAction(_ sender: AnyObject) { let alertController = UIAlertController(title: nil, message: "ReportErrorMessage".i18n(), preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "ReportErrorCancel".i18n(), style: .cancel) { (action) in }) alertController.addAction(UIAlertAction(title: "ReportErrorButton".i18n(), style: .destructive) { (action) in self.performSegue(withIdentifier: "reportError", sender: self) }) self.present(alertController, animated: true, completion: nil) } // MARK: Transition methods func selectedIndexPath() -> IndexPath{ return IndexPath(row: self.selectedIndex, section: 0) } func getSelectedCell() -> CouponDetailCollectionViewCell { return self.collectionView!.scrollToAndGetCell(atIndexPath: selectedIndexPath()) as! CouponDetailCollectionViewCell } func zoomTransitionDestinationView() -> UIView { let header = getSelectedCell().couponHeaderView if (!(header?.couponDetailImageView.isHidden)!) { return header!.couponDetailImageView } return header!.couponImageView } func zoomTransitionOriginView() -> UIView { return getSelectedCell().getSelectedCell().couponImageView } }
44.056911
212
0.662945
7a6024223bfe33858b634d8c65c255219f9d6783
998
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "JFMarkSlider", platforms: [ .iOS(.v9), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "JFMarkSlider", targets: ["JFMarkSlider"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "JFMarkSlider", path: "JFMarkSlider/JFMarkSlider"), ] )
34.413793
122
0.630261
6aaf5d28969e7da3566b2af31d6db951bb8921fe
5,899
// // NoteEditVC.swift // Notes App // // Created by Gary Singh on 2/15/17. // Copyright © 2017 AmanGarry. All rights reserved. // import UIKit class NoteEditVC: UIViewController { @IBOutlet weak var deleteView: UIVisualEffectView! // outlet for deleteView @IBOutlet weak var cancelBtn: UIButton! // outlet for Cancek Button @IBOutlet weak var deleteBtn: UIButton! // outlet for Delete Button @IBOutlet weak var textView: UITextView! // outlet for textView @IBOutlet weak var dateLabel: UILabel! // outlet for dateLabel var noteToEdit: Note? // Create a note //------------------------------------------------------------------------------------ override func viewDidLoad() { super.viewDidLoad() // dismiss keyboard when tapped on screen let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) // if note to edit is not nil then load data of note to screen if noteToEdit != nil { loadItemData() // else create a new date and set date after formatting it to date label } else { // get current date let date = NSDate() // date format let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM d, yyyy, h:mm a" // set date as string dateLabel.text = dateFormatter.string(from: date as Date) } } //------------------------------------------------------------------------------------ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //------------------------------------------------------------------------------------ // doneBtnPressed: Save the note if it is not empty and segue to main screen // but if it is empty then segue to main screen without // saving it. // @IBAction func doneBtnPressed(_ sender: UIButton) { // run if text is in the textView and atleast having one character if let textData = textView.text, textData.characters.count > 0 { let note: Note! // set the note // if note is empty then create a new note in memory if noteToEdit == nil { note = Note(context: context) // else initialize the note to existing note } else { note = noteToEdit } // set note data to entered text note.data = textData // set the current date as created date note.created = NSDate() // save the note to memory ad.saveContext() } // segue to the main screen dismiss(animated: true, completion: nil) } //------------------------------------------------------------------------------------ // deleteIconTapped: if note in not nil(empty) then // unhide 1. deleteView, 2. Cancel & 3. Delete Buttons // and if note is nil then segue to main screen // @IBAction func deleteIconTapped(_ sender: UIButton) { // if note in not nil(empty) then // unhide 1. deleteView, 2. Cancel & 3. Delete Buttons if noteToEdit != nil { deleteView.isHidden = false cancelBtn.isHidden = false deleteBtn.isHidden = false // else segue to main screen } else { dismiss(animated: true, completion: nil) } } //------------------------------------------------------------------------------------ // deleteBtnTapped: delete the note from the memory and show the // unhidden 1. deleteView, 2. Delete & 3. Cancel Button // and segue to main screen // @IBAction func deleteBtnTapped(_ sender: UIButton) { // delete note context.delete(noteToEdit!) ad.saveContext() // get back deleteView.isHidden = true deleteBtn.isHidden = true cancelBtn.isHidden = true // segue back to main screen dismiss(animated: true, completion: nil) } //------------------------------------------------------------------------------------ // cancelBtnTapped: Unhide the 1. deleteView, 2. Delete & 3. Cancel Buttons // @IBAction func cancelBtnTapped(_ sender: UIButton) { // Unhide the 1. deleteView, 2. Delete & 3. Cancel Buttons deleteView.isHidden = true deleteBtn.isHidden = true cancelBtn.isHidden = true } //------------------------------------------------------------------------------------ // loadItemData: Load the data from the existing note data // func loadItemData() { // if note to edit is not nil then proceed if let note = noteToEdit { // set textView text to note data textView.text = note.data // date format let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM d, yyyy, h:mm a" // set date label as string dateLabel.text = dateFormatter.string(from: note.created as! Date) } } }
34.7
90
0.471775
1a37c24282b4f6c021d46c5a39f16f6b1a9fc030
169
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(ExpressionEvaluatorTests.allTests), ] } #endif
16.9
52
0.692308
1e8b34a448564e35798d8dfa33749f9829ce4164
1,712
// // EventEditView.swift // EventKit.Example // // Created by Filip Němeček on 04/08/2020. // Copyright © 2020 Filip Němeček. All rights reserved. // import SwiftUI import EventKitUI struct EventEditView: UIViewControllerRepresentable { func makeCoordinator() -> Coordinator { return Coordinator(self) } @Environment(\.presentationMode) var presentationMode let eventStore: EKEventStore let event: EKEvent? func makeUIViewController(context: UIViewControllerRepresentableContext<EventEditView>) -> EKEventEditViewController { let eventEditViewController = EKEventEditViewController() eventEditViewController.eventStore = eventStore if let event = event { eventEditViewController.event = event // when set to nil the controller would not display anything } eventEditViewController.editViewDelegate = context.coordinator return eventEditViewController } func updateUIViewController(_ uiViewController: EKEventEditViewController, context: UIViewControllerRepresentableContext<EventEditView>) { } class Coordinator: NSObject, EKEventEditViewDelegate { let parent: EventEditView init(_ parent: EventEditView) { self.parent = parent } func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { parent.presentationMode.wrappedValue.dismiss() if action != .canceled { NotificationCenter.default.post(name: .eventsDidChange, object: nil) } } } }
31.127273
142
0.673481
e0127aae6fc9ffec28f6ef0f3dc1badd9c2c596e
8,270
// // Copyright 2020 Wultra s.r.o. // // 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 PowerAuth2 /// A class returned as Error from the library interfaces. public class WPNError: Error { public init(reason: WPNErrorReason, error: Error? = nil) { #if DEBUG if let error = error as? WPNError { D.error("You should not embed WPNError into another WPNError object. Please use .wrap() function if you're not sure what type of error is passed to initializer. Error: \(error.localizedDescription)") } #endif self.reason = reason self.nestedError = error } /// Private initializer fileprivate convenience init(reason: WPNErrorReason, nestedError: Error?, httpUrlResponse: HTTPURLResponse?, restApiError: WPNRestApiError?) { self.init(reason: reason, error: nestedError) self.httpUrlResponse = httpUrlResponse self.restApiError = restApiError } // MARK: - Properties /// Reason why the error was created public let reason: WPNErrorReason /// Nested error. public let nestedError: Error? /// A full response received from the server. /// /// If you set a valid object to this property, then the `httpStatusCode` starts /// returning status code from the response. You can set this value in cases that, /// it's important to investigate a whole response, after the authentication fails. /// /// Normally, setting `httpStatusCode` is enough for proper handling authentication errors. internal(set) public var httpUrlResponse: HTTPURLResponse? private var _restApiError: WPNRestApiError? // backing field /// An optional error describing details about REST API failure. internal(set) public var restApiError: WPNRestApiError? { get { if let rae = _restApiError { return rae } if let pae = powerAuthRestApiError?.responseObject { return WPNRestApiError(code: pae.code, message: pae.message) } return nil } set { _restApiError = newValue } } // MARK: - Computed properties /// HTTP status code. /// /// nil if not available (not an HTTP error). public var httpStatusCode: Int? { if let httpUrlResponse = httpUrlResponse { return Int(httpUrlResponse.statusCode) } else if let responseObject = powerAuthRestApiError { return Int(responseObject.httpStatusCode) } else { return nil } } /// Returns `PowerAuthRestApiErrorResponse` if such object is embedded in nested error. This is typically useful /// for getting error HTTP response created in the PowerAuth2 library. public var powerAuthRestApiError: PowerAuthRestApiErrorResponse? { return userInfo[PowerAuthErrorDomain] as? PowerAuthRestApiErrorResponse } /// Returns PowerAuth error code when the error was caused by the PowerAuth2 library. /// /// For possible values, visit [PowerAuth Documentation](https://developers.wultra.com/components/powerauth-mobile-sdk/develop/documentation/PowerAuth-SDK-for-iOS#error-handling) public var powerAuthErrorCode: PowerAuthErrorCode? { return (nestedError as NSError?)?.powerAuthErrorCode } /// Returns error message when the underlying error was caused by the PowerAuth2 library. public var powerAuthErrorMessage: String? { guard domain == PowerAuthErrorDomain else { return nil } return userInfo[NSLocalizedDescriptionKey] as? String } /// Returns true if the error is caused by the missing network connection. /// The device is typically not connected to the internet. public var networkIsNotReachable: Bool { if domain == NSURLErrorDomain || domain == kCFErrorDomainCFNetwork as String { let ec = CFNetworkErrors(rawValue: Int32(code)) return ec == .cfurlErrorNotConnectedToInternet || ec == .cfurlErrorInternationalRoamingOff || ec == .cfurlErrorDataNotAllowed } return false } /// Returns true if the error is related to the connection security - like untrusted TLS /// certificate, or similar TLS related problems. public var networkConnectionIsNotTrusted: Bool { if domain == NSURLErrorDomain || domain == kCFErrorDomainCFNetwork as String { let code = Int32(code) if code == CFNetworkErrors.cfurlErrorServerCertificateHasBadDate.rawValue || code == CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue || code == CFNetworkErrors.cfurlErrorServerCertificateHasUnknownRoot.rawValue || code == CFNetworkErrors.cfurlErrorServerCertificateNotYetValid.rawValue || code == CFNetworkErrors.cfurlErrorSecureConnectionFailed.rawValue { return true } } return false } /// Returns WPNError object with nested error and additional nested description. /// If the provided error object is already WPNError, then returns copy of the object, /// with modified nested description. public static func wrap(_ reason: WPNErrorReason, _ error: Error? = nil) -> WPNError { if let error = error as? WPNError { return WPNError( reason: reason, nestedError: error.nestedError, httpUrlResponse: error.httpUrlResponse, restApiError: error.restApiError) } return WPNError(reason: reason, error: error) } } /// Reason of the error. public struct WPNErrorReason: RawRepresentable, Equatable, Hashable { public static let missingActivation = WPNErrorReason(rawValue: "missingActivation") public static let unknown = WPNErrorReason(rawValue: "unknown") public typealias RawValue = String public var rawValue: RawValue public init(rawValue: RawValue) { self.rawValue = rawValue } } public extension WPNError { var code: Int { guard let e = nestedError as NSError? else { return 0 } return e.code } var domain: String { guard let e = nestedError as NSError? else { return "WPNError" } return e.domain } var userInfo: [String: Any] { guard let e = nestedError as NSError? else { return [:] } return e.userInfo } } extension WPNError: CustomStringConvertible { public var description: String { if let powerAuthErrorMessage = powerAuthErrorMessage { return powerAuthErrorMessage } if let nsne = nestedError as NSError? { return nsne.description } var result = "Error reason: \(reason)" result += "\nError domain: \(domain), code: \(code)" if let httpStatusCode = httpStatusCode { result += "\nHTTP Status Code: \(httpStatusCode)" } if let powerAuthRestApiError = powerAuthRestApiError { result += "\nPA REST API Code: \(powerAuthRestApiError)" } return result } } extension D { static func error(_ error: @autoclosure () -> WPNError) { D.error(error().description) } } /// Simple error class to add developer comment when throwing an WPNError internal class WPNSimpleError: Error { let localizedDescription: String init(message: String) { localizedDescription = message } }
35.34188
211
0.645466
4a291db6496977ee995d5eab507820895c89c436
1,405
// // EmoticonCell.swift // EmoticonKeyBoard // // Created by apple on 15/11/20. // Copyright © 2015年 apple. All rights reserved. // import UIKit class EmoticonCell: UICollectionViewCell { //设置模型 绑定数据 var emoticon: Emoticon? { didSet { //设置按钮的图片 emoticonBtn.setImage(UIImage(contentsOfFile: emoticon?.imagePath ?? ""), forState: .Normal) //设置emoji字符串 emoticonBtn.setTitle(emoticon?.emojiStr ?? "", forState: .Normal) //设置删除按钮的图片 if let em = emoticon where em.isRemove { emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal) } } } //MARK: 3.重写父类的构造方法 调用设置UI override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(emoticonBtn) //要使用bounds // emoticonBtn.frame = self.bounds emoticonBtn.frame = CGRectInset(bounds, 4, 4) emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32) emoticonBtn.backgroundColor = UIColor.whiteColor() //设置不能交互 emoticonBtn.userInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 1. 懒加载所有子控件 private lazy var emoticonBtn: UIButton = UIButton() }
27.54902
103
0.598577
1c03a1a1359e891b3e112f5536350e2fd5215a1c
635
// // SwiftMessage+Error.swift // GitHubFolks // // Created by Eric Hsu on 2020/6/10. // Copyright © 2020 Anonymous Ltd. All rights reserved. // import SwiftMessages extension SwiftMessages { static func showError(_ error: Error) { guard let error = error as? LocalizedError else { return } let config = SwiftMessages.defaultConfig let view = MessageView.viewFromNib(layout: .messageView) view.configureContent(title: "Server Error", body: error.localizedDescription) view.configureTheme(.warning) view.button?.isHidden = true show(config: config, view: view) } }
27.608696
86
0.680315
e0edba1cccc0dc2183e27475a236c067990f45e8
448
// // CellInterface.swift // PixPic // // Created by AndrewPetrov on 2/17/16. // Copyright © 2016 Yalantis. All rights reserved. // import Foundation protocol CellInterface { static var id: String { get } static var cellNib: UINib { get } } extension CellInterface { static var id: String { return String(describing: Self) } static var cellNib: UINib { return UINib(nibName: id, bundle: nil) } }
15.448276
51
0.638393
1846e9769168389be6b3fea38b92acf0869ad743
1,123
// // LogViewController.swift // BluejayHeartSensorDemo // // Created by Jeremy Chiang on 2019-01-02. // Copyright © 2019 Steamclock Software. All rights reserved. // import Bluejay import UIKit // should only ever be one of these, keep a local reference to it so we can implement a general // debug logging free function below private weak var logViewControllerInstance: LogViewController? func debugLog(_ text: String) { logViewControllerInstance?.logTextView.text.append(text + "\n") } class LogViewController: UIViewController { @IBOutlet fileprivate var logTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() clearLogs() bluejay.register(logObserver: self) } @IBAction func clearLogs() { logTextView.text = "" } @IBAction func exportLogs() { present(UIActivityViewController(activityItems: [logTextView.text ?? ""], applicationActivities: nil), animated: true, completion: nil) } } extension LogViewController: LogObserver { func debug(_ text: String) { logTextView.text.append(text + "\n") } }
24.413043
143
0.700801
3327933a54f18b3ee8718ec50f000739dd2d731f
340
// // Store.swift // FruitMart // // Created by hanwe on 2020/12/28. // Copyright © 2020 Giftbot. All rights reserved. // import Foundation final class Store { var products: [Product] init(fileName: String = "ProductData.json") { self.products = Bundle.main.decode(fileName: fileName, as: [Product].self) } }
18.888889
82
0.644118
fefdaf5623c1b3ac9b3deaecb8dabe71f22afd5b
974
// // TippyTests.swift // TippyTests // // Created by Becker, Kathrine V on 9/19/16. // Copyright © 2016 Becker, Kathrine V. All rights reserved. // import XCTest @testable import Tippy class TippyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.324324
111
0.629363
1a6a7b2e8c76d3867d07b3379055422ca78feb10
2,191
// // File.swift // // // Created by Finer Vine on 2021/1/4. // // https://docs.microsoft.com/zh-cn/graph/api/resources/drive?view=graph-rest-1.0 /* "createdBy": { "@odata.type": "microsoft.graph.identitySet" }, "createdDateTime": "string (timestamp)", "description": "string", "driveType": "personal | business | documentLibrary", "following": [{"@odata.type": "microsoft.graph.driveItem"}], "items": [ { "@odata.type": "microsoft.graph.driveItem" } ], "lastModifiedBy": { "@odata.type": "microsoft.graph.identitySet" }, "lastModifiedDateTime": "string (timestamp)", "name": "string", "owner": { "@odata.type": "microsoft.graph.identitySet" }, "quota": { "@odata.type": "microsoft.graph.quota" }, "root": { "@odata.type": "microsoft.graph.driveItem" }, "sharepointIds": { "@odata.type": "microsoft.graph.sharepointIds" }, "special": [ { "@odata.type": "microsoft.graph.driveItem" }], "system": { "@odata.type": "microsoft.graph.systemFacet" }, "webUrl": "url" */ import Foundation import Core // MARK: - FileDriveModel public final class FileDriveModel: FileBaseItem { public let driveType: String? // public let following: [CreatedBy] // public let items: [CreatedBy] // public let owner, quota, root, sharepointIDS: CreatedBy // public let special: [CreatedBy] // public let system: CreatedBy enum CodingKeys: String, CodingKey { // case id, createdBy, createdDateTime case driveType // ,following // , // items, // lastModifiedBy, lastModifiedDateTime, name, owner, quota, root // case sharepointIDS = "sharepointIds" // case special, system // case webURL = "webUrl" } // MARK: - CreatedBy // public // struct CreatedBy: Codable { // let odataType: String // // enum CodingKeys: String, CodingKey { // case odataType = "@odata.type" // } // } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) driveType = try container.decodeIfPresent(String.self, forKey: .driveType) try super.init(from: decoder) } }
32.220588
82
0.629849
2676545e85361ba425b11e570122a9250a5ba97f
1,687
import AppKit import WebKit final class GeminiBrowserController: NSViewController { private var webView: WKWebView { view as! WKWebView } override func loadView() { let view = WKWebView(frame: .zero, configuration: .gemini) view.navigationDelegate = self self.view = view } override func viewDidLoad() { super.viewDidLoad() let request = URLRequest(url: URL(string: "gemini://rawtext.club:1965/~sloum/spacewalk.gmi")!) webView.load(request) } } extension GeminiBrowserController: WKNavigationDelegate { func webView(_: WKWebView, didFinish navigation: WKNavigation!) { print(navigation) } func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) { print(error) } func webView(_: WKWebView, didCommit navigation: WKNavigation!) { print(navigation) } func webView(_: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print(navigation) } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { print(webView) } func webView(_: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { print(navigation) } func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) { print(error) } } private extension WKWebViewConfiguration { static var gemini: WKWebViewConfiguration { let config = WKWebViewConfiguration() config.applicationNameForUserAgent = Localizable.App.name GeminiSchemeHandler.register(for: config) return config } }
27.655738
108
0.685833
753b0f5f71f71bdb60d7def3060a280e43429721
2,744
// // SupervisorLogModel.swift // Supervisor // // Created by 梁宪松 on 2020/3/24. // import Foundation @objc public enum SupervisorLogType: Int { case off case debug case info case warn case error } extension SupervisorLogType { public static func description(with type: SupervisorLogType) -> String { switch type { case .off: return "OFF" case .debug: return "DEBUG" case .info: return "INFO" case .warn: return "WARN" case .error: return "ERROR" default: return "" } } } @objcMembers open class SupervisorLogModel: NSObject { open private(set) var type : SupervisorLogType! /// date for timestamp open private(set) var date: Date! /// thread which log the message open private(set) var thread: Thread? /// filename with extension open private(set) var file: String? /// number of line in source code file open private(set) var line: Int? /// name of the function which log the message open private(set) var function: String? /// message be logged open private(set) var message: String? init(type:SupervisorLogType, thread: Thread, message: String?, file: String?, line: Int?, function: String?) { super.init() self.date = Date() self.type = type self.thread = thread self.file = file self.line = line self.function = function self.message = message } open override var description: String { get { var des = String.init() if let executeableName = Bundle.main.object(forInfoDictionaryKey: kCFBundleExecutableKey as String) as? String { des.append(contentsOf: executeableName) } des.append(contentsOf: " [\(SupervisorLogType.description(with: self.type))]") des.append(contentsOf: " \(self.date.description)") if let threadStr = thread?.description { des.append(contentsOf: " \(threadStr)") } if let fileStr = file { des.append(contentsOf: " \(fileStr)") } if let lineInt = line { des.append(contentsOf: " \(lineInt)") } if let funcStr = function { des.append(contentsOf: " \(funcStr)") } des.append(contentsOf: " \(message ?? "")") return des } } }
24.283186
124
0.519315
468b1182a9b41afdb3c242b950588099edfde642
913
// // ViewController.swift // ImagePickerEasy // // Created by wajeehulhassan on 11/26/2021. // Copyright (c) 2021 wajeehulhassan. All rights reserved. // import UIKit import ImagePickerEasy class ViewController: UIViewController { @IBOutlet weak var mImageView: UIImageView! 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. } @IBAction func pickImageAction(_ sender: Any) { ImagePickerEasy.shared.present(from: sender as! UIView, vc: self) { image in if image != nil{ self.mImageView.image = image } } } }
14.967213
84
0.593647
e2ee8c993e2bf4e7e5acf2c60daf924e1f2c3765
372
// // Constants.swift // WSTagsField // // Created by Ilya Seliverstov on 11/07/2017. // Copyright © 2017 Whitesmith. All rights reserved. // import UIKit internal struct Constants { internal static let TEXT_FIELD_HSPACE: CGFloat = 6.0 internal static let MINIMUM_TEXTFIELD_WIDTH: CGFloat = 56.0 internal static let STANDARD_ROW_HEIGHT: CGFloat = 30.0 }
23.25
63
0.731183
165a04f588dbf71ba16f46e20f0142d439947de1
583
// // DrawingCell.swift // Drawy // // Created by Gal Orlanczyk on 11/01/2018. // Copyright © 2018 GO. All rights reserved. // import UIKit class DrawingCell: UITableViewCell { @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var creationDateLabel: 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 } }
20.821429
65
0.670669
395a47120ff26893cf6d58b97a2550e63ae1ee54
6,758
// // TimelineViewController.swift // Twitter // // Created by Xiang Yu on 9/26/17. // Copyright © 2017 Xiang Yu. All rights reserved. // import UIKit import MBProgressHUD @objc protocol TimelineViewControllerDelegate { @objc optional func timelineViewController(_ timelineViewController: TimelineViewController, didTapOnScreenname: String) } class TimelineViewController: UIViewController { var tweets: [Tweet] = [] var isMoreDataLoading = false var timelineType: TwitterService.TimelineType! @IBOutlet weak var tweetsTableView: UITableView! @IBOutlet weak var loadingMoreView: UIView! var hamburgerViewController: HamburgerViewController? override func viewDidLoad() { super.viewDidLoad() // Initialize a UIRefreshControl let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) // add refresh control to table view tweetsTableView.insertSubview(refreshControl, at: 0) refreshControlAction() tweetsTableView.delegate = self tweetsTableView.dataSource = self tweetsTableView.estimatedRowHeight = 100 tweetsTableView.rowHeight = UITableViewAutomaticDimension self.navigationItem.title = (timelineType == .mentions) ? "Mentions" : "Home" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLogoutButton(_ sender: Any) { TwitterService.sharedInstance?.logout() } @objc private func refreshControlAction(_ refreshControl: UIRefreshControl?=nil) { // Display HUD right before the request is made let initialLoad = (refreshControl == nil) if initialLoad { MBProgressHUD.showAdded(to: self.view, animated: true) } TwitterService.sharedInstance?.getTimeline(timelineType, olderthan: nil, forScreenName: nil, success: { (tweets: [Tweet]) in // Hide HUD once the network request comes back (must be done on main UI thread) MBProgressHUD.hide(for: self.view, animated: true) self.tweets = tweets self.tweetsTableView.reloadData() refreshControl?.endRefreshing() }, failure: { (error: Error) in // Hide HUD once the network request comes back (must be done on main UI thread) MBProgressHUD.hide(for: self.view, animated: true) refreshControl?.endRefreshing() Utils.popAlertWith(msg: "error in get home time line: \(error.localizedDescription)", in: self) }) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationViewController = segue.destination as? TweetViewController { let indexPath = tweetsTableView.indexPath(for: sender as! UITableViewCell)! destinationViewController.tweet = tweets[indexPath.row] destinationViewController.composeViewDelegate = self } else if let destinationViewController = segue.destination as? UINavigationController { guard let composeTweetViewController = destinationViewController.topViewController as? ComposeTweetViewController else { return } composeTweetViewController.delegate = self } } } // MARK: - Table View Delegate extension TimelineViewController: UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tweetsTableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell cell.tweet = tweets[indexPath.row] cell.delegate = self.hamburgerViewController return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tweetsTableView.deselectRow(at: indexPath, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = tweetsTableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - tweetsTableView.bounds.size.height // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && tweetsTableView.isDragging) { isMoreDataLoading = true let progressHUD = MBProgressHUD.showAdded(to: loadingMoreView, animated: true) progressHUD.bezelView.backgroundColor = .clear //artificially delay for 3 sec to avoid 429 error let when = DispatchTime.now() + 3 DispatchQueue.main.asyncAfter(deadline: when) { TwitterService.sharedInstance?.getTimeline(self.timelineType, olderthan: self.tweets.last?.id, forScreenName: nil, success: { (tweets: [Tweet]) in // Hide HUD once the network request comes back (must be done on main UI thread) MBProgressHUD.hide(for: self.loadingMoreView, animated: true) self.isMoreDataLoading = false self.tweets.append(contentsOf: tweets) self.tweetsTableView.reloadData() }, failure: { (error: Error) in // Hide HUD once the network request comes back (must be done on main UI thread) MBProgressHUD.hide(for: self.loadingMoreView, animated: true) self.isMoreDataLoading = false Utils.popAlertWith(msg: "error in get more time line: \(error.localizedDescription)", in: self) }) } } } } } // MARK: - Compose Tweet View Delegate extension TimelineViewController: ComposeTweetViewControllerDelegate { func composeTweetViewController(_ composeTweetViewController: ComposeTweetViewController, didTweet status: Tweet) { self.tweets.insert(status, at: 0) self.tweetsTableView.reloadData() } }
40.710843
166
0.640278
eb0e775d8d8846e188db2f47c5d3094e64a571e0
2,618
// RUN: %target-swift-frontend -module-name pointer_conversion -emit-sil -O %s | %FileCheck %s // REQUIRES: optimized_stdlib // UNSUPPORTED: objc_interop // Opaque, unoptimizable functions to call. @_silgen_name("takesConstRawPointer") func takesConstRawPointer(_ x: UnsafeRawPointer) @_silgen_name("takesOptConstRawPointer") func takesOptConstRawPointer(_ x: UnsafeRawPointer?) @_silgen_name("takesMutableRawPointer") func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) @_silgen_name("takesOptMutableRawPointer") func takesOptMutableRawPointer(_ x: UnsafeMutableRawPointer?) // Opaque function for generating values @_silgen_name("get") func get<T>() -> T // The purpose of these tests is to make sure the storage is never released // before the call to the opaque function. // CHECK-LABEL: sil @$s18pointer_conversion17testOptionalArrayyyF public func testOptionalArray() { let array: [Int]? = get() takesOptConstRawPointer(array) // CHECK: bb0: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]( // CHECK: [[OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.some!enumelt, // CHECK-NEXT: [[POINTER:%.+]] = struct $UnsafeRawPointer ( // CHECK-NEXT: [[DEP_POINTER:%.+]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] : $Optional<AnyObject> // CHECK-NEXT: [[OPT_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP_POINTER]] // CHECK-NEXT: br [[CALL_BRANCH:bb[0-9]+]]([[OPT_POINTER]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[CALL_BRANCH]]([[OPT_POINTER:%.+]] : $Optional<UnsafeRawPointer>, [[OWNER:%.+]] : $Optional<AnyObject>): // CHECK-NOT: release // CHECK-NEXT: [[DEP_OPT_POINTER:%.+]] = mark_dependence [[OPT_POINTER]] : $Optional<UnsafeRawPointer> on [[OWNER]] : $Optional<AnyObject> // CHECK: [[FN:%.+]] = function_ref @takesOptConstRawPointer // CHECK-NEXT: apply [[FN]]([[DEP_OPT_POINTER]]) // CHECK-NOT: release // CHECK-NOT: {{^bb[0-9]+:}} // CHECK: release_value {{%.+}} : $Optional<Array<Int>> // CHECK-NEXT: [[EMPTY:%.+]] = tuple () // CHECK-NEXT: return [[EMPTY]] // CHECK: [[NONE_BB]]: // CHECK-NEXT: [[NO_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.none!enumelt // CHECK-NEXT: [[NO_OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK-NEXT: br [[CALL_BRANCH]]([[NO_POINTER]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>) } // CHECK: end sil function '$s18pointer_conversion17testOptionalArrayyyF'
49.396226
140
0.697097
dec4e2b1edeafedfbc2bf781355ecd7a6f31e4d1
1,597
// // Global.swift // TutorFinder // // Created by Andreas Loizides on 28/11/2021. // import Foundation import Combine class GlobalConfigurator{ static let main = GlobalConfigurator() private init(){} private(set) var configuredForCurrentUser=false private(set) var storedUserID="" func initialize(){ print("[GlobalConfigurator]: Initializing") CourseListViewModel.initialize() } func userInfoChanged(user: UserVM, userID: String){ guard !configuredForCurrentUser && userID != storedUserID else{return} loggedOut() print("[GlobalConfigurator]: User changed") GradeListVM.userChanged() CourseListViewModel.observeCurrentUsersCourses(userID: userID) switch user.model.userType{ case .student: CourseRegisterListViewModel.observeStudentsCourses(studentID: userID) print("[GlobalConfigurator]: Now observing student \(userID)'s course IDs") case .teacher: Professor.current.loadModel(userID: userID) ProfessorCoursesVM.loggedIn(profID: userID) UserListVM.professorsStudents.observeStudentsOfProfessor(professorID: userID) print("[GlobalConfigurator]: \tNow observing professor \(userID)") } print("[GlobalConfigurator]: Now observing courses of user \(userID)") configuredForCurrentUser=true storedUserID=userID } func loggedOut(){ print("[GlobalConfigurator]: User logged out. Removing all observers.") self.configuredForCurrentUser=false self.storedUserID="" CourseListViewModel.loggedOut() CourseRegisterListViewModel.loggedOut() ProfessorCoursesVM.loggedOut() UserListVM.loggedOut() Professor.current.signOut() } }
30.711538
80
0.770194
f8469ab1d5171ead02958a2ab589c7a2d79bceec
2,460
// UITextViewHelper.swift // Layout Helper // // Created by Kuldeep Tanwar on 4/15/19. // Copyright © 2019 Kuldeep Tanwar. All rights reserved. import UIKit @IBDesignable class UITextViewHelper : UITextView { @IBInspectable var iPhone4s: CGFloat = 0.0 { didSet { deviceFont(.i3_5Inch,value:iPhone4s) } } @IBInspectable var iPhoneSE: CGFloat = 0.0 { didSet { deviceFont(.i4Inch,value:iPhoneSE) } } @IBInspectable var iPhone8: CGFloat = 0.0 { didSet { deviceFont(.i4_7Inch,value:iPhone8) } } @IBInspectable var iPhone8Plus: CGFloat = 0.0 { didSet { deviceFont(.i5_5Inch,value:iPhone8Plus) } } @IBInspectable var iPhone11Pro: CGFloat = 0.0 { didSet { deviceFont(.i5_8Inch,value:iPhone11Pro) } } @IBInspectable var iPhone11: CGFloat = 0.0 { didSet { deviceFont(.i6_1Inch,value:iPhone11) } } @IBInspectable var iPhone11Max: CGFloat = 0.0 { didSet { deviceFont(.i6_5Inch,value:iPhone11Max) } } @IBInspectable var iPhone12Mini: CGFloat = 0.0 { didSet { deviceFont(.i5_4Inch,value:iPhone12Mini) } } @IBInspectable var iPhone12: CGFloat = 0.0 { didSet { deviceFont(.i6_1Inch,value:iPhone12) } } @IBInspectable var iPhone12Pro: CGFloat = 0.0 { didSet { deviceFont(.i6_1Inch,value:iPhone12Pro) } } @IBInspectable var iPhone12ProMax: CGFloat = 0.0 { didSet { deviceFont(.i6_7Inch,value:iPhone12ProMax) } } @IBInspectable var iPadMini: CGFloat = 0.0 { didSet { deviceFont(.i7_9Inch,value:iPadMini) } } @IBInspectable var iPadPro9_7: CGFloat = 0.0 { didSet { deviceFont(.i9_7Inch,value:iPadPro9_7) } } @IBInspectable var iPadPro10_5: CGFloat = 0.0 { didSet { deviceFont(.i10_5Inch,value:iPadPro10_5) } } @IBInspectable var iPadAir10_8: CGFloat = 0.0 { didSet { deviceFont(.i10_8Inch,value:iPadAir10_8) } } @IBInspectable var iPadPro11: CGFloat = 0.0 { didSet { deviceFont(.i11_Inch,value:iPadPro11) } } @IBInspectable var iPadPro12_9: CGFloat = 0.0 { didSet { deviceFont(.i12_9Inch,value:iPadPro12_9) } } // Helpers open func deviceFont(_ device:UIDeviceSize,value:CGFloat) { if deviceSize == device { if let font = font { self.font = UIFont(descriptor: font.fontDescriptor, size: value) layoutIfNeeded() } } } }
35.142857
80
0.637398
d7ae62ece2f2213125da5d3941b2066a1bac7544
436
// // ServerConfigVideoCaptionFile.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct ServerConfigVideoCaptionFile: Codable { public var size: ServerConfigAvatarFileSize? public var extensions: [String]? public init(size: ServerConfigAvatarFileSize? = nil, extensions: [String]? = nil) { self.size = size self.extensions = extensions } }
20.761905
87
0.711009
389522a39b67827d4f43e5b1ec74339f39f11058
1,405
// // AppDelegate.swift // Project8 // // Created by Tao.T on 2020/7/27. // Copyright © 2020 TaoTao. 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.973684
179
0.745907
500a53123be09eadfbb9a0c847383cd8dd0101af
44,756
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016, 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if canImport(Darwin) import Darwin #endif extension Process { public enum TerminationReason : Int { case exit case uncaughtSignal } } private func WIFEXITED(_ status: Int32) -> Bool { return _WSTATUS(status) == 0 } private func _WSTATUS(_ status: Int32) -> Int32 { return status & 0x7f } private func WIFSIGNALED(_ status: Int32) -> Bool { return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f) } private func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xff } private func WTERMSIG(_ status: Int32) -> Int32 { return status & 0x7f } private var managerThreadRunLoop : RunLoop? = nil private var managerThreadRunLoopIsRunning = false private var managerThreadRunLoopIsRunningCondition = NSCondition() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) internal let kCFSocketNoCallBack: CFOptionFlags = 0 // .noCallBack cannot be used because empty option flags are imported as unavailable. internal let kCFSocketAcceptCallBack = CFSocketCallBackType.acceptCallBack.rawValue internal let kCFSocketDataCallBack = CFSocketCallBackType.dataCallBack.rawValue internal let kCFSocketSuccess = CFSocketError.success internal let kCFSocketError = CFSocketError.error internal let kCFSocketTimeout = CFSocketError.timeout extension CFSocketError { init?(_ value: CFIndex) { self.init(rawValue: value) } } #endif #if !canImport(Darwin) && !os(Windows) private func findMaximumOpenFromProcSelfFD() -> CInt? { guard let dirPtr = opendir("/proc/self/fd") else { return nil } defer { closedir(dirPtr) } var highestFDSoFar = CInt(0) while let dirEntPtr = readdir(dirPtr) { var entryName = dirEntPtr.pointee.d_name let thisFD = withUnsafeBytes(of: &entryName) { entryNamePtr -> CInt? in CInt(String(decoding: entryNamePtr.prefix(while: { $0 != 0 }), as: Unicode.UTF8.self)) } highestFDSoFar = max(thisFD ?? -1, highestFDSoFar) } return highestFDSoFar } func findMaximumOpenFD() -> CInt { if let maxFD = findMaximumOpenFromProcSelfFD() { // the precise method worked, let's return this fd. return maxFD } // We don't have /proc, let's go with the best estimate. #if os(Linux) return getdtablesize() #else return 4096 #endif } #endif private func emptyRunLoopCallback(_ context : UnsafeMutableRawPointer?) -> Void {} // Retain method for run loop source private func runLoopSourceRetain(_ pointer : UnsafeRawPointer?) -> UnsafeRawPointer? { let ref = Unmanaged<AnyObject>.fromOpaque(pointer!).takeUnretainedValue() let retained = Unmanaged<AnyObject>.passRetained(ref) return unsafeBitCast(retained, to: UnsafeRawPointer.self) } // Release method for run loop source private func runLoopSourceRelease(_ pointer : UnsafeRawPointer?) -> Void { Unmanaged<AnyObject>.fromOpaque(pointer!).release() } // Equal method for run loop source private func runloopIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean { let unmanagedrunLoopA = Unmanaged<AnyObject>.fromOpaque(a!) guard let runLoopA = unmanagedrunLoopA.takeUnretainedValue() as? RunLoop else { return false } let unmanagedRunLoopB = Unmanaged<AnyObject>.fromOpaque(a!) guard let runLoopB = unmanagedRunLoopB.takeUnretainedValue() as? RunLoop else { return false } guard runLoopA == runLoopB else { return false } return true } // Equal method for process in run loop source private func processIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean { let unmanagedProcessA = Unmanaged<AnyObject>.fromOpaque(a!) guard let processA = unmanagedProcessA.takeUnretainedValue() as? Process else { return false } let unmanagedProcessB = Unmanaged<AnyObject>.fromOpaque(a!) guard let processB = unmanagedProcessB.takeUnretainedValue() as? Process else { return false } guard processA == processB else { return false } return true } #if os(Windows) private func quoteWindowsCommandLine(_ commandLine: [String]) -> String { func quoteWindowsCommandArg(arg: String) -> String { // Windows escaping, adapted from Daniel Colascione's "Everyone quotes // command line arguments the wrong way" - Microsoft Developer Blog if !arg.contains(where: {" \t\n\"".contains($0)}) { return arg } // To escape the command line, we surround the argument with quotes. However // the complication comes due to how the Windows command line parser treats // backslashes (\) and quotes (") // // - \ is normally treated as a literal backslash // - e.g. foo\bar\baz => foo\bar\baz // - However, the sequence \" is treated as a literal " // - e.g. foo\"bar => foo"bar // // But then what if we are given a path that ends with a \? Surrounding // foo\bar\ with " would be "foo\bar\" which would be an unterminated string // since it ends on a literal quote. To allow this case the parser treats: // // - \\" as \ followed by the " metachar // - \\\" as \ followed by a literal " // - In general: // - 2n \ followed by " => n \ followed by the " metachar // - 2n+1 \ followed by " => n \ followed by a literal " var quoted = "\"" var unquoted = arg.unicodeScalars while !unquoted.isEmpty { guard let firstNonBackslash = unquoted.firstIndex(where: { $0 != "\\" }) else { // String ends with a backslash e.g. foo\bar\, escape all the backslashes // then add the metachar " below let backslashCount = unquoted.count quoted.append(String(repeating: "\\", count: backslashCount * 2)) break } let backslashCount = unquoted.distance(from: unquoted.startIndex, to: firstNonBackslash) if (unquoted[firstNonBackslash] == "\"") { // This is a string of \ followed by a " e.g. foo\"bar. Escape the // backslashes and the quote quoted.append(String(repeating: "\\", count: backslashCount * 2 + 1)) quoted.append(String(unquoted[firstNonBackslash])) } else { // These are just literal backslashes quoted.append(String(repeating: "\\", count: backslashCount)) quoted.append(String(unquoted[firstNonBackslash])) } // Drop the backslashes and the following character unquoted.removeFirst(backslashCount + 1) } quoted.append("\"") return quoted } return commandLine.map(quoteWindowsCommandArg).joined(separator: " ") } #endif open class Process: NSObject { private static func setup() { struct Once { static var done = false static let lock = NSLock() } Once.lock.synchronized { if !Once.done { let thread = Thread { managerThreadRunLoop = RunLoop.current var emptySourceContext = CFRunLoopSourceContext() emptySourceContext.version = 0 emptySourceContext.retain = runLoopSourceRetain emptySourceContext.release = runLoopSourceRelease emptySourceContext.equal = runloopIsEqual emptySourceContext.perform = emptyRunLoopCallback managerThreadRunLoop!.withUnretainedReference { (refPtr: UnsafeMutablePointer<UInt8>) in emptySourceContext.info = UnsafeMutableRawPointer(refPtr) } CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &emptySourceContext), kCFRunLoopDefaultMode) managerThreadRunLoopIsRunningCondition.lock() CFRunLoopPerformBlock(managerThreadRunLoop?._cfRunLoop, kCFRunLoopDefaultMode) { managerThreadRunLoopIsRunning = true managerThreadRunLoopIsRunningCondition.broadcast() managerThreadRunLoopIsRunningCondition.unlock() } managerThreadRunLoop?.run() fatalError("Process manager run loop exited unexpectedly; it should run forever once initialized") } thread.start() managerThreadRunLoopIsRunningCondition.lock() while managerThreadRunLoopIsRunning == false { managerThreadRunLoopIsRunningCondition.wait() } managerThreadRunLoopIsRunningCondition.unlock() Once.done = true } } } // Create an Process which can be run at a later time // An Process can only be run once. Subsequent attempts to // run an Process will raise. // Upon process death a notification will be sent // { Name = ProcessDidTerminateNotification; object = process; } // public override init() { } // These properties can only be set before a launch. private var _executable: URL? open var executableURL: URL? { get { _executable } set { guard let url = newValue, url.isFileURL else { fatalError("must provide a launch path") } _executable = url } } private var _currentDirectoryPath = FileManager.default.currentDirectoryPath open var currentDirectoryURL: URL? { get { _currentDirectoryPath == "" ? nil : URL(fileURLWithPath: _currentDirectoryPath, isDirectory: true) } set { // Setting currentDirectoryURL to nil resets to the current directory if let url = newValue { guard url.isFileURL else { fatalError("non-file URL argument") } _currentDirectoryPath = url.path } else { _currentDirectoryPath = FileManager.default.currentDirectoryPath } } } open var arguments: [String]? open var environment: [String : String]? // if not set, use current @available(*, deprecated, renamed: "executableURL") open var launchPath: String? { get { return executableURL?.path } set { executableURL = (newValue != nil) ? URL(fileURLWithPath: newValue!) : nil } } @available(*, deprecated, renamed: "currentDirectoryURL") open var currentDirectoryPath: String { get { _currentDirectoryPath } set { _currentDirectoryPath = newValue } } // Standard I/O channels; could be either a FileHandle or a Pipe open var standardInput: Any? = FileHandle._stdinFileHandle { willSet { precondition(newValue is Pipe || newValue is FileHandle || newValue == nil, "standardInput must be either Pipe or FileHandle") } } open var standardOutput: Any? = FileHandle._stdoutFileHandle { willSet { precondition(newValue is Pipe || newValue is FileHandle || newValue == nil, "standardOutput must be either Pipe or FileHandle") } } open var standardError: Any? = FileHandle._stderrFileHandle { willSet { precondition(newValue is Pipe || newValue is FileHandle || newValue == nil, "standardError must be either Pipe or FileHandle") } } private var runLoopSourceContext : CFRunLoopSourceContext? private var runLoopSource : CFRunLoopSource? fileprivate weak var runLoop : RunLoop? = nil private var processLaunchedCondition = NSCondition() // Actions @available(*, deprecated, renamed: "run") open func launch() { do { try run() } catch let nserror as NSError { if let path = nserror.userInfo[NSFilePathErrorKey] as? String, path == currentDirectoryPath { // Foundation throws an NSException when changing the working directory fails, // and unfortunately launch() is not marked `throws`, so we get away with a // fatalError. switch CocoaError.Code(rawValue: nserror.code) { case .fileReadNoSuchFile: fatalError("Process: The specified working directory does not exist.") case .fileReadNoPermission: fatalError("Process: The specified working directory cannot be accessed.") default: fatalError("Process: The specified working directory cannot be set.") } } else { fatalError(String(describing: nserror)) } } catch { fatalError(String(describing: error)) } } #if os(Windows) private func _socketpair() -> (first: SOCKET, second: SOCKET) { let listener: SOCKET = socket(AF_INET, SOCK_STREAM, 0) if listener == INVALID_SOCKET { return (first: INVALID_SOCKET, second: INVALID_SOCKET) } defer { closesocket(listener) } var result: Int32 = SOCKET_ERROR var address: sockaddr_in = sockaddr_in(sin_family: ADDRESS_FAMILY(AF_INET), sin_port: USHORT(0), sin_addr: IN_ADDR(S_un: in_addr.__Unnamed_union_S_un(S_un_b: in_addr.__Unnamed_union_S_un.__Unnamed_struct_S_un_b(s_b1: 127, s_b2: 0, s_b3: 0, s_b4: 1))), sin_zero: (CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0))) withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { result = bind(listener, $0, Int32(MemoryLayout<sockaddr_in>.size)) } } if result == SOCKET_ERROR { return (first: INVALID_SOCKET, second: INVALID_SOCKET) } if listen(listener, 1) == SOCKET_ERROR { return (first: INVALID_SOCKET, second: INVALID_SOCKET) } withUnsafeMutablePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { var value: Int32 = Int32(MemoryLayout<sockaddr_in>.size) result = getsockname(listener, $0, &value) } } if result == SOCKET_ERROR { return (first: INVALID_SOCKET, second: INVALID_SOCKET) } let first: SOCKET = socket(AF_INET, SOCK_STREAM, 0) if first == INVALID_SOCKET { return (first: INVALID_SOCKET, second: INVALID_SOCKET) } withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { result = connect(first, $0, Int32(MemoryLayout<sockaddr_in>.size)) } } if result == SOCKET_ERROR { closesocket(first) return (first: INVALID_SOCKET, second: INVALID_SOCKET) } var value: u_long = 1 if ioctlsocket(first, FIONBIO, &value) == SOCKET_ERROR { closesocket(first) return (first: INVALID_SOCKET, second: INVALID_SOCKET) } let second: SOCKET = accept(listener, nil, nil) if second == INVALID_SOCKET { closesocket(first) return (first: INVALID_SOCKET, second: INVALID_SOCKET) } return (first: first, second: second) } #endif open func run() throws { self.processLaunchedCondition.lock() defer { self.processLaunchedCondition.broadcast() self.processLaunchedCondition.unlock() } // Dispatch the manager thread if it isn't already running Process.setup() // Check that the process isnt run more than once guard hasStarted == false && hasFinished == false else { throw NSError(domain: NSCocoaErrorDomain, code: NSExecutableLoadError) } // Ensure that the launch path is set guard let launchPath = self.executableURL?.path else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError) } #if os(Windows) var command: [String] = [launchPath] if let arguments = self.arguments { command.append(contentsOf: arguments) } var siStartupInfo: STARTUPINFOW = STARTUPINFOW() siStartupInfo.cb = DWORD(MemoryLayout<STARTUPINFOW>.size) siStartupInfo.dwFlags = DWORD(STARTF_USESTDHANDLES) var _devNull: FileHandle? func devNullFd() throws -> HANDLE { _devNull = try _devNull ?? FileHandle(forUpdating: URL(fileURLWithPath: "NUL", isDirectory: false)) return _devNull!.handle } var modifiedPipes: [(handle: HANDLE, prevValue: DWORD)] = [] defer { modifiedPipes.forEach { SetHandleInformation($0.handle, DWORD(HANDLE_FLAG_INHERIT), $0.prevValue) } } func deferReset(handle: HANDLE) throws { var handleInfo: DWORD = 0 guard GetHandleInformation(handle, &handleInfo) else { throw _NSErrorWithWindowsError(GetLastError(), reading: false) } modifiedPipes.append((handle: handle, prevValue: handleInfo & DWORD(HANDLE_FLAG_INHERIT))) } switch standardInput { case let pipe as Pipe: siStartupInfo.hStdInput = pipe.fileHandleForReading.handle try deferReset(handle: pipe.fileHandleForWriting.handle) SetHandleInformation(pipe.fileHandleForWriting.handle, DWORD(HANDLE_FLAG_INHERIT), 0) // nil or NullDevice maps to NUL case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: siStartupInfo.hStdInput = try devNullFd() case let handle as FileHandle: siStartupInfo.hStdInput = handle.handle try deferReset(handle: handle.handle) SetHandleInformation(handle.handle, DWORD(HANDLE_FLAG_INHERIT), 1) default: break } switch standardOutput { case let pipe as Pipe: siStartupInfo.hStdOutput = pipe.fileHandleForWriting.handle try deferReset(handle: pipe.fileHandleForReading.handle) SetHandleInformation(pipe.fileHandleForReading.handle, DWORD(HANDLE_FLAG_INHERIT), 0) // nil or NullDevice maps to NUL case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: siStartupInfo.hStdOutput = try devNullFd() case let handle as FileHandle: siStartupInfo.hStdOutput = handle.handle try deferReset(handle: handle.handle) SetHandleInformation(handle.handle, DWORD(HANDLE_FLAG_INHERIT), 1) default: break } switch standardError { case let pipe as Pipe: siStartupInfo.hStdError = pipe.fileHandleForWriting.handle try deferReset(handle: pipe.fileHandleForReading.handle) SetHandleInformation(pipe.fileHandleForReading.handle, DWORD(HANDLE_FLAG_INHERIT), 0) // nil or NullDevice maps to NUL case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: siStartupInfo.hStdError = try devNullFd() case let handle as FileHandle: siStartupInfo.hStdError = handle.handle try deferReset(handle: handle.handle) SetHandleInformation(handle.handle, DWORD(HANDLE_FLAG_INHERIT), 1) default: break } var piProcessInfo: PROCESS_INFORMATION = PROCESS_INFORMATION() var environment: [String:String] = [:] if let env = self.environment { environment = env } else { environment = ProcessInfo.processInfo.environment } // On Windows, the PATH is required in order to locate dlls needed by // the process so we should also pass that to the child if environment["Path"] == nil, let path = ProcessInfo.processInfo.environment["Path"] { environment["Path"] = path } // NOTE(compnerd) the environment string must be terminated by a double // null-terminator. Otherwise, CreateProcess will fail with // INVALID_PARMETER. let szEnvironment: String = environment.map { $0.key + "=" + $0.value }.joined(separator: "\0") + "\0\0" let sockets: (first: SOCKET, second: SOCKET) = _socketpair() var context: CFSocketContext = CFSocketContext() context.version = 0 context.retain = runLoopSourceRetain context.release = runLoopSourceRelease context.info = Unmanaged.passUnretained(self).toOpaque() let socket: CFSocket = CFSocketCreateWithNative(nil, CFSocketNativeHandle(sockets.first), CFOptionFlags(kCFSocketDataCallBack), { (socket, type, address, data, info) in let process: Process = NSObject.unretainedReference(info!) process.processLaunchedCondition.lock() while process.isRunning == false { process.processLaunchedCondition.wait() } process.processLaunchedCondition.unlock() WaitForSingleObject(process.processHandle, WinSDK.INFINITE) // On Windows, the top nibble of an NTSTATUS indicates severity, with // the top two bits both being set (0b11) indicating an error. In // addition, in a well formed NTSTATUS, the 4th bit must be 0. // The third bit indicates if the error is a Microsoft defined error // and may or may not be set. // // If we receive such an error, we'll indicate that the process // exited abnormally (confusingly indicating "signalled" so we match // POSIX behaviour for abnormal exits). // // However, we don't want user programs which normally exit -1, -2, // etc to count as exited abnormally, so we specifically check for a // top nibble of 0b11_0 so that e.g. 0xFFFFFFFF, won't trigger an // abnormal exit. // // Additionally, on Windows, an uncaught signal terminates the // program with the magic exit code 3, regardless of the signal (I'd // personally love to know the reason for this). So we also consider // 3 to be an abnormal exit. var dwExitCode: DWORD = 0 GetExitCodeProcess(process.processHandle, &dwExitCode) if (dwExitCode & 0xF0000000) == 0xC0000000 || (dwExitCode & 0xF0000000) == 0xE0000000 || dwExitCode == 3 { process._terminationStatus = Int32(dwExitCode & 0x3FFFFFFF) process._terminationReason = .uncaughtSignal } else { process._terminationStatus = Int32(bitPattern: dwExitCode) process._terminationReason = .exit } if let handler = process.terminationHandler { let thread: Thread = Thread { handler(process) } thread.start() } process.isRunning = false // Invalidate the source and wake up the run loop, if it is available CFRunLoopSourceInvalidate(process.runLoopSource) if let runloop = process.runLoop { CFRunLoopWakeUp(runloop._cfRunLoop) } CFSocketInvalidate(socket) }, &context) CFSocketSetSocketFlags(socket, CFOptionFlags(kCFSocketCloseOnInvalidate)) let source: CFRunLoopSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0) CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, source, kCFRunLoopDefaultMode) let workingDirectory = currentDirectoryURL?.path ?? FileManager.default.currentDirectoryPath try quoteWindowsCommandLine(command).withCString(encodedAs: UTF16.self) { wszCommandLine in try workingDirectory.withCString(encodedAs: UTF16.self) { wszCurrentDirectory in try szEnvironment.withCString(encodedAs: UTF16.self) { wszEnvironment in if !CreateProcessW(nil, UnsafeMutablePointer<WCHAR>(mutating: wszCommandLine), nil, nil, true, DWORD(CREATE_UNICODE_ENVIRONMENT), UnsafeMutableRawPointer(mutating: wszEnvironment), wszCurrentDirectory, &siStartupInfo, &piProcessInfo) { let error = GetLastError() // If the current directory doesn't exist, Windows // throws an ERROR_DIRECTORY. Since POSIX gives an // ENOENT, we intercept the error to match the POSIX // behaviour if error == ERROR_DIRECTORY { throw _NSErrorWithWindowsError(DWORD(ERROR_FILE_NOT_FOUND), reading: true) } throw _NSErrorWithWindowsError(GetLastError(), reading: true) } } } } self.processHandle = piProcessInfo.hProcess if !CloseHandle(piProcessInfo.hThread) { throw _NSErrorWithWindowsError(GetLastError(), reading: false) } if let pipe = standardInput as? Pipe { pipe.fileHandleForReading.closeFile() } if let pipe = standardOutput as? Pipe { pipe.fileHandleForWriting.closeFile() } if let pipe = standardError as? Pipe { pipe.fileHandleForWriting.closeFile() } self.runLoop = RunLoop.current self.runLoopSourceContext = CFRunLoopSourceContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: { runLoopSourceRetain($0) }, release: { runLoopSourceRelease($0) }, copyDescription: nil, equal: { processIsEqual($0, $1) }, hash: nil, schedule: nil, cancel: nil, perform: { emptyRunLoopCallback($0) }) self.runLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &self.runLoopSourceContext!) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode) isRunning = true closesocket(sockets.second) #else // Initial checks that the launchPath points to an executable file. posix_spawn() // can return success even if executing the program fails, eg fork() works but execve() // fails, so try and check as much as possible beforehand. try FileManager.default._fileSystemRepresentation(withPath: launchPath, { fsRep in var statInfo = stat() guard stat(fsRep, &statInfo) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: launchPath) } let isRegularFile: Bool = statInfo.st_mode & S_IFMT == S_IFREG guard isRegularFile == true else { throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError) } guard access(fsRep, X_OK) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: launchPath) } }) // Convert the arguments array into a posix_spawn-friendly format var args = [launchPath] if let arguments = self.arguments { args.append(contentsOf: arguments) } let argv : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> = args.withUnsafeBufferPointer { let array : UnsafeBufferPointer<String> = $0 let buffer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: array.count + 1) buffer.initialize(from: array.map { $0.withCString(strdup) }, count: array.count) buffer[array.count] = nil return buffer } defer { for arg in argv ..< argv + args.count { free(UnsafeMutableRawPointer(arg.pointee)) } argv.deallocate() } var env: [String: String] if let e = environment { env = e } else { env = ProcessInfo.processInfo.environment } let nenv = env.count let envp = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1 + nenv) envp.initialize(from: env.map { strdup("\($0)=\($1)") }, count: nenv) envp[env.count] = nil defer { for pair in envp ..< envp + env.count { free(UnsafeMutableRawPointer(pair.pointee)) } envp.deallocate() } var taskSocketPair : [Int32] = [0, 0] #if os(macOS) || os(iOS) || os(Android) socketpair(AF_UNIX, SOCK_STREAM, 0, &taskSocketPair) #else socketpair(AF_UNIX, Int32(SOCK_STREAM.rawValue), 0, &taskSocketPair) #endif var context = CFSocketContext() context.version = 0 context.retain = runLoopSourceRetain context.release = runLoopSourceRelease context.info = Unmanaged.passUnretained(self).toOpaque() let socket = CFSocketCreateWithNative( nil, taskSocketPair[0], CFOptionFlags(kCFSocketDataCallBack), { (socket, type, address, data, info ) in let process: Process = NSObject.unretainedReference(info!) process.processLaunchedCondition.lock() while process.isRunning == false { process.processLaunchedCondition.wait() } process.processLaunchedCondition.unlock() var exitCode : Int32 = 0 #if CYGWIN let exitCodePtrWrapper = withUnsafeMutablePointer(to: &exitCode) { exitCodePtr in __wait_status_ptr_t(__int_ptr: exitCodePtr) } #endif var waitResult : Int32 = 0 repeat { #if CYGWIN waitResult = waitpid( process.processIdentifier, exitCodePtrWrapper, 0) #else waitResult = waitpid( process.processIdentifier, &exitCode, 0) #endif } while ( (waitResult == -1) && (errno == EINTR) ) if WIFSIGNALED(exitCode) { process._terminationStatus = WTERMSIG(exitCode) process._terminationReason = .uncaughtSignal } else { assert(WIFEXITED(exitCode)) process._terminationStatus = WEXITSTATUS(exitCode) process._terminationReason = .exit } // If a termination handler has been set, invoke it on a background thread if let terminationHandler = process.terminationHandler { let thread = Thread { terminationHandler(process) } thread.start() } // Set the running flag to false process.isRunning = false // Invalidate the source and wake up the run loop, if it's available CFRunLoopSourceInvalidate(process.runLoopSource) if let runLoop = process.runLoop { CFRunLoopWakeUp(runLoop._cfRunLoop) } CFSocketInvalidate( socket ) }, &context ) CFSocketSetSocketFlags( socket, CFOptionFlags(kCFSocketCloseOnInvalidate)) let source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0) CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, source, kCFRunLoopDefaultMode) var fileActions = _CFPosixSpawnFileActionsAlloc() posix(_CFPosixSpawnFileActionsInit(fileActions)) defer { _CFPosixSpawnFileActionsDestroy(fileActions) _CFPosixSpawnFileActionsDealloc(fileActions) } // File descriptors to duplicate in the child process. This allows // output redirection to NSPipe or NSFileHandle. var adddup2 = [Int32: Int32]() // File descriptors to close in the child process. A set so that // shared pipes only get closed once. Would result in EBADF on OSX // otherwise. var addclose = Set<Int32>() var _devNull: FileHandle? func devNullFd() throws -> Int32 { _devNull = try _devNull ?? FileHandle(forUpdating: URL(fileURLWithPath: "/dev/null", isDirectory: false)) return _devNull!.fileDescriptor } switch standardInput { case let pipe as Pipe: adddup2[STDIN_FILENO] = pipe.fileHandleForReading.fileDescriptor addclose.insert(pipe.fileHandleForWriting.fileDescriptor) // nil or NullDevice map to /dev/null case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: adddup2[STDIN_FILENO] = try devNullFd() // No need to dup stdin to stdin case let handle as FileHandle where handle === FileHandle._stdinFileHandle: break case let handle as FileHandle: adddup2[STDIN_FILENO] = handle.fileDescriptor default: break } switch standardOutput { case let pipe as Pipe: adddup2[STDOUT_FILENO] = pipe.fileHandleForWriting.fileDescriptor addclose.insert(pipe.fileHandleForReading.fileDescriptor) // nil or NullDevice map to /dev/null case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: adddup2[STDOUT_FILENO] = try devNullFd() // No need to dup stdout to stdout case let handle as FileHandle where handle === FileHandle._stdoutFileHandle: break case let handle as FileHandle: adddup2[STDOUT_FILENO] = handle.fileDescriptor default: break } switch standardError { case let pipe as Pipe: adddup2[STDERR_FILENO] = pipe.fileHandleForWriting.fileDescriptor addclose.insert(pipe.fileHandleForReading.fileDescriptor) // nil or NullDevice map to /dev/null case let handle as FileHandle where handle === FileHandle._nulldeviceFileHandle: fallthrough case .none: adddup2[STDERR_FILENO] = try devNullFd() // No need to dup stderr to stderr case let handle as FileHandle where handle === FileHandle._stderrFileHandle: break case let handle as FileHandle: adddup2[STDERR_FILENO] = handle.fileDescriptor default: break } for (new, old) in adddup2 { posix(_CFPosixSpawnFileActionsAddDup2(fileActions, old, new)) } for fd in addclose.filter({ $0 >= 0 }) { posix(_CFPosixSpawnFileActionsAddClose(fileActions, fd)) } #if canImport(Darwin) var spawnAttrs: posix_spawnattr_t? = nil posix_spawnattr_init(&spawnAttrs) posix_spawnattr_setflags(&spawnAttrs, .init(POSIX_SPAWN_CLOEXEC_DEFAULT)) #else for fd in 3 ... findMaximumOpenFD() { guard adddup2[fd] == nil && !addclose.contains(fd) && fd != taskSocketPair[1] else { continue // Do not double-close descriptors, or close those pertaining to Pipes or FileHandles we want inherited. } posix(_CFPosixSpawnFileActionsAddClose(fileActions, fd)) } #endif let fileManager = FileManager() let previousDirectoryPath = fileManager.currentDirectoryPath if let dir = currentDirectoryURL?.path, !fileManager.changeCurrentDirectoryPath(dir) { throw _NSErrorWithErrno(errno, reading: true, url: currentDirectoryURL) } defer { // Reset the previous working directory path. fileManager.changeCurrentDirectoryPath(previousDirectoryPath) } // Launch var pid = pid_t() #if os(macOS) guard _CFPosixSpawn(&pid, launchPath, fileActions, &spawnAttrs, argv, envp) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: launchPath) } #else guard _CFPosixSpawn(&pid, launchPath, fileActions, nil, argv, envp) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: launchPath) } #endif // Close the write end of the input and output pipes. if let pipe = standardInput as? Pipe { pipe.fileHandleForReading.closeFile() } if let pipe = standardOutput as? Pipe { pipe.fileHandleForWriting.closeFile() } if let pipe = standardError as? Pipe { pipe.fileHandleForWriting.closeFile() } close(taskSocketPair[1]) self.runLoop = RunLoop.current self.runLoopSourceContext = CFRunLoopSourceContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: { return runLoopSourceRetain($0) }, release: { runLoopSourceRelease($0) }, copyDescription: nil, equal: { return processIsEqual($0, $1) }, hash: nil, schedule: nil, cancel: nil, perform: { emptyRunLoopCallback($0) }) self.runLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &runLoopSourceContext!) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode) isRunning = true self.processIdentifier = pid #endif } open func interrupt() { precondition(hasStarted, "task not launched") #if os(Windows) TerminateProcess(processHandle, UINT(SIGINT)) #else kill(processIdentifier, SIGINT) #endif } open func terminate() { precondition(hasStarted, "task not launched") #if os(Windows) TerminateProcess(processHandle, UINT(0xC0000000 | DWORD(SIGTERM))) #else kill(processIdentifier, SIGTERM) #endif } // Every suspend() has to be balanced with a resume() so keep a count of both. private var suspendCount = 0 open func suspend() -> Bool { #if os(Windows) let pNTSuspendProcess: Optional<(HANDLE) -> LONG> = unsafeBitCast(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtSuspendProcess"), to: Optional<(HANDLE) -> LONG>.self) if let pNTSuspendProcess = pNTSuspendProcess { if pNTSuspendProcess(processHandle) < 0 { return false } suspendCount += 1 return true } return false #else if kill(processIdentifier, SIGSTOP) == 0 { suspendCount += 1 return true } else { return false } #endif } open func resume() -> Bool { var success: Bool = true #if os(Windows) if suspendCount == 1 { let pNTResumeProcess: Optional<(HANDLE) -> NTSTATUS> = unsafeBitCast(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtResumeProcess"), to: Optional<(HANDLE) -> NTSTATUS>.self) if let pNTResumeProcess = pNTResumeProcess { if pNTResumeProcess(processHandle) < 0 { success = false } } } #else if suspendCount == 1 { success = kill(processIdentifier, SIGCONT) == 0 } #endif if success { suspendCount -= 1 } return success } // status #if os(Windows) open private(set) var processHandle: HANDLE = INVALID_HANDLE_VALUE open var processIdentifier: Int32 { guard processHandle != INVALID_HANDLE_VALUE else { return 0 } return Int32(GetProcessId(processHandle)) } open private(set) var isRunning: Bool = false private var hasStarted: Bool { return processHandle != INVALID_HANDLE_VALUE } private var hasFinished: Bool { return hasStarted && !isRunning } #else open private(set) var processIdentifier: Int32 = 0 open private(set) var isRunning: Bool = false private var hasStarted: Bool { return processIdentifier > 0 } private var hasFinished: Bool { return !isRunning && processIdentifier > 0 } #endif private var _terminationStatus: Int32 = 0 public var terminationStatus: Int32 { precondition(hasStarted, "task not launched") precondition(hasFinished, "task still running") return _terminationStatus } private var _terminationReason: TerminationReason = .exit public var terminationReason: TerminationReason { precondition(hasStarted, "task not launched") precondition(hasFinished, "task still running") return _terminationReason } /* A block to be invoked when the process underlying the Process terminates. Setting the block to nil is valid, and stops the previous block from being invoked, as long as it hasn't started in any way. The Process is passed as the argument to the block so the block does not have to capture, and thus retain, it. The block is copied when set. Only one termination handler block can be set at any time. The execution context in which the block is invoked is undefined. If the Process has already finished, the block is executed immediately/soon (not necessarily on the current thread). If a terminationHandler is set on an Process, the ProcessDidTerminateNotification notification is not posted for that process. Also note that -waitUntilExit won't wait until the terminationHandler has been fully executed. You cannot use this property in a concrete subclass of Process which hasn't been updated to include an implementation of the storage and use of it. */ open var terminationHandler: ((Process) -> Void)? open var qualityOfService: QualityOfService = .default // read-only after the process is launched open class func run(_ url: URL, arguments: [String], terminationHandler: ((Process) -> Void)? = nil) throws -> Process { let process = Process() process.executableURL = url process.arguments = arguments process.terminationHandler = terminationHandler try process.run() return process } @available(*, deprecated, renamed: "run(_:arguments:terminationHandler:)") // convenience; create and launch open class func launchedProcess(launchPath path: String, arguments: [String]) -> Process { let process = Process() process.launchPath = path process.arguments = arguments process.launch() return process } // poll the runLoop in defaultMode until process completes open func waitUntilExit() { repeat { } while( self.isRunning == true && RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.05)) ) self.runLoop = nil } } extension Process { public static let didTerminateNotification = NSNotification.Name(rawValue: "NSTaskDidTerminateNotification") } private func posix(_ code: Int32, file: StaticString = #file, line: UInt = #line) { switch code { case 0: return case EBADF: fatalError("POSIX command failed with error: \(code) -- EBADF", file: file, line: line) default: fatalError("POSIX command failed with error: \(code)", file: file, line: line) } }
39.054101
966
0.61375
ef255feb188184c9e1ac38d13409514b6c2cd95c
401
// // KeyboardAlert.swift // KeyboardKit // // Created by Daniel Saidi on 2018-02-01. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit /** This protocol can be used to display alerts within keyboard extensions, since they don't support `UIAlertController`. */ public protocol KeyboardAlert { func alert(message: String, in view: UIView, withDuration: Double) }
21.105263
70
0.715711
6203fef5ac6f584ce32fd3708a8241fc689ae93f
70,800
// Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // //TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION // //1. Definitions. // // "License" shall mean the terms and conditions for use, reproduction, // and distribution as defined by Sections 1 through 9 of this document. // // "Licensor" shall mean the copyright owner or entity authorized by // the copyright owner that is granting the License. // // "Legal Entity" shall mean the union of the acting entity and all // other entities that control, are controlled by, or are under common // control with that entity. For the purposes of this definition, // "control" means (i) the power, direct or indirect, to cause the // direction or management of such entity, whether by contract or // otherwise, or (ii) ownership of fifty percent (50%) or more of the // outstanding shares, or (iii) beneficial ownership of such entity. // // "You" (or "Your") shall mean an individual or Legal Entity // exercising permissions granted by this License. // // "Source" form shall mean the preferred form for making modifications, // including but not limited to software source code, documentation // source, and configuration files. // // "Object" form shall mean any form resulting from mechanical // transformation or translation of a Source form, including but // not limited to compiled object code, generated documentation, // and conversions to other media types. // // "Work" shall mean the work of authorship, whether in Source or // Object form, made available under the License, as indicated by a // copyright notice that is included in or attached to the work // (an example is provided in the Appendix below). // // "Derivative Works" shall mean any work, whether in Source or Object // form, that is based on (or derived from) the Work and for which the // editorial revisions, annotations, elaborations, or other modifications // represent, as a whole, an original work of authorship. For the purposes // of this License, Derivative Works shall not include works that remain // separable from, or merely link (or bind by name) to the interfaces of, // the Work and Derivative Works thereof. // // "Contribution" shall mean any work of authorship, including // the original version of the Work and any modifications or additions // to that Work or Derivative Works thereof, that is intentionally // submitted to Licensor for inclusion in the Work by the copyright owner // or by an individual or Legal Entity authorized to submit on behalf of // the copyright owner. For the purposes of this definition, "submitted" // means any form of electronic, verbal, or written communication sent // to the Licensor or its representatives, including but not limited to // communication on electronic mailing lists, source code control systems, // and issue tracking systems that are managed by, or on behalf of, the // Licensor for the purpose of discussing and improving the Work, but // excluding communication that is conspicuously marked or otherwise // designated in writing by the copyright owner as "Not a Contribution." // // "Contributor" shall mean Licensor and any individual or Legal Entity // on behalf of whom a Contribution has been received by Licensor and // subsequently incorporated within the Work. // //2. Grant of Copyright License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // copyright license to reproduce, prepare Derivative Works of, // publicly display, publicly perform, sublicense, and distribute the // Work and such Derivative Works in Source or Object form. // //3. Grant of Patent License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // (except as stated in this section) patent license to make, have made, // use, offer to sell, sell, import, and otherwise transfer the Work, // where such license applies only to those patent claims licensable // by such Contributor that are necessarily infringed by their // Contribution(s) alone or by combination of their Contribution(s) // with the Work to which such Contribution(s) was submitted. If You // institute patent litigation against any entity (including a // cross-claim or counterclaim in a lawsuit) alleging that the Work // or a Contribution incorporated within the Work constitutes direct // or contributory patent infringement, then any patent licenses // granted to You under this License for that Work shall terminate // as of the date such litigation is filed. // //4. Redistribution. You may reproduce and distribute copies of the // Work or Derivative Works thereof in any medium, with or without // modifications, and in Source or Object form, provided that You // meet the following conditions: // // (a) You must give any other recipients of the Work or // Derivative Works a copy of this License; and // // (b) You must cause any modified files to carry prominent notices // stating that You changed the files; and // // (c) You must retain, in the Source form of any Derivative Works // that You distribute, all copyright, patent, trademark, and // attribution notices from the Source form of the Work, // excluding those notices that do not pertain to any part of // the Derivative Works; and // // (d) If the Work includes a "NOTICE" text file as part of its // distribution, then any Derivative Works that You distribute must // include a readable copy of the attribution notices contained // within such NOTICE file, excluding those notices that do not // pertain to any part of the Derivative Works, in at least one // of the following places: within a NOTICE text file distributed // as part of the Derivative Works; within the Source form or // documentation, if provided along with the Derivative Works; or, // within a display generated by the Derivative Works, if and // wherever such third-party notices normally appear. The contents // of the NOTICE file are for informational purposes only and // do not modify the License. You may add Your own attribution // notices within Derivative Works that You distribute, alongside // or as an addendum to the NOTICE text from the Work, provided // that such additional attribution notices cannot be construed // as modifying the License. // // You may add Your own copyright statement to Your modifications and // may provide additional or different license terms and conditions // for use, reproduction, or distribution of Your modifications, or // for any such Derivative Works as a whole, provided Your use, // reproduction, and distribution of the Work otherwise complies with // the conditions stated in this License. // //5. Submission of Contributions. Unless You explicitly state otherwise, // any Contribution intentionally submitted for inclusion in the Work // by You to the Licensor shall be under the terms and conditions of // this License, without any additional terms or conditions. // Notwithstanding the above, nothing herein shall supersede or modify // the terms of any separate license agreement you may have executed // with Licensor regarding such Contributions. // //6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor, // except as required for reasonable and customary use in describing the // origin of the Work and reproducing the content of the NOTICE file. // //7. Disclaimer of Warranty. Unless required by applicable law or // agreed to in writing, Licensor provides the Work (and each // Contributor provides its Contributions) on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied, including, without limitation, any warranties or conditions // of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A // PARTICULAR PURPOSE. You are solely responsible for determining the // appropriateness of using or redistributing the Work and assume any // risks associated with Your exercise of permissions under this License. // //8. Limitation of Liability. In no event and under no legal theory, // whether in tort (including negligence), contract, or otherwise, // unless required by applicable law (such as deliberate and grossly // negligent acts) or agreed to in writing, shall any Contributor be // liable to You for damages, including any direct, indirect, special, // incidental, or consequential damages of any character arising as a // result of this License or out of the use or inability to use the // Work (including but not limited to damages for loss of goodwill, // work stoppage, computer failure or malfunction, or any and all // other commercial damages or losses), even if such Contributor // has been advised of the possibility of such damages. // //9. Accepting Warranty or Additional Liability. While redistributing // the Work or Derivative Works thereof, You may choose to offer, // and charge a fee for, acceptance of support, warranty, indemnity, // or other liability obligations and/or rights consistent with this // License. However, in accepting such obligations, You may act only // on Your own behalf and on Your sole responsibility, not on behalf // of any other Contributor, and only if You agree to indemnify, // defend, and hold each Contributor harmless for any liability // incurred by, or claims asserted against, such Contributor by reason // of your accepting any such warranty or additional liability. // //END OF TERMS AND CONDITIONS // //APPENDIX: How to apply the Apache License to your work. // // To apply the Apache License to your work, attach the following // boilerplate notice, with the fields enclosed by brackets "[]" // replaced with your own identifying information. (Don't include // the brackets!) The text should be enclosed in the appropriate // comment syntax for the file format. We also recommend that a // file or class name and description of purpose be included on the // same "printed page" as the copyright notice for easier // identification within third-party archives. // //Copyright 2019 mongodb // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. import UIKit import RealmSwift extension UIImage { func resized(withPercentage percentage: CGFloat) -> UIImage? { let canvas = CGSize(width: size.width * percentage, height: size.height * percentage) return UIGraphicsImageRenderer(size: canvas, format: imageRendererFormat).image { _ in draw(in: CGRect(origin: .zero, size: canvas)) } } func whiteMask() -> UIImage? { let opaqueImage = UIImage(data: jpegData(compressionQuality: 1.0)!)! let opaqueImageRef: CGImage = opaqueImage.cgImage! let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255] UIGraphicsBeginImageContext(opaqueImage.size); let maskedImageRef = opaqueImageRef.copy(maskingColorComponents: colorMasking) UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: opaqueImage.size.height) UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0) UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: opaqueImage.size.width, height: opaqueImage.size.height)) let transparentImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return transparentImage } } class DrawViewController: BaseViewController, UITextFieldDelegate { // MARK: - OUTLETS @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var tempImageView: UIImageView! @IBOutlet weak var hiddenTextField: UITextField! @IBOutlet weak var pencilButton: DrawToolbarPersistedButton! @IBOutlet weak var leftToolbarParent: UIView! @IBOutlet weak var drawToolbar: DrawToolbarStackView! @IBOutlet weak var parentGridHorizontalStackView: UIStackView! @IBOutlet weak var scribbleButton: DrawToolbarPopoverButton! @IBOutlet weak var sansSerifButton: DrawToolbarPopoverButton! @IBOutlet weak var opacityButton: DrawToolbarPopoverButton! @IBOutlet weak var stampButton: DrawToolbarPopoverButton! @IBOutlet weak var rectangleButton: DrawToolbarPersistedButton! @IBOutlet weak var ovalButton: DrawToolbarPersistedButton! @IBOutlet weak var triangleButton: DrawToolbarPersistedButton! @IBOutlet weak var usernameLabel: UILabel! // MARK: - INIT let scribblePopoverParent = UIView() let scribblePopoverToolbar = DrawToolbarStackView() let sansSerifPopoverParent = UIView() let sansSerifPopoverToolbar = DrawToolbarStackView() let stampsPopoverParent = UIView() let stampsPopoverToolbar = DrawToolbarStackView() let opacityPopoverParent = UIView() let opacityPopoverToolbar = DrawToolbarStackView() let rectanglePopoverParent = UIView() let rectanglePopoverToolbar = DrawToolbarStackView() let ovalPopoverParent = UIView() let ovalPopoverToolbar = DrawToolbarStackView() let trianglePopoverParent = UIView() let trianglePopoverToolbar = DrawToolbarStackView() var popoverParents: [UIView] = [] var shapes: Results<Shape>? let storedImages: Results<StoredImage>? var notificationToken: NotificationToken! var lastPoint = CGPoint.zero var swiped = false private var currentShape: Shape? private var lineCount = 0 required init?(coder aDecoder: NSCoder) { if RealmConnection.connect() { self.shapes = RealmConnection.realm!.objects(Shape.self) self.storedImages = RealmConnection.realmAtlas!.objects(StoredImage.self).sorted(byKeyPath: "timestamp", ascending: true) } else { self.shapes = nil self.storedImages = nil } super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() ErrorReporter.resetError() tempImageView.isUserInteractionEnabled = true mainImageView.isUserInteractionEnabled = true if Constants.ARTIST_MODE { usernameLabel!.text = "\(User.userName) - artist" } else { usernameLabel!.text = User.userName } if shapes == nil || storedImages == nil { ErrorReporter.raiseError("viewDidLoad cannot complete as the Realm live queries haven't been set up. Try restarting the app.") } else { popoverParents = [scribblePopoverParent, sansSerifPopoverParent, stampsPopoverParent, opacityPopoverParent, rectanglePopoverParent, ovalPopoverParent, trianglePopoverParent] pencilButton.select() notificationToken = shapes!.observe { [weak self] changes in guard let strongSelf = self else { ErrorReporter.raiseError("Cannot find self, try restarting the app") return } self!.hiddenTextField.delegate = self switch changes { case .initial(let shapes): strongSelf.draw { context in shapes.forEach { $0.draw(context) } } break case .update(let shapes, let deletions, let insertions, let modifications): (insertions + modifications).forEach { index in if shapes[index].deviceId != thisDevice { strongSelf.draw { context in let shape = shapes[index] shape.draw(context) } } } if deletions.count > 0 { strongSelf.mainImageView.image = nil strongSelf.shapes!.forEach { shape in strongSelf.draw { context in shape.draw(context) } } } strongSelf.mergeViews() break case .error(let error): ErrorReporter.raiseError("Unexpected Realm notification type: \(error.localizedDescription)") // fatalError(error.localizedDescription) } } } } deinit { notificationToken?.invalidate() } // MARK: - BUSINESS LOGIC func mergeViews() { // Merge tempImageView into mainImageView UIGraphicsBeginImageContext(mainImageView.frame.size) mainImageView.image?.draw(in: mainImageView.bounds, blendMode: .normal, alpha: 1.0) tempImageView?.image?.draw(in: tempImageView.bounds, blendMode: .normal, alpha: 1.0) mainImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() tempImageView.image = nil } private func draw(_ block: (CGContext) -> Void) { UIGraphicsBeginImageContext(self.tempImageView.frame.size) guard let context = UIGraphicsGetCurrentContext() else { ErrorReporter.raiseError("Failed to get UIGraphicsGetCurrentContext") return } // Render tempImageView in the current context (context) self.tempImageView.image?.draw(in: tempImageView.bounds) block(context) self.tempImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } func extractImage() -> Data? { guard let image = mainImageView.image?.jpegData(compressionQuality: 1.0) else { ErrorReporter.raiseError("Failed to get the main image view") return nil } return image } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { ErrorReporter.raiseError("Cannot find the first touch") return } guard let myRealm = RealmConnection.realm else { ErrorReporter.raiseError("Cannot access realm from RealmConnection") return } currentShape = Shape() currentShape!.shapeType = CurrentTool.shapeType currentShape!.color = CurrentTool.color.toHex currentShape!.brushWidth = CurrentTool.brushWidth currentShape!.fontStyle = CurrentTool.fontStyle currentShape!.filled = CurrentTool.filled if CurrentTool.shapeType == ShapeType.stamp { currentShape!.stampFIle = CurrentTool.stampFile } do { if CurrentTool.shapeType == .line { try myRealm.write { RealmConnection.realm!.add(currentShape!) } } } catch { ErrorReporter.raiseError("Unable to add line segment") } swiped = false do { try myRealm.write { currentShape!.append(point: LinkedPoint(touch.location(in: tempImageView))) } } catch { ErrorReporter.raiseError("Unable to append the current point") } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { ErrorReporter.raiseError("Cannot find the first touch") return } guard let myRealm = RealmConnection.realm else { ErrorReporter.raiseError("Cannot access realm from RealmConnection") return } guard let currentShape = currentShape, !currentShape.isInvalidated else { return } // For any shape other than a freehand line, don't want the tempView // to also contain previous versions of the shape (as they replace // the in-progress shape rather than extending them) if CurrentTool.shapeType != .line { self.tempImageView.image = nil } let currentPoint = touch.location(in: tempImageView) draw { context in switch CurrentTool.shapeType { // if the shape is a line, simply append the current point to the head of the list case .line: do { try myRealm.write { currentShape.append(point: LinkedPoint(currentPoint)) } } catch { ErrorReporter.raiseError("Failed to append points on pen move") } // if the shape is a rect or an ellipse, replace the head of the list // with the dragged point. the LinkedPoint list should always contain // (x₁, y₁) and (x₂, y₂), the top left and and bottom right corners // of the rect case .straightLine: do { try myRealm.write { currentShape.lastPoint!.nextPoint = LinkedPoint(currentPoint) } } catch { ErrorReporter.raiseError("Failed to move straight line") } case .rect, .ellipse, .stamp, .text: do { try myRealm.write { currentShape.replaceHead(point: LinkedPoint(currentPoint)) } } catch { ErrorReporter.raiseError("Failed to move shape") } // if the shape is a triangle, have the original point be the tail // of the list, the 2nd point being where the current touch is, // and the 3rd point (x₁ - (x₂ - x₁), y₂) case .triangle: do { try RealmConnection.realm!.write { let point2 = LinkedPoint(currentPoint) currentShape.lastPoint?.nextPoint = point2 let point3 = LinkedPoint() point3.y = point2.y point3.x = currentShape.lastPoint!.x - (point2.x - currentShape.lastPoint!.x) point2.nextPoint = point3 } } catch { ErrorReporter.raiseError("Failed to move a triangle") } } currentShape.draw(context) } swiped = true lastPoint = currentPoint } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let myRealm = RealmConnection.realm else { ErrorReporter.raiseError("Cannot access realm from RealmConnection") return } if !swiped { // draw a single point draw { context in currentShape!.draw(context) } } switch CurrentTool.shapeType { case .text: // The bounding rectangle for the text has been created but the user // must now type in their text hiddenTextField.becomeFirstResponder() // The text shape will be stored and merged after the user hits return default: // if the shape is not a line, it exists in a draft state. // add it to the realm now if CurrentTool.shapeType != .line { do { try myRealm.write { RealmConnection.realm!.add(currentShape!) } } catch { ErrorReporter.raiseError("Touches ended but unable to add line") } } mergeViews() } } func clearDrawing() { guard let myRealm = RealmConnection.realm else { ErrorReporter.raiseError("Cannot access realm from RealmConnection") return } do { try myRealm.write { // Delete all of the Realm drawing objects myRealm.delete(RealmConnection.realm!.objects(LinkedPoint.self)) myRealm.delete(RealmConnection.realm!.objects(Shape.self)) } } catch { ErrorReporter.raiseError("Failed to clear drawing objects") } tempImageView.image = nil mainImageView.image = nil } // MARK: - DELEGATES func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { // Finished typing so store the new text shape hiddenTextField.text = "" hiddenTextField.resignFirstResponder() do { try RealmConnection.realm!.write { RealmConnection.realm!.add(currentShape!) } } catch { ErrorReporter.raiseError("Failed to store updated text") } mergeViews() return false } else { tempImageView.image = nil var newText = textField.text ?? "" newText += string self.draw { context in mainImageView.image = nil shapes!.forEach { $0.draw(context) } currentShape!.text = newText currentShape!.draw(context) } return true } } func textFieldDidBeginEditing(_ textField: UITextField) { print("Started editing") } // MARK: - ACTIONS @IBAction func straightLineTapped(_ sender: Any) { print("Stright line button tapped") clearSecondaryPopovers(except: nil) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } CurrentTool.shapeType = .straightLine } @IBAction func toolbarButtonTapped(_ sender: UIButton) { print("Main toolbar button tapped") if let button = sender as? DrawToolbarPersistedButton { self.drawToolbar.clearCurrentButtonSelection() button.select() } } @objc func scribblePopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary scribble toolbar tap") scribblePopoverToolbar.clearCurrentButtonSelection() } @objc func sansSerifPopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary sans serif toolbar tap") sansSerifPopoverToolbar.clearCurrentButtonSelection() CurrentTool.shapeType = .text } @objc func stampsPopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary stamps toolbar tap") stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.shapeType = .stamp } @objc func rectanglePopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary rectangle toolbar tap") rectanglePopoverToolbar.clearCurrentButtonSelection() } @objc func rectangleFilledTapped(sender: UIButton) { print("Secondary rectangle filled toolbar tap") rectanglePopoverToolbar.clearCurrentButtonSelection() rectanglePopoverToolbar.savedSelection = 0 rectangleButton.setImage(UIImage(named: "RectangleFilled.pdf"), for: .normal) CurrentTool.filled = true } @objc func rectangleEmptyTapped(sender: UIButton) { print("Secondary rectangle empty toolbar tap") rectanglePopoverToolbar.clearCurrentButtonSelection() rectanglePopoverToolbar.savedSelection = 1 rectangleButton.setImage(UIImage(named: "Rectangle.pdf"), for: .normal) CurrentTool.filled = false } @objc func ovalPopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary oval toolbar tap") ovalPopoverToolbar.clearCurrentButtonSelection() } @objc func ovalFilledTapped(sender: UIButton) { print("Secondary oval filled toolbar tap") ovalPopoverToolbar.clearCurrentButtonSelection() ovalPopoverToolbar.savedSelection = 0 ovalButton.setImage(UIImage(named: "OvalFilled.pdf"), for: .normal) CurrentTool.filled = true } @objc func ovalEmptyTapped(sender: UIButton) { print("Secondary oval empty toolbar tap") ovalPopoverToolbar.clearCurrentButtonSelection() ovalPopoverToolbar.savedSelection = 1 ovalButton.setImage(UIImage(named: "Oval.pdf"), for: .normal) CurrentTool.filled = false } @objc func trianglePopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary triangle toolbar tap") trianglePopoverToolbar.clearCurrentButtonSelection() } @objc func triangleFilledTapped(sender: UIButton) { print("Secondary triangle filled toolbar tap") trianglePopoverToolbar.clearCurrentButtonSelection() trianglePopoverToolbar.savedSelection = 0 triangleButton.setImage(UIImage(named: "TriangleFilled.pdf"), for: .normal) CurrentTool.filled = true } @objc func triangleEmptyTapped(sender: UIButton) { print("Secondary triangle empty toolbar tap") trianglePopoverToolbar.clearCurrentButtonSelection() trianglePopoverToolbar.savedSelection = 1 triangleButton.setImage(UIImage(named: "Triangle.pdf"), for: .normal) CurrentTool.filled = false } @objc func opacityPopoverTapHandler(gesture: UITapGestureRecognizer) { print("Secondary opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() } @objc func opacityBlackTapped(sender: UIButton) { print("Secondary Black opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() opacityPopoverToolbar.savedSelection = 0 opacityButton.setImage(UIImage(named: "shade100.pdf"), for: .normal) guard let pencil = Pencil(tag: 1) else { return } CurrentTool.color = pencil.color } @objc func opacityDarkestTapped(sender: UIButton) { print("Secondary Darkest Grey opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() opacityPopoverToolbar.savedSelection = 1 opacityButton.setImage(UIImage(named: "shade70.pdf"), for: .normal) guard let pencil = Pencil(tag: 2) else { return } CurrentTool.color = pencil.color } @objc func opacityMidTapped(sender: UIButton) { print("Secondary Mid Grey opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() opacityPopoverToolbar.savedSelection = 2 opacityButton.setImage(UIImage(named: "shade50.pdf"), for: .normal) guard let pencil = Pencil(tag: 3) else { return } CurrentTool.color = pencil.color } @objc func opacityLightestTapped(sender: UIButton) { print("Secondary Lightest Grey opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() opacityPopoverToolbar.savedSelection = 3 opacityButton.setImage(UIImage(named: "shade30.pdf"), for: .normal) guard let pencil = Pencil(tag: 4) else { return } CurrentTool.color = pencil.color } @objc func opacityEraserTapped(sender: UIButton) { print("Secondary Eraser opacity toolbar tap") opacityPopoverToolbar.clearCurrentButtonSelection() opacityPopoverToolbar.savedSelection = 4 opacityButton.setImage(UIImage(named: "shade0.pdf"), for: .normal) guard let pencil = Pencil(tag: 5) else { return } CurrentTool.color = pencil.color } @objc func secondaryToolbarButtonTapped(sender: DrawToolbarPersistedButton) { print("Secondary button tap") sender.select() clearSecondaryPopovers(except: nil) } // MARK: - PRIMARY TOOLBAR TAP HANDLDERS @IBAction func finishButtonTapped(_ sender: UIButton) { print("Finish button tapped") if Constants.ARTIST_MODE { let alert = UIAlertController(title: "Confirm you want to clear the drawing", message: "Please confirm if you want to clear the drawing", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes - clear the drawing", style: .default, handler: { action in self.clearDrawing() })) alert.addAction(UIAlertAction(title: "Clear drawing and log out", style: .default, handler: { action in self.clearDrawing() if let user = SyncUser.current { user.logOut() } let _ = self.navigationController?.popToRootViewController(animated: true) })) alert.addAction(UIAlertAction(title: "No – continue drawing", style: .cancel, handler:nil)) self.present(alert, animated: true) } else { guard let image = extractImage() else { ErrorReporter.raiseError("Failed to extract image") return } print("Drawing to be uploaded is \(image.count / 1000)kb") let storedImage = StoredImage(image: image) storedImage.userContact?.email = User.email do { try RealmConnection.realmAtlas!.write { RealmConnection.realmAtlas!.add(storedImage) User.imageToSend = storedImage } } catch { ErrorReporter.raiseError("Failed to persist the finished image") } let submitVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SubmitFormViewController") as? SubmitFormViewController submitVC?.drawing = mainImageView.image?.whiteMask() self.navigationController!.pushViewController(submitVC!, animated: true) } } @IBAction func undoButtonTapped(_ sender: UIButton) { print("Undo button tapped") guard shapes!.count > 0 else { return } draw { context in // find the last non-erased shape associated with this device Id. // then erase it, mark it as erased, and redraw the history of the drawing guard let shape = shapes!.last(where: { $0.deviceId == thisDevice }) else { return } do { try RealmConnection.realm!.write { RealmConnection.realm!.delete(shape) } } catch { ErrorReporter.raiseError("Unable to delete a shape") } shapes!.forEach { $0.draw(context) } } currentShape = nil } @IBAction func pencilButtonTapped(_ sender: UIButton) { print("Pencil button tapped") clearSecondaryPopovers(except: nil) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } CurrentTool.shapeType = .line } @IBAction func scribbleButtonTapped(_ sender: UIButton) { print("Scribble button tapped") clearSecondaryPopovers(except: [scribblePopoverParent]) if scribblePopoverParent.isDescendant(of: self.view) { return } scribblePopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(scribblePopoverParent) scribblePopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = scribblePopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = scribblePopoverParent.topAnchor.constraint(equalTo: scribbleButton.topAnchor, constant: 0) let widthConstraint = scribblePopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = scribblePopoverParent.heightAnchor.constraint(equalTo: scribbleButton.heightAnchor, multiplier: 3) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) scribblePopoverToolbar.axis = .vertical scribblePopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(scribblePopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false scribblePopoverToolbar.addGestureRecognizer(tapGesture) let scribbleLightImage = UIImage(named: "line_thin.pdf") let scribbleLightButton = DrawToolbarPersistedButton(image: scribbleLightImage!) scribbleLightButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) scribbleLightButton.addTarget(self, action: #selector(scribbleLightTapped(sender:)), for: .touchUpInside) scribbleLightButton.tintColor = .white let scribbleMediumImage = UIImage(named: "line_med.pdf") let scribbleMediumButton = DrawToolbarPersistedButton(image: scribbleMediumImage!) scribbleMediumButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) scribbleMediumButton.addTarget(self, action: #selector(scribbleMediumTapped(sender:)), for: .touchUpInside) scribbleMediumButton.tintColor = .white let scribbleHeavyImage = UIImage(named: "line_fat.pdf") let scribbleHeavyButton = DrawToolbarPersistedButton(image: scribbleHeavyImage!) scribbleHeavyButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) scribbleHeavyButton.addTarget(self, action: #selector(scribbleHeavyTapped(sender:)), for: .touchUpInside) scribbleHeavyButton.tintColor = .white scribblePopoverToolbar.addArrangedSubview(scribbleLightButton) scribblePopoverToolbar.addArrangedSubview(scribbleMediumButton) scribblePopoverToolbar.addArrangedSubview(scribbleHeavyButton) scribblePopoverParent.addSubview(scribblePopoverToolbar) scribblePopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = scribblePopoverToolbar.leadingAnchor.constraint(equalTo: scribblePopoverParent.leadingAnchor) let top = scribblePopoverToolbar.topAnchor.constraint(equalTo: scribblePopoverParent.topAnchor) let trailing = scribblePopoverToolbar.trailingAnchor.constraint(equalTo: scribblePopoverParent.trailingAnchor) let bottom = scribblePopoverToolbar.bottomAnchor.constraint(equalTo: scribblePopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = scribblePopoverToolbar.arrangedSubviews[scribblePopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } } @IBAction func eraserButtonTapped(_ sender: UIButton) { print("Eraser button tapped") clearSecondaryPopovers(except: nil) print("previous color: \(CurrentTool.previousColor)") if !CurrentTool.erasing { CurrentTool.previousColor = CurrentTool.color } CurrentTool.color = .white CurrentTool.erasing = true CurrentTool.shapeType = .line } @IBAction func textboxButtonTapped(_ sender: UIButton) { print("Textbox button tapped") if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } CurrentTool.shapeType = .text } @IBAction func sansSerifButtonTapped(_ sender: UIButton) { if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } print("Sans Serif button tapped") clearSecondaryPopovers(except: [sansSerifPopoverParent]) if sansSerifPopoverParent.isDescendant(of: self.view) { return } CurrentTool.shapeType = .text sansSerifPopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(sansSerifPopoverParent) sansSerifPopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = sansSerifPopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = sansSerifPopoverParent.topAnchor.constraint(equalTo: sansSerifButton.topAnchor, constant: 0) let widthConstraint = sansSerifPopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = sansSerifPopoverParent.heightAnchor.constraint(equalTo: sansSerifButton.heightAnchor, multiplier: 4) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) sansSerifPopoverToolbar.axis = .vertical sansSerifPopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(sansSerifPopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false sansSerifPopoverToolbar.addGestureRecognizer(tapGesture) let sansSerifNormalImage = UIImage(named: "helveticaFont.pdf") let sansSerifNormalButton = DrawToolbarPersistedButton(image: sansSerifNormalImage!) sansSerifNormalButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) sansSerifNormalButton.addTarget(self, action: #selector(sansSerifNormalTapped(sender:)), for: .touchUpInside) sansSerifNormalButton.tintColor = .white let sansSerifSerifImage = UIImage(named: "fontBradley.pdf") let sansSerifSerifButton = DrawToolbarPersistedButton(image: sansSerifSerifImage!) sansSerifSerifButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) sansSerifSerifButton.addTarget(self, action: #selector(sansSerifSerifTapped(sender:)), for: .touchUpInside) sansSerifSerifButton.tintColor = .white let sansSerifHandImage = UIImage(named: "fontDin.pdf") let sansSeriHandfButton = DrawToolbarPersistedButton(image: sansSerifHandImage!) sansSeriHandfButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) sansSeriHandfButton.addTarget(self, action: #selector(sansSerifHandTapped(sender:)), for: .touchUpInside) sansSeriHandfButton.tintColor = .white let sansSerifMonoImage = UIImage(named: "fontMarker.podf") let sansSerifMonoButton = DrawToolbarPersistedButton(image: sansSerifMonoImage!) sansSerifMonoButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) sansSerifMonoButton.addTarget(self, action: #selector(sansSerifMonoTapped(sender:)), for: .touchUpInside) sansSerifMonoButton.tintColor = .white sansSerifPopoverToolbar.addArrangedSubview(sansSerifNormalButton) sansSerifPopoverToolbar.addArrangedSubview(sansSerifSerifButton) sansSerifPopoverToolbar.addArrangedSubview(sansSeriHandfButton) sansSerifPopoverToolbar.addArrangedSubview(sansSerifMonoButton) sansSerifPopoverParent.addSubview(sansSerifPopoverToolbar) sansSerifPopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = sansSerifPopoverToolbar.leadingAnchor.constraint(equalTo: sansSerifPopoverParent.leadingAnchor) let top = sansSerifPopoverToolbar.topAnchor.constraint(equalTo: sansSerifPopoverParent.topAnchor) let trailing = sansSerifPopoverToolbar.trailingAnchor.constraint(equalTo: sansSerifPopoverParent.trailingAnchor) let bottom = sansSerifPopoverToolbar.bottomAnchor.constraint(equalTo: sansSerifPopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = sansSerifPopoverToolbar.arrangedSubviews[sansSerifPopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } } @objc func sansSerifNormalTapped(sender: UIButton) { print("Secondary Text normal toolbar tap") sansSerifPopoverToolbar.savedSelection = 0 sansSerifPopoverToolbar.clearCurrentButtonSelection() CurrentTool.fontStyle = .normal clearSecondaryPopovers(except: nil) } @objc func sansSerifSerifTapped(sender: UIButton) { print("Secondary Text serif toolbar tap") sansSerifPopoverToolbar.savedSelection = 1 sansSerifPopoverToolbar.clearCurrentButtonSelection() CurrentTool.fontStyle = .serif clearSecondaryPopovers(except: nil) } @objc func sansSerifHandTapped(sender: UIButton) { print("Secondary Text hand toolbar tap") sansSerifPopoverToolbar.savedSelection = 2 sansSerifPopoverToolbar.clearCurrentButtonSelection() CurrentTool.fontStyle = .hand clearSecondaryPopovers(except: nil) } @objc func sansSerifMonoTapped(sender: UIButton) { print("Secondary Text mono toolbar tap") sansSerifPopoverToolbar.savedSelection = 3 sansSerifPopoverToolbar.clearCurrentButtonSelection() CurrentTool.fontStyle = .monospace clearSecondaryPopovers(except: nil) } @IBAction func stampsButtonTapped(_ sender: UIButton) { print("Stamps button tapped") clearSecondaryPopovers(except: [stampsPopoverParent]) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor } if stampsPopoverParent.isDescendant(of: self.view) { return } stampsPopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(stampsPopoverParent) stampsPopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = stampsPopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = stampsPopoverParent.topAnchor.constraint(equalTo: leftToolbarParent.topAnchor, constant: 0) let widthConstraint = stampsPopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let bottomConstraint = stampsPopoverParent.bottomAnchor.constraint(equalTo: leftToolbarParent.bottomAnchor, constant: 0) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, bottomConstraint]) stampsPopoverToolbar.axis = .vertical stampsPopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(stampsPopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false stampsPopoverToolbar.addGestureRecognizer(tapGesture) let owlImage = UIImage(named: "owl.pdf") let owlButton = DrawToolbarPersistedButton(image: owlImage!) owlButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) owlButton.addTarget(self, action: #selector(stampOwlTapped(sender:)), for: .touchUpInside) owlButton.tintColor = .white let planetImage = UIImage(named: "planet.pdf") let planetButton = DrawToolbarPersistedButton(image: planetImage!) planetButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) planetButton.addTarget(self, action: #selector(stampPlanetTapped(sender:)), for: .touchUpInside) planetButton.tintColor = .white let eyeImage = UIImage(named: "eye.pdf") let eyeButton = DrawToolbarPersistedButton(image: eyeImage!) eyeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) eyeButton.addTarget(self, action: #selector(stampEyeTapped(sender:)), for: .touchUpInside) eyeButton.tintColor = .white let arrowsImage = UIImage(named: "arrows.pdf") let arrowsButton = DrawToolbarPersistedButton(image: arrowsImage!) arrowsButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) arrowsButton.addTarget(self, action: #selector(stampArrowsTapped(sender:)), for: .touchUpInside) arrowsButton.tintColor = .white let leafImage = UIImage(named: "leaf_outline.pdf") let leafButton = DrawToolbarPersistedButton(image: leafImage!) leafButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) leafButton.addTarget(self, action: #selector(stampLeafTapped(sender:)), for: .touchUpInside) leafButton.tintColor = .white let databaseImage = UIImage(named: "database.pdf") let databaseButton = DrawToolbarPersistedButton(image: databaseImage!) databaseButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) databaseButton.addTarget(self, action: #selector(stampDatabaseTapped(sender:)), for: .touchUpInside) databaseButton.tintColor = .white let serverImage = UIImage(named: "server.pdf") let serverButton = DrawToolbarPersistedButton(image: serverImage!) serverButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) serverButton.addTarget(self, action: #selector(stampServerTapped(sender:)), for: .touchUpInside) serverButton.tintColor = .white let anchorImage = UIImage(named: "anchor.pdf") let anchorButton = DrawToolbarPersistedButton(image: anchorImage!) anchorButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) anchorButton.addTarget(self, action: #selector(stampAnchorTapped(sender:)), for: .touchUpInside) anchorButton.tintColor = .white let planet2Image = UIImage(named: "planet2.pdf") let planet2Button = DrawToolbarPersistedButton(image: planet2Image!) planet2Button.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) planet2Button.addTarget(self, action: #selector(stampPlanet2Tapped(sender:)), for: .touchUpInside) planet2Button.tintColor = .white let beachImage = UIImage(named: "beach.pdf") let beachButton = DrawToolbarPersistedButton(image: beachImage!) beachButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) beachButton.addTarget(self, action: #selector(stampBeachTapped(sender:)), for: .touchUpInside) beachButton.tintColor = .white let swordsImage = UIImage(named: "swords.pdf") let swordsButton = DrawToolbarPersistedButton(image: swordsImage!) swordsButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) swordsButton.addTarget(self, action: #selector(stampSwordsTapped(sender:)), for: .touchUpInside) swordsButton.tintColor = .white let diamondImage = UIImage(named: "diamond.pdf") let diamondButton = DrawToolbarPersistedButton(image: diamondImage!) diamondButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) diamondButton.addTarget(self, action: #selector(stampDiamondTapped(sender:)), for: .touchUpInside) diamondButton.tintColor = .white stampsPopoverToolbar.addArrangedSubview(owlButton) stampsPopoverToolbar.addArrangedSubview(planetButton) stampsPopoverToolbar.addArrangedSubview(eyeButton) stampsPopoverToolbar.addArrangedSubview(arrowsButton) stampsPopoverToolbar.addArrangedSubview(leafButton) stampsPopoverToolbar.addArrangedSubview(databaseButton) stampsPopoverToolbar.addArrangedSubview(serverButton) stampsPopoverToolbar.addArrangedSubview(anchorButton) stampsPopoverToolbar.addArrangedSubview(planet2Button) stampsPopoverToolbar.addArrangedSubview(beachButton) stampsPopoverToolbar.addArrangedSubview(swordsButton) stampsPopoverToolbar.addArrangedSubview(diamondButton) stampsPopoverParent.addSubview(stampsPopoverToolbar) stampsPopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = stampsPopoverToolbar.leadingAnchor.constraint(equalTo: stampsPopoverParent.leadingAnchor) let top = stampsPopoverToolbar.topAnchor.constraint(equalTo: stampsPopoverParent.topAnchor) let trailing = stampsPopoverToolbar.trailingAnchor.constraint(equalTo: stampsPopoverParent.trailingAnchor) let bottom = stampsPopoverToolbar.bottomAnchor.constraint(equalTo: stampsPopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = stampsPopoverToolbar.arrangedSubviews[stampsPopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } } @objc func stampOwlTapped(sender: UIButton) { print("Secondary stamp owl toolbar tap") stampsPopoverToolbar.savedSelection = 0 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_owl.png" stampButton.setImage(UIImage(named: "owl.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampPlanetTapped(sender: UIButton) { print("Secondary stamp planet toolbar tap") stampsPopoverToolbar.savedSelection = 1 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_planet.png" stampButton.setImage(UIImage(named: "planet.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampEyeTapped(sender: UIButton) { print("Secondary stamp eye toolbar tap") stampsPopoverToolbar.savedSelection = 2 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_eye.png" stampButton.setImage(UIImage(named: "eye.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampArrowsTapped(sender: UIButton) { print("Secondary stamp arrows toolbar tap") stampsPopoverToolbar.savedSelection = 3 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_arrows.png" stampButton.setImage(UIImage(named: "arrows.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampLeafTapped(sender: UIButton) { print("Secondary stamp leaf toolbar tap") stampsPopoverToolbar.savedSelection = 4 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_leaf_outline.png" stampButton.setImage(UIImage(named: "leaf_outline.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampDatabaseTapped(sender: UIButton) { print("Secondary stamp database toolbar tap") stampsPopoverToolbar.savedSelection = 5 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_database.png" stampButton.setImage(UIImage(named: "database.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampServerTapped(sender: UIButton) { print("Secondary stamp server toolbar tap") stampsPopoverToolbar.savedSelection = 6 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_server.png" stampButton.setImage(UIImage(named: "server.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampAnchorTapped(sender: UIButton) { print("Secondary stamp anchor toolbar tap") stampsPopoverToolbar.savedSelection = 7 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_anchor.png" stampButton.setImage(UIImage(named: "anchor.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampPlanet2Tapped(sender: UIButton) { print("Secondary stamp planet2 toolbar tap") stampsPopoverToolbar.savedSelection = 8 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_planet2.png" stampButton.setImage(UIImage(named: "planet2.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampBeachTapped(sender: UIButton) { print("Secondary stamp beach toolbar tap") stampsPopoverToolbar.savedSelection = 9 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_beach.png" stampButton.setImage(UIImage(named: "beach.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampSwordsTapped(sender: UIButton) { print("Secondary stamp swords toolbar tap") stampsPopoverToolbar.savedSelection = 10 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_swords.png" stampButton.setImage(UIImage(named: "swords.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @objc func stampDiamondTapped(sender: UIButton) { print("Secondary stamp diamond toolbar tap") stampsPopoverToolbar.savedSelection = 11 stampsPopoverToolbar.clearCurrentButtonSelection() CurrentTool.stampFile = "stamp_diamond.png" stampButton.setImage(UIImage(named: "diamond.pdf"), for: .normal) clearSecondaryPopovers(except: nil) } @IBAction func opacityButtonTapped(_ sender: UIButton) { print("Opacity button tapped") if CurrentTool.erasing { print("Opacity menu disabled while erasing") return } clearSecondaryPopovers(except: [opacityPopoverParent]) if opacityPopoverParent.isDescendant(of: self.view) { return } opacityPopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(opacityPopoverParent) opacityPopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = opacityPopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = opacityPopoverParent.topAnchor.constraint(equalTo: opacityButton.topAnchor, constant: 0) let widthConstraint = opacityPopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = opacityPopoverParent.heightAnchor.constraint(equalTo: opacityButton.heightAnchor, multiplier: 5) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) opacityPopoverToolbar.axis = .vertical opacityPopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(opacityPopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false opacityPopoverToolbar.addGestureRecognizer(tapGesture) let blackShadeImage = UIImage(named: "shade100.pdf") let blackShadeButton = DrawToolbarPersistedButton(image: blackShadeImage!) blackShadeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) blackShadeButton.addTarget(self, action: #selector(opacityBlackTapped(sender:)), for: .touchUpInside) blackShadeButton.tintColor = .white let darkestShadeImage = UIImage(named: "shade70.pdf") let darkestShadeButton = DrawToolbarPersistedButton(image: darkestShadeImage!) darkestShadeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) darkestShadeButton.addTarget(self, action: #selector(opacityDarkestTapped(sender:)), for: .touchUpInside) darkestShadeButton.tintColor = .white let midShadeImage = UIImage(named: "shade50.pdf") let midShadeButton = DrawToolbarPersistedButton(image: midShadeImage!) midShadeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) midShadeButton.addTarget(self, action: #selector(opacityMidTapped(sender:)), for: .touchUpInside) midShadeButton.tintColor = .white let lightestShadeImage = UIImage(named: "shade30.pdf") let lightestShadeButton = DrawToolbarPersistedButton(image: lightestShadeImage!) lightestShadeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) lightestShadeButton.addTarget(self, action: #selector(opacityLightestTapped(sender:)), for: .touchUpInside) lightestShadeButton.tintColor = .white let eraserShadeImage = UIImage(named: "shade0.pdf") let eraserShadeButton = DrawToolbarPersistedButton(image: eraserShadeImage!) eraserShadeButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) eraserShadeButton.addTarget(self, action: #selector(opacityEraserTapped(sender:)), for: .touchUpInside) eraserShadeButton.tintColor = .white opacityPopoverToolbar.addArrangedSubview(blackShadeButton) opacityPopoverToolbar.addArrangedSubview(darkestShadeButton) opacityPopoverToolbar.addArrangedSubview(midShadeButton) opacityPopoverToolbar.addArrangedSubview(lightestShadeButton) opacityPopoverToolbar.addArrangedSubview(eraserShadeButton) opacityPopoverParent.addSubview(opacityPopoverToolbar) opacityPopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = opacityPopoverToolbar.leadingAnchor.constraint(equalTo: opacityPopoverParent.leadingAnchor) let top = opacityPopoverToolbar.topAnchor.constraint(equalTo: opacityPopoverParent.topAnchor) let trailing = opacityPopoverToolbar.trailingAnchor.constraint(equalTo: opacityPopoverParent.trailingAnchor) let bottom = opacityPopoverToolbar.bottomAnchor.constraint(equalTo: opacityPopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = opacityPopoverToolbar.arrangedSubviews[opacityPopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } } @IBAction func squareButtonTapped(_ sender: UIButton) { print("Square button tapped") clearSecondaryPopovers(except: [rectanglePopoverParent]) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } if rectanglePopoverParent.isDescendant(of: self.view) { return } rectanglePopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(rectanglePopoverParent) rectanglePopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = rectanglePopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = rectanglePopoverParent.topAnchor.constraint(equalTo: rectangleButton.topAnchor, constant: 0) let widthConstraint = rectanglePopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = rectanglePopoverParent.heightAnchor.constraint(equalTo: rectangleButton.heightAnchor, multiplier: 2) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) rectanglePopoverToolbar.axis = .vertical rectanglePopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(rectanglePopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false rectanglePopoverToolbar.addGestureRecognizer(tapGesture) let rectangleFilledImage = UIImage(named: "RectangleFilled.pdf") let rectangleFilledButton = DrawToolbarPersistedButton(image: rectangleFilledImage!) rectangleFilledButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) rectangleFilledButton.addTarget(self, action: #selector(rectangleFilledTapped(sender:)), for: .touchUpInside) rectangleFilledButton.tintColor = .white let rectangleImage = UIImage(named: "Rectangle.pdf") let rectangleButton = DrawToolbarPersistedButton(image: rectangleImage!) rectangleButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) rectangleButton.addTarget(self, action: #selector(rectangleEmptyTapped(sender:)), for: .touchUpInside) rectangleButton.tintColor = .white rectanglePopoverToolbar.addArrangedSubview(rectangleFilledButton) rectanglePopoverToolbar.addArrangedSubview(rectangleButton) rectanglePopoverParent.addSubview(rectanglePopoverToolbar) rectanglePopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = rectanglePopoverToolbar.leadingAnchor.constraint(equalTo: rectanglePopoverParent.leadingAnchor) let top = rectanglePopoverToolbar.topAnchor.constraint(equalTo: rectanglePopoverParent.topAnchor) let trailing = rectanglePopoverToolbar.trailingAnchor.constraint(equalTo: rectanglePopoverParent.trailingAnchor) let bottom = rectanglePopoverToolbar.bottomAnchor.constraint(equalTo: rectanglePopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = rectanglePopoverToolbar.arrangedSubviews[rectanglePopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } CurrentTool.shapeType = .rect } @IBAction func circleButtonTapped(_ sender: UIButton) { print("Circle button tapped") clearSecondaryPopovers(except: [ovalPopoverParent]) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } if ovalPopoverParent.isDescendant(of: self.view) { return } ovalPopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(ovalPopoverParent) ovalPopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = ovalPopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = ovalPopoverParent.topAnchor.constraint(equalTo: ovalButton.topAnchor, constant: 0) let widthConstraint = ovalPopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = ovalPopoverParent.heightAnchor.constraint(equalTo: ovalButton.heightAnchor, multiplier: 2) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) ovalPopoverToolbar.axis = .vertical ovalPopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ovalPopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false ovalPopoverToolbar.addGestureRecognizer(tapGesture) let ovalFilledImage = UIImage(named: "OvalFilled.pdf") let ovalFilledButton = DrawToolbarPersistedButton(image: ovalFilledImage!) ovalFilledButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) ovalFilledButton.addTarget(self, action: #selector(ovalFilledTapped(sender:)), for: .touchUpInside) ovalFilledButton.tintColor = .white let ovalImage = UIImage(named: "Oval.pdf") let ovalButton = DrawToolbarPersistedButton(image: ovalImage!) ovalButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) ovalButton.addTarget(self, action: #selector(ovalEmptyTapped(sender:)), for: .touchUpInside) ovalButton.tintColor = .white ovalPopoverToolbar.addArrangedSubview(ovalFilledButton) ovalPopoverToolbar.addArrangedSubview(ovalButton) ovalPopoverParent.addSubview(ovalPopoverToolbar) ovalPopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = ovalPopoverToolbar.leadingAnchor.constraint(equalTo: ovalPopoverParent.leadingAnchor) let top = ovalPopoverToolbar.topAnchor.constraint(equalTo: ovalPopoverParent.topAnchor) let trailing = ovalPopoverToolbar.trailingAnchor.constraint(equalTo: ovalPopoverParent.trailingAnchor) let bottom = ovalPopoverToolbar.bottomAnchor.constraint(equalTo: ovalPopoverParent.bottomAnchor) NSLayoutConstraint.activate([leading, top, trailing, bottom]) if let selectedButton = ovalPopoverToolbar.arrangedSubviews[ovalPopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } CurrentTool.shapeType = .ellipse } @IBAction func triangleButtonTapped(_ sender: UIButton) { print("Triangle button tapped") clearSecondaryPopovers(except: [trianglePopoverParent]) if CurrentTool.erasing { CurrentTool.color = CurrentTool.previousColor CurrentTool.erasing = false } if trianglePopoverParent.isDescendant(of: self.view) { return } trianglePopoverParent.backgroundColor = UIColor(red: 48/255, green: 52/255, blue: 52/255, alpha: 1) self.view.addSubview(trianglePopoverParent) trianglePopoverParent.translatesAutoresizingMaskIntoConstraints = false let leadingConstraint = trianglePopoverParent.leadingAnchor.constraint(equalTo: leftToolbarParent.trailingAnchor, constant: 2) let topConstraint = trianglePopoverParent.topAnchor.constraint(equalTo: triangleButton.topAnchor, constant: 0) let widthConstraint = trianglePopoverParent.widthAnchor.constraint(equalTo: leftToolbarParent.widthAnchor, constant: 0) let heightConstraint = trianglePopoverParent.heightAnchor.constraint(equalTo: triangleButton.heightAnchor, multiplier: 2) NSLayoutConstraint.activate([leadingConstraint, topConstraint, widthConstraint, heightConstraint]) trianglePopoverToolbar.axis = .vertical trianglePopoverToolbar.distribution = .fillEqually let tapGesture = UITapGestureRecognizer(target: self, action: #selector(trianglePopoverTapHandler(gesture:))) tapGesture.cancelsTouchesInView = false trianglePopoverToolbar.addGestureRecognizer(tapGesture) let triangleFilledImage = UIImage(named: "TriangleFilled.pdf") let triangleFilledButton = DrawToolbarPersistedButton(image: triangleFilledImage!) triangleFilledButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) triangleFilledButton.addTarget(self, action: #selector(triangleFilledTapped(sender:)), for: .touchUpInside) triangleFilledButton.tintColor = .white let triangleImage = UIImage(named: "Triangle.pdf") let triangleButton = DrawToolbarPersistedButton(image: triangleImage!) triangleButton.addTarget(self, action: #selector(secondaryToolbarButtonTapped(sender:)), for: .touchUpInside) triangleButton.addTarget(self, action: #selector(triangleEmptyTapped(sender:)), for: .touchUpInside) triangleButton.tintColor = .white trianglePopoverToolbar.addArrangedSubview(triangleFilledButton) trianglePopoverToolbar.addArrangedSubview(triangleButton) trianglePopoverParent.addSubview(trianglePopoverToolbar) trianglePopoverToolbar.translatesAutoresizingMaskIntoConstraints = false let leading = trianglePopoverToolbar.leadingAnchor.constraint(equalTo: trianglePopoverParent.leadingAnchor) let top = trianglePopoverToolbar.topAnchor.constraint(equalTo: trianglePopoverParent.topAnchor) let trailing = trianglePopoverToolbar.trailingAnchor.constraint(equalTo: trianglePopoverParent.trailingAnchor) let bottom = trianglePopoverToolbar.bottomAnchor.constraint(equalTo: drawToolbar.bottomAnchor) NSLayoutConstraint.activate([leading, trailing, top, bottom]) if let selectedButton = trianglePopoverToolbar.arrangedSubviews[trianglePopoverToolbar.savedSelection] as? DrawToolbarPersistedButton { selectedButton.select() } CurrentTool.shapeType = .triangle } // MARK: - SECONDARY TOOLBAR TAP HANDLDERS @objc func scribbleLightTapped(sender: UIButton) { print("Scribble light tapped") scribblePopoverToolbar.savedSelection = 0 scribbleButton.setImage(UIImage(named: "line_thin.pdf"), for: .normal) CurrentTool.setWidth(width: Constants.DRAW_PEN_WIDTH_THIN) clearSecondaryPopovers(except: nil) } @objc func scribbleMediumTapped(sender: UIButton) { print("Scribble medium tapped") scribblePopoverToolbar.savedSelection = 1 scribbleButton.setImage(UIImage(named: "line_med.pdf"), for: .normal) CurrentTool.setWidth(width: Constants.DRAW_PEN_WIDTH_MEDIUM) clearSecondaryPopovers(except: nil) } @objc func scribbleHeavyTapped(sender: UIButton) { print("Scribble heavy tapped") scribblePopoverToolbar.savedSelection = 2 scribbleButton.setImage(UIImage(named: "line_fat.pdf"), for: .normal) CurrentTool.setWidth(width: Constants.DRAW_PEN_WIDTH_WIDE) clearSecondaryPopovers(except: nil) } // MARK: - UTIL private func clearSecondaryPopovers(except: [UIView]?) { for view in popoverParents { if except != nil { if except!.contains(view) { continue } } view.removeFromSuperview() view.subviews.forEach { subview in if let subStackView = subview as? UIStackView { subStackView.safelyRemoveArrangedSubviews() } subview.removeFromSuperview() } } } }
45.974026
179
0.746144
f5d74e1566964dfda68b9e879311ab81beebacc0
1,101
// // UIViewControllerExtensions.swift // UIKitTheme // // Created by Brian Strobach on 12/7/18. // Copyright © 2018 Brian Strobach. All rights reserved. // import UIKit extension UIViewController { @discardableResult public func setupNavigationBarTitleLabel(text: String = "", inset: UIEdgeInsets? = nil, style: TextStyle = NavigationBarStyle.default.titleTextStyle, maxNumberOfLines: Int = 1) -> UILabel? { if let navBar = navigationController?.navigationBar { let frame = navBar.bounds.insetBy(dx: navBar.frame.w/6.0, dy: navBar.frame.h/5.0) let titleLabel = UILabel(frame: frame, text: text) titleLabel.apply(textStyle: style) titleLabel.adjustsFontSizeToFitWidth = true titleLabel.numberOfLines = maxNumberOfLines titleLabel.textAlignment = .center navigationItem.titleView = titleLabel return titleLabel } return nil } }
35.516129
106
0.589464
7105c6f68407b048eb8d9215d90193f362855770
8,813
// // TimelineCellLayout.swift // NetNewsWire // // Created by Brent Simmons on 2/6/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import AppKit import RSCore struct TimelineCellLayout { let width: CGFloat let height: CGFloat let feedNameRect: NSRect let dateRect: NSRect let titleRect: NSRect let numberOfLinesForTitle: Int let summaryRect: NSRect let textRect: NSRect let unreadIndicatorRect: NSRect let starRect: NSRect let iconImageRect: NSRect let separatorRect: NSRect let paddingBottom: CGFloat init(width: CGFloat, height: CGFloat, feedNameRect: NSRect, dateRect: NSRect, titleRect: NSRect, numberOfLinesForTitle: Int, summaryRect: NSRect, textRect: NSRect, unreadIndicatorRect: NSRect, starRect: NSRect, iconImageRect: NSRect, separatorRect: NSRect, paddingBottom: CGFloat) { self.width = width self.feedNameRect = feedNameRect self.dateRect = dateRect self.titleRect = titleRect self.numberOfLinesForTitle = numberOfLinesForTitle self.summaryRect = summaryRect self.textRect = textRect self.unreadIndicatorRect = unreadIndicatorRect self.starRect = starRect self.iconImageRect = iconImageRect self.separatorRect = separatorRect self.paddingBottom = paddingBottom if height > 0.1 { self.height = height } else { self.height = [feedNameRect, dateRect, titleRect, summaryRect, textRect, unreadIndicatorRect, iconImageRect].maxY() + paddingBottom } } init(width: CGFloat, height: CGFloat, cellData: TimelineCellData, appearance: TimelineCellAppearance, hasIcon: Bool) { // If height == 0.0, then height is calculated. let showIcon = cellData.showIcon var textBoxRect = TimelineCellLayout.rectForTextBox(appearance, cellData, showIcon, width) let (titleRect, numberOfLinesForTitle) = TimelineCellLayout.rectForTitle(textBoxRect, appearance, cellData) let summaryRect = numberOfLinesForTitle > 0 ? TimelineCellLayout.rectForSummary(textBoxRect, titleRect, numberOfLinesForTitle, appearance, cellData) : NSRect.zero let textRect = numberOfLinesForTitle > 0 ? NSRect.zero : TimelineCellLayout.rectForText(textBoxRect, appearance, cellData) var lastTextRect = titleRect if numberOfLinesForTitle == 0 { lastTextRect = textRect } else if numberOfLinesForTitle == 1 { if summaryRect.height > 0.1 { lastTextRect = summaryRect } } let dateRect = TimelineCellLayout.rectForDate(textBoxRect, lastTextRect, appearance, cellData) let feedNameRect = TimelineCellLayout.rectForFeedName(textBoxRect, dateRect, appearance, cellData) textBoxRect.size.height = ceil([titleRect, summaryRect, textRect, dateRect, feedNameRect].maxY() - textBoxRect.origin.y) let iconImageRect = TimelineCellLayout.rectForIcon(cellData, appearance, showIcon, textBoxRect, width, height) let unreadIndicatorRect = TimelineCellLayout.rectForUnreadIndicator(appearance, textBoxRect) let starRect = TimelineCellLayout.rectForStar(appearance, unreadIndicatorRect) let separatorRect = TimelineCellLayout.rectForSeparator(cellData, appearance, showIcon ? iconImageRect : titleRect, width, height) let paddingBottom = appearance.cellPadding.bottom self.init(width: width, height: height, feedNameRect: feedNameRect, dateRect: dateRect, titleRect: titleRect, numberOfLinesForTitle: numberOfLinesForTitle, summaryRect: summaryRect, textRect: textRect, unreadIndicatorRect: unreadIndicatorRect, starRect: starRect, iconImageRect: iconImageRect, separatorRect: separatorRect, paddingBottom: paddingBottom) } static func height(for width: CGFloat, cellData: TimelineCellData, appearance: TimelineCellAppearance) -> CGFloat { let layout = TimelineCellLayout(width: width, height: 0.0, cellData: cellData, appearance: appearance, hasIcon: true) return layout.height } } // MARK: - Calculate Rects private extension TimelineCellLayout { static func rectForTextBox(_ appearance: TimelineCellAppearance, _ cellData: TimelineCellData, _ showIcon: Bool, _ width: CGFloat) -> NSRect { // Returned height is a placeholder. Not needed when this is calculated. let iconSpace = showIcon ? appearance.iconSize.width + appearance.iconMarginRight : 0.0 let textBoxOriginX = appearance.cellPadding.left + appearance.unreadCircleDimension + appearance.unreadCircleMarginRight + iconSpace let textBoxMaxX = floor(width - appearance.cellPadding.right) let textBoxWidth = floor(textBoxMaxX - textBoxOriginX) let textBoxRect = NSRect(x: textBoxOriginX, y: appearance.cellPadding.top, width: textBoxWidth, height: 1000000) return textBoxRect } static func rectForTitle(_ textBoxRect: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> (NSRect, Int) { var r = textBoxRect if cellData.title.isEmpty { r.size.height = 0 return (r, 0) } let sizeInfo = MultilineTextFieldSizer.size(for: cellData.title, font: appearance.titleFont, numberOfLines: appearance.titleNumberOfLines, width: Int(textBoxRect.width)) r.size.height = sizeInfo.size.height if sizeInfo.numberOfLinesUsed < 1 { r.size.height = 0 } return (r, sizeInfo.numberOfLinesUsed) } static func rectForSummary(_ textBoxRect: NSRect, _ titleRect: NSRect, _ titleNumberOfLines: Int, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { if titleNumberOfLines >= appearance.titleNumberOfLines || cellData.text.isEmpty { return NSRect.zero } return rectOfLineBelow(titleRect, titleRect, 0, cellData.text, appearance.textFont) } static func rectForText(_ textBoxRect: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { var r = textBoxRect if cellData.text.isEmpty { r.size.height = 0 return r } let sizeInfo = MultilineTextFieldSizer.size(for: cellData.text, font: appearance.textOnlyFont, numberOfLines: appearance.titleNumberOfLines, width: Int(textBoxRect.width)) r.size.height = sizeInfo.size.height if sizeInfo.numberOfLinesUsed < 1 { r.size.height = 0 } return r } static func rectForDate(_ textBoxRect: NSRect, _ rectAbove: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { return rectOfLineBelow(textBoxRect, rectAbove, appearance.titleBottomMargin, cellData.dateString, appearance.dateFont) } static func rectForFeedName(_ textBoxRect: NSRect, _ dateRect: NSRect, _ appearance: TimelineCellAppearance, _ cellData: TimelineCellData) -> NSRect { if !cellData.showFeedName { return NSZeroRect } return rectOfLineBelow(textBoxRect, dateRect, appearance.dateMarginBottom, cellData.feedName, appearance.feedNameFont) } static func rectOfLineBelow(_ textBoxRect: NSRect, _ rectAbove: NSRect, _ topMargin: CGFloat, _ value: String, _ font: NSFont) -> NSRect { let textFieldSize = SingleLineTextFieldSizer.size(for: value, font: font) var r = NSZeroRect r.size = textFieldSize r.origin.y = NSMaxY(rectAbove) + topMargin r.origin.x = textBoxRect.origin.x var width = textFieldSize.width width = min(width, textBoxRect.size.width) width = max(width, 0.0) r.size.width = width return r } static func rectForUnreadIndicator(_ appearance: TimelineCellAppearance, _ titleRect: NSRect) -> NSRect { var r = NSZeroRect r.size = NSSize(width: appearance.unreadCircleDimension, height: appearance.unreadCircleDimension) r.origin.x = appearance.cellPadding.left r.origin.y = titleRect.minY + 6 // r = RSRectCenteredVerticallyInRect(r, titleRect) // r.origin.y += 1 return r } static func rectForStar(_ appearance: TimelineCellAppearance, _ unreadIndicatorRect: NSRect) -> NSRect { var r = NSRect.zero r.size.width = appearance.starDimension r.size.height = appearance.starDimension r.origin.x = floor(unreadIndicatorRect.origin.x - ((appearance.starDimension - appearance.unreadCircleDimension) / 2.0)) r.origin.y = unreadIndicatorRect.origin.y - 4.0 return r } static func rectForIcon(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ showIcon: Bool, _ textBoxRect: NSRect, _ width: CGFloat, _ height: CGFloat) -> NSRect { var r = NSRect.zero if !showIcon { return r } r.size = appearance.iconSize r.origin.x = appearance.cellPadding.left + appearance.unreadCircleDimension + appearance.unreadCircleMarginRight r.origin.y = textBoxRect.origin.y + appearance.iconAdjustmentTop return r } static func rectForSeparator(_ cellData: TimelineCellData, _ appearance: TimelineCellAppearance, _ alignmentRect: NSRect, _ width: CGFloat, _ height: CGFloat) -> NSRect { return NSRect(x: alignmentRect.minX, y: height - 1, width: width - alignmentRect.minX, height: 1) } } private extension Array where Element == NSRect { func maxY() -> CGFloat { var y: CGFloat = 0.0 self.forEach { y = Swift.max(y, $0.maxY) } return y } }
37.987069
355
0.768524
d5f09a25a8818d1dc94a2ef23dc146dd9445f39e
204
import Foundation import Combine let myPublisher = Just("55") .map({ value in return Int(value) ?? 0 }) .sink(receiveValue: { value in print("Value received: \(value * 100)") })
17
45
0.602941
64d22ed5944a5d21e452f6ee65dc3bee49a55562
1,016
import Foundation struct Districts: Decodable { let districts: [Int: String] init(districts: [Int : String]) { self.districts = districts } init(from decoder: Decoder) throws { let districtContainer = try decoder .container(keyedBy: AnyCodingKey.self) .nestedUnkeyedContainer(forKey: "districts") let seq = sequence(state: districtContainer) { container -> (key: Int, value: String)? in if container.isAtEnd { return nil } guard let nestedContainer = try? container.nestedContainer(keyedBy: AnyCodingKey.self), let key = try? nestedContainer.decode("district_id", as: Int.self), let value = try? nestedContainer.decode("district_name", as: String.self) else { return nil } return (key, value) } self.districts = seq.reduce(into: [Int: String]()) { dictionary, tuple in dictionary[tuple.key] = tuple.value } } }
33.866667
97
0.600394
e9de7991455224da5b762b059c33ca70f00c1320
229
// // FactoryProducer.swift // // // Created by Shaun Hubbard on 4/23/20. // import Foundation typealias FactoryProducers = [FactoryProducer] public protocol FactoryProducer { var factories: ServiceFactories { get } }
15.266667
46
0.716157
7217bd80401b560e7406f09af34550a6c60a6579
3,471
// Copyright © 2019 Stormbird PTE. LTD. import Foundation import UIKit class AccountViewTableSectionHeader: UIView { enum HeaderType: Int { case hdWallet = 0 case keystoreWallet = 1 case watchedWallet = 2 var title: String { switch self { case .hdWallet: return R.string.localizable.walletTypesHdWallets().uppercased() case .keystoreWallet: return R.string.localizable.walletTypesKeystoreWallets().uppercased() case .watchedWallet: return R.string.localizable.walletTypesWatchedWallets().uppercased() } } } private let label = UILabel() private var heightConstraint: NSLayoutConstraint? private var constraintsWhenVisible: [NSLayoutConstraint] = [] private let topSeperatorView = UIView.tableHeaderFooterViewSeparatorView() private let bottomSeperatorView = UIView.tableHeaderFooterViewSeparatorView() override init(frame: CGRect) { super.init(frame: CGRect()) label.translatesAutoresizingMaskIntoConstraints = false addSubview(topSeperatorView) addSubview(bottomSeperatorView) addSubview(label) let topConstraint = label.topAnchor.constraint(equalTo: topSeperatorView.bottomAnchor, constant: 13) let bottomConstraint = label.bottomAnchor.constraint(equalTo: bottomSeperatorView.topAnchor, constant: -13) let constraintsWhenVisible = [ label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), label.trailingAnchor.constraint(equalTo: trailingAnchor), topSeperatorView.leadingAnchor.constraint(equalTo: leadingAnchor), topSeperatorView.trailingAnchor.constraint(equalTo: trailingAnchor), topSeperatorView.topAnchor.constraint(equalTo: topAnchor), bottomSeperatorView.leadingAnchor.constraint(equalTo: leadingAnchor), bottomSeperatorView.trailingAnchor.constraint(equalTo: trailingAnchor), bottomSeperatorView.bottomAnchor.constraint(equalTo: bottomAnchor), topConstraint, bottomConstraint ] NSLayoutConstraint.activate(constraintsWhenVisible) //UIKit doesn't like headers with a height of 0 heightConstraint = heightAnchor.constraint(equalToConstant: 1) self.constraintsWhenVisible = constraintsWhenVisible } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(type: HeaderType, shouldHide: Bool) { backgroundColor = GroupedTable.Color.background label.backgroundColor = GroupedTable.Color.background label.textColor = GroupedTable.Color.title label.font = Fonts.tableHeader label.text = type.title label.isHidden = shouldHide heightConstraint?.isActive = shouldHide if shouldHide { NSLayoutConstraint.deactivate(constraintsWhenVisible) } else { NSLayoutConstraint.activate(constraintsWhenVisible) } } } extension UIView { static func tableHeaderFooterViewSeparatorView() -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.heightAnchor.constraint(equalToConstant: 0.5).isActive = true view.backgroundColor = DataEntry.Color.border return view } }
36.15625
115
0.68741
e269c03f3505d470ed01002103b89ad0fe87b581
1,405
// // AppDelegate.swift // Example // // Created by daniel on 2021/9/12. // Copyright © 2021 daniel. 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.973684
179
0.746619
918e918e67bf3ca43c176e40f70f7f5135e9ac87
7,373
// // ArrayListItemSource.swift // ShelfCentered // // Created by Greg Langmead on 10/6/18. // Copyright © 2018 Greg Langmead. All rights reserved. // import Foundation import CloudKit class ArrayListItemSource : SCListItemSource, CustomStringConvertible { var isMe: Bool func userIsMe(user: String) -> Bool { return user == "Greg" } var lists : [SCListViewModel] var listItems : [[SCItemViewModel]] var listItemComments: [[[SCCommentViewModel]]] let isReadOnly : Bool init(lists: [SCListViewModel], listItems: [[SCItemViewModel]], listItemComments: [[[SCCommentViewModel]]], readOnly: Bool) { self.lists = lists self.listItems = listItems self.listItemComments = listItemComments self.isReadOnly = readOnly self.isMe = !isReadOnly } public var description: String { var result : String = "" for (listIndex, list) in lists.enumerated() { result += "list: \(list.name) (\(list.user))\n" for item in listItems[listIndex] { result += " \(item.name)\n" } } return result } func readOnly() -> Bool { return self.isReadOnly } // create func addList(list: SCListViewModel) { self.lists.append(list) self.listItems.append([]) } func addItem(inList: Int, item: SCItemViewModel) { self.listItems[inList].append(item) } // read func numberOfLists() -> Int { return listItems.count } func list(index : Int) -> SCListViewModel { return lists[index] } func numberOfItems(inList: Int) -> Int { return listItems[inList].count } func item(inList: Int, index: Int) -> SCItemViewModel { return listItems[inList][index] } public func numberOfComments(inList: Int, index: Int) -> Int { return self.listItemComments[inList][index].count } public func comment(inList: Int, index: Int, commentIndex: Int) -> SCCommentViewModel { return self.listItemComments[inList][index][commentIndex] } // update func updateList(index: Int, newData: SCListViewModel) { self.lists[index] = newData } func updateItem(inList: Int, index: Int, newData: SCItemViewModel) { self.listItems[inList][index] = newData } func deleteItemComment(inList: Int, index: Int, commentIndex: Int) { listItemComments[inList][index].remove(at: commentIndex) } func addItemComment(inList: Int, index: Int, comment: SCCommentViewModel) { listItemComments[inList][index].append(comment) } // delete func deleteList(index: Int) { self.lists.remove(at: index) } func deleteItem(inList: Int, index: Int) { self.listItems[inList].remove(at: index) } // sort func sortByModifiedLatestFirst() { for var list in listItems { list.sort(by: {$0.modifiedAt.value < $1.modifiedAt.value}) } } static func getTestSharedItemSource() -> SCListItemSource { let myBundle = Bundle(for: ArrayListItemSource.self) let suckerPunchImage = UIImage(named: "suckerPunch.jpg", in: myBundle, compatibleWith: nil) let suckerPunchItem = SCItemViewModel(name: "Sucker Punch, an item I've always wanted but never bought", image: suckerPunchImage, url: "https://smile.amazon.com/Sucker-Gimmicks-Online-Instructions-Southworth/dp/B01N4GYHMQ/ref=sr_1_10?ie=UTF8&qid=1518628995&sr=8-10&keywords=sucker+punch", description: "", createdAt: Date(), modifiedAt: Date(), claimed: false, editable: false) let redFamineItem = SCItemViewModel(name: "Red Famine book", image: UIImage(named:"redFamineBook.jpg", in: myBundle, compatibleWith: nil), url: "", description: "", createdAt: Date(), modifiedAt: Date(), claimed: false, editable: false) let bpItem = SCItemViewModel(name: "Black Panther", image: UIImage(named:"blackPantherBook.jpg", in: myBundle, compatibleWith: nil), url: "", description: "", createdAt: Date(), modifiedAt: Date(), claimed: false, editable: false) let deskItem = SCItemViewModel(name: "Tummy desk", image: UIImage(named:"tummyDesk.jpg", in: myBundle, compatibleWith: nil), url: "", description: "", createdAt: Date(), modifiedAt: Date(), claimed: false, editable: false) let shelfItemSource = ArrayListItemSource( lists: [SCListViewModel(name: "Birthday 2018", description: "Aw yeah", user: "Mom", createdAt: Date(), modifiedAt: Date()), SCListViewModel(name: "Christmas 2017", description: "Aw yeah", user: "Mom", createdAt: Date(), modifiedAt: Date())], listItems: [[suckerPunchItem, redFamineItem], [bpItem, deskItem]], listItemComments: [[[], []], [[], []]], readOnly: true ) return shelfItemSource } static func getTestMyItemSource() -> SCListItemSource { let myBundle = Bundle(for: ArrayListItemSource.self) var laboItem = SCItemViewModel(name: "Labo", image: UIImage(named:"labo.jpg", in: myBundle, compatibleWith: nil), url: "", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit vitae velit sed mollis. Pellentesque sodales consequat urna quis fermentum. Donec arcu urna, suscipit quis fringilla a, venenatis non lectus. Phasellus tristique nulla id sollicitudin auctor. Nunc tincidunt felis sed rutrum fermentum. Sed ullamcorper tincidunt nunc, eu pretium mauris ultricies blandit. Donec faucibus commodo leo, viverra auctor lacus egestas a.") let laboComments = [ SCCommentViewModel(comment: "The Labo looks neat, I wonder if anyone will really play with it or if it'll just sit there unused.", user: "Judgment", editable: true), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Greg", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk2", editable: true), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk3", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk4", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk5", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk6", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk7", editable: false), SCCommentViewModel(comment: "Me too. I wonder that.", user: "Jerk8", editable: false) ] let iceItem = SCItemViewModel(name: "Ice maker", image: UIImage(named:"ice.jpg", in: myBundle, compatibleWith: nil), url: "", description: "") let penItem = SCItemViewModel(name: "Pen", image: UIImage(named:"pen.jpg", in: myBundle, compatibleWith: nil), url: "", description: "") let shelfItemSource = ArrayListItemSource( lists: [SCListViewModel(name: "My Birthday 2018", description: "Aw yeah", user: "Me", createdAt: Date(), modifiedAt: Date()), SCListViewModel(name: "My Christmas 2017", description: "Aw yeah", user: "Me", createdAt: Date(), modifiedAt: Date())], listItems: [[laboItem, iceItem], [penItem]], listItemComments: [[laboComments, []], [[]]], readOnly: false ) return shelfItemSource } }
52.29078
581
0.655907
87fc15830f48c7275529c97f0391158a525a1091
7,782
// // Models.swift // tictactoe // // Created by ECE564 on 7/6/19. // Copyright © 2019 mobilecenter. All rights reserved. // import Foundation enum difficultyLevels: String { case easy = "Easy (Smart Random)" case medium = "Medium (Greed)" case hard = "Hard (Minmax)" } enum Piece: String { case X = "❌" case O = "⭕️" case E = " " var opposite: Piece { switch self { case .X: return .O case .O: return .X case .E: return .E } } } struct Board { let position: [Piece] let turn: Piece let lastMove: Int let level: difficultyLevels init(position: [Piece] = [.E, .E, .E, .E, .E, .E, .E, .E, .E], turn: Piece = .X, lastMove: Int = -1, level: difficultyLevels = .easy) { self.position = position self.turn = turn self.lastMove = lastMove self.level = level } init(level: difficultyLevels) { self.position = [.E, .E, .E, .E, .E, .E, .E, .E, .E] self.turn = .X self.lastMove = -1 self.level = level } func move(_ location: Int) -> Board { var tempPosition = position tempPosition[location] = turn return Board(position: tempPosition, turn: turn.opposite, lastMove: location, level: self.level) } func aiMovePosition() -> Int? { if self.legalMoves.count < 1 { return nil } if self.level == .medium { return self.mediumMove() } if self.level == .hard { return self.hardMove() } if self.level == .easy { return self.easyMove() } return nil } // smarter random guess, super easy to defeat private func easyMove() -> Int? { var bests: [Int] = [] for combo in winningCombos { if position[combo[0]] == position[combo[1]] && position[combo[0]] != .E && position[combo[2]] == .E { if position[combo[0]] == self.turn { return combo[2] } else { bests.append(combo[2]) } } if position[combo[0]] == position[combo[2]] && position[combo[0]] != .E && position[combo[1]] == .E { if position[combo[0]] == self.turn { return combo[1] } else { bests.append(combo[1]) } } if position[combo[1]] == position[combo[2]] && position[combo[1]] != .E && position[combo[0]] == .E { if position[combo[1]] == self.turn { return combo[0] } else { bests.append(combo[0]) } } } if !bests.isEmpty { return bests.randomElement() } return self.legalMoves.randomElement() } private func mediumMove() -> Int? { // first try to stop opponent from winning var bests: [Int] = [] for combo in winningCombos { if position[combo[0]] == position[combo[1]] && position[combo[0]] != .E && position[combo[2]] == .E { if position[combo[0]] == self.turn { return combo[2] } else { bests.append(combo[2]) } } if position[combo[0]] == position[combo[2]] && position[combo[0]] != .E && position[combo[1]] == .E { if position[combo[0]] == self.turn { return combo[1] } else { bests.append(combo[1]) } } if position[combo[1]] == position[combo[2]] && position[combo[1]] != .E && position[combo[0]] == .E { if position[combo[1]] == self.turn { return combo[0] } else { bests.append(combo[0]) } } } if !bests.isEmpty { return bests.randomElement() } // take center will have better chance to tie if position[4] == .E { return 4 } // then corners let corners = [0, 2, 6, 8] for p in corners { if position[p] == .E { return p } } // should not come to this case unless already tied, maybe design early termination later return self.legalMoves.randomElement() } private func hardMove() -> Int? { // first, second step optimization, to avoid huge recursive stack. let corners = [0, 2, 6, 8] if self.legalMoves.count > 8 { return corners.randomElement() // corner is the best first step strategy } if self.legalMoves.count == 8 { if self.position[4] != .E { return corners.randomElement() // corner is the best strategy } for c in corners { if self.position[c] != .E { return 4 // must go center to ensure tie } } return (self.legalMoves.reduce(0, +) - 4) % 8 // this is magic ;-) } // then run minmax algorithm var bestEval = Int.min var bestMove: Int? = nil for move in self.legalMoves { let result = minimax(self.move(move), maximizing: false, originalPlayer: self.turn) if result > bestEval { bestEval = result bestMove = move } } return bestMove } // Find the best possible outcome for originalPlayer private func minimax(_ board: Board, maximizing: Bool, originalPlayer: Piece) -> Int { // Base case — evaluate the position if it is a win or a draw if board.isWin && originalPlayer == board.turn.opposite { return 1 } // win else if board.isWin && originalPlayer != board.turn.opposite { return -1 } // loss else if board.isDraw { return 0 } // draw // Recursive case — maximize your gains or minimize the opponent's gains if maximizing { var bestEval = Int.min for move in board.legalMoves { // find the move with the highest evaluation let result = minimax(board.move(move), maximizing: false, originalPlayer: originalPlayer) bestEval = max(result, bestEval) } return bestEval } else { // minimizing var worstEval = Int.max for move in board.legalMoves { let result = minimax(board.move(move), maximizing: true, originalPlayer: originalPlayer) worstEval = min(result, worstEval) } return worstEval } } private var winningCombos: [[Int]] { /* 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8 */ return [ [0,1,2],[3,4,5],[6,7,8], /* horizontals */ [0,3,6],[1,4,7],[2,5,8], /* veritcals */ [0,4,8],[2,4,6] /* diagonals */ ] } var legalMoves: [Int] { return position.indices.filter { position[$0] == .E } } var isWin: Bool { for combo in winningCombos { if position[combo[0]] == position[combo[1]] && position[combo[0]] == position[combo[2]] && position[combo[0]] != .E { return true } } return false } var isDraw: Bool { return !isWin && legalMoves.count == 0 } }
31.253012
139
0.473529
23524853bcbe23447c3f3440d57ddc0063222a5c
2,297
// // SceneDelegate.swift // Prework // // Created by Sebastian De Los Rios on 9/4/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.339623
147
0.712669
acec77b0923bdee32521b5c1318e954ff643860f
26,340
// // SubscriptionForm.swift // SwiftTalkServerLib // // Created by Florian Kugler on 23-07-2019. // import Foundation import HTML import WebServer func subscriptionForm(_ data: SubscriptionFormData, initial: BillingInfo? = nil, action: Route) -> Node { let planRadios: [Node] = data.plans.map { plan in var a: [String: String] = ["value": plan.plan_code] if plan.plan_code == data.plan { a["checked"] = "true" } return .input(class: "visuallyhidden", name: "plan_id", id: "plan_id\(plan.plan_code)", type: "radio", attributes: a) } let form: Node if initial == nil { form = .div(class: "cols m-|stack++", [ .div(class: "col m+|width-2/3", [ .p(class: "mb++ bgcolor-invalid color-white ms-1 pa radius-3 bold", attributes: ["id": "errors"], []), data.gift ? giftSection() : .div(), creditCardSection(initial: initial), billingDetailsSection(initial: initial) ]), .div(class: "col width-full m+|width-1/3", attributes: ["id": "pricingInfo"]) ]) } else { form = .div(class: "m-|stack++", [ .p(class: "mb++ bgcolor-invalid color-white ms-1 pa radius-3 bold", attributes: ["id": "errors"], []), data.gift ? giftSection() : .div(), creditCardSection(initial: initial), billingDetailsSection(initial: initial), .button(class: "c-button c-button--wide", ["Update"]) ]) } return .withCSRF { csrf in Node.div(class: "container", [ .form(action: action.path, method: .post, attributes: ["id": "cc-form"], planRadios + [ .input(name: "_method", type: "hidden", attributes: ["value": "POST"]), .input(name: "csrf", id: "csrf", type: "hidden", attributes: ["value": csrf.string]), .input(name: "billing_info[token]", type: "hidden", attributes: ["value": ""]), form ]), .script(code: formJS(recurlyPublicKey: env.recurlyPublicKey, data: data)) ]) } } fileprivate func giftSection() -> Node { return .div(class: "mb+++", [ textField(name: "gifter_name", title: "Your Name"), textField(name: "gifter_email", title: "Your Email"), ]); } fileprivate func field(name: String, title: String, required: Bool = true, input: Node) -> Node { return Node.fieldset(class: "input-unit mb+", attributes: ["id": name], [ .label(class: "input-label block" + (required ? "input-label--required" : ""), attributes: ["for": name], [.text(title)]), input ]) } fileprivate func textField(name: String, title: String, initial: String? = nil, required: Bool = true) -> Node { return field(name: name, title: title, required: required, input: .input(class: "text-input inline-block width-full form-control-danger", name: name, id: name, type: "text", attributes: [ "data-recurly": name, "value": initial ?? "" ]) ) } fileprivate func recurlyField(name: String, title: String, required: Bool = true) -> Node { return field(name: name, title: title, required: required, input: .div(attributes: ["data-recurly": name])) } fileprivate func creditCardSection(initial: BillingInfo?) -> Node { return Node.div([ .h2(class: "ms1 color-blue bold mb+", ["Credit Card"]), .div(class: "cols", [ .div(class: "col width-1/2", [textField(name: "first_name", title: "First name", initial: initial?.first_name)]), .div(class: "col width-1/2", [textField(name: "last_name", title: "Last name", initial: initial?.last_name)]), ]), .div(class: "cols", [ .div(class: "col width-full s+|width-1/2", [recurlyField(name: "number", title: "Number")]), .div(class: "col s+|width-1/2", [ .div(class: "cols", [ .div(class: "col width-1/3", [recurlyField(name: "cvv", title: "CVV")]), .div(class: "col width-2/3", [ .fieldset(class: "input-unit mb+", attributes: ["id": "expiry"], [ .label(class: "input-label input-label--required block", attributes: ["for": "month"], ["Expiration"]), .div(class: "flex items-center", [ .div(class: "flex-1", attributes: ["data-recurly": "month"]), .span(class: "ph- color-gray-30 bold", ["/"]), .div(class: "flex-2", attributes: ["data-recurly": "year"]), ]) ]) ]) ]) ]) ]) ]) } fileprivate func billingDetailsSection(initial: BillingInfo?) -> Node { return .div([ .h2(class: "ms1 color-blue bold mb+ mt++", ["Billing Address"]), textField(name: "address1", title: "Street Address", initial: initial?.address1), textField(name: "address2", title: "Street Address (cont.)", initial: initial?.address2, required: false), .div(class: "cols", [ .div(class: "col width-1/2", [textField(name: "city", title: "City", initial: initial?.city)]), .div(class: "col width-1/2", [textField(name: "state", title: "State", initial: initial?.state)]), .div(class: "col width-1/2", [textField(name: "postal_code", title: "Zip/Postal code", initial: initial?.zip)]), .div(class: "col width-1/2", [ field(name: "country", title: "Country", input: Node.select(class: "text-input inline-block width-full c-select", name: "country", attributes: ["id": "country"], options: countries, selected: initial?.country)), .input(name: "realCountry", id: "realCountry", type: "hidden", attributes: ["data-recurly": "country", "value": initial?.country ?? ""]) ]), ]), .div(class: "cols", [ .div(class: "col width-1/2", [textField(name: "company", title: "Company", initial: initial?.company, required: false)]), .div(class: "col width-1/2", [textField(name: "vat_number", title: "EU VAT ID (if applicable)", initial: initial?.vat_number, required: false)]), ]) ]) } fileprivate struct JSONOptional<A: Encodable>: Encodable, ExpressibleByNilLiteral { var value: A? func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if let v = value { try container.encode(v) } else { try container.encodeNil() } } init(_ value: A?) { self.value = value } init(nilLiteral: ()) { self.value = nil } } fileprivate struct FormPlan: Codable { var id: String var base_price: Int var interval: String var plan_code: String init(_ plan: Plan) { id = plan.plan_code base_price = plan.unit_amount_in_cents.usdCents interval = plan.prettyDuration plan_code = plan.plan_code } } fileprivate struct FormCoupon: Encodable { var code: String var discount_type: String var discount_percent: JSONOptional<Int> var description: String var discount_in_cents: JSONOptional<Amount> var free_trial_amount: JSONOptional<Int> var free_trial_unit: JSONOptional<TemporalUnit> init(_ coupon: Coupon) { code = coupon.coupon_code discount_type = coupon.discount_type.rawValue description = coupon.description discount_percent = JSONOptional(coupon.discount_percent) discount_in_cents = JSONOptional(coupon.discount_in_cents) free_trial_amount = JSONOptional(coupon.free_trial_amount) free_trial_unit = JSONOptional(coupon.free_trial_unit) } } struct SubscriptionFormData: Encodable { fileprivate var gift: Bool = false fileprivate var plans: [FormPlan] fileprivate var errorFields: [String] = [] fileprivate var errorMessages: [String] = [] fileprivate var loading: Bool = false fileprivate var plan: String fileprivate var vatRate: JSONOptional<Double> = nil fileprivate var country: JSONOptional<String> = nil fileprivate var coupon: JSONOptional<FormCoupon> = nil fileprivate var belowButtonText: String = "" init(error: RecurlyError? = nil) { self.plans = [] self.plan = "" self.errorMessages = error.map { [$0.transaction_error.customer_message] } ?? []; } init(giftPlan: Plan, startDate: String, errors: [ValidationError] = []) { self.gift = true self.plans = [FormPlan(giftPlan)] self.plan = giftPlan.plan_code self.errorFields = errors.map { $0.field }.filter { !$0.isEmpty } self.errorMessages = errors.filter { $0.field.isEmpty && !$0.message.isEmpty }.map { $0.message } self.belowButtonText = "Your card will be billed on \(startDate)." } init(plans: [Plan], selectedPlan: Plan, coupon: SwiftTalkServerLib.Coupon? = nil, error: RecurlyError? = nil) { self.plans = plans.map { .init($0) } self.plan = selectedPlan.plan_code self.errorMessages = error.map { [$0.transaction_error.customer_message] } ?? []; self.coupon = JSONOptional(coupon.map { .init($0) }) } } fileprivate func formJS(recurlyPublicKey: String, data: SubscriptionFormData) -> String { let data = try! JSONEncoder().encode(data) let json = String(data: data, encoding: .utf8)! return """ const recurlyPublicKey = '\(recurlyPublicKey)'; var state = \(json); function setState(newState) { Object.keys(newState).forEach((key) => { state[key] = newState[key]; }); update(); } function formatAmount(amount, forcePadding) { if (!forcePadding && Math.floor(amount/100) == amount/100) { return `$${amount/100}` } else { return `$${(amount / 100).toFixed(2)}`; } }; function computeDiscountedPrice (basePrice, coupon) { if (coupon == null) { return basePrice } let price = basePrice switch (coupon.discount_type) { case "dollars": price = basePrice - coupon.discount_in_cents.USD if (price < 0) { price = 0 } break case "percent": price = basePrice * (100 - coupon.discount_percent) / 100 break } return price } function update() { function removeErrors() { document.querySelectorAll('fieldset.input-unit').forEach((fs) => { fs.classList.remove('has-error'); }); } function showErrors() { const errorContainer = document.getElementById('errors'); if (state.errorFields.length > 0 || state.errorMessages.length > 0) { state.errorFields.forEach((fieldName) => { if (fieldName == "year" || fieldName == "month") { fieldName = "expiry"; } let element = document.querySelector('fieldset#' + fieldName); if (element) { element.classList.add('has-error'); } }); let messages = [] if (state.errorFields.length > 0) { messages.push('There were errors in the fields marked in red. Please correct and try again.'); } messages = messages.concat(state.errorMessages); errorContainer.innerHTML = messages.join('<br/>'); errorContainer.hidden = messages.length === 0; } else { errorContainer.hidden = true } } function updatePricingInfo() { const pricingContainer = document.getElementById('pricingInfo'); const selectedPlan = state.plans.find((plan) => { return plan.id === state.plan; }); if (!pricingContainer || !selectedPlan) return; let html = []; if (state.gift) { html.push(` <div class="pa border-bottom border-color-white border-2 flex justify-between items-center"> <span class="smallcaps-large">Gift</span> <span class="bold">${selectedPlan.interval} of Swift Talk</span> </div> `); } else { html.push(` <div class="pv ph- border-bottom border-color-white border-2 flex"> ${ state.plans.map((plan) => { return ` <div class="flex-1 block mh- pv ph-- radius-5 cursor-pointer border border-2 text-center ${plan.id === state.plan ? 'color-white border-color-transparent bgcolor-blue' : 'color-gray-60 border-color-gray-90'}"> <input type="radio" name="plan_id" value="${plan.id}" id="plan_id${plan.id}" class="visuallyhidden"> <label for="plan_id${plan.id}" class="block cursor-pointer"> <div class="smallcaps mb">${plan.interval}</div> <div class="ms3 bold">${formatAmount(plan.base_price)}</div> </label> </div> `; }).join('') } </div> `); } html.push(` <div class="pa border-bottom border-color-white border-2 flex justify-between items-center"> <span class="smallcaps-large">Price</span> <span>${formatAmount(selectedPlan.base_price, true)}</span> </div> `); var discountedPrice = selectedPlan.base_price; if (state.coupon !== null && state.coupon.discount_type) { html.push(` <div class="pa border-bottom border-color-white border-2"> <span class="ms-1">${state.coupon.description}</span> </div> `); if (state.coupon.discount_type !== 'free_trial') { discountedPrice = computeDiscountedPrice(selectedPlan.base_price, state.coupon); html.push(` <div class="pa border-bottom border-color-white border-2 flex justify-between items-center"> <span class="smallcaps-large">Discount</span> <span>${formatAmount(selectedPlan.base_price - discountedPrice)}</span> </div> `); } } var taxAmount = 0; const vatNumber = (document.querySelector('input#vat_number').value || "") const vatExempt = vatNumber.length > 0 && state.country != "DE" if (state.vatRate !== null) { if (vatExempt) { html.push(` <div class="pa border-bottom border-color-white border-2 flex justify-between items-center"> <span>VAT Exempt</span> </div> `) } else { taxAmount = discountedPrice * state.vatRate; html.push(` <div class="pa border-bottom border-color-white border-2 flex justify-between items-center"> <span className="smallcaps-large">VAT (${state.vatRate * 100}%)</span> <span>${formatAmount(taxAmount, true)}</span> </div> `); } } html.push(` <div class="bgcolor-gray-90 color-gray-15 bold pa flex justify-between items-center"> <span class="smallcaps-large">Total</span> <span>${formatAmount(discountedPrice + taxAmount, true)}</span> </div> `); pricingContainer.innerHTML = ` <div class="bgcolor-gray-95 color-gray-40 radius-5 overflow-hidden mb"> ${html.join('')} </div> <div> <button type='submit' class='c-button c-button--wide' ${state.loading ? 'disabled' : ''}> ${state.loading ? "<span>Please wait...</span>" : "<span>" + state.gift === true ? "Pay Gift" : "Subscribe" + "</span>" } </button> <p class="mt color-gray-60 ms-1 text-center">${state.belowButtonText}</p> </div> `; } removeErrors(); showErrors(); updatePricingInfo(); addPlanListeners(); } var taxRequestPromise = null; function fetchTaxRate(country, callback) { if (country) { setState({ loading: true }); var currentPromise = window.fetch('https://api.recurly.com/js/v1/tax?country=' + country + '&tax_code=digital&version=4.0.4&key=' + recurlyPublicKey).then(function(response) { return response.json(); }).then(function(json) { if (currentPromise === taxRequestPromise) { setState({ loading: false }); callback(json[0] || null); } }); taxRequestPromise = currentPromise; } else { callback(null); } } function configureRecurly() { recurly.configure({ publicKey: recurlyPublicKey, style: { all: { fontFamily: 'Cousine', fontSize: '20px', fontColor: '#4d4d4d', placeholder: { fontColor: '#bfbfbf !important' } }, number: { placeholder: { content: '•••• •••• •••• ••••' } }, month: { placeholder: { content: 'MM' } }, year: { placeholder: { content: 'YYYY' } }, cvv: { placeholder: { content: '•••', } } } }); } function handleSubmit(e) { e.preventDefault() setState({ loading: true }) var form = document.querySelector('form#cc-form'); recurly.token(form, function (err, token) { if (err) { setState({ loading: false, errorFields: err.fields }) } else { setState({ errors: [] }); document.querySelector('input[name="billing_info[token]"]').value = token.id form.submit(); } }); } function handleCountryChange(event) { const country = event.target.value; document.querySelector('input#realCountry').value = country; fetchTaxRate(country, function(taxInfo) { setState({ vatRate: taxInfo !== null ? Number.parseFloat(taxInfo.rate) : null, country: country }); }); } function addPlanListeners() { const planButtons = document.querySelectorAll('input[name="plan_id"]'); planButtons.forEach(function(button) { button.addEventListener('change', (event) => { setState({ plan: event.target.value }); }); }); } window.addEventListener('DOMContentLoaded', (event) => { update(); document.querySelector('form#cc-form').addEventListener('submit', handleSubmit); const countryField = document.querySelector('select#country'); countryField.addEventListener('change', handleCountryChange); countryField.addEventListener('blur', handleCountryChange); document.querySelector('input#vat_number').addEventListener('change', update); addPlanListeners(); configureRecurly(); }); """ } fileprivate let countries: [(String, String)] = [ ("", "Select Country"), ("AX", "Åland Islands"), ("AL", "Albania"), ("DZ", "Algeria"), ("AS", "American Samoa"), ("AD", "Andorra"), ("AO", "Angola"), ("AI", "Anguilla"), ("AQ", "Antarctica"), ("AG", "Antigua and Barbuda"), ("AR", "Argentina"), ("AM", "Armenia"), ("AW", "Aruba"), ("AU", "Australia"), ("AT", "Austria"), ("AZ", "Azerbaijan"), ("BS", "Bahamas"), ("BH", "Bahrain"), ("BD", "Bangladesh"), ("BB", "Barbados"), ("BY", "Belarus"), ("BE", "Belgium"), ("BZ", "Belize"), ("BJ", "Benin"), ("BM", "Bermuda"), ("BT", "Bhutan"), ("BO", "Bolivia"), ("BA", "Bosnia and Herzegovina"), ("BW", "Botswana"), ("BV", "Bouvet Island"), ("BR", "Brazil"), ("IO", "British Indian Ocean Territory"), ("BN", "Brunei Darussalam"), ("BG", "Bulgaria"), ("BF", "Burkina Faso"), ("BI", "Burundi"), ("KH", "Cambodia"), ("CM", "Cameroon"), ("CA", "Canada"), ("CV", "Cape Verde"), ("KY", "Cayman Islands"), ("CF", "Central African Republic"), ("TD", "Chad"), ("CL", "Chile"), ("CN", "China"), ("CX", "Christmas Island"), ("CC", "Cocos (Keeling) Islands"), ("CO", "Colombia"), ("KM", "Comoros"), ("CG", "Congo"), ("CD", "Congo, The Democratic Republic of the"), ("CK", "Cook Islands"), ("CR", "Costa Rica"), ("CI", "Cote D'Ivoire"), ("HR", "Croatia"), ("CU", "Cuba"), ("CY", "Cyprus"), ("CZ", "Czech Republic"), ("DK", "Denmark"), ("DJ", "Djibouti"), ("DM", "Dominica"), ("DO", "Dominican Republic"), ("EC", "Ecuador"), ("EG", "Egypt"), ("SV", "El Salvador"), ("GQ", "Equatorial Guinea"), ("ER", "Eritrea"), ("EE", "Estonia"), ("ET", "Ethiopia"), ("FK", "Falkland Islands (Malvinas)"), ("FO", "Faroe Islands"), ("FJ", "Fiji"), ("FI", "Finland"), ("FR", "France"), ("GF", "French Guiana"), ("PF", "French Polynesia"), ("TF", "French Southern Territories"), ("GA", "Gabon"), ("GM", "Gambia"), ("GE", "Georgia"), ("DE", "Germany"), ("GH", "Ghana"), ("GI", "Gibraltar"), ("GR", "Greece"), ("GL", "Greenland"), ("GD", "Grenada"), ("GP", "Guadeloupe"), ("GU", "Guam"), ("GT", "Guatemala"), ("GG", "Guernsey"), ("GN", "Guinea"), ("GW", "Guinea-Bissau"), ("GY", "Guyana"), ("HT", "Haiti"), ("HM", "Heard Island and Mcdonald Islands"), ("VA", "Holy See (Vatican City State)"), ("HN", "Honduras"), ("HK", "Hong Kong"), ("HU", "Hungary"), ("IS", "Iceland"), ("IN", "India"), ("ID", "Indonesia"), ("IR", "Iran, Islamic Republic Of"), ("IQ", "Iraq"), ("IE", "Ireland"), ("IM", "Isle of Man"), ("IL", "Israel"), ("IT", "Italy"), ("JM", "Jamaica"), ("JP", "Japan"), ("JE", "Jersey"), ("JO", "Jordan"), ("KZ", "Kazakhstan"), ("KE", "Kenya"), ("KI", "Kiribati"), ("KP", "Democratic People's Republic of Korea"), ("KR", "Korea, Republic of"), ("XK", "Kosovo"), ("KW", "Kuwait"), ("KG", "Kyrgyzstan"), ("LA", "Lao People's Democratic Republic"), ("LV", "Latvia"), ("LB", "Lebanon"), ("LS", "Lesotho"), ("LR", "Liberia"), ("LY", "Libyan Arab Jamahiriya"), ("LI", "Liechtenstein"), ("LT", "Lithuania"), ("LU", "Luxembourg"), ("MO", "Macao"), ("MK", "Macedonia, The Former Yugoslav Republic of"), ("MG", "Madagascar"), ("MW", "Malawi"), ("MY", "Malaysia"), ("MV", "Maldives"), ("ML", "Mali"), ("MT", "Malta"), ("MH", "Marshall Islands"), ("MQ", "Martinique"), ("MR", "Mauritania"), ("MU", "Mauritius"), ("YT", "Mayotte"), ("MX", "Mexico"), ("FM", "Micronesia, Federated States of"), ("MD", "Moldova, Republic of"), ("MC", "Monaco"), ("MN", "Mongolia"), ("ME", "Montenegro"), ("MS", "Montserrat"), ("MA", "Morocco"), ("MZ", "Mozambique"), ("MM", "Myanmar"), ("NA", "Namibia"), ("NR", "Nauru"), ("NP", "Nepal"), ("NL", "Netherlands"), ("AN", "Netherlands Antilles"), ("NC", "New Caledonia"), ("NZ", "New Zealand"), ("NI", "Nicaragua"), ("NE", "Niger"), ("NG", "Nigeria"), ("NU", "Niue"), ("NF", "Norfolk Island"), ("MP", "Northern Mariana Islands"), ("NO", "Norway"), ("OM", "Oman"), ("PK", "Pakistan"), ("PW", "Palau"), ("PS", "Palestinian Territory, Occupied"), ("PA", "Panama"), ("PG", "Papua New Guinea"), ("PY", "Paraguay"), ("PE", "Peru"), ("PH", "Philippines"), ("PN", "Pitcairn"), ("PL", "Poland"), ("PT", "Portugal"), ("PR", "Puerto Rico"), ("QA", "Qatar"), ("RE", "Reunion"), ("RO", "Romania"), ("RU", "Russian Federation"), ("RW", "Rwanda"), ("SH", "Saint Helena"), ("KN", "Saint Kitts and Nevis"), ("LC", "Saint Lucia"), ("PM", "Saint Pierre and Miquelon"), ("VC", "Saint Vincent and the Grenadines"), ("WS", "Samoa"), ("SM", "San Marino"), ("ST", "Sao Tome and Principe"), ("SA", "Saudi Arabia"), ("SN", "Senegal"), ("RS", "Serbia"), ("SC", "Seychelles"), ("SL", "Sierra Leone"), ("SG", "Singapore"), ("SK", "Slovakia"), ("SI", "Slovenia"), ("SB", "Solomon Islands"), ("SO", "Somalia"), ("ZA", "South Africa"), ("GS", "South Georgia and the South Sandwich Islands"), ("ES", "Spain"), ("LK", "Sri Lanka"), ("SD", "Sudan"), ("SR", "Suriname"), ("SJ", "Svalbard and Jan Mayen"), ("SZ", "Swaziland"), ("SE", "Sweden"), ("CH", "Switzerland"), ("SY", "Syrian Arab Republic"), ("TW", "Taiwan"), ("TJ", "Tajikistan"), ("TZ", "Tanzania, United Republic of"), ("TH", "Thailand"), ("TL", "Timor-Leste"), ("TG", "Togo"), ("TK", "Tokelau"), ("TO", "Tonga"), ("TT", "Trinidad and Tobago"), ("TN", "Tunisia"), ("TR", "Turkey"), ("TM", "Turkmenistan"), ("TC", "Turks and Caicos Islands"), ("TV", "Tuvalu"), ("UG", "Uganda"), ("UA", "Ukraine"), ("AE", "United Arab Emirates"), ("GB", "United Kingdom"), ("US", "United States"), ("UM", "United States Minor Outlying Islands"), ("UY", "Uruguay"), ("UZ", "Uzbekistan"), ("VU", "Vanuatu"), ("VE", "Venezuela"), ("VN", "Viet Nam"), ("VG", "Virgin Islands, British"), ("VI", "Virgin Islands, U.S."), ("WF", "Wallis and Futuna"), ("EH", "Western Sahara"), ("YE", "Yemen"), ("ZM", "Zambia"), ("ZW", "Zimbabwe") ]
34.612352
241
0.522703
2831c37137da99a343996c41ac32abe2a1b94651
972
// // CryptoSwift // // Copyright (C) 2014-2021 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public enum PKCS7 { typealias Padding = PKCS7Padding }
51.157895
217
0.766461
1e47bfac96951d1f4ebf2760cbc727b2e800bd2b
906
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation import UIKit /// Contains the styling customization options for a list section header. public struct ListSectionHeaderStyle: ViewStyle { /// The title style. public var title = TextStyle(font: .preferredFont(forTextStyle: .subheadline), color: UIColor.Adyen.componentSecondaryLabel, textAlignment: .natural) /// :nodoc: public var backgroundColor = UIColor.Adyen.componentBackground /// Initializes the list header style. /// /// - Parameter title: The title style. public init(title: TextStyle) { self.title = title } /// Initializes the list header style with the default style. public init() {} }
28.3125
100
0.635762
76ccec6dc5f96becdb0ba989a32a5c0ca8c3d583
1,547
// // ScreenshotMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2016-11-23. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) || os(tvOS) import Foundation import UIKit /// /// A `ScreenshotMonitor` instance monitors the app for screenshots. /// public class ScreenshotMonitor: BaseNotificationMonitor { /// /// Encapsulates screenshots taken when the user presses the Home and /// Lock buttons. /// public enum Event { /// /// The user has taken a screenshot. /// case userDidTake } /// /// Initializes a new `ScreenshotMonitor`. /// /// - Parameters: /// - queue: The operation queue on which the handler executes. /// By default, the main operation queue is used. /// - handler: The handler to call when the user presses the Home /// and Lock buttons to take a screenshot. /// public init(queue: OperationQueue = .main, handler: @escaping (Event) -> Void) { self.application = ApplicationInjector.inject() self.handler = handler super.init(queue: queue) } private let application: ApplicationProtocol private let handler: (Event) -> Void override public func addNotificationObservers() { super.addNotificationObservers() observe(.UIApplicationUserDidTakeScreenshot, object: application) { [unowned self] _ in self.handler(.userDidTake) } } } #endif
25.360656
74
0.598578
db7486628f5b7126e9b182ee5ff2c2b966fa19f0
591
// // TravelLocationMapCoordinator.swift // VirtualTourist // // Created by Jess Le on 4/24/20. // Copyright © 2020 lovelejess. All rights reserved. // import Foundation import UIKit import MapKit protocol Coordinatable: class { var rootViewController: UIViewController! { get } var childControllers: [UIViewController]? { get set } var parentCoordinator: Coordinatable? { get set } var userPreferences: UserPreferences! { get set } func navigate(to route: Route) } enum Route { case travelLocationsMap case photoAlbum(location: CLLocationCoordinate2D) }
22.730769
57
0.730964
6784793272f36c8c2defefd4e90f67b8c8958ff2
1,133
// // PhotoShareViewController.swift // Photostream // // Created by Mounir Ybanez on 18/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit class PhotoShareViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var contentTextView: UITextView! var presenter: PhotoShareModuleInterface! var image: UIImage! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) imageView.image = image } override var prefersStatusBarHidden: Bool { return true } @IBAction func didTapCancel(_ sender: AnyObject) { presenter.cancel() presenter.pop() } @IBAction func didTapDone(_ sender: AnyObject) { guard let message = contentTextView.text, !message.isEmpty else { return } presenter.finish(with: image, content:message) presenter.dismiss() } } extension PhotoShareViewController: PhotoShareViewInterface { var controller: UIViewController? { return self } }
21.788462
73
0.653133
08e024a23712133ffcc9f7b6724416d16a0954ed
748
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func o<t>() -> (t, t -> t) -> t { j j j.o = { } { t) { h } } protocol o { } e o<j : u> { } func n<q>() { b b { } k { } struct c<d : Sequence> { var b: [c<d>] { return [] } protocol a { } class b: a { } func f<T : Boolean>(b: T) { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type protocol c : b { func b
20.216216
78
0.586898
62002a01d32b04de591e33b4a46d487643a7c91a
4,170
// Copyright © 2019 Stormbird PTE. LTD. import Foundation import UIKit protocol ReusableTableHeaderViewType: UIView, WithReusableIdentifier { } extension TokensViewController { class TableViewSectionHeader: UITableViewHeaderFooterView { var filterView: SegmentedControl? { didSet { guard let filterView = filterView else { if let oldValue = oldValue { oldValue.removeFromSuperview() } return } filterView.backgroundColor = Colors.appWhite filterView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(filterView) NSLayoutConstraint.activate([ filterView.anchorsConstraint(to: contentView), ]) } } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = Colors.appWhite } required init?(coder aDecoder: NSCoder) { return nil } } class GeneralTableViewSectionHeader<T: ReusableTableHeaderViewType>: UITableViewHeaderFooterView { var subview: T? { didSet { guard let subview = subview else { if let oldValue = oldValue { oldValue.removeFromSuperview() } return } subview.backgroundColor = Colors.appWhite subview.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(subview) contentView.addSubview(bottomSeparator) contentView.addSubview(topSeparator) NSLayoutConstraint.activate([ subview.anchorsConstraint(to: contentView), ] + topSeparator.anchorSeparatorToTop(to: contentView) + bottomSeparator.anchorSeparatorToBottom(to: contentView)) } } private var bottomSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private var topSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() var useSeparatorLine: Bool { get { !bottomSeparator.isHidden } set { bottomSeparator.isHidden = !newValue topSeparator.isHidden = !newValue } } override var reuseIdentifier: String? { T.reusableIdentifier } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = Colors.appWhite bottomSeparator.isHidden = true topSeparator.isHidden = true bottomSeparator.backgroundColor = GroupedTable.Color.cellSeparator topSeparator.backgroundColor = GroupedTable.Color.cellSeparator } required init?(coder aDecoder: NSCoder) { return nil } } } extension UIView { func anchorSeparatorToTop(to superView: UIView) -> [NSLayoutConstraint] { return [ centerXAnchor.constraint(equalTo: superView.centerXAnchor), widthAnchor.constraint(equalTo: superView.widthAnchor), heightAnchor.constraint(equalToConstant: GroupedTable.Metric.cellSeparatorHeight), topAnchor.constraint(equalTo: superView.topAnchor) ] } func anchorSeparatorToBottom(to superView: UIView) -> [NSLayoutConstraint] { return [ centerXAnchor.constraint(equalTo: superView.centerXAnchor), widthAnchor.constraint(equalTo: superView.widthAnchor), heightAnchor.constraint(equalToConstant: GroupedTable.Metric.cellSeparatorHeight), bottomAnchor.constraint(equalTo: superView.bottomAnchor) ] } }
33.36
130
0.593765
e4f43e9b98d17d7837ba63cd76d77fa6888fa109
3,406
import XCTest @testable import Malline class ContextTests: XCTestCase { static var allTests: [(String, (ContextTests) -> () throws -> Void)] { return [ ("testGetValueViaSubscripting", testGetValueViaSubscripting), ("testSetValueViaSubscripting", testSetValueViaSubscripting), ("testRemovalOfValueViaSubscripting", testRemovalOfValueViaSubscripting), ("testRetrievingValueFromParent", testRetrievingValueFromParent), ("testOverridingParentValue", testOverridingParentValue), ("testPopToPreviousState", testPopToPreviousState), ("testRemoveParentValueFromLevel", testRemoveParentValueFromLevel), ("testDictionaryPushWithRestoreClosure", testDictionaryPushWithRestoreClosure), ("testFlattenContextContents", testFlattenContextContents), ("testPerformanceExample", testPerformanceExample), ] } let context = Context(dictionary: ["name": "Tauno"]) 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 testGetValueViaSubscripting() { XCTAssertEqual(context["name"] as? String, "Tauno") } func testSetValueViaSubscripting() { context["name"] = "Airi" XCTAssertEqual(context["name"] as? String, "Airi") } func testRemovalOfValueViaSubscripting() { context["name"] = nil XCTAssertNil(context["name"]) } func testRetrievingValueFromParent() { context.push { XCTAssertEqual(context["name"] as? String, "Tauno") } } func testOverridingParentValue() { context.push { context["name"] = "Airi" XCTAssertEqual(context["name"] as? String, "Airi") } } func testPopToPreviousState() { context.push { context["name"] = "Airi" } XCTAssertEqual(context["name"] as? String, "Tauno") } func testRemoveParentValueFromLevel() { context.push { context["name"] = nil XCTAssertNil(context["name"]) } XCTAssertEqual(context["name"] as? String, "Tauno") } func testDictionaryPushWithRestoreClosure() { var didRun = false context.push(dictionary: ["name": "Airi"]) { didRun = true XCTAssertEqual(context["name"] as? String, "Airi") } XCTAssertTrue(didRun) XCTAssertEqual(context["name"] as? String, "Tauno") } func testFlattenContextContents() { context.push(dictionary: ["test": "abc"]) { let flattened = context.flatten() XCTAssertEqual(flattened.count, 2) XCTAssertEqual(context["name"] as? String, "Tauno") XCTAssertEqual(context["test"] as? String, "abc") } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
30.963636
111
0.592484
188b93031771e52118ee254b52468ede1460d27a
3,208
/// Copyright (c) 2021 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 SwiftUI import ChuckNorrisJokesModel struct SavedJokesView: View { var body: some View { VStack { NavigationView { List { ForEach(jokes, id: \.self) { joke in // 1 Text(self.showTranslation ? joke.translatedValue ?? "N/A" : joke.value ?? "N/A") .lineLimit(nil) } .onDelete { indices in // 2 self.jokes.delete(at: indices, inViewContext: self.viewContext) } } .navigationBarTitle("Saved Jokes") .navigationBarItems(trailing: Button(action: { self.showTranslation.toggle() }) { Text("Toggle Language") } ) } Button(action: { let url = URL(string: "http://translate.yandex.com")! UIApplication.shared.open(url) }) { Text("Translations Powered by Yandex.Translate") .font(.caption) } .opacity(showTranslation ? 1 : 0) .animation(.easeInOut) } } @State private var showTranslation = false @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor( keyPath: \JokeManagedObject.value, ascending: true) ], animation: .default ) private var jokes: FetchedResults<JokeManagedObject> } struct SavedJokesView_Previews: PreviewProvider { static var previews: some View { SavedJokesView() } }
36.454545
83
0.660536