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
e837805ffc42414100aed1bd4d76676a24e30567
1,730
// // AppDelegate.swift // Homepwner // // Created by Christopher Nady on 7/27/17. // Copyright © 2017 Nady Analytics, LLC. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let itemStore = ItemStore() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print(#function) // Override point for customization after application launch. // Create an ImageStore let imageStore = ImageStore() // Access the ItemsViewController and set its item store let navController = window!.rootViewController as! UINavigationController let itemsController = navController.topViewController as! ItemsViewController itemsController.itemStore = itemStore itemsController.imageStore = imageStore return true } func applicationWillResignActive(_ application: UIApplication) { print(#function) } func applicationDidEnterBackground(_ application: UIApplication) { print(#function) let success = itemStore.saveChanges() if (success) { print("Saved all of the Items") } else { print("Could not save any of the items") } } func applicationWillEnterForeground(_ application: UIApplication) { print(#function) } func applicationDidBecomeActive(_ application: UIApplication) { print(#function) } func applicationWillTerminate(_ application: UIApplication) { print(#function) } }
25.820896
144
0.657803
d7df590a05a969d3284654b43a937e1b3b8d83b9
1,061
import XCTest @testable import Nlp_swift final class Nlp_swiftTests: XCTestCase { func testExample() { let quote = "President George Bush went to Mexico with IBM representatives. Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do. - Steve Jobs (Founder of Apple Inc.)" if #available(OSX 10.13, *) { print("\nEntities:\n") print(getEntities(for: quote)) print("\nLemmas:\n") print(getLemmas(for: quote)) } } static var allTests = [ ("testExample", testExample), ] }
55.842105
671
0.68803
48cbb0c9a188db59d245b6852806318df95f0f5d
1,727
// // Copyright © 2014 Yalantis // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at http://github.com/yalantis/Side-Menu.iOS // import UIKit import SideMenu protocol MenuViewControllerDelegate: class { func menu(menu: MenuViewController, didSelectItemAtIndex index: Int, atPoint point: CGPoint) func menuDidCancel(menu: MenuViewController) } class MenuViewController: UITableViewController { weak var delegate: MenuViewControllerDelegate? var selectedItem = 0 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let indexPath = NSIndexPath(forRow: selectedItem, inSection: 0) tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) } } extension MenuViewController { @IBAction private func dismissMenu() { delegate?.menuDidCancel(self) } } extension MenuViewController: Menu { var menuItems: [UIView] { return [tableView.tableHeaderView!] + tableView.visibleCells() as [UIView] } } extension MenuViewController: UITableViewDelegate { override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { return indexPath == tableView.indexPathForSelectedRow() ? nil : indexPath } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let rect = tableView.rectForRowAtIndexPath(indexPath) var point = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)) point = tableView.convertPoint(point, toView: nil) delegate?.menu(self, didSelectItemAtIndex: indexPath.row, atPoint:point) } }
33.211538
118
0.736537
616ede278ef82b3f485cd381579fdc9588144142
242
public enum Fuel: String, Decodable { case jetA = "Jet A" case jetB = "Jet B" case oneHundredLowLead = "100LL" } extension Fuel: CustomStringConvertible { public var description: String { return self.rawValue } }
20.166667
41
0.657025
db91da5528151601501d671a5830dca41225aeda
4,007
// // RegisterView.swift // mongodb-swiftui // // Created by Amey Sunu on 14/07/21. // import SwiftUI var e: String? struct RegisterView: View { @State private var email: String = "" @State private var password: String = "" @State private var confirmpwd: String = "" @State var load: Bool = false @State var alertItem: AlertItem? @Environment(\.presentationMode) var presentationMode var body: some View { VStack(alignment: .leading){ TextField("Email ID",text: $email) .padding() .overlay(RoundedRectangle(cornerRadius: 5.0) .stroke(lineWidth: 1.0)) .padding(.bottom, 20) .autocapitalization(.none) SecureField("Password", text: $password) .padding() .overlay(RoundedRectangle(cornerRadius: 5.0) .stroke(lineWidth: 1.0)) .padding(.bottom, 20) SecureField("Confirm Password", text: $confirmpwd) .padding() .overlay(RoundedRectangle(cornerRadius: 5.0) .stroke(lineWidth: 1.0)) Button(action: { if(password == confirmpwd){ self.load.toggle() RealmRegister(email: email, password: password){ (success) -> Void in if success { self.load.toggle() self.alertItem = AlertItem(title: Text("Success"), message: Text("Created an account successfully! Kindly login with your credentials."), dismissButton: .default(Text("Done"), action: { self.presentationMode.wrappedValue.dismiss() })) } else { self.load.toggle() self.alertItem = AlertItem(title: Text("Error"), message: Text(e!), dismissButton: .default(Text("Done"))) } } } else { self.alertItem = AlertItem(title: Text("Error"), message: Text("Passwords do not match."), dismissButton: .default(Text("Done"))) } }) { if(load != true){ Text("Create an account") .padding(8) .frame(maxWidth: .infinity) .foregroundColor(.white) .padding(10) .overlay(RoundedRectangle(cornerRadius: 10) .stroke(lineWidth: 2.0) .shadow(color: .blue, radius: 10.0)) .background(RoundedRectangle(cornerRadius: 10).fill(Color.blue)) } else { HStack{ Spacer() ProgressView() Spacer() } .padding(8) .frame(maxWidth: .infinity) .foregroundColor(.white) .padding(10) .overlay(RoundedRectangle(cornerRadius: 10) .stroke(lineWidth: 2.0) .shadow(color: .gray, radius: 10.0)) .background(RoundedRectangle(cornerRadius: 10).fill(Color.gray)) .disabled(true) } } .padding(.top, 10) } .alert(item: $alertItem){ item in Alert(title: item.title, message: item.message, dismissButton: item.dismissButton) } .navigationTitle("Register") .padding() } } struct RegisterView_Previews: PreviewProvider { static var previews: some View { RegisterView() } }
37.448598
213
0.450711
1a6487bd3047b932233e201e70da556816477291
9,672
import UIKit public extension UIViewController { /// 添加子控制器 func addChildViewController(_ child: UIViewController, toContainerView containerView: UIView) { addChild(child) containerView.addSubview(child.view) child.didMove(toParent: self) } /// 移除子控制器 func removeChildViewController(_ child: UIViewController) { guard parent != nil else { return } child.willMove(toParent: nil) child.view.removeFromSuperview() child.removeFromParent() } /// push func pushViewController(_ controller: UIViewController) { self.navigationController?.pushViewController(controller, animated: true) } /// pop func popViewController() { self.navigationController?.popViewController(animated: true) } /// popToRoot func popToRootViewController() { self.navigationController?.popToRootViewController(animated: true) } /// pop到指定控制器 /// /// - Parameter backNum: 回退几个 大于栈中元素个数 会直接到根 func popToViewController(_ backNum: Int, animated: Bool? = true) { guard let vcs = self.navigationController?.viewControllers else { return } if vcs.count - 1 - backNum < 0 { self.navigationController?.popToRootViewController(animated: animated ?? true) return } let vc = vcs[vcs.count - 1 - backNum] self.navigationController?.popToViewController(vc, animated: animated ?? true) } /// pop到指定控制器 /// /// - Parameter index: 指定下标 func popToViewController(index: Int) { guard let vcs = self.navigationController?.viewControllers else { return } if index > vcs.count - 1 { return } let vc = vcs[index] self.navigationController?.popToViewController(vc, animated: true) } /// pop到指定控制器 /// /// - Paramete@objc r className: 指定控制器 func popToViewController(className: String) { guard let clsName: String = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String else { return } guard let vcs = self.navigationController?.viewControllers, let vc: AnyClass = NSClassFromString(clsName + "." + className) else { return } vcs.forEach { if $0.isKind(of: vc) { self.navigationController?.popToViewController($0, animated: true) } } } /// 模态跳转 func present(_ viewController: UIViewController) { self.navigationController?.present(viewController, animated: true, completion: nil) } /// 跨页面跳转 func resetVCS(backNum: Int? = 1, vc: UIViewController, animated: Bool? = true) { guard self.isPush(), let num = backNum, let vcArray = self.navigationController?.viewControllers else { return } if vcArray.count < num { return } var vcResult: [UIViewController] = vcArray for _ in 0..<num { vcResult.removeLast() } vcResult.append(vc) self.navigationController?.setViewControllers(vcResult, animated: animated ?? true) } /// 弹一个窗口 func presentPop(_ viewController : UIViewController) { viewController.modalTransitionStyle = .crossDissolve viewController.modalPresentationStyle = .overCurrentContext self.present(viewController, animated: true, completion: nil) } /// 模态返回 func dismiss() { self.navigationController?.dismiss(animated: true, completion: nil) } /// 判断当前控制器是不是push弹出 func isPush() -> Bool { guard let viewcontrollers = self.navigationController?.viewControllers else { return false } if viewcontrollers.count > 1 && viewcontrollers[viewcontrollers.count - 1] == self { return true } return false } /// pop 或 dismiss func backLastController() { if let navCtr = self.navigationController{ navCtr.popViewController(animated: true) }else{ self.dismiss(animated: true) } } /// 系统alertView func showAlertView(title: String? = nil, message: String? = nil, actionItems: [UIAlertAction]) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for action in actionItems { alertController.addAction(action) } self.present(alertController, animated: true, completion: nil) } /// 系统sheetView func showSheetView(title: String? = nil, message: String? = nil, actionItems: [UIAlertAction]) { let sheetController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) for action in actionItems { sheetController.addAction(action) } self.present(sheetController, animated: true, completion: nil) } /// 设置状态栏背景颜色 func setStatus(backgroundColor: UIColor) { if #available(iOS 13.0, *) { let barView = UIView(frame: UIApplication.shared.statusBarFrame) barView.backgroundColor = backgroundColor UIApplication.shared.keyWindow?.addSubview(barView) }else { let barWindow: UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView let barView: UIView = barWindow.value(forKey: "statusBar") as! UIView barView.backgroundColor = backgroundColor } } } public extension UIViewController { /// 监听键盘 func addKeyboardMonitor() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notifi:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notifi:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notifi: Notification) { if let nInfo = (notifi as Notification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { let frame = value.cgRectValue keyboardWillShowWithFrame(frame) } } @objc func keyboardWillHide(notifi: Notification) { if let nInfo = (notifi as Notification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { let frame = value.cgRectValue keyboardWillHideWithFrame(frame) } } @objc open func keyboardWillShowWithFrame(_ frame: CGRect) { } @objc open func keyboardWillHideWithFrame(_ frame: CGRect) { } } public extension UIViewController { enum ItemType { case leftItem case rightItem } /// 添加文字item func customTxtItem(type: ItemType, title: String, titleColor: UIColor? = UIColor.black, titleFont: UIFont? = UIFont.systemFont(ofSize: 15), action: Selector) -> UIBarButtonItem { let itemButton = UIButton(type: .custom) itemButton.setTitle(title, for: .normal) let appearanceNavBar = UINavigationBar.appearance() if titleColor != nil { itemButton.setTitleColor(titleColor, for: .normal) }else { if appearanceNavBar == NSNull() { itemButton.setTitleColor(titleColor, for: .normal) }else { itemButton.setTitleColor(appearanceNavBar.tintColor, for: .normal) } } itemButton.sizeToFit() itemButton.width = itemButton.width < 40 ? 40 : itemButton.width itemButton.height = itemButton.height < 40 ? 40 : itemButton.height itemButton.titleLabel?.font = titleFont switch type { case .leftItem: itemButton.contentHorizontalAlignment = .left case .rightItem: itemButton.contentHorizontalAlignment = .right } itemButton.addTarget(self, action: action, for: .touchUpInside) let item = UIBarButtonItem(customView: itemButton) return item } /// 添加图片item func customImgItem(type: ItemType, image: UIImage?, imageSize: CGSize? = CGSize(width: 40, height: 40), action: Selector) -> UIBarButtonItem { let itemButton = UIButton(type: .custom) itemButton.setImage(image, for: .normal) var imgSize = itemButton.imageView?.bounds.size if #available(iOS 11.0, *) { imgSize = itemButton.imageView?.bounds.size }else { imgSize = imageSize } if let imgS = imgSize, imgS.width < 40 { imgSize = CGSize(width: 40, height: 40) } itemButton.frame = CGRect.init(origin: CGPoint.zero, size: imgSize ?? CGSize(width: 40, height: 40)) switch type { case .leftItem: itemButton.contentHorizontalAlignment = .left case .rightItem: itemButton.contentHorizontalAlignment = .right } itemButton.addTarget(self, action: action, for: .touchUpInside) let item = UIBarButtonItem(customView: itemButton) return item } }
35.170909
161
0.596361
50f9d5395481684ae40d7978c5e602c352bb6277
1,193
// // MuscleAssert.swift // MuscleAssert // // Created by akuraru on 2016/12/17. // // class MUSDictionaryDiffer: MUSCustomDiffer { func match(left: Any, right: Any) -> Bool { return false } func diff(left: Any, right: Any, path: String?, delegatge: MUSDeepDiffProtocol) -> [MUSDifference] { return [] } } /* #import "MUSDictionaryDiffer.h" #import "MUSDifference.h" NS_ASSUME_NONNULL_BEGIN @implementation MUSDictionaryDiffer - (Class)matchClass { return [NSDictionary class]; } - (NSArray<MUSDifference *> *)diff:(id)left right:(id)right path:(nullable NSString *)path delegatge:(id<MUSDeepDiffProtocol>)delegate { NSSet *set = [NSSet setWithArray:[[right allKeys] arrayByAddingObjectsFromArray:[left allKeys]]]; NSMutableArray *result = [NSMutableArray array]; for (id key in set) { id rightValue = right[key]; id leftValue = left[key]; NSString *nextPath = path ? [path stringByAppendingFormat:@".%@", [key description]] : [key description]; [result addObjectsFromArray:[delegate diff:rightValue left:leftValue path:nextPath]]; } return [result copy]; } @end NS_ASSUME_NONNULL_END */
24.854167
136
0.679799
565f74946c452417ff670e5f421aea29fb807a59
4,421
// // SendBirdDelegateProxy+Calls.swift // SendBirdCombine // // The MIT License (MIT) // // Copyright (c) 2020 Velos Mobile LLC. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Combine import AVKit import SendBirdSDK import SendBirdCalls public enum SendBirdCallEvent { case startedRinging(DirectCall) } public enum DirectCallEvent { case established case connected case startedReconnecting case reconnected case remoteAudioSettingsChanged case remoteVideoSettingsChanged case audioDeviceChanged(AVAudioSession, AVAudioSessionRouteDescription, AVAudioSession.RouteChangeReason) case customItemsUpdated([String]) case customItemsDeleted([String]) case ended } struct DirectCallEventInfo { let call: DirectCall let event: DirectCallEvent } class SendBirdCallsDelegateProxy: NSObject { static let sharedInstance = SendBirdCallsDelegateProxy() let callPassthrough: PassthroughSubject<SendBirdCallEvent, Never> let directCallPassthrough: PassthroughSubject<DirectCallEventInfo, Never> deinit { SendBirdCall.removeAllDelegates() } override init() { callPassthrough = PassthroughSubject<SendBirdCallEvent, Never>() directCallPassthrough = PassthroughSubject<DirectCallEventInfo, Never>() super.init() SendBirdCall.addDelegate(self, identifier: "SendBirdCallDelegate") } } extension SendBirdCallsDelegateProxy: SendBirdCallDelegate { func didStartRinging(_ call: DirectCall) { callPassthrough.send(.startedRinging(call)) } } extension SendBirdCallsDelegateProxy: DirectCallDelegate { func didEstablish(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .established)) } func didConnect(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .connected)) } func didStartReconnecting(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .startedReconnecting)) } func didReconnect(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .reconnected)) } func didRemoteAudioSettingsChange(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .remoteAudioSettingsChanged)) } func didRemoteVideoSettingsChange(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .remoteVideoSettingsChanged)) } func didEnd(_ call: DirectCall) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .ended)) } func didAudioDeviceChange(_ call: DirectCall, session: AVAudioSession, previousRoute: AVAudioSessionRouteDescription, reason: AVAudioSession.RouteChangeReason) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .audioDeviceChanged(session, previousRoute, reason))) } func didUpdateCustomItems(call: DirectCall, updatedKeys: [String]) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .customItemsUpdated(updatedKeys))) } func didDeleteCustomItems(call: DirectCall, deletedKeys: [String]) { directCallPassthrough.send(DirectCallEventInfo(call: call, event: .customItemsDeleted(deletedKeys))) } }
35.943089
165
0.752318
e21860266ca3cf5770af1d042725d92db0094843
1,734
// // BFCoreApps.swift // buildflow-core: Collection of Apps // // Created by Roger Boesch on 03.10.17. // Copyright © 2017 Roger Boesch. All rights reserved. // import Foundation class BFCoreApps : BFCoreBaseCollection, BFCoreCollectionProtocol { private var _collection = Array<BFCoreApp>() // ------------------------------------------------------------------------- // MARK: - Access (Use protocl implemetation later) var count: Int { get { return _collection.count } } // ------------------------------------------------------------------------- var first: BFCoreApp? { get { if _collection.count > 0 { return _collection.first } return nil } } // ------------------------------------------------------------------------- func list() -> Array<BFCoreApp> { return _collection } // ------------------------------------------------------------------------- func clear() { _collection.removeAll() self.asState = .notLoaded } // ------------------------------------------------------------------------- func add(_ app: BFCoreApp) { _collection.append(app) } // ------------------------------------------------------------------------- func find(Id: String) -> BFCoreApp? { return first } // ------------------------------------------------------------------------- // MARK: - Dump func dump() { for app in _collection { app.dump() } } // ------------------------------------------------------------------------- }
24.083333
80
0.33045
5dc68628d9f40890f751649801f79ac6e05357f9
510
// // Created by Jim van Zummeren on 08/05/16. // Copyright © 2016 M2mobi. All rights reserved. // import Foundation public protocol UnderlineStylingRule : ItemStyling { var isUnderlined : Bool { get } } extension ItemStyling { func shouldFontBeUnderlined() -> Bool { for styling in stylingWithPrecedingStyling() { if let styling = styling as? UnderlineStylingRule { return styling.isUnderlined } } return false } }
22.173913
63
0.619608
1d3a389fa969932ace83ddd0efb2ed94d6dd9c2f
6,383
// // OrderTests.swift // Stripe // // Created by Andrew Edwards on 8/23/17. // // import XCTest @testable import Stripe @testable import Vapor class OrderTests: XCTestCase { let orderString = """ { "amount": 1500, "created": 1234567890, "currency": "usd", "id": "or_1BoJ2NKrZ43eBVAbFf4SZyvD", "items": [ { "amount": 1500, "currency": "usd", "description": "Gold Special", "object": "order_item", "parent": "sk_1BoJ2KKrZ43eBVAbu7ioKR0i", "quantity": null, "type": "sku" } ], "livemode": false, "metadata": { "hello": "world" }, "object": "order", "returns": { "data": [ { "amount": 1500, "created": 1234567890, "currency": "usd", "id": "orret_1BoJ2NKrZ43eBVAb8r8dx0GO", "items": [ { "amount": 1500, "currency": "usd", "description": "Gold Special", "object": "order_item", "parent": "sk_1BoJ2NKrZ43eBVAb4RD4HHuH", "quantity": null, "type": "sku" } ], "livemode": false, "object": "order_return", "order": "or_1BoJ2NKrZ43eBVAbSnN443id", "refund": "re_1BoJ2NKrZ43eBVAbop3rb4h1" } ], "has_more": false, "object": "list", "url": "/v1/order_returns?order=or_1BoJ2NKrZ43eBVAbFf4SZyvD" }, "shipping": { "address": { "city": "Anytown", "country": "US", "line1": "1234 Main street", "line2": "suite 123", "postal_code": "123456", "state": "AL" }, "carrier": "UPS", "name": "Jenny Rosen", "phone": null, "tracking_number": null }, "status": "created", "status_transitions": { "canceled": 1515290550, "fulfiled": 1507690550, "paid": 1517688550, "returned": 1927690550 }, "updated": 1234567890 } """ func testOrderIsProperlyParsed() throws { do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let body = HTTPBody(string: orderString) var headers: HTTPHeaders = [:] headers.replaceOrAdd(name: .contentType, value: MediaType.json.description) let request = HTTPRequest(headers: headers, body: body) let futureOrder = try decoder.decode(StripeOrder.self, from: request, maxSize: 65_536, on: EmbeddedEventLoop()) futureOrder.do { (order) in XCTAssertEqual(order.id, "or_1BoJ2NKrZ43eBVAbFf4SZyvD") XCTAssertEqual(order.amount, 1500) XCTAssertEqual(order.created, Date(timeIntervalSince1970: 1234567890)) XCTAssertEqual(order.currency, .usd) XCTAssertEqual(order.livemode, false) XCTAssertEqual(order.metadata?["hello"], "world") XCTAssertEqual(order.object, "order") XCTAssertEqual(order.status, .created) // This test covers the Order Item object XCTAssertEqual(order.statusTransitions?.canceled, Date(timeIntervalSince1970: 1515290550)) XCTAssertEqual(order.statusTransitions?.fulfiled, Date(timeIntervalSince1970: 1507690550)) XCTAssertEqual(order.statusTransitions?.paid, Date(timeIntervalSince1970: 1517688550)) XCTAssertEqual(order.statusTransitions?.returned, Date(timeIntervalSince1970: 1927690550)) XCTAssertEqual(order.updated, Date(timeIntervalSince1970: 1234567890)) XCTAssertEqual(order.items?[0].amount, 1500) XCTAssertEqual(order.items?[0].currency, .usd) XCTAssertEqual(order.items?[0].description, "Gold Special") XCTAssertEqual(order.items?[0].object, "order_item") XCTAssertEqual(order.items?[0].parent, "sk_1BoJ2KKrZ43eBVAbu7ioKR0i") XCTAssertEqual(order.items?[0].quantity, nil) XCTAssertEqual(order.items?[0].type, .sku) XCTAssertEqual(order.returns?.hasMore, false) XCTAssertEqual(order.returns?.object, "list") XCTAssertEqual(order.returns?.url, "/v1/order_returns?order=or_1BoJ2NKrZ43eBVAbFf4SZyvD") // This test covers the OrderItem Return object XCTAssertEqual(order.returns?.data?[0].amount, 1500) XCTAssertEqual(order.returns?.data?[0].created, Date(timeIntervalSince1970: 1234567890)) XCTAssertEqual(order.returns?.data?[0].currency, .usd) XCTAssertEqual(order.returns?.data?[0].id, "orret_1BoJ2NKrZ43eBVAb8r8dx0GO") XCTAssertEqual(order.returns?.data?[0].livemode, false) XCTAssertEqual(order.returns?.data?[0].object, "order_return") XCTAssertEqual(order.returns?.data?[0].order, "or_1BoJ2NKrZ43eBVAbSnN443id") XCTAssertEqual(order.returns?.data?[0].refund, "re_1BoJ2NKrZ43eBVAbop3rb4h1") XCTAssertEqual(order.shipping?.address?.city, "Anytown") XCTAssertEqual(order.shipping?.address?.country, "US") XCTAssertEqual(order.shipping?.address?.line1, "1234 Main street") XCTAssertEqual(order.shipping?.address?.line2, "suite 123") XCTAssertEqual(order.shipping?.address?.postalCode, "123456") XCTAssertEqual(order.shipping?.address?.state, "AL") XCTAssertEqual(order.shipping?.carrier, "UPS") XCTAssertEqual(order.shipping?.name, "Jenny Rosen") XCTAssertEqual(order.shipping?.phone, nil) XCTAssertEqual(order.shipping?.trackingNumber, nil) }.catch { (error) in XCTFail("\(error.localizedDescription)") } } catch { XCTFail("\(error.localizedDescription)") } } }
40.144654
123
0.546922
d97268d5d69815e12ac80ec52ffe341a7449f12f
1,222
// // BottomRightWidth.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct BottomRightWidth { let bottomRight: LayoutElement.Point let width: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.BottomRightWidth { private func makeFrame(bottomRight: Point, width: Float, height: Float) -> Rect { let x = bottomRight.x - width let y = bottomRight.y - height let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.BottomRightWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0)) let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(bottomRight: bottomRight, width: width, height: height) } }
23.056604
116
0.730769
ff1bde49d60c6e9a3ecea487e6ebf49799aac143
21,501
// RUN: %target-swift-emit-silgen -module-name default_arguments -Xllvm -sil-full-demangle -swift-version 4 %s | %FileCheck %s // RUN: %target-swift-emit-silgen -module-name default_arguments -Xllvm -sil-full-demangle -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE // __FUNCTION__ used as top-level parameter produces the module name. // CHECK-LABEL: sil [ossa] @main // CHECK: string_literal utf8 "default_arguments" // Default argument for first parameter. // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments7defarg11i1d1sySi_SdSStFfA_ : $@convention(thin) () -> Int // CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 17 // CHECK: [[INT:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[CVT:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[INT]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: return [[RESULT]] : $Int // Default argument for third parameter. // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments7defarg11i1d1sySi_SdSStFfA1_ : $@convention(thin) () -> @owned String // CHECK: [[LIT:%[0-9]+]] = string_literal utf8 "Hello" // CHECK: [[LEN:%[0-9]+]] = integer_literal $Builtin.Word, 5 // CHECK: [[STRING:%[0-9]+]] = metatype $@thin String.Type // CHECK: [[CVT:%[0-9]+]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[LEN]], {{[^,]+}}, [[STRING]]) : $@convention(method) // CHECK: return [[RESULT]] : $String func defarg1(i: Int = 17, d: Double, s: String = "Hello") { } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15testDefaultArg1yyF func testDefaultArg1() { // CHECK: [[FLOATLIT:%[0-9]+]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4009000000000000|0x4000C800000000000000}} // CHECK: [[FLOAT64:%[0-9]+]] = metatype $@thin Double.Type // CHECK: [[LITFN:%[0-9]+]] = function_ref @$sSd20_builtinFloatLiteralSdBf{{[_0-9]*}}__tcfC // CHECK: [[FLOATVAL:%[0-9]+]] = apply [[LITFN]]([[FLOATLIT]], [[FLOAT64]]) // CHECK: [[DEF0FN:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{.*}}A_ // CHECK: [[DEF0:%[0-9]+]] = apply [[DEF0FN]]() // CHECK: [[DEF2FN:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{.*}}A1_ // CHECK: [[DEF2:%[0-9]+]] = apply [[DEF2FN]]() // CHECK: [[FNREF:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FNREF]]([[DEF0]], [[FLOATVAL]], [[DEF2]]) defarg1(d:3.125) } func defarg2(_ i: Int, d: Double = 3.125, s: String = "Hello") { } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15testDefaultArg2{{[_0-9a-zA-Z]*}}F func testDefaultArg2() { // CHECK: [[INTLIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 5 // CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[LITFN:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC // CHECK: [[I:%[0-9]+]] = apply [[LITFN]]([[INTLIT]], [[INT64]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[DFN:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{.*}}A0_ : $@convention(thin) () -> Double // CHECK: [[D:%[0-9]+]] = apply [[DFN]]() : $@convention(thin) () -> Double // CHECK: [[SFN:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{.*}}A1_ : $@convention(thin) () -> @owned String // CHECK: [[S:%[0-9]+]] = apply [[SFN]]() : $@convention(thin) () -> @owned String // CHECK: [[FNREF:%[0-9]+]] = function_ref @$s17default_arguments7defarg2{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int, Double, @guaranteed String) -> () // CHECK: apply [[FNREF]]([[I]], [[D]], [[S]]) : $@convention(thin) (Int, Double, @guaranteed String) -> () defarg2(5) } func autocloseFile(x: @autoclosure () -> String = #file, y: @autoclosure () -> Int = #line) { } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments17testAutocloseFileyyF func testAutocloseFile() { // CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments17testAutocloseFileyyFSSyXEfu_ : $@convention(thin) () -> @owned String // CHECK: string_literal utf8{{.*}}default_arguments.swift // CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments17testAutocloseFileyyFSiyXEfu0_ : $@convention(thin) () -> Int // CHECK: integer_literal $Builtin.IntLiteral, [[@LINE+1]] autocloseFile() } func testMagicLiterals(file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) {} // Check that default argument generator functions don't leak information about // user's source. // // NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA_ // // NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA0_ // // NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA1_ // // NEGATIVE-NOT: sil hidden [ossa] @$s17default_arguments17testMagicLiteralsySS4file_SS8functionSi4lineSi6columntFfA2_ func closure(_: () -> ()) {} func autoclosure(_: @autoclosure () -> ()) {} // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyF // CHECK: string_literal utf8 "testCallWithMagicLiterals()" // CHECK: string_literal utf8 "testCallWithMagicLiterals()" // CHECK-LABEL: sil private [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyFyyXEfU_ // CHECK: string_literal utf8 "testCallWithMagicLiterals()" // CHECK-LABEL: sil private [transparent] [ossa] @$s17default_arguments25testCallWithMagicLiteralsyyFyyXEfu_ // CHECK: string_literal utf8 "testCallWithMagicLiterals()" func testCallWithMagicLiterals() { testMagicLiterals() testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testPropWithMagicLiteralsSivg // CHECK: string_literal utf8 "testPropWithMagicLiterals" var testPropWithMagicLiterals: Int { testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) return 0 } class Foo { // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooC3int6stringACSi_SStcfc : $@convention(method) (Int, @owned String, @owned Foo) -> @owned Foo // CHECK: string_literal utf8 "init(int:string:)" init(int: Int, string: String = #function) { testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooCfd // CHECK: string_literal utf8 "deinit" deinit { testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments3FooCyS2icig // CHECK: string_literal utf8 "subscript(_:)" subscript(x: Int) -> Int { testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) return x } // CHECK-LABEL: sil private [ossa] @globalinit_33_E52D764B1F2009F2390B2B8DF62DAEB8_func0 // CHECK: string_literal utf8 "Foo" static let x = Foo(int:0) } // Test at top level. testMagicLiterals() closure { testMagicLiterals() } autoclosure(testMagicLiterals()) // CHECK: string_literal utf8 "default_arguments" let y : String = #function // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments16testSelectorCall_17withMagicLiteralsySi_SitF // CHECK: string_literal utf8 "testSelectorCall(_:withMagicLiterals:)" func testSelectorCall(_ x: Int, withMagicLiterals y: Int) { testMagicLiterals() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments32testSelectorCallWithUnnamedPieceyySi_SitF // CHECK: string_literal utf8 "testSelectorCallWithUnnamedPiece(_:_:)" func testSelectorCallWithUnnamedPiece(_ x: Int, _ y: Int) { testMagicLiterals() } // Test default arguments in an inherited subobject initializer class SuperDefArg { init(int i: Int = 10) { } } // CHECK: sil hidden [ossa] @$s17default_arguments11SuperDefArgC3intACSi_tcfcfA_ : $@convention(thin) () -> Int // CHECK-NOT: sil hidden [ossa] @$s17default_arguments9SubDefArgCAC3intSi_tcfcfA_ : $@convention(thin) () -> Int class SubDefArg : SuperDefArg { } // CHECK: sil hidden [ossa] @$s17default_arguments13testSubDefArgAA0deF0CyF : $@convention(thin) () -> @owned SubDefArg func testSubDefArg() -> SubDefArg { // CHECK: function_ref @$s17default_arguments11SuperDefArgC3intACSi_tcfcfA_ // CHECK: function_ref @$s17default_arguments9SubDefArgC{{[_0-9a-zA-Z]*}}fC // CHECK: return return SubDefArg() } // CHECK-NOT: sil hidden [ossa] @$s17default_arguments9SubDefArgCACSi3int_tcfcfA_ : $@convention(thin) () -> Int // <rdar://problem/17379550> func takeDefaultArgUnnamed(_ x: Int = 5) { } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments25testTakeDefaultArgUnnamed{{[_0-9a-zA-Z]*}}F func testTakeDefaultArgUnnamed(_ i: Int) { // CHECK: bb0([[I:%[0-9]+]] : $Int): // CHECK: [[FN:%[0-9]+]] = function_ref @$s17default_arguments21takeDefaultArgUnnamedyySiF : $@convention(thin) (Int) -> () // CHECK: apply [[FN]]([[I]]) : $@convention(thin) (Int) -> () takeDefaultArgUnnamed(i) } func takeDSOHandle(_ handle: UnsafeRawPointer = #dsohandle) { } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments13testDSOHandleyyF func testDSOHandle() { // CHECK: [[DSO_HANDLE:%[0-9]+]] = global_addr {{@__dso_handle|@__ImageBase}} : $*Builtin.RawPointer takeDSOHandle() } // Test __FUNCTION__ in an extension initializer. rdar://problem/19792181 extension SuperDefArg { static let extensionInitializerWithClosure: Int = { return 22 }() } // <rdar://problem/19086357> SILGen crashes reabstracting default argument closure in members class ReabstractDefaultArgument<T> { init(a: (T, T) -> Bool = { _, _ in true }) { } } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments32testDefaultArgumentReabstractionyyF // function_ref default_arguments.ReabstractDefaultArgument.__allocating_init <A>(default_arguments.ReabstractDefaultArgument<A>.Type)(a : (A, A) -> Swift.Bool) -> default_arguments.ReabstractDefaultArgument<A> // CHECK: [[FN:%.*]] = function_ref @$s17default_arguments25ReabstractDefaultArgument{{.*}} : $@convention(thin) <τ_0_0> () -> @owned @callee_guaranteed (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Int>() : $@convention(thin) <τ_0_0> () -> @owned @callee_guaranteed (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool // CHECK-NEXT: function_ref reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Swift.Int, @in_guaranteed Swift.Int) -> (@unowned Swift.Bool) to @escaping @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> (@unowned Swift.Bool) // CHECK-NEXT: [[THUNK:%.*]] = function_ref @$sS2iSbIegnnd_S2iSbIegyyd_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Int, @in_guaranteed Int) -> Bool) -> Bool // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[RESULT]]) : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Int, @in_guaranteed Int) -> Bool) -> Bool // CHECK-NEXT: [[CONV_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[FN]] // function_ref reabstraction thunk helper from @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> (@unowned Swift.Bool) to @callee_guaranteed (@in_guaranteed Swift.Int, @in_guaranteed Swift.Int) -> (@unowned Swift.Bool) // CHECK: [[THUNK:%.*]] = function_ref @$sS2iSbIgyyd_S2iSbIegnnd_TR : $@convention(thin) (@in_guaranteed Int, @in_guaranteed Int, @noescape @callee_guaranteed (Int, Int) -> Bool) -> Bool // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CONV_FN]]) : $@convention(thin) (@in_guaranteed Int, @in_guaranteed Int, @noescape @callee_guaranteed (Int, Int) -> Bool) -> Bool // CHECK-NEXT: [[CONV_FN:%.*]] = convert_escape_to_noescape [not_guaranteed] [[FN]] // CHECK: [[INITFN:%[0-9]+]] = function_ref @$s17default_arguments25ReabstractDefaultArgumentC{{[_0-9a-zA-Z]*}}fC // CHECK-NEXT: apply [[INITFN]]<Int>([[CONV_FN]], func testDefaultArgumentReabstraction() { _ = ReabstractDefaultArgument<Int>() } // <rdar://problem/20494437> SILGen crash handling default arguments // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments18r20494437onSuccessyyAA25r20494437ExecutionContext_pF // CHECK: function_ref @$s17default_arguments19r20494437onCompleteyyAA25r20494437ExecutionContext_pF // <rdar://problem/20494437> SILGen crash handling default arguments protocol r20494437ExecutionContext {} let r20494437Default: r20494437ExecutionContext func r20494437onComplete(_ executionContext: r20494437ExecutionContext = r20494437Default) {} func r20494437onSuccess(_ a: r20494437ExecutionContext) { r20494437onComplete(a) } // <rdar://problem/18400194> Parenthesized function expression crashes the compiler func r18400194(_ a: Int, x: Int = 97) {} // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments9r18400194_1xySi_SitFfA0_ // CHECK: integer_literal $Builtin.IntLiteral, 97 // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments14test_r18400194yyF // CHECK: integer_literal $Builtin.IntLiteral, 1 // CHECK: function_ref @$s17default_arguments9r18400194_1xySi_SitFfA0_ : $@convention(thin) () -> Int // CHECK: function_ref @$s17default_arguments9r18400194_1xySi_SitF : $@convention(thin) (Int, Int) -> (){{.*}} func test_r18400194() { (r18400194)(1) } // rdar://24242783 // Don't add capture arguments to local default argument generators. func localFunctionWithDefaultArg() { var z = 5 func bar(_ x: Int? = nil) { z += 1 } bar() } // CHECK-LABEL: sil private [ossa] @$s17default_arguments27localFunctionWithDefaultArgyyF3barL_yySiSgFfA_ // CHECK-SAME: $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15throwingDefault7closureySbyKXE_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) func throwingDefault(closure: () throws -> Bool = { return true }) throws { try _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) func throwingAutoclosureDefault(closure: @autoclosure () throws -> Bool = true ) throws { try _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments0A3Arg7closureySbyXE_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool func defaultArg(closure: () -> Bool = { return true }) { _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool func autoclosureDefaultArg(closure: @autoclosure () -> Bool = true ) { _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) func throwingDefaultEscaping(closure: @escaping () throws -> Bool = { return true }) throws { try _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) func throwingAutoclosureDefaultEscaping(closure: @escaping @autoclosure () throws -> Bool = true ) throws { try _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments0A8Escaping7closureySbyc_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool func defaultEscaping(closure: @escaping () -> Bool = { return true }) { _ = closure() } // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool { func autoclosureDefaultEscaping(closure: @escaping @autoclosure () -> Bool = true ) { _ = closure() } // CHECK-LABEL: sil hidden [ossa] @{{.*}}callThem{{.*}} : $@convention(thin) () -> @error Error // CHECK: [[F:%.*]] = function_ref @$s17default_arguments15throwingDefault7closureySbyKXE_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]] // CHECK: [[R:%.*]] = function_ref @$s17default_arguments15throwingDefault7closureySbyKXE_tKF : $@convention(thin) (@noescape @callee_guaranteed () -> (Bool, @error Error)) -> @error Error // CHECK: try_apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]] // CHECK: [[R:%.*]] = function_ref @$s17default_arguments26throwingAutoclosureDefault7closureySbyKXK_tKF : $@convention(thin) (@noescape @callee_guaranteed () -> (Bool, @error Error)) -> @error Error // CHECK: try_apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments0A3Arg7closureySbyXE_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]] // CHECK: [[R:%.*]] = function_ref @$s17default_arguments0A3Arg7closureySbyXE_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Bool) -> () // CHECK: apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Boo // CHECK: [[C:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[E:%.*]] = convert_escape_to_noescape [not_guaranteed] [[C]] // CHECK: [[R:%.*]] = function_ref @$s17default_arguments21autoclosureDefaultArg7closureySbyXK_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Bool) -> () // CHECK: apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[R:%.*]] = function_ref @$s17default_arguments23throwingDefaultEscaping7closureySbyKc_tKF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Bool, @error Error)) -> @error Erro // CHECK: try_apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> (Bool, @error Error) // CHECK: [[R:%.*]] = function_ref @$s17default_arguments34throwingAutoclosureDefaultEscaping7closureySbyKXA_tKF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Bool, @error Error)) -> @error Error // CHECK: try_apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments0A8Escaping7closureySbyc_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[R:%.*]] = function_ref @$s17default_arguments0A8Escaping7closureySbyc_tF : $@convention(thin) (@guaranteed @callee_guaranteed () -> Bool) -> () // CHECK: apply [[R]]([[E]]) // CHECK: [[F:%.*]] = function_ref @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tFfA_ : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[E:%.*]] = apply [[F]]() : $@convention(thin) () -> @owned @callee_guaranteed () -> Bool // CHECK: [[R:%.*]] = function_ref @$s17default_arguments26autoclosureDefaultEscaping7closureySbyXA_tF : $@convention(thin) (@guaranteed @callee_guaranteed () -> Bool) -> () // CHECK: apply [[R]]([[E]]) func callThem() throws { try throwingDefault() try throwingAutoclosureDefault() defaultArg() autoclosureDefaultArg() try throwingDefaultEscaping() try throwingAutoclosureDefaultEscaping() defaultEscaping() autoclosureDefaultEscaping() } func tupleDefaultArg(x: (Int, Int) = (1, 2)) {} // CHECK-LABEL: sil hidden [ossa] @$s17default_arguments19callTupleDefaultArgyyF : $@convention(thin) () -> () // CHECK: function_ref @$s17default_arguments15tupleDefaultArg1xySi_Sit_tFfA_ : $@convention(thin) () -> (Int, Int) // CHECK: function_ref @$s17default_arguments15tupleDefaultArg1xySi_Sit_tF : $@convention(thin) (Int, Int) -> () // CHECK: return func callTupleDefaultArg() { tupleDefaultArg() } // FIXME: Should this be banned? func stupidGames(x: Int = 3) -> Int { return x } stupidGames(x:)() func genericMagic<T : ExpressibleByStringLiteral>(x: T = #file) -> T { return x } let _: String = genericMagic()
54.84949
264
0.700014
46d5112cf321b16f68a32fc7686c262183c3fa68
538
// swift-tools-version: 5.6 import PackageDescription let package = Package( name: "PluginWithInternalExecutable", products: [ .plugin( name: "PluginScriptProduct", targets: ["PluginScriptTarget"] ), ], targets: [ .plugin( name: "PluginScriptTarget", capability: .buildTool(), dependencies: [ "PluginExecutable", ] ), .executableTarget( name: "PluginExecutable" ), ] )
21.52
43
0.505576
fec37cf4b2fe1e9d46d731f0c29ad7b9f59686e7
1,923
import Foundation final class AtomicBuckets: CustomStringConvertible { var count: Int { return buckets.count } var description: String { return withBucketsLocked { "\(buckets)" } } var total: Int { return withBucketsLocked { buckets.reduce(0, +) } } private let lock = DispatchSemaphore(value: 1) private var buckets: [Int] subscript(n: Int) -> Int { return withBucketsLocked { buckets[n] } } init(with buckets: [Int]) { self.buckets = buckets } func transfer(amount: Int, from: Int, to: Int) { withBucketsLocked { let transferAmount = buckets[from] >= amount ? amount : buckets[from] buckets[from] -= transferAmount buckets[to] += transferAmount } } private func withBucketsLocked<T>(do: () -> T) -> T { let ret: T lock.wait() ret = `do`() lock.signal() return ret } } let bucks = AtomicBuckets(with: [21, 39, 40, 20]) let order = DispatchSource.makeTimerSource() let chaos = DispatchSource.makeTimerSource() let printer = DispatchSource.makeTimerSource() printer.setEventHandler { print("\(bucks) = \(bucks.total)") } printer.schedule(deadline: .now(), repeating: .seconds(1)) printer.activate() order.setEventHandler { let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count)) let (v1, v2) = (bucks[b1], bucks[b2]) guard v1 != v2 else { return } if v1 > v2 { bucks.transfer(amount: (v1 - v2) / 2, from: b1, to: b2) } else { bucks.transfer(amount: (v2 - v1) / 2, from: b2, to: b1) } } order.schedule(deadline: .now(), repeating: .milliseconds(5)) order.activate() chaos.setEventHandler { let (b1, b2) = (Int.random(in: 0..<bucks.count), Int.random(in: 0..<bucks.count)) bucks.transfer(amount: Int.random(in: 0..<(bucks[b1] + 1)), from: b1, to: b2) } chaos.schedule(deadline: .now(), repeating: .milliseconds(5)) chaos.activate() dispatchMain()
21.852273
83
0.642226
bb94a04e5555f27a89a7ffa1e1a1ff478c0520df
5,136
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material import Motion class PhotoViewController: UIViewController { fileprivate var closeButton: IconButton! fileprivate var collectionView: UICollectionView! fileprivate var index: Int var dataSourceItems = [DataSourceItem]() public required init?(coder aDecoder: NSCoder) { index = 0 super.init(coder: aDecoder) } public init(index: Int) { self.index = index super.init(nibName: nil, bundle: nil) } open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white prepareCloseButton() preparePhotos() prepareCollectionView() prepareToolbar() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } } extension PhotoViewController { func prepareCloseButton() { closeButton = IconButton(image: Icon.cm.close) closeButton.addTarget(self, action: #selector(handleCloseButton(button:)) , for: .touchUpInside) } fileprivate func preparePhotos() { PhotosDataSource.forEach { [weak self, w = view.bounds.width] in guard let image = UIImage(named: $0) else { return } self?.dataSourceItems.append(DataSourceItem(data: image, width: w)) } } fileprivate func prepareCollectionView() { let w = view.bounds.width let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: w, height: w) collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = .clear collectionView.dataSource = self collectionView.delegate = self collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCollectionViewCell") view.layout(collectionView).center(offsetY: -44).width(w).height(w) collectionView.scrollRectToVisible(CGRect(x: w * CGFloat(index), y: 0, width: w, height: w), animated: false) } func prepareToolbar() { guard let toolbar = toolbarController?.toolbar else { return } toolbar.titleLabel.text = "Photo Name" toolbar.detailLabel.text = "July 19 2017" toolbar.leftViews = [closeButton] } } extension PhotoViewController: CollectionViewDataSource { @objc open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } @objc open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSourceItems.count } @objc open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as! PhotoCollectionViewCell guard let image = dataSourceItems[indexPath.item].data as? UIImage else { return cell } cell.imageView.image = image cell.imageView.motionIdentifier = "photo_\(indexPath.item)" return cell } } extension PhotoViewController: CollectionViewDelegate {} fileprivate extension PhotoViewController { @objc func handleCloseButton(button: UIButton) { toolbarController?.transition(to: PhotoCollectionViewController()) } }
34.013245
141
0.737928
2620ff42a5b02e64d880c17b1117935adbc1b1ab
465
// // SwiftUI_AnimationApp.swift // SwiftUI-Animation // // Created by Finsi Ennes on 24/11/2020. // import SwiftUI @main struct SwiftUI_AnimationApp: App { var body: some Scene { WindowGroup { ZStack { //darkGray.edgesIgnoringSafeArea(.all) VStack { Spacer() PageControlPreview() Spacer() } } } } }
16.034483
54
0.466667
e93fadcd7697b66b989761439fd38454e4baca58
3,774
// // GeometryFilter.swift // SCNRecorder // // Created by Vladislav Grigoryev on 11/03/2019. // Copyright © 2020 GORA Studio. https://gora.studio // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation ///CICategoryGeometryAdjustment enum GeometryFilter { ///CIAffineTransform case affineTransform(transform: CGAffineTransform) ///CICrop case crop(rectangle: CGRect) ///CILanczosScaleTransform case lanczosScale(scale: CGFloat, aspectRatio: CGFloat) ///CIPerspectiveCorrection case perspectiveCorrection( topLeft: CGPoint, topRight: CGPoint, bottomRight: CGPoint, bottomLeft: CGPoint ) ///CIPerspectiveTransform case perspectiveTransform( topLeft: CGPoint, topRight: CGPoint, bottomRight: CGPoint, bottomLeft: CGPoint ) ///CIPerspectiveTransformWithExtent case perspectiveTransformWithExtent( extent: CGRect, topLeft: CGPoint, topRight: CGPoint, bottomRight: CGPoint, bottomLeft: CGPoint ) ///CIStraightenFilter case strainghten(angle: CGFloat) } extension GeometryFilter: Filter { public var inputKeys: [String] { return (try? makeCIFilter().inputKeys) ?? [] } public var name: String { switch self { case .affineTransform: return "CIAffineTransform" case .crop: return "CICrop" case .lanczosScale: return "CILanczosScaleTransform" case .perspectiveCorrection: return "CIPerspectiveCorrection" case .perspectiveTransform: return "CIPerspectiveTransform" case .perspectiveTransformWithExtent: return "CIPerspectiveTransformWithExtent" case .strainghten: return "CIStraightenFilter" } } public func makeCIFilter() throws -> CIFilter { guard let filter = CIFilter(name: name) else { throw Error.notFound } switch self { case .affineTransform(let transform): try filter.setAffineTransform(transform) case .crop(let rectangle): try filter.setRectangle(rectangle) case .lanczosScale(let scale, let aspectRatio): try filter.setScale(scale) try filter.setAspectRatio(aspectRatio) case .perspectiveTransformWithExtent( let extent, let topLeft, let topRight, let bottomRight, let bottomLeft ): try filter.setExtent(extent) fallthrough case .perspectiveCorrection(let topLeft, let topRight, let bottomRight, let bottomLeft), .perspectiveTransform(let topLeft, let topRight, let bottomRight, let bottomLeft): try filter.setTopLeft(topLeft) try filter.setTopRight(topRight) try filter.setBottomRight(bottomRight) try filter.setBottomLeft(bottomLeft) case .strainghten(let angle): try filter.setAngle(angle) } return filter } }
30.682927
92
0.728935
fc49ed3651cae70684e340bcc4e02249c60b7c24
853
// // BundleUtil.swift // PasswordTextField // // Created by Chris Jimenez on 2/12/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation /// Get the Pod Bundle open class BundleUtil:NSObject{ /// Gets the bundle property for the pod public static var bundle:Bundle{ get{ //Get the bundle var bundle = Bundle(for: self.classForCoder()) //Trys to load the path to resource(In case we are calling this from the pod) if let bundlePath:String = bundle.path(forResource: "PasswordTextField", ofType: "bundle") { //If we get the path to resource, set the bundle path bundle = Bundle(path: bundlePath)! } return bundle } } }
22.447368
102
0.556858
5bc51e2ed95b17f0fb28e0125377a659c3479183
7,577
// // MoviesViewController.swift // MovieViewer // // Created by Brandon Arroyo on 1/17/16. // Copyright © 2016 Brandon Arroyo. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD class MoviesViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! // This is where we will be storying the json that we retrieved var movies = [NSDictionary]() var dataTest: [String]! var filteredData: [String]! var endPoint: String! //------------------------------------------------------------------------------ override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self loadDataFromNetwork() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged) collectionView.insertSubview(refreshControl, atIndex: 0) } //------------------------------------------------------------------------------ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //------------------------------------------------------------------------------ @available(iOS 6.0, *) internal func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return movies.count } //------------------------------------------------------------------------------ @available(iOS 6.0, *) public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCell",forIndexPath: indexPath) as! MovieCell let movie = movies[indexPath.row] let title = movie["title"] as! String let overview = movie["overview"] as! String if let posterPath = movie["poster_path"] as? String{ let baseURL = "http://image.tmdb.org/t/p/w500/" let imageURL = NSURL(string: baseURL + posterPath) // cell.poserView.setImageWithURL(imageURL!) let imageRequest = NSURLRequest(URL: imageURL!) cell.poserView.setImageWithURLRequest( imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in // imageResponse will be nil if the image is cached if imageResponse != nil { print("Image was NOT cached, fade in image") cell.poserView.alpha = 0.0 cell.poserView.image = image UIView.animateWithDuration(0.3, animations: { () -> Void in cell.poserView.alpha = 1.0 }) } else { print("Image was cached so just update the image") cell.poserView.image = image } }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition }) } print("row \(indexPath.row)") return cell } //------------------------------------------------------------------------------ func loadDataFromNetwork() { // ... Create the NSURLRequest (myRequest) ... let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = NSURL(string:"https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)") let myRequest = NSURLRequest(URL: url!) // Configure session so that completion handler is executed on main UI thread let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) // Display HUD right before the request is made MBProgressHUD.showHUDAddedTo(self.view, animated: true) let task : NSURLSessionDataTask = session.dataTaskWithRequest(myRequest, completionHandler: { (dataOrNil, response, error) in // Hide HUD once the network request comes back (must be done on main UI thread) MBProgressHUD.hideHUDForView(self.view, animated: true) if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { self.movies = responseDictionary["results"] as! [NSDictionary] self.collectionView.reloadData() } } }); task.resume() } //------------------------------------------------------------------------------ func refreshControlAction(refreshControl: UIRefreshControl) { // ... Create the NSURLRequest (myRequest) ... let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = NSURL(string:"https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)") let myRequest = NSURLRequest(URL: url!) // Configure session so that completion handler is executed on main UI thread let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) let task : NSURLSessionDataTask = session.dataTaskWithRequest(myRequest, completionHandler: { (dataOrNil, response, error) in // ... Use the new data to update the data source ... if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { NSLog("response: \(responseDictionary)") self.movies = responseDictionary["results"] as! [NSDictionary] self.collectionView.reloadData() } } // Reload the tableView now that there is new data self.collectionView.reloadData() // Tell the refreshControl to stop spinning refreshControl.endRefreshing() }); task.resume() } //------------------------------------------------------------------------------ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let cell = sender as! UICollectionViewCell let indexPath = collectionView.indexPathForCell(cell) let movie = movies[indexPath!.row] let detailViewController = segue.destinationViewController as! DetailViewController detailViewController.movies = movie } } //------------------------------------------------------------------------------
40.736559
136
0.536624
6aabe672f5348fe071b25d9e1814a46452d88766
188
import App import Vapor var env = try Environment.detect() try LoggingSystem.bootstrap(from: &env) let app = Application(env) defer { app.shutdown() } try configure(app) try app.run()
14.461538
39
0.734043
38ed3d554c26b67ff167931feb960ca095915444
4,173
// // CommentTableViewCell.swift // Hackers2 // // Created by Weiran Zhang on 07/06/2014. // Copyright (c) 2014 Glass Umbrella. All rights reserved. // import Foundation import UIKit class CommentTableViewCell : UITableViewCell { var delegate: CommentDelegate? var level: Int = 0 { didSet { updateIndentPadding() } } var comment: CommentModel? { didSet { guard let comment = comment else { return } updateCommentContent(with: comment) } } @IBOutlet var commentTextView: TouchableTextView! @IBOutlet var authorLabel : UILabel! @IBOutlet var datePostedLabel : UILabel! @IBOutlet var leftPaddingConstraint : NSLayoutConstraint! @IBOutlet weak var separatorView: UIView! override func awakeFromNib() { super.awakeFromNib() setupTheming() contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CommentTableViewCell.cellTapped))) } @objc func cellTapped() { delegate?.commentTapped(self) setSelected(!isSelected, animated: false) } func updateIndentPadding() { let levelIndent = 15 let padding = CGFloat(levelIndent * (level + 1)) leftPaddingConstraint.constant = padding } func updateCommentContent(with comment: CommentModel) { let isCollapsed = comment.visibility != .visible level = comment.level authorLabel.text = comment.authorUsername authorLabel.font = AppFont.commentUsernameFont(collapsed: isCollapsed) datePostedLabel.text = comment.dateCreatedString datePostedLabel.font = AppFont.commentDateFont(collapsed: isCollapsed) if let commentTextView = commentTextView, comment.visibility == .visible { // only for expanded comments let commentFont = UIFont.preferredFont(forTextStyle: .subheadline) let commentTextColor = AppThemeProvider.shared.currentTheme.textColor let commentAttributedString = NSMutableAttributedString(string: comment.text.parsedHTML()) let commentRange = NSMakeRange(0, commentAttributedString.length) commentAttributedString.addAttribute(NSAttributedString.Key.font, value: commentFont, range: commentRange) commentAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: commentTextColor, range: commentRange) commentTextView.attributedText = commentAttributedString } } } extension CommentTableViewCell: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { if let delegate = delegate { delegate.linkTapped(URL, sender: textView) return false } return true } } extension CommentTableViewCell { override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) selected ? setSelectedBackground() : setUnselectedBackground() } override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) highlighted ? setSelectedBackground() : setUnselectedBackground() } func setSelectedBackground() { backgroundColor = AppThemeProvider.shared.currentTheme.cellHighlightColor } func setUnselectedBackground() { backgroundColor = AppThemeProvider.shared.currentTheme.backgroundColor } } extension CommentTableViewCell: Themed { func applyTheme(_ theme: AppTheme) { backgroundColor = theme.backgroundColor if commentTextView != nil { commentTextView.tintColor = theme.appTintColor } if authorLabel != nil { authorLabel.textColor = theme.titleTextColor } if datePostedLabel != nil { datePostedLabel.textColor = theme.lightTextColor } if separatorView != nil { separatorView.backgroundColor = theme.separatorColor } } }
34.487603
134
0.673137
cc508abb2a00d15a613ac190c25b699fae1b6921
6,551
// // AppDelegate.swift // DDDestroyer // // Created by Rafaj Design on 22/03/2017. // Copyright © 2017 Rafaj Design. All rights reserved. // import Cocoa import AppKit import Reloaded import SwiftShell import SwiftGit2 @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var statusItem: NSStatusItem? var menuItems: [NSMenuItem] = [] var subDirectories: [URL] = [] // MARK: Application delegate methods func applicationDidFinishLaunching(_ aNotification: Notification) { self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) self.statusItem?.image = NSImage(named: "icon") self.statusItem?.image?.isTemplate = true self.statusItem?.image?.size = CGSize(width: 16, height: 16) self.statusItem?.action = #selector(didTapStatusBarIcon) } let subsAsCatsKey = "SubsAsCats" @objc func didTapStatusBarIcon() { let menu: NSMenu = NSMenu() var item = NSMenuItem(title: "Configuration", action: nil, keyEquivalent: "") let configuration = NSMenu() // Use subfolders as categories let prefix: String let subEnabled = UserDefaults.standard.bool(forKey: subsAsCatsKey) if subEnabled { prefix = "✔ " } else { prefix = "" } var config = NSMenuItem(title: prefix + "Use subfolders as categories", action: #selector(toggleSubfolders(_:)), keyEquivalent: "") configuration.addItem(config) // Load all projects let projects = Project.all() // Remove all projects from the app let selector: Selector? if projects.count > 0 { selector = #selector(removeAllProjects(_:)) } else { selector = nil } config = NSMenuItem(title: "Remove all projects at once ...", action: selector, keyEquivalent: "") configuration.addItem(config) // Go to github homepage config = NSMenuItem(title: "Github.com homepage ...", action: #selector(goHome(_:)), keyEquivalent: "") configuration.addItem(config) item.submenu = configuration menu.addItem(item) menu.addItem(.separator()) // Add projects if projects.count > 0 { menu.add(projects: projects) menu.addItem(.separator()) } // Add new project item = NSMenuItem(title: "Add projects ...", action: #selector(addProject(_:)), keyEquivalent: "a") menu.addItem(item) menu.addItem(.separator()) // Quit app item = NSMenuItem(title: "Quit", action: #selector(exit(_:)), keyEquivalent: "q") menu.addItem(item) self.statusItem?.popUpMenu(menu) } // MARK: Actions @objc func commit(_ sender: NSMenuItem) { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: "Commit Window Controller") as! NSWindowController guard let path = sender.project.path else { return } var context = CustomContext() context.currentdirectory = path if let commitWindow = windowController.window { let controller = commitWindow.contentViewController as! CommitViewController controller.project = sender.project controller.cancel = { windowController.close() } controller.stageAll = { try? context.runAndPrint("git", "add", ".", "-A") } controller.commit = { commitMessage in try? context.runAndPrint("git", "commit", "-m", commitMessage) } NSApplication.shared.runModal(for: commitWindow) commitWindow.close() } } @objc func open(_ sender: NSMenuItem) { guard let path = sender.project.path else { return } NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: path) } @objc func fetch(_ sender: NSMenuItem) { guard let path = sender.project.path else { return } // TODO: Refactor all these custom context stuff!!!! var context = CustomContext() context.currentdirectory = path try? context.runAndPrint("git", "push") } @objc func push(_ sender: NSMenuItem) { guard let path = sender.project.path else { return } var context = CustomContext() context.currentdirectory = path try? context.runAndPrint("git", "push") } @objc func pull(_ sender: NSMenuItem) { guard let path = sender.project.path else { return } var context = CustomContext() context.currentdirectory = path try? context.runAndPrint("git", "pull") } @objc func revealInFinder(_ sender: NSMenuItem) { guard let info = sender.representedObject as? FileInfo else { return } NSWorkspace.shared.selectFile(info.fullPath, inFileViewerRootedAtPath: info.fullPath) } @objc func removeProject(_ sender: NSMenuItem) { Projects.remove(sender.project) } @objc func removeAllProjects(_ sender: NSMenuItem) { let alert = NSAlert() alert.messageText = "Confirmation" alert.informativeText = "Are you really sure? Like really, really sure?!" alert.addButton(withTitle: "Yes") alert.addButton(withTitle: "No") if alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn { Projects.removeAllProjects() } } @objc func toggleSubfolders(_ sender: NSMenuItem) { let subEnabled = UserDefaults.standard.bool(forKey: subsAsCatsKey) UserDefaults.standard.set(!subEnabled, forKey: subsAsCatsKey) UserDefaults.standard.synchronize() } @objc func goHome(_ sender: NSMenuItem) { guard let url = URL(string: "https://github.com/LiveUI/SwiftGit") else { return } NSWorkspace.shared.open(url) } @objc func addProject(_ sender: NSMenuItem) { Projects.addProject() } @objc func exit(_ sender: NSMenuItem) { NSApplication.shared.terminate(self) } }
32.112745
139
0.598077
61706d1ac93ffc9f9156ff3738d922223f321cc0
621
// // ZSFloatingViewController.swift // zhuishushenqi // // Created by daye on 2021/6/9. // Copyright © 2021 QS. All rights reserved. // import UIKit class ZSFloatingViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear } override var prefersStatusBarHidden: Bool { return KeyWindow?.rootViewController?.prefersStatusBarHidden ?? true } override var preferredStatusBarStyle: UIStatusBarStyle { return KeyWindow?.rootViewController?.preferredStatusBarStyle ?? .lightContent } }
23
86
0.703704
186f73da413446847b6f9c874c6e0a36c9ba14f8
1,270
// // ViewController.swift // SearchBar in TableView // // Created by Satori Maru on 16.12.08. // Copyright © 2016年 Satori Maru. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 80 tableView.estimatedRowHeight = tableView.rowHeight tableView.contentInset = UIEdgeInsets(top: -searchBar.frame.size.height, left: 0, bottom: 0, right: 0) tableView.contentOffset.y = searchBar.frame.size.height } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UIScrollViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let offset = scrollView.contentOffset.y if offset > searchBar.frame.size.height { scrollView.contentInset = UIEdgeInsets.zero return } let top = (offset > searchBar.frame.size.height / 2.0) ? -searchBar.frame.size.height : CGFloat(0) scrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) scrollView.contentOffset.y = offset } }
26.458333
104
0.74252
795e95bdaa91e064fb6a3411f2724af4d1a0bc37
1,146
// // UILocalizedButton.swift // testLocalization // // Created by Robin Guignard-perret on 11/03/2019. // Copyright © 2019 Robin Guignard-perret. All rights reserved. // import Foundation import UIKit public class UILocalizedButton: UIButton, LocalizedProtocol { @IBInspectable public var localizationID: String? = nil public func updateLocalization() { self.setTitle(getLocalizedString(), for: .normal) } public func getLocalizedString() -> String? { guard let identifier = self.localizationID else { if let s_text = self.titleLabel?.text { return DynLocalization.localizeString(s_text) } return nil } return DynLocalization.localizeString(identifier) } override init(frame: CGRect) { super.init(frame: frame) DynLocalization.registerDynamicLocalization(self) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) DynLocalization.registerDynamicLocalization(self) } deinit { DynLocalization.unregisterDynamicLocalization(self) } }
26.651163
64
0.660558
c1cc5afc9b403932f9a2f5e865efec3a35edab9d
679
// // Aside.swift // SwiftHtml // // Created by Tibor Bodecs on 2021. 07. 19.. // /// The `<aside>` tag defines some content aside from the content it is placed in. /// /// The aside content should be indirectly related to the surrounding content. /// /// **Tip:** The `<aside>` content is often placed as a sidebar in a document. /// /// **Note:** The `<aside>` element does not render as anything special in a browser. /// However, you can use CSS to style the `<aside>` element (see example below). open class Aside: Tag { public init(@TagBuilder _ builder: () -> [Tag]) { super.init(Node(type: .standard, name: "aside"), children: builder()) } }
29.521739
85
0.642121
612daecf937c61c6cb9264a76505e5a4f14826a1
1,802
// // GCDAide.swift // CICOFoundationKit // // Created by Ethan.Li on 2019/5/31. // Copyright © 2019 cico. All rights reserved. // import Foundation public class GCDAide { public static func syncOnMain(_ closure: (() -> Void)? = nil) { if Thread.current.isMainThread { closure?() } else { DispatchQueue.main.sync { closure?() } } } public static func asyncOnMain(_ closure: (() -> Void)? = nil) { DispatchQueue.main.async { closure?() } } public static func asyncOnMain(after delayInS: Double, _ closure: (() -> Void)? = nil) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInS) { closure?() } } public static func syncOnGlobal(_ closure: (() -> Void)? = nil) { DispatchQueue.global().sync { closure?() } } public static func asyncOnGlobal(_ closure: (() -> Void)? = nil) { DispatchQueue.global().async { closure?() } } public static func asyncOnGlobal(after delayInS: Double, _ closure: (() -> Void)? = nil) { DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + delayInS) { closure?() } } public static func syncRunForAsyncClosure<T>(type: T.Type = T.self, _ asyncClosure: @escaping (@escaping (T) -> Void) -> Void) -> T { var result: T? let semaphore = DispatchSemaphore.init(value: 0) self.asyncOnGlobal { asyncClosure({ (completionResult) in result = completionResult semaphore.signal() }) } semaphore.wait() return result! } }
27.30303
114
0.529412
2088c69b1cd9394ab29c1d8806ae49768db39a83
3,942
// // YelpClient.swift // Yelp // // Created by Timothy Lee on 9/19/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // import UIKit import CoreLocation import AFNetworking import BDBOAuth1Manager // You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA" let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ" let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV" let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y" enum YelpSortMode: Int { case BestMatched = 0, Distance, HighestRated } class YelpClient: BDBOAuth1RequestOperationManager { var accessToken: String! var accessSecret: String! class var sharedInstance : YelpClient { struct Static { static var token : dispatch_once_t = 0 static var instance : YelpClient? = nil } dispatch_once(&Static.token) { Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret) } return Static.instance! } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) { self.accessToken = accessToken self.accessSecret = accessSecret let baseUrl = NSURL(string: "https://api.yelp.com/v2/") super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret); let token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil) self.requestSerializer.saveAccessToken(token) } func searchWithTerm(term: String?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation { return searchWithTerm(term, sort: nil, location: nil, categories: nil, deals: nil, offset: nil, completion: completion) } func searchWithTerm(term: String?, sort: YelpSortMode?, location: CLLocation?, categories: [String]?, deals: Bool?, offset: Int?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation { // For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api var parameters: [String: AnyObject]! if term != nil { parameters = ["term": term!] } else { //Default search for all restaurants parameters = ["term": "restaurants"] } if location != nil { // parameters = ["term": term, "ll": "\(location!.coordinate.latitude),\(location!.coordinate.longitude)"] parameters["ll"] = "\(location!.coordinate.latitude),\(location!.coordinate.longitude)" } else { // Default the location to San Francisco // parameters = ["term": term, "ll": "37.785771,-122.406165"] parameters["ll"] = "37.785771,-122.406165" } if sort != nil { parameters["sort"] = sort!.rawValue } if categories != nil && categories!.count > 0 { parameters["category_filter"] = (categories!).joinWithSeparator(",") } if deals != nil { parameters["deals_filter"] = deals! } if offset != nil { parameters["offset"] = offset! } print(parameters) return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in let dictionaries = response["businesses"] as? [NSDictionary] if dictionaries != nil { completion(Business.businesses(array: dictionaries!), nil) } }, failure: { (operation: AFHTTPRequestOperation?, error: NSError!) -> Void in completion(nil, error) })! } }
36.841121
206
0.6276
b9b53f272e44c9006d66e28b45e51303f5fa8016
5,091
import Foundation extension Unicode { typealias CodePoint = UInt32 typealias Character = Scalar // Encoded character typealias GraphemeCluster = Swift.Character } enum JoiningForm: String, Decodable { case isol, `init`, medi, fina case unknown } enum OrthogonallyJoiningType: String, Decodable { case leading, trailing_major, trailing_minor case unknown } let jsonDecoder = JSONDecoder() jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase enum WrittenUnit: String, CaseIterable, Decodable { case A, Aa, I, Ii, O, Ue, U, Uu, N, B, P, H, Gh, G, Gg, M, L, S, Sh, T, D, Dd, Ch, J, Y, R, W, F, K, C, Z, Hh, Rh, Zr, Cr case unknown var data: Data? { WrittenUnit.dataDict[self] } } enum Character: String, Decodable { // case MVS, FVS1, FVS2, FVS3 case aleph case a, e, ee, i, o, u, oe, ue, n, ng, b, p, h, g, m, l, s, sh, t, d, ch, j, y, r, w, f, k, c, z, hh, rh, lh, zr, cr case unknown var data: Data? { Character.dataDict[self] } init?(codePoint: Unicode.CodePoint) { if let (char, _) = Character.dataDict.first(where: { _, data in data.codePoint == codePoint }) { self = char } else { return nil } } func resolveWrittenUnits(where joiningForm: JoiningForm, with condition: Condition) -> [WrittenUnit]? { return data?[joiningForm]?.first { $0.conditions?.contains(condition) ?? false }?.writtenUnits } } enum Condition: String, Decodable { // Contextual shaping condition case chachlag, particle, devsger case fallback case unknown // init(rawValue: Condition.RawValue) { // switch rawValue { // case "chachlag": self = .chachlag // case "particle": self = .particle // case "devsger": self = .devsger // case "fallback": self = .fallback // default: self = .unknown // } // } } typealias WrittenForm = (joiningForm: JoiningForm, writtenUnits: [WrittenUnit]) //dump(Character.a.applyCondition(.fallback, where: .isol) ?? []) struct State { var joiningForm: JoiningForm? var condition: Condition? } let str = "ᠮᠣᠩᠭᠣᠯ" //let str = "ᠠᠳᠠ" var buffer = [(character: Character, state: State)]() for char in str.unicodeScalars.map({ Character(codePoint: $0.value) ?? .unknown }) { buffer.append((char, State())) } for index in buffer.indices { buffer[index].state.joiningForm = .medi } for (char, state) in buffer { print( char.rawValue, state.joiningForm ?? "[joining form n/a]", state.condition ?? "[condition n/a]", state.joiningForm.flatMap { joiningForm in state.condition.flatMap { condition in char.resolveWrittenUnits(where: joiningForm, with: condition) } } ?? "[variant n/a]" ) } //dump(WrittenUnit.A.data?[.medi]) //letter.joiningForm = .isol // //print(letter.joiningForm ?? "unknown") // //letter.applyCondition(.fallback) // //print(letter.writtenUnits ?? "unknown") //func resolveVariant(for letter: Letter, in context: Context) -> Variant { // // var condition = Condition.fallback // // // Chachlag // if [.a, .e].contains(letter), context.before.hasSuffix(.MVS) { // condition = .chachlag // } // // // Syllabic // switch letter { // case .o, .u, .oe, .ue: // if context.before { // condition = .marked // } // case .n, .j, .y, .w: // if context.after { // condition = .chachlag_onset // } // case .h, .g: // if context.after { // condition = .chachlag_onset // } // case .n, .d: // if context.after { // condition = .onset // } else if context.before { // condition = .devsger // } // case .h, .g: // if context.after { // condition = .masculine_onset // } else if context.after { // condition = .feminine // } // case .g: // if context.before { // condition = .masculine_devsger // } else if context.before { // condition = .feminine // } else if context.before { // condition = .masculine_devsger // } else { // condition = .feminine // } // default: // break // } // // // Particle // switch letter { // case .a, .i, .u, .ue, .d: // if context.before == .nnbsp { // condition = .particle // } // case .u, .ue: // if context.before { // condition = .particle // } // case .y: // if context.before, context.after { // condition = .particle // } // default: // break // } // // // Devsger i // switch letter { // case .i: // if context.before { // condition = .devsger // } // default: // break // } // // // Post-bowed // if [.o, .u, .oe, .ue].contains(letter), written_form == .U, context.before { // condition = .post_bowed // } // // return condition //}
26.794737
107
0.554901
e0792eeddf39b8c2627f678abe3a9547f9fa55b9
1,283
// // q104-maximum-depth-of-binary-tree.swift // leetcode-swift // Source* : https://leetcode.com/problems/maximum-depth-of-binary-tree/ // Category* : BinaryTree RecursiveAlgorithm // // Created by Tianyu Wang on 16/6/27. // Github : http://github.com/wty21cn // Website : http://wty.im // Linkedin : https://www.linkedin.com/in/wty21cn // Mail : mailto:[email protected] /********************************************************************************** * * Given a binary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the root node * down to the farthest leaf node. * **********************************************************************************/ import Foundation struct q104 { class Solution { func maxDepth(_ root: TreeNode?) -> Int { if root == nil { return 0 } else { return 1 + max(maxDepth(root!.left), maxDepth(root!.right)) } } } static func getSolution() -> Void { let root = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,nil,6,7,8,nil,10,nil,nil,nil,14,15]) print(root ?? "") print(Solution().maxDepth(root)) } }
27.891304
102
0.506625
6177845b1ebe0b919028299f7b0f07fb3b3acc0c
215
// // ItemAtributeHandler+CoreDataClass.swift // // // Created by Jakub on 16.09.2017. // // import Foundation import CoreData @objc(ItemAtributeHandler) public class ItemAtributeHandler: NSManagedObject { }
13.4375
51
0.739535
bf4cf4b41c828cbef419bda85bccdb4f59a520c6
152
// // Details.swift // BitLabs // // Created by Omar Raad on 28.04.22. // import Foundation struct Details: Codable { let category: Category }
11.692308
37
0.651316
ddbb1dc39b0d3db9af8c20675bf123427e2192ed
2,660
import SwiftBlend2D @resultBuilder struct SceneBuilder { static func buildFinalResult(_ component: PartialScene) -> Scene { let scene = Scene() if let skyColor = component.skyColor { scene.skyColor = skyColor } if let sunDirection = component.sunDirection { scene.sunDirection = sunDirection } for geo in component.geometries { scene.addGeometry(geo) } return scene } static func buildExpression<C: Convex3Type & BoundableType>(_ expression: C) -> PartialScene where C.Vector == RVector3D { SceneGeometry(convex3: expression, material: .default).toPartialScene() } static func buildExpression<C: Convex3Type & BoundableType>(_ expression: (C, Material)) -> PartialScene where C.Vector == RVector3D { SceneGeometry(convex3: expression.0, material: expression.1).toPartialScene() } static func buildExpression(_ expression: RDisk3D) -> PartialScene { SceneGeometry(plane: expression, material: .default).toPartialScene() } static func buildExpression(_ expression: (RDisk3D, Material)) -> PartialScene { SceneGeometry(plane: expression.0, material: expression.1).toPartialScene() } static func buildExpression(_ expression: RPlane3D) -> PartialScene { SceneGeometry(plane: expression, material: .default).toPartialScene() } static func buildExpression(_ expression: (RPlane3D, Material)) -> PartialScene { SceneGeometry(plane: expression.0, material: expression.1).toPartialScene() } static func buildExpression(_ expression: SceneGeometry) -> PartialScene { PartialScene(skyColor: nil, geometries: [expression]) } static func buildBlock(_ components: PartialScene...) -> PartialScene { if components.isEmpty { return PartialScene() } return components.reduce(PartialScene(), { $0.merge($1) }) } } private extension SceneGeometry { func toPartialScene() -> PartialScene { return PartialScene(geometries: [self]) } } struct PartialScene { var skyColor: BLRgba32? var sunDirection: RVector3D? var geometries: [SceneGeometry] = [] func merge(_ other: PartialScene) -> PartialScene { PartialScene(skyColor: skyColor ?? other.skyColor, sunDirection: sunDirection ?? other.sunDirection, geometries: geometries + other.geometries) } } extension SceneBuilder { static func makeScene(@SceneBuilder _ builder: () -> Scene) -> Scene { builder() } }
33.670886
138
0.652256
39b3139e0583b5c1f9b70d0fb3eda53328263dba
90,193
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore extension Snowball { public struct Address: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "City", required: false, type: .string), AWSShapeMember(label: "Company", required: false, type: .string), AWSShapeMember(label: "Country", required: false, type: .string), AWSShapeMember(label: "IsRestricted", required: false, type: .boolean), AWSShapeMember(label: "Landmark", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "PhoneNumber", required: false, type: .string), AWSShapeMember(label: "PostalCode", required: false, type: .string), AWSShapeMember(label: "PrefectureOrDistrict", required: false, type: .string), AWSShapeMember(label: "StateOrProvince", required: false, type: .string), AWSShapeMember(label: "Street1", required: false, type: .string), AWSShapeMember(label: "Street2", required: false, type: .string), AWSShapeMember(label: "Street3", required: false, type: .string) ] /// The unique ID for an address. public let addressId: String? /// The city in an address that a Snowball is to be delivered to. public let city: String? /// The name of the company to receive a Snowball at an address. public let company: String? /// The country in an address that a Snowball is to be delivered to. public let country: String? /// If the address you are creating is a primary address, then set this option to true. This field is not supported in most regions. public let isRestricted: Bool? /// This field is no longer used and the value is ignored. public let landmark: String? /// The name of a person to receive a Snowball at an address. public let name: String? /// The phone number associated with an address that a Snowball is to be delivered to. public let phoneNumber: String? /// The postal code in an address that a Snowball is to be delivered to. public let postalCode: String? /// This field is no longer used and the value is ignored. public let prefectureOrDistrict: String? /// The state or province in an address that a Snowball is to be delivered to. public let stateOrProvince: String? /// The first line in a street address that a Snowball is to be delivered to. public let street1: String? /// The second line in a street address that a Snowball is to be delivered to. public let street2: String? /// The third line in a street address that a Snowball is to be delivered to. public let street3: String? public init(addressId: String? = nil, city: String? = nil, company: String? = nil, country: String? = nil, isRestricted: Bool? = nil, landmark: String? = nil, name: String? = nil, phoneNumber: String? = nil, postalCode: String? = nil, prefectureOrDistrict: String? = nil, stateOrProvince: String? = nil, street1: String? = nil, street2: String? = nil, street3: String? = nil) { self.addressId = addressId self.city = city self.company = company self.country = country self.isRestricted = isRestricted self.landmark = landmark self.name = name self.phoneNumber = phoneNumber self.postalCode = postalCode self.prefectureOrDistrict = prefectureOrDistrict self.stateOrProvince = stateOrProvince self.street1 = street1 self.street2 = street2 self.street3 = street3 } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.city, name:"city", parent: name, min: 1) try validate(self.company, name:"company", parent: name, min: 1) try validate(self.country, name:"country", parent: name, min: 1) try validate(self.landmark, name:"landmark", parent: name, min: 1) try validate(self.name, name:"name", parent: name, min: 1) try validate(self.phoneNumber, name:"phoneNumber", parent: name, min: 1) try validate(self.postalCode, name:"postalCode", parent: name, min: 1) try validate(self.prefectureOrDistrict, name:"prefectureOrDistrict", parent: name, min: 1) try validate(self.stateOrProvince, name:"stateOrProvince", parent: name, min: 1) try validate(self.street1, name:"street1", parent: name, min: 1) try validate(self.street2, name:"street2", parent: name, min: 1) try validate(self.street3, name:"street3", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case city = "City" case company = "Company" case country = "Country" case isRestricted = "IsRestricted" case landmark = "Landmark" case name = "Name" case phoneNumber = "PhoneNumber" case postalCode = "PostalCode" case prefectureOrDistrict = "PrefectureOrDistrict" case stateOrProvince = "StateOrProvince" case street1 = "Street1" case street2 = "Street2" case street3 = "Street3" } } public struct CancelClusterRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterId", required: true, type: .string) ] /// The 39-character ID for the cluster that you want to cancel, for example CID123e4567-e89b-12d3-a456-426655440000. public let clusterId: String public init(clusterId: String) { self.clusterId = clusterId } public func validate(name: String) throws { try validate(self.clusterId, name:"clusterId", parent: name, max: 39) try validate(self.clusterId, name:"clusterId", parent: name, min: 39) try validate(self.clusterId, name:"clusterId", parent: name, pattern: "CID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case clusterId = "ClusterId" } } public struct CancelClusterResult: AWSShape { public init() { } } public struct CancelJobRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: true, type: .string) ] /// The 39-character job ID for the job that you want to cancel, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct CancelJobResult: AWSShape { public init() { } } public struct ClusterListEntry: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterId", required: false, type: .string), AWSShapeMember(label: "ClusterState", required: false, type: .enum), AWSShapeMember(label: "CreationDate", required: false, type: .timestamp), AWSShapeMember(label: "Description", required: false, type: .string) ] /// The 39-character ID for the cluster that you want to list, for example CID123e4567-e89b-12d3-a456-426655440000. public let clusterId: String? /// The current state of this cluster. For information about the state of a specific node, see JobListEntry$JobState. public let clusterState: ClusterState? /// The creation date for this cluster. public let creationDate: TimeStamp? /// Defines an optional description of the cluster, for example Environmental Data Cluster-01. public let description: String? public init(clusterId: String? = nil, clusterState: ClusterState? = nil, creationDate: TimeStamp? = nil, description: String? = nil) { self.clusterId = clusterId self.clusterState = clusterState self.creationDate = creationDate self.description = description } private enum CodingKeys: String, CodingKey { case clusterId = "ClusterId" case clusterState = "ClusterState" case creationDate = "CreationDate" case description = "Description" } } public struct ClusterMetadata: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "ClusterId", required: false, type: .string), AWSShapeMember(label: "ClusterState", required: false, type: .enum), AWSShapeMember(label: "CreationDate", required: false, type: .timestamp), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "JobType", required: false, type: .enum), AWSShapeMember(label: "KmsKeyARN", required: false, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: false, type: .structure), AWSShapeMember(label: "RoleARN", required: false, type: .string), AWSShapeMember(label: "ShippingOption", required: false, type: .enum), AWSShapeMember(label: "SnowballType", required: false, type: .enum) ] /// The automatically generated ID for a specific address. public let addressId: String? /// The automatically generated ID for a cluster. public let clusterId: String? /// The current status of the cluster. public let clusterState: ClusterState? /// The creation date for this cluster. public let creationDate: TimeStamp? /// The optional description of the cluster. public let description: String? /// The ID of the address that you want a cluster shipped to, after it will be shipped to its primary address. This field is not supported in most regions. public let forwardingAddressId: String? /// The type of job for this cluster. Currently, the only job type supported for clusters is LOCAL_USE. public let jobType: JobType? /// The KmsKeyARN Amazon Resource Name (ARN) associated with this cluster. This ARN was created using the CreateKey API action in AWS Key Management Service (AWS KMS). public let kmsKeyARN: String? /// The Amazon Simple Notification Service (Amazon SNS) notification settings for this cluster. public let notification: Notification? /// The arrays of JobResource objects that can include updated S3Resource objects or LambdaResource objects. public let resources: JobResource? /// The role ARN associated with this cluster. This ARN was created using the CreateRole API action in AWS Identity and Access Management (IAM). public let roleARN: String? /// The shipping speed for each node in this cluster. This speed doesn't dictate how soon you'll get each Snowball Edge device, rather it represents how quickly each device moves to its destination while in transit. Regional shipping speeds are as follows: In Australia, you have access to express shipping. Typically, devices shipped express are delivered in about a day. In the European Union (EU), you have access to express shipping. Typically, Snowball Edges shipped express are delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically takes less than a week, one way. In India, Snowball Edges are delivered in one to seven days. In the US, you have access to one-day shipping and two-day shipping. public let shippingOption: ShippingOption? /// The type of AWS Snowball device to use for this cluster. Currently, the only supported device type for cluster jobs is EDGE. public let snowballType: SnowballType? public init(addressId: String? = nil, clusterId: String? = nil, clusterState: ClusterState? = nil, creationDate: TimeStamp? = nil, description: String? = nil, forwardingAddressId: String? = nil, jobType: JobType? = nil, kmsKeyARN: String? = nil, notification: Notification? = nil, resources: JobResource? = nil, roleARN: String? = nil, shippingOption: ShippingOption? = nil, snowballType: SnowballType? = nil) { self.addressId = addressId self.clusterId = clusterId self.clusterState = clusterState self.creationDate = creationDate self.description = description self.forwardingAddressId = forwardingAddressId self.jobType = jobType self.kmsKeyARN = kmsKeyARN self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingOption = shippingOption self.snowballType = snowballType } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case clusterId = "ClusterId" case clusterState = "ClusterState" case creationDate = "CreationDate" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case jobType = "JobType" case kmsKeyARN = "KmsKeyARN" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingOption = "ShippingOption" case snowballType = "SnowballType" } } public enum ClusterState: String, CustomStringConvertible, Codable { case awaitingquorum = "AwaitingQuorum" case pending = "Pending" case inuse = "InUse" case complete = "Complete" case cancelled = "Cancelled" public var description: String { return self.rawValue } } public struct CompatibleImage: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AmiId", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string) ] /// The unique identifier for an individual Snowball Edge AMI. public let amiId: String? /// The optional name of a compatible image. public let name: String? public init(amiId: String? = nil, name: String? = nil) { self.amiId = amiId self.name = name } private enum CodingKeys: String, CodingKey { case amiId = "AmiId" case name = "Name" } } public struct CreateAddressRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Address", required: true, type: .structure) ] /// The address that you want the Snowball shipped to. public let address: Address public init(address: Address) { self.address = address } public func validate(name: String) throws { try self.address.validate(name: "\(name).address") } private enum CodingKeys: String, CodingKey { case address = "Address" } } public struct CreateAddressResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string) ] /// The automatically generated ID for a specific address. You'll use this ID when you create a job to specify which address you want the Snowball for that job shipped to. public let addressId: String? public init(addressId: String? = nil) { self.addressId = addressId } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" } } public struct CreateClusterRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: true, type: .string), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "JobType", required: true, type: .enum), AWSShapeMember(label: "KmsKeyARN", required: false, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: true, type: .structure), AWSShapeMember(label: "RoleARN", required: true, type: .string), AWSShapeMember(label: "ShippingOption", required: true, type: .enum), AWSShapeMember(label: "SnowballType", required: false, type: .enum) ] /// The ID for the address that you want the cluster shipped to. public let addressId: String /// An optional description of this specific cluster, for example Environmental Data Cluster-01. public let description: String? /// The forwarding address ID for a cluster. This field is not supported in most regions. public let forwardingAddressId: String? /// The type of job for this cluster. Currently, the only job type supported for clusters is LOCAL_USE. public let jobType: JobType /// The KmsKeyARN value that you want to associate with this cluster. KmsKeyARN values are created by using the CreateKey API action in AWS Key Management Service (AWS KMS). public let kmsKeyARN: String? /// The Amazon Simple Notification Service (Amazon SNS) notification settings for this cluster. public let notification: Notification? /// The resources associated with the cluster job. These resources include Amazon S3 buckets and optional AWS Lambda functions written in the Python language. public let resources: JobResource /// The RoleARN that you want to associate with this cluster. RoleArn values are created by using the CreateRole API action in AWS Identity and Access Management (IAM). public let roleARN: String /// The shipping speed for each node in this cluster. This speed doesn't dictate how soon you'll get each Snowball Edge device, rather it represents how quickly each device moves to its destination while in transit. Regional shipping speeds are as follows: In Australia, you have access to express shipping. Typically, devices shipped express are delivered in about a day. In the European Union (EU), you have access to express shipping. Typically, Snowball Edges shipped express are delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically takes less than a week, one way. In India, Snowball Edges are delivered in one to seven days. In the US, you have access to one-day shipping and two-day shipping. public let shippingOption: ShippingOption /// The type of AWS Snowball device to use for this cluster. Currently, the only supported device type for cluster jobs is EDGE. public let snowballType: SnowballType? public init(addressId: String, description: String? = nil, forwardingAddressId: String? = nil, jobType: JobType, kmsKeyARN: String? = nil, notification: Notification? = nil, resources: JobResource, roleARN: String, shippingOption: ShippingOption, snowballType: SnowballType? = nil) { self.addressId = addressId self.description = description self.forwardingAddressId = forwardingAddressId self.jobType = jobType self.kmsKeyARN = kmsKeyARN self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingOption = shippingOption self.snowballType = snowballType } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.description, name:"description", parent: name, min: 1) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, max: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, min: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.kmsKeyARN, name:"kmsKeyARN", parent: name, max: 255) try validate(self.kmsKeyARN, name:"kmsKeyARN", parent: name, pattern: "arn:aws.*:kms:.*:[0-9]{12}:key/.*") try self.notification?.validate(name: "\(name).notification") try self.resources.validate(name: "\(name).resources") try validate(self.roleARN, name:"roleARN", parent: name, max: 255) try validate(self.roleARN, name:"roleARN", parent: name, pattern: "arn:aws.*:iam::[0-9]{12}:role/.*") } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case jobType = "JobType" case kmsKeyARN = "KmsKeyARN" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingOption = "ShippingOption" case snowballType = "SnowballType" } } public struct CreateClusterResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterId", required: false, type: .string) ] /// The automatically generated ID for a cluster. public let clusterId: String? public init(clusterId: String? = nil) { self.clusterId = clusterId } private enum CodingKeys: String, CodingKey { case clusterId = "ClusterId" } } public struct CreateJobRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "ClusterId", required: false, type: .string), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "JobType", required: false, type: .enum), AWSShapeMember(label: "KmsKeyARN", required: false, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: false, type: .structure), AWSShapeMember(label: "RoleARN", required: false, type: .string), AWSShapeMember(label: "ShippingOption", required: false, type: .enum), AWSShapeMember(label: "SnowballCapacityPreference", required: false, type: .enum), AWSShapeMember(label: "SnowballType", required: false, type: .enum) ] /// The ID for the address that you want the Snowball shipped to. public let addressId: String? /// The ID of a cluster. If you're creating a job for a node in a cluster, you need to provide only this clusterId value. The other job attributes are inherited from the cluster. public let clusterId: String? /// Defines an optional description of this specific job, for example Important Photos 2016-08-11. public let description: String? /// The forwarding address ID for a job. This field is not supported in most regions. public let forwardingAddressId: String? /// Defines the type of job that you're creating. public let jobType: JobType? /// The KmsKeyARN that you want to associate with this job. KmsKeyARNs are created using the CreateKey AWS Key Management Service (KMS) API action. public let kmsKeyARN: String? /// Defines the Amazon Simple Notification Service (Amazon SNS) notification settings for this job. public let notification: Notification? /// Defines the Amazon S3 buckets associated with this job. With IMPORT jobs, you specify the bucket or buckets that your transferred data will be imported into. With EXPORT jobs, you specify the bucket or buckets that your transferred data will be exported from. Optionally, you can also specify a KeyRange value. If you choose to export a range, you define the length of the range by providing either an inclusive BeginMarker value, an inclusive EndMarker value, or both. Ranges are UTF-8 binary sorted. public let resources: JobResource? /// The RoleARN that you want to associate with this job. RoleArns are created using the CreateRole AWS Identity and Access Management (IAM) API action. public let roleARN: String? /// The shipping speed for this job. This speed doesn't dictate how soon you'll get the Snowball, rather it represents how quickly the Snowball moves to its destination while in transit. Regional shipping speeds are as follows: In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a day. In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically takes less than a week, one way. In India, Snowballs are delivered in one to seven days. In the US, you have access to one-day shipping and two-day shipping. public let shippingOption: ShippingOption? /// If your job is being created in one of the US regions, you have the option of specifying what size Snowball you'd like for this job. In all other regions, Snowballs come with 80 TB in storage capacity. public let snowballCapacityPreference: SnowballCapacity? /// The type of AWS Snowball device to use for this job. Currently, the only supported device type for cluster jobs is EDGE. public let snowballType: SnowballType? public init(addressId: String? = nil, clusterId: String? = nil, description: String? = nil, forwardingAddressId: String? = nil, jobType: JobType? = nil, kmsKeyARN: String? = nil, notification: Notification? = nil, resources: JobResource? = nil, roleARN: String? = nil, shippingOption: ShippingOption? = nil, snowballCapacityPreference: SnowballCapacity? = nil, snowballType: SnowballType? = nil) { self.addressId = addressId self.clusterId = clusterId self.description = description self.forwardingAddressId = forwardingAddressId self.jobType = jobType self.kmsKeyARN = kmsKeyARN self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingOption = shippingOption self.snowballCapacityPreference = snowballCapacityPreference self.snowballType = snowballType } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.clusterId, name:"clusterId", parent: name, max: 39) try validate(self.clusterId, name:"clusterId", parent: name, min: 39) try validate(self.clusterId, name:"clusterId", parent: name, pattern: "CID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.description, name:"description", parent: name, min: 1) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, max: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, min: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.kmsKeyARN, name:"kmsKeyARN", parent: name, max: 255) try validate(self.kmsKeyARN, name:"kmsKeyARN", parent: name, pattern: "arn:aws.*:kms:.*:[0-9]{12}:key/.*") try self.notification?.validate(name: "\(name).notification") try self.resources?.validate(name: "\(name).resources") try validate(self.roleARN, name:"roleARN", parent: name, max: 255) try validate(self.roleARN, name:"roleARN", parent: name, pattern: "arn:aws.*:iam::[0-9]{12}:role/.*") } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case clusterId = "ClusterId" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case jobType = "JobType" case kmsKeyARN = "KmsKeyARN" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingOption = "ShippingOption" case snowballCapacityPreference = "SnowballCapacityPreference" case snowballType = "SnowballType" } } public struct CreateJobResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: false, type: .string) ] /// The automatically generated ID for a job, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String? public init(jobId: String? = nil) { self.jobId = jobId } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct DataTransfer: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "BytesTransferred", required: false, type: .long), AWSShapeMember(label: "ObjectsTransferred", required: false, type: .long), AWSShapeMember(label: "TotalBytes", required: false, type: .long), AWSShapeMember(label: "TotalObjects", required: false, type: .long) ] /// The number of bytes transferred between a Snowball and Amazon S3. public let bytesTransferred: Int64? /// The number of objects transferred between a Snowball and Amazon S3. public let objectsTransferred: Int64? /// The total bytes of data for a transfer between a Snowball and Amazon S3. This value is set to 0 (zero) until all the keys that will be transferred have been listed. public let totalBytes: Int64? /// The total number of objects for a transfer between a Snowball and Amazon S3. This value is set to 0 (zero) until all the keys that will be transferred have been listed. public let totalObjects: Int64? public init(bytesTransferred: Int64? = nil, objectsTransferred: Int64? = nil, totalBytes: Int64? = nil, totalObjects: Int64? = nil) { self.bytesTransferred = bytesTransferred self.objectsTransferred = objectsTransferred self.totalBytes = totalBytes self.totalObjects = totalObjects } private enum CodingKeys: String, CodingKey { case bytesTransferred = "BytesTransferred" case objectsTransferred = "ObjectsTransferred" case totalBytes = "TotalBytes" case totalObjects = "TotalObjects" } } public struct DescribeAddressRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: true, type: .string) ] /// The automatically generated ID for a specific address. public let addressId: String public init(addressId: String) { self.addressId = addressId } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" } } public struct DescribeAddressResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Address", required: false, type: .structure) ] /// The address that you want the Snowball or Snowballs associated with a specific job to be shipped to. public let address: Address? public init(address: Address? = nil) { self.address = address } private enum CodingKeys: String, CodingKey { case address = "Address" } } public struct DescribeAddressesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The number of ADDRESS objects to return. public let maxResults: Int? /// HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS objects, you have the option of specifying a value for NextToken as the starting point for your list of returned addresses. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeAddressesResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Addresses", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The Snowball shipping addresses that were created for this account. public let addresses: [Address]? /// HTTP requests are stateless. If you use the automatically generated NextToken value in your next DescribeAddresses call, your list of returned addresses will start from this point in the array. public let nextToken: String? public init(addresses: [Address]? = nil, nextToken: String? = nil) { self.addresses = addresses self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case addresses = "Addresses" case nextToken = "NextToken" } } public struct DescribeClusterRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterId", required: true, type: .string) ] /// The automatically generated ID for a cluster. public let clusterId: String public init(clusterId: String) { self.clusterId = clusterId } public func validate(name: String) throws { try validate(self.clusterId, name:"clusterId", parent: name, max: 39) try validate(self.clusterId, name:"clusterId", parent: name, min: 39) try validate(self.clusterId, name:"clusterId", parent: name, pattern: "CID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case clusterId = "ClusterId" } } public struct DescribeClusterResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterMetadata", required: false, type: .structure) ] /// Information about a specific cluster, including shipping information, cluster status, and other important metadata. public let clusterMetadata: ClusterMetadata? public init(clusterMetadata: ClusterMetadata? = nil) { self.clusterMetadata = clusterMetadata } private enum CodingKeys: String, CodingKey { case clusterMetadata = "ClusterMetadata" } } public struct DescribeJobRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: true, type: .string) ] /// The automatically generated ID for a job, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct DescribeJobResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobMetadata", required: false, type: .structure), AWSShapeMember(label: "SubJobMetadata", required: false, type: .list) ] /// Information about a specific job, including shipping information, job status, and other important metadata. public let jobMetadata: JobMetadata? /// Information about a specific job part (in the case of an export job), including shipping information, job status, and other important metadata. public let subJobMetadata: [JobMetadata]? public init(jobMetadata: JobMetadata? = nil, subJobMetadata: [JobMetadata]? = nil) { self.jobMetadata = jobMetadata self.subJobMetadata = subJobMetadata } private enum CodingKeys: String, CodingKey { case jobMetadata = "JobMetadata" case subJobMetadata = "SubJobMetadata" } } public struct Ec2AmiResource: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AmiId", required: true, type: .string), AWSShapeMember(label: "SnowballAmiId", required: false, type: .string) ] /// The ID of the AMI in Amazon EC2. public let amiId: String /// The ID of the AMI on the Snowball Edge device. public let snowballAmiId: String? public init(amiId: String, snowballAmiId: String? = nil) { self.amiId = amiId self.snowballAmiId = snowballAmiId } public func validate(name: String) throws { try validate(self.amiId, name:"amiId", parent: name, max: 21) try validate(self.amiId, name:"amiId", parent: name, min: 12) try validate(self.amiId, name:"amiId", parent: name, pattern: "(ami-[0-9a-f]{8})|(ami-[0-9a-f]{17})") try validate(self.snowballAmiId, name:"snowballAmiId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case amiId = "AmiId" case snowballAmiId = "SnowballAmiId" } } public struct EventTriggerDefinition: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "EventResourceARN", required: false, type: .string) ] /// The Amazon Resource Name (ARN) for any local Amazon S3 resource that is an AWS Lambda function's event trigger associated with this job. public let eventResourceARN: String? public init(eventResourceARN: String? = nil) { self.eventResourceARN = eventResourceARN } public func validate(name: String) throws { try validate(self.eventResourceARN, name:"eventResourceARN", parent: name, max: 255) } private enum CodingKeys: String, CodingKey { case eventResourceARN = "EventResourceARN" } } public struct GetJobManifestRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: true, type: .string) ] /// The ID for a job that you want to get the manifest file for, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct GetJobManifestResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ManifestURI", required: false, type: .string) ] /// The Amazon S3 presigned URL for the manifest file associated with the specified JobId value. public let manifestURI: String? public init(manifestURI: String? = nil) { self.manifestURI = manifestURI } private enum CodingKeys: String, CodingKey { case manifestURI = "ManifestURI" } } public struct GetJobUnlockCodeRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: true, type: .string) ] /// The ID for the job that you want to get the UnlockCode value for, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct GetJobUnlockCodeResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "UnlockCode", required: false, type: .string) ] /// The UnlockCode value for the specified job. The UnlockCode value can be accessed for up to 90 days after the job has been created. public let unlockCode: String? public init(unlockCode: String? = nil) { self.unlockCode = unlockCode } private enum CodingKeys: String, CodingKey { case unlockCode = "UnlockCode" } } public struct GetSnowballUsageRequest: AWSShape { public init() { } } public struct GetSnowballUsageResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "SnowballLimit", required: false, type: .integer), AWSShapeMember(label: "SnowballsInUse", required: false, type: .integer) ] /// The service limit for number of Snowballs this account can have at once. The default service limit is 1 (one). public let snowballLimit: Int? /// The number of Snowballs that this account is currently using. public let snowballsInUse: Int? public init(snowballLimit: Int? = nil, snowballsInUse: Int? = nil) { self.snowballLimit = snowballLimit self.snowballsInUse = snowballsInUse } private enum CodingKeys: String, CodingKey { case snowballLimit = "SnowballLimit" case snowballsInUse = "SnowballsInUse" } } public struct GetSoftwareUpdatesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobId", required: true, type: .string) ] /// The ID for a job that you want to get the software update file for, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String public init(jobId: String) { self.jobId = jobId } public func validate(name: String) throws { try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") } private enum CodingKeys: String, CodingKey { case jobId = "JobId" } } public struct GetSoftwareUpdatesResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "UpdatesURI", required: false, type: .string) ] /// The Amazon S3 presigned URL for the update file associated with the specified JobId value. The software update will be available for 2 days after this request is made. To access an update after the 2 days have passed, you'll have to make another call to GetSoftwareUpdates. public let updatesURI: String? public init(updatesURI: String? = nil) { self.updatesURI = updatesURI } private enum CodingKeys: String, CodingKey { case updatesURI = "UpdatesURI" } } public struct JobListEntry: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "CreationDate", required: false, type: .timestamp), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "IsMaster", required: false, type: .boolean), AWSShapeMember(label: "JobId", required: false, type: .string), AWSShapeMember(label: "JobState", required: false, type: .enum), AWSShapeMember(label: "JobType", required: false, type: .enum), AWSShapeMember(label: "SnowballType", required: false, type: .enum) ] /// The creation date for this job. public let creationDate: TimeStamp? /// The optional description of this specific job, for example Important Photos 2016-08-11. public let description: String? /// A value that indicates that this job is a master job. A master job represents a successful request to create an export job. Master jobs aren't associated with any Snowballs. Instead, each master job will have at least one job part, and each job part is associated with a Snowball. It might take some time before the job parts associated with a particular master job are listed, because they are created after the master job is created. public let isMaster: Bool? /// The automatically generated ID for a job, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String? /// The current state of this job. public let jobState: JobState? /// The type of job. public let jobType: JobType? /// The type of device used with this job. public let snowballType: SnowballType? public init(creationDate: TimeStamp? = nil, description: String? = nil, isMaster: Bool? = nil, jobId: String? = nil, jobState: JobState? = nil, jobType: JobType? = nil, snowballType: SnowballType? = nil) { self.creationDate = creationDate self.description = description self.isMaster = isMaster self.jobId = jobId self.jobState = jobState self.jobType = jobType self.snowballType = snowballType } private enum CodingKeys: String, CodingKey { case creationDate = "CreationDate" case description = "Description" case isMaster = "IsMaster" case jobId = "JobId" case jobState = "JobState" case jobType = "JobType" case snowballType = "SnowballType" } } public struct JobLogs: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobCompletionReportURI", required: false, type: .string), AWSShapeMember(label: "JobFailureLogURI", required: false, type: .string), AWSShapeMember(label: "JobSuccessLogURI", required: false, type: .string) ] /// A link to an Amazon S3 presigned URL where the job completion report is located. public let jobCompletionReportURI: String? /// A link to an Amazon S3 presigned URL where the job failure log is located. public let jobFailureLogURI: String? /// A link to an Amazon S3 presigned URL where the job success log is located. public let jobSuccessLogURI: String? public init(jobCompletionReportURI: String? = nil, jobFailureLogURI: String? = nil, jobSuccessLogURI: String? = nil) { self.jobCompletionReportURI = jobCompletionReportURI self.jobFailureLogURI = jobFailureLogURI self.jobSuccessLogURI = jobSuccessLogURI } private enum CodingKeys: String, CodingKey { case jobCompletionReportURI = "JobCompletionReportURI" case jobFailureLogURI = "JobFailureLogURI" case jobSuccessLogURI = "JobSuccessLogURI" } } public struct JobMetadata: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "ClusterId", required: false, type: .string), AWSShapeMember(label: "CreationDate", required: false, type: .timestamp), AWSShapeMember(label: "DataTransferProgress", required: false, type: .structure), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "JobId", required: false, type: .string), AWSShapeMember(label: "JobLogInfo", required: false, type: .structure), AWSShapeMember(label: "JobState", required: false, type: .enum), AWSShapeMember(label: "JobType", required: false, type: .enum), AWSShapeMember(label: "KmsKeyARN", required: false, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: false, type: .structure), AWSShapeMember(label: "RoleARN", required: false, type: .string), AWSShapeMember(label: "ShippingDetails", required: false, type: .structure), AWSShapeMember(label: "SnowballCapacityPreference", required: false, type: .enum), AWSShapeMember(label: "SnowballType", required: false, type: .enum) ] /// The ID for the address that you want the Snowball shipped to. public let addressId: String? /// The 39-character ID for the cluster, for example CID123e4567-e89b-12d3-a456-426655440000. public let clusterId: String? /// The creation date for this job. public let creationDate: TimeStamp? /// A value that defines the real-time status of a Snowball's data transfer while the device is at AWS. This data is only available while a job has a JobState value of InProgress, for both import and export jobs. public let dataTransferProgress: DataTransfer? /// The description of the job, provided at job creation. public let description: String? /// The ID of the address that you want a job shipped to, after it will be shipped to its primary address. This field is not supported in most regions. public let forwardingAddressId: String? /// The automatically generated ID for a job, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String? /// Links to Amazon S3 presigned URLs for the job report and logs. For import jobs, the PDF job report becomes available at the end of the import process. For export jobs, your job report typically becomes available while the Snowball for your job part is being delivered to you. public let jobLogInfo: JobLogs? /// The current status of the jobs. public let jobState: JobState? /// The type of job. public let jobType: JobType? /// The Amazon Resource Name (ARN) for the AWS Key Management Service (AWS KMS) key associated with this job. This ARN was created using the CreateKey API action in AWS KMS. public let kmsKeyARN: String? /// The Amazon Simple Notification Service (Amazon SNS) notification settings associated with a specific job. The Notification object is returned as a part of the response syntax of the DescribeJob action in the JobMetadata data type. public let notification: Notification? /// An array of S3Resource objects. Each S3Resource object represents an Amazon S3 bucket that your transferred data will be exported from or imported into. public let resources: JobResource? /// The role ARN associated with this job. This ARN was created using the CreateRole API action in AWS Identity and Access Management (IAM). public let roleARN: String? /// A job's shipping information, including inbound and outbound tracking numbers and shipping speed options. public let shippingDetails: ShippingDetails? /// The Snowball capacity preference for this job, specified at job creation. In US regions, you can choose between 50 TB and 80 TB Snowballs. All other regions use 80 TB capacity Snowballs. public let snowballCapacityPreference: SnowballCapacity? /// The type of device used with this job. public let snowballType: SnowballType? public init(addressId: String? = nil, clusterId: String? = nil, creationDate: TimeStamp? = nil, dataTransferProgress: DataTransfer? = nil, description: String? = nil, forwardingAddressId: String? = nil, jobId: String? = nil, jobLogInfo: JobLogs? = nil, jobState: JobState? = nil, jobType: JobType? = nil, kmsKeyARN: String? = nil, notification: Notification? = nil, resources: JobResource? = nil, roleARN: String? = nil, shippingDetails: ShippingDetails? = nil, snowballCapacityPreference: SnowballCapacity? = nil, snowballType: SnowballType? = nil) { self.addressId = addressId self.clusterId = clusterId self.creationDate = creationDate self.dataTransferProgress = dataTransferProgress self.description = description self.forwardingAddressId = forwardingAddressId self.jobId = jobId self.jobLogInfo = jobLogInfo self.jobState = jobState self.jobType = jobType self.kmsKeyARN = kmsKeyARN self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingDetails = shippingDetails self.snowballCapacityPreference = snowballCapacityPreference self.snowballType = snowballType } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case clusterId = "ClusterId" case creationDate = "CreationDate" case dataTransferProgress = "DataTransferProgress" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case jobId = "JobId" case jobLogInfo = "JobLogInfo" case jobState = "JobState" case jobType = "JobType" case kmsKeyARN = "KmsKeyARN" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingDetails = "ShippingDetails" case snowballCapacityPreference = "SnowballCapacityPreference" case snowballType = "SnowballType" } } public struct JobResource: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Ec2AmiResources", required: false, type: .list), AWSShapeMember(label: "LambdaResources", required: false, type: .list), AWSShapeMember(label: "S3Resources", required: false, type: .list) ] /// The Amazon Machine Images (AMIs) associated with this job. public let ec2AmiResources: [Ec2AmiResource]? /// The Python-language Lambda functions for this job. public let lambdaResources: [LambdaResource]? /// An array of S3Resource objects. public let s3Resources: [S3Resource]? public init(ec2AmiResources: [Ec2AmiResource]? = nil, lambdaResources: [LambdaResource]? = nil, s3Resources: [S3Resource]? = nil) { self.ec2AmiResources = ec2AmiResources self.lambdaResources = lambdaResources self.s3Resources = s3Resources } public func validate(name: String) throws { try self.ec2AmiResources?.forEach { try $0.validate(name: "\(name).ec2AmiResources[]") } try self.lambdaResources?.forEach { try $0.validate(name: "\(name).lambdaResources[]") } try self.s3Resources?.forEach { try $0.validate(name: "\(name).s3Resources[]") } } private enum CodingKeys: String, CodingKey { case ec2AmiResources = "Ec2AmiResources" case lambdaResources = "LambdaResources" case s3Resources = "S3Resources" } } public enum JobState: String, CustomStringConvertible, Codable { case new = "New" case preparingappliance = "PreparingAppliance" case preparingshipment = "PreparingShipment" case intransittocustomer = "InTransitToCustomer" case withcustomer = "WithCustomer" case intransittoaws = "InTransitToAWS" case withawssortingfacility = "WithAWSSortingFacility" case withaws = "WithAWS" case inprogress = "InProgress" case complete = "Complete" case cancelled = "Cancelled" case listing = "Listing" case pending = "Pending" public var description: String { return self.rawValue } } public enum JobType: String, CustomStringConvertible, Codable { case `import` = "IMPORT" case export = "EXPORT" case localUse = "LOCAL_USE" public var description: String { return self.rawValue } } public struct KeyRange: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "BeginMarker", required: false, type: .string), AWSShapeMember(label: "EndMarker", required: false, type: .string) ] /// The key that starts an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted. public let beginMarker: String? /// The key that ends an optional key range for an export job. Ranges are inclusive and UTF-8 binary sorted. public let endMarker: String? public init(beginMarker: String? = nil, endMarker: String? = nil) { self.beginMarker = beginMarker self.endMarker = endMarker } public func validate(name: String) throws { try validate(self.beginMarker, name:"beginMarker", parent: name, min: 1) try validate(self.endMarker, name:"endMarker", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case beginMarker = "BeginMarker" case endMarker = "EndMarker" } } public struct LambdaResource: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "EventTriggers", required: false, type: .list), AWSShapeMember(label: "LambdaArn", required: false, type: .string) ] /// The array of ARNs for S3Resource objects to trigger the LambdaResource objects associated with this job. public let eventTriggers: [EventTriggerDefinition]? /// An Amazon Resource Name (ARN) that represents an AWS Lambda function to be triggered by PUT object actions on the associated local Amazon S3 resource. public let lambdaArn: String? public init(eventTriggers: [EventTriggerDefinition]? = nil, lambdaArn: String? = nil) { self.eventTriggers = eventTriggers self.lambdaArn = lambdaArn } public func validate(name: String) throws { try self.eventTriggers?.forEach { try $0.validate(name: "\(name).eventTriggers[]") } try validate(self.lambdaArn, name:"lambdaArn", parent: name, max: 255) } private enum CodingKeys: String, CodingKey { case eventTriggers = "EventTriggers" case lambdaArn = "LambdaArn" } } public struct ListClusterJobsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterId", required: true, type: .string), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The 39-character ID for the cluster that you want to list, for example CID123e4567-e89b-12d3-a456-426655440000. public let clusterId: String /// The number of JobListEntry objects to return. public let maxResults: Int? /// HTTP requests are stateless. To identify what object comes "next" in the list of JobListEntry objects, you have the option of specifying NextToken as the starting point for your returned list. public let nextToken: String? public init(clusterId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.clusterId = clusterId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.clusterId, name:"clusterId", parent: name, max: 39) try validate(self.clusterId, name:"clusterId", parent: name, min: 39) try validate(self.clusterId, name:"clusterId", parent: name, pattern: "CID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clusterId = "ClusterId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListClusterJobsResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobListEntries", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// Each JobListEntry object contains a job's state, a job's ID, and a value that indicates whether the job is a job part, in the case of export jobs. public let jobListEntries: [JobListEntry]? /// HTTP requests are stateless. If you use the automatically generated NextToken value in your next ListClusterJobsResult call, your list of returned jobs will start from this point in the array. public let nextToken: String? public init(jobListEntries: [JobListEntry]? = nil, nextToken: String? = nil) { self.jobListEntries = jobListEntries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case jobListEntries = "JobListEntries" case nextToken = "NextToken" } } public struct ListClustersRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The number of ClusterListEntry objects to return. public let maxResults: Int? /// HTTP requests are stateless. To identify what object comes "next" in the list of ClusterListEntry objects, you have the option of specifying NextToken as the starting point for your returned list. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListClustersResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ClusterListEntries", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// Each ClusterListEntry object contains a cluster's state, a cluster's ID, and other important status information. public let clusterListEntries: [ClusterListEntry]? /// HTTP requests are stateless. If you use the automatically generated NextToken value in your next ClusterListEntry call, your list of returned clusters will start from this point in the array. public let nextToken: String? public init(clusterListEntries: [ClusterListEntry]? = nil, nextToken: String? = nil) { self.clusterListEntries = clusterListEntries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case clusterListEntries = "ClusterListEntries" case nextToken = "NextToken" } } public struct ListCompatibleImagesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The maximum number of results for the list of compatible images. Currently, a Snowball Edge device can store 10 AMIs. public let maxResults: Int? /// HTTP requests are stateless. To identify what object comes "next" in the list of compatible images, you can specify a value for NextToken as the starting point for your list of returned images. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListCompatibleImagesResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "CompatibleImages", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// A JSON-formatted object that describes a compatible AMI, including the ID and name for a Snowball Edge AMI. public let compatibleImages: [CompatibleImage]? /// Because HTTP requests are stateless, this is the starting point for your next list of returned images. public let nextToken: String? public init(compatibleImages: [CompatibleImage]? = nil, nextToken: String? = nil) { self.compatibleImages = compatibleImages self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case compatibleImages = "CompatibleImages" case nextToken = "NextToken" } } public struct ListJobsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The number of JobListEntry objects to return. public let maxResults: Int? /// HTTP requests are stateless. To identify what object comes "next" in the list of JobListEntry objects, you have the option of specifying NextToken as the starting point for your returned list. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.maxResults, name:"maxResults", parent: name, max: 100) try validate(self.maxResults, name:"maxResults", parent: name, min: 0) try validate(self.nextToken, name:"nextToken", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListJobsResult: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobListEntries", required: false, type: .list), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// Each JobListEntry object contains a job's state, a job's ID, and a value that indicates whether the job is a job part, in the case of export jobs. public let jobListEntries: [JobListEntry]? /// HTTP requests are stateless. If you use this automatically generated NextToken value in your next ListJobs call, your returned JobListEntry objects will start from this point in the array. public let nextToken: String? public init(jobListEntries: [JobListEntry]? = nil, nextToken: String? = nil) { self.jobListEntries = jobListEntries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case jobListEntries = "JobListEntries" case nextToken = "NextToken" } } public struct Notification: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "JobStatesToNotify", required: false, type: .list), AWSShapeMember(label: "NotifyAll", required: false, type: .boolean), AWSShapeMember(label: "SnsTopicARN", required: false, type: .string) ] /// The list of job states that will trigger a notification for this job. public let jobStatesToNotify: [JobState]? /// Any change in job state will trigger a notification for this job. public let notifyAll: Bool? /// The new SNS TopicArn that you want to associate with this job. You can create Amazon Resource Names (ARNs) for topics by using the CreateTopic Amazon SNS API action. You can subscribe email addresses to an Amazon SNS topic through the AWS Management Console, or by using the Subscribe AWS Simple Notification Service (SNS) API action. public let snsTopicARN: String? public init(jobStatesToNotify: [JobState]? = nil, notifyAll: Bool? = nil, snsTopicARN: String? = nil) { self.jobStatesToNotify = jobStatesToNotify self.notifyAll = notifyAll self.snsTopicARN = snsTopicARN } public func validate(name: String) throws { try validate(self.snsTopicARN, name:"snsTopicARN", parent: name, max: 255) try validate(self.snsTopicARN, name:"snsTopicARN", parent: name, pattern: "arn:aws.*:sns:.*:[0-9]{12}:.*") } private enum CodingKeys: String, CodingKey { case jobStatesToNotify = "JobStatesToNotify" case notifyAll = "NotifyAll" case snsTopicARN = "SnsTopicARN" } } public struct S3Resource: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "BucketArn", required: false, type: .string), AWSShapeMember(label: "KeyRange", required: false, type: .structure) ] /// The Amazon Resource Name (ARN) of an Amazon S3 bucket. public let bucketArn: String? /// For export jobs, you can provide an optional KeyRange within a specific Amazon S3 bucket. The length of the range is defined at job creation, and has either an inclusive BeginMarker, an inclusive EndMarker, or both. Ranges are UTF-8 binary sorted. public let keyRange: KeyRange? public init(bucketArn: String? = nil, keyRange: KeyRange? = nil) { self.bucketArn = bucketArn self.keyRange = keyRange } public func validate(name: String) throws { try validate(self.bucketArn, name:"bucketArn", parent: name, max: 255) try self.keyRange?.validate(name: "\(name).keyRange") } private enum CodingKeys: String, CodingKey { case bucketArn = "BucketArn" case keyRange = "KeyRange" } } public struct Shipment: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Status", required: false, type: .string), AWSShapeMember(label: "TrackingNumber", required: false, type: .string) ] /// Status information for a shipment. public let status: String? /// The tracking number for this job. Using this tracking number with your region's carrier's website, you can track a Snowball as the carrier transports it. For India, the carrier is Amazon Logistics. For all other regions, UPS is the carrier. public let trackingNumber: String? public init(status: String? = nil, trackingNumber: String? = nil) { self.status = status self.trackingNumber = trackingNumber } private enum CodingKeys: String, CodingKey { case status = "Status" case trackingNumber = "TrackingNumber" } } public struct ShippingDetails: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "InboundShipment", required: false, type: .structure), AWSShapeMember(label: "OutboundShipment", required: false, type: .structure), AWSShapeMember(label: "ShippingOption", required: false, type: .enum) ] /// The Status and TrackingNumber values for a Snowball being returned to AWS for a particular job. public let inboundShipment: Shipment? /// The Status and TrackingNumber values for a Snowball being delivered to the address that you specified for a particular job. public let outboundShipment: Shipment? /// The shipping speed for a particular job. This speed doesn't dictate how soon you'll get the Snowball from the job's creation date. This speed represents how quickly it moves to its destination while in transit. Regional shipping speeds are as follows: In Australia, you have access to express shipping. Typically, Snowballs shipped express are delivered in about a day. In the European Union (EU), you have access to express shipping. Typically, Snowballs shipped express are delivered in about a day. In addition, most countries in the EU have access to standard shipping, which typically takes less than a week, one way. In India, Snowballs are delivered in one to seven days. In the United States of America (US), you have access to one-day shipping and two-day shipping. public let shippingOption: ShippingOption? public init(inboundShipment: Shipment? = nil, outboundShipment: Shipment? = nil, shippingOption: ShippingOption? = nil) { self.inboundShipment = inboundShipment self.outboundShipment = outboundShipment self.shippingOption = shippingOption } private enum CodingKeys: String, CodingKey { case inboundShipment = "InboundShipment" case outboundShipment = "OutboundShipment" case shippingOption = "ShippingOption" } } public enum ShippingOption: String, CustomStringConvertible, Codable { case secondDay = "SECOND_DAY" case nextDay = "NEXT_DAY" case express = "EXPRESS" case standard = "STANDARD" public var description: String { return self.rawValue } } public enum SnowballCapacity: String, CustomStringConvertible, Codable { case t50 = "T50" case t80 = "T80" case t100 = "T100" case t42 = "T42" case nopreference = "NoPreference" public var description: String { return self.rawValue } } public enum SnowballType: String, CustomStringConvertible, Codable { case standard = "STANDARD" case edge = "EDGE" case edgeC = "EDGE_C" case edgeCg = "EDGE_CG" public var description: String { return self.rawValue } } public struct UpdateClusterRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "ClusterId", required: true, type: .string), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: false, type: .structure), AWSShapeMember(label: "RoleARN", required: false, type: .string), AWSShapeMember(label: "ShippingOption", required: false, type: .enum) ] /// The ID of the updated Address object. public let addressId: String? /// The cluster ID of the cluster that you want to update, for example CID123e4567-e89b-12d3-a456-426655440000. public let clusterId: String /// The updated description of this cluster. public let description: String? /// The updated ID for the forwarding address for a cluster. This field is not supported in most regions. public let forwardingAddressId: String? /// The new or updated Notification object. public let notification: Notification? /// The updated arrays of JobResource objects that can include updated S3Resource objects or LambdaResource objects. public let resources: JobResource? /// The new role Amazon Resource Name (ARN) that you want to associate with this cluster. To create a role ARN, use the CreateRole API action in AWS Identity and Access Management (IAM). public let roleARN: String? /// The updated shipping option value of this cluster's ShippingDetails object. public let shippingOption: ShippingOption? public init(addressId: String? = nil, clusterId: String, description: String? = nil, forwardingAddressId: String? = nil, notification: Notification? = nil, resources: JobResource? = nil, roleARN: String? = nil, shippingOption: ShippingOption? = nil) { self.addressId = addressId self.clusterId = clusterId self.description = description self.forwardingAddressId = forwardingAddressId self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingOption = shippingOption } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.clusterId, name:"clusterId", parent: name, max: 39) try validate(self.clusterId, name:"clusterId", parent: name, min: 39) try validate(self.clusterId, name:"clusterId", parent: name, pattern: "CID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.description, name:"description", parent: name, min: 1) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, max: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, min: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.notification?.validate(name: "\(name).notification") try self.resources?.validate(name: "\(name).resources") try validate(self.roleARN, name:"roleARN", parent: name, max: 255) try validate(self.roleARN, name:"roleARN", parent: name, pattern: "arn:aws.*:iam::[0-9]{12}:role/.*") } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case clusterId = "ClusterId" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingOption = "ShippingOption" } } public struct UpdateClusterResult: AWSShape { public init() { } } public struct UpdateJobRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "AddressId", required: false, type: .string), AWSShapeMember(label: "Description", required: false, type: .string), AWSShapeMember(label: "ForwardingAddressId", required: false, type: .string), AWSShapeMember(label: "JobId", required: true, type: .string), AWSShapeMember(label: "Notification", required: false, type: .structure), AWSShapeMember(label: "Resources", required: false, type: .structure), AWSShapeMember(label: "RoleARN", required: false, type: .string), AWSShapeMember(label: "ShippingOption", required: false, type: .enum), AWSShapeMember(label: "SnowballCapacityPreference", required: false, type: .enum) ] /// The ID of the updated Address object. public let addressId: String? /// The updated description of this job's JobMetadata object. public let description: String? /// The updated ID for the forwarding address for a job. This field is not supported in most regions. public let forwardingAddressId: String? /// The job ID of the job that you want to update, for example JID123e4567-e89b-12d3-a456-426655440000. public let jobId: String /// The new or updated Notification object. public let notification: Notification? /// The updated JobResource object, or the updated JobResource object. public let resources: JobResource? /// The new role Amazon Resource Name (ARN) that you want to associate with this job. To create a role ARN, use the CreateRoleAWS Identity and Access Management (IAM) API action. public let roleARN: String? /// The updated shipping option value of this job's ShippingDetails object. public let shippingOption: ShippingOption? /// The updated SnowballCapacityPreference of this job's JobMetadata object. The 50 TB Snowballs are only available in the US regions. public let snowballCapacityPreference: SnowballCapacity? public init(addressId: String? = nil, description: String? = nil, forwardingAddressId: String? = nil, jobId: String, notification: Notification? = nil, resources: JobResource? = nil, roleARN: String? = nil, shippingOption: ShippingOption? = nil, snowballCapacityPreference: SnowballCapacity? = nil) { self.addressId = addressId self.description = description self.forwardingAddressId = forwardingAddressId self.jobId = jobId self.notification = notification self.resources = resources self.roleARN = roleARN self.shippingOption = shippingOption self.snowballCapacityPreference = snowballCapacityPreference } public func validate(name: String) throws { try validate(self.addressId, name:"addressId", parent: name, max: 40) try validate(self.addressId, name:"addressId", parent: name, min: 40) try validate(self.addressId, name:"addressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.description, name:"description", parent: name, min: 1) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, max: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, min: 40) try validate(self.forwardingAddressId, name:"forwardingAddressId", parent: name, pattern: "ADID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try validate(self.jobId, name:"jobId", parent: name, max: 39) try validate(self.jobId, name:"jobId", parent: name, min: 39) try validate(self.jobId, name:"jobId", parent: name, pattern: "(M|J)ID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") try self.notification?.validate(name: "\(name).notification") try self.resources?.validate(name: "\(name).resources") try validate(self.roleARN, name:"roleARN", parent: name, max: 255) try validate(self.roleARN, name:"roleARN", parent: name, pattern: "arn:aws.*:iam::[0-9]{12}:role/.*") } private enum CodingKeys: String, CodingKey { case addressId = "AddressId" case description = "Description" case forwardingAddressId = "ForwardingAddressId" case jobId = "JobId" case notification = "Notification" case resources = "Resources" case roleARN = "RoleARN" case shippingOption = "ShippingOption" case snowballCapacityPreference = "SnowballCapacityPreference" } } public struct UpdateJobResult: AWSShape { public init() { } } }
51.597826
796
0.644219
e992b9e22f9058c364c009da900fdce132e358fa
1,384
import Foundation // Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string. The variable name is the base name of the input file, with the value from an environment value prepended. The input file is the first argument and the output file is the second. if ProcessInfo.processInfo.arguments.count != 3 { print("usage: MySourceGenBuildTool <input> <output>") exit(1) } let inputFile = ProcessInfo.processInfo.arguments[1] let outputFile = ProcessInfo.processInfo.arguments[2] let variablePrefix = ProcessInfo.processInfo.environment["VARIABLE_NAME_PREFIX"] ?? "" let variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent let inputData = FileManager.default.contents(atPath: inputFile) ?? Data() let dataAsHex = inputData.map { String(format: "%02hhx", $0) }.joined() let outputString = "public var \(variablePrefix)\(variableName) = \(dataAsHex.quotedForSourceCode)\n" let outputData = outputString.data(using: .utf8) FileManager.default.createFile(atPath: outputFile, contents: outputData) extension String { public var quotedForSourceCode: String { return "\"" + self .replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") + "\"" } }
47.724138
343
0.729769
90aa7728ff3bf904dd4a2885b7b72e3b945b46b9
450
// // See LICENSE folder for this template’s licensing information. // // Abstract: // Instantiates a live view and passes it to the PlaygroundSupport framework. // import UIKit import BookCore import PlaygroundSupport // Instantiate a new instance of the live view from BookCore and pass it to PlaygroundSupport. PlaygroundPage.current.liveView = instantiateLiveMainViewController() PlaygroundPage.current.needsIndefiniteExecution = true
21.428571
94
0.795556
e848381d05380d11af04095bb5f261c0b658edd5
15,042
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) extension SSMIncidents { // MARK: Async API Calls /// A replication set replicates and encrypts your data to the provided Regions with the provided KMS key. public func createReplicationSet(_ input: CreateReplicationSetInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateReplicationSetOutput { return try await self.client.execute(operation: "CreateReplicationSet", path: "/createReplicationSet", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a response plan that automates the initial response to incidents. A response plan engages contacts, starts chat channel collaboration, and initiates runbooks at the beginning of an incident. public func createResponsePlan(_ input: CreateResponsePlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateResponsePlanOutput { return try await self.client.execute(operation: "CreateResponsePlan", path: "/createResponsePlan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a custom timeline event on the incident details page of an incident record. Timeline events are automatically created by Incident Manager, marking key moment during an incident. You can create custom timeline events to mark important events that are automatically detected by Incident Manager. public func createTimelineEvent(_ input: CreateTimelineEventInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateTimelineEventOutput { return try await self.client.execute(operation: "CreateTimelineEvent", path: "/createTimelineEvent", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Delete an incident record from Incident Manager. public func deleteIncidentRecord(_ input: DeleteIncidentRecordInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteIncidentRecordOutput { return try await self.client.execute(operation: "DeleteIncidentRecord", path: "/deleteIncidentRecord", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes all Regions in your replication set. Deleting the replication set deletes all Incident Manager data. public func deleteReplicationSet(_ input: DeleteReplicationSetInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteReplicationSetOutput { return try await self.client.execute(operation: "DeleteReplicationSet", path: "/deleteReplicationSet", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the resource policy that Resource Access Manager uses to share your Incident Manager resource. public func deleteResourcePolicy(_ input: DeleteResourcePolicyInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteResourcePolicyOutput { return try await self.client.execute(operation: "DeleteResourcePolicy", path: "/deleteResourcePolicy", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified response plan. Deleting a response plan stops all linked CloudWatch alarms and EventBridge events from creating an incident with this response plan. public func deleteResponsePlan(_ input: DeleteResponsePlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteResponsePlanOutput { return try await self.client.execute(operation: "DeleteResponsePlan", path: "/deleteResponsePlan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a timeline event from an incident. public func deleteTimelineEvent(_ input: DeleteTimelineEventInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteTimelineEventOutput { return try await self.client.execute(operation: "DeleteTimelineEvent", path: "/deleteTimelineEvent", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the details for the specified incident record. public func getIncidentRecord(_ input: GetIncidentRecordInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetIncidentRecordOutput { return try await self.client.execute(operation: "GetIncidentRecord", path: "/getIncidentRecord", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieve your Incident Manager replication set. public func getReplicationSet(_ input: GetReplicationSetInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetReplicationSetOutput { return try await self.client.execute(operation: "GetReplicationSet", path: "/getReplicationSet", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves the resource policies attached to the specified response plan. public func getResourcePolicies(_ input: GetResourcePoliciesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetResourcePoliciesOutput { return try await self.client.execute(operation: "GetResourcePolicies", path: "/getResourcePolicies", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves the details of the specified response plan. public func getResponsePlan(_ input: GetResponsePlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetResponsePlanOutput { return try await self.client.execute(operation: "GetResponsePlan", path: "/getResponsePlan", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Retrieves a timeline event based on its ID and incident record. public func getTimelineEvent(_ input: GetTimelineEventInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetTimelineEventOutput { return try await self.client.execute(operation: "GetTimelineEvent", path: "/getTimelineEvent", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists all incident records in your account. Use this command to retrieve the Amazon Resource Name (ARN) of the incident record you want to update. public func listIncidentRecords(_ input: ListIncidentRecordsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListIncidentRecordsOutput { return try await self.client.execute(operation: "ListIncidentRecords", path: "/listIncidentRecords", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// List all related items for an incident record. public func listRelatedItems(_ input: ListRelatedItemsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListRelatedItemsOutput { return try await self.client.execute(operation: "ListRelatedItems", path: "/listRelatedItems", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists details about the replication set configured in your account. public func listReplicationSets(_ input: ListReplicationSetsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListReplicationSetsOutput { return try await self.client.execute(operation: "ListReplicationSets", path: "/listReplicationSets", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists all response plans in your account. public func listResponsePlans(_ input: ListResponsePlansInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListResponsePlansOutput { return try await self.client.execute(operation: "ListResponsePlans", path: "/listResponsePlans", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the tags that are attached to the specified response plan. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse { return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{resourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists timeline events for the specified incident record. public func listTimelineEvents(_ input: ListTimelineEventsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTimelineEventsOutput { return try await self.client.execute(operation: "ListTimelineEvents", path: "/listTimelineEvents", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds a resource policy to the specified response plan. public func putResourcePolicy(_ input: PutResourcePolicyInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> PutResourcePolicyOutput { return try await self.client.execute(operation: "PutResourcePolicy", path: "/putResourcePolicy", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Used to start an incident from CloudWatch alarms, EventBridge events, or manually. public func startIncident(_ input: StartIncidentInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartIncidentOutput { return try await self.client.execute(operation: "StartIncident", path: "/startIncident", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds a tag to a response plan. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> TagResourceResponse { return try await self.client.execute(operation: "TagResource", path: "/tags/{resourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes a tag from a resource. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UntagResourceResponse { return try await self.client.execute(operation: "UntagResource", path: "/tags/{resourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Update deletion protection to either allow or deny deletion of the final Region in a replication set. public func updateDeletionProtection(_ input: UpdateDeletionProtectionInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateDeletionProtectionOutput { return try await self.client.execute(operation: "UpdateDeletionProtection", path: "/updateDeletionProtection", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Update the details of an incident record. You can use this operation to update an incident record from the defined chat channel. For more information about using actions in chat channels, see Interacting through chat. public func updateIncidentRecord(_ input: UpdateIncidentRecordInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateIncidentRecordOutput { return try await self.client.execute(operation: "UpdateIncidentRecord", path: "/updateIncidentRecord", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Add or remove related items from the related items tab of an incident record. public func updateRelatedItems(_ input: UpdateRelatedItemsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateRelatedItemsOutput { return try await self.client.execute(operation: "UpdateRelatedItems", path: "/updateRelatedItems", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Add or delete Regions from your replication set. public func updateReplicationSet(_ input: UpdateReplicationSetInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateReplicationSetOutput { return try await self.client.execute(operation: "UpdateReplicationSet", path: "/updateReplicationSet", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the specified response plan. public func updateResponsePlan(_ input: UpdateResponsePlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateResponsePlanOutput { return try await self.client.execute(operation: "UpdateResponsePlan", path: "/updateResponsePlan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates a timeline event. You can update events of type Custom Event. public func updateTimelineEvent(_ input: UpdateTimelineEventInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateTimelineEventOutput { return try await self.client.execute(operation: "UpdateTimelineEvent", path: "/updateTimelineEvent", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
86.947977
309
0.751895
9c17d06394b5ef84026e885db13c967dd93e88e2
7,720
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) extension FIS { // MARK: Async API Calls /// Creates an experiment template. To create a template, specify the following information: Targets: A target can be a specific resource in your AWS environment, or one or more resources that match criteria that you specify, for example, resources that have specific tags. Actions: The actions to carry out on the target. You can specify multiple actions, the duration of each action, and when to start each action during an experiment. Stop conditions: If a stop condition is triggered while an experiment is running, the experiment is automatically stopped. You can define a stop condition as a CloudWatch alarm. For more information, see the AWS Fault Injection Simulator User Guide. public func createExperimentTemplate(_ input: CreateExperimentTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateExperimentTemplateResponse { return try await self.client.execute(operation: "CreateExperimentTemplate", path: "/experimentTemplates", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified experiment template. public func deleteExperimentTemplate(_ input: DeleteExperimentTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteExperimentTemplateResponse { return try await self.client.execute(operation: "DeleteExperimentTemplate", path: "/experimentTemplates/{id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets information about the specified AWS FIS action. public func getAction(_ input: GetActionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetActionResponse { return try await self.client.execute(operation: "GetAction", path: "/actions/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets information about the specified experiment. public func getExperiment(_ input: GetExperimentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetExperimentResponse { return try await self.client.execute(operation: "GetExperiment", path: "/experiments/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets information about the specified experiment template. public func getExperimentTemplate(_ input: GetExperimentTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetExperimentTemplateResponse { return try await self.client.execute(operation: "GetExperimentTemplate", path: "/experimentTemplates/{id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the available AWS FIS actions. public func listActions(_ input: ListActionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListActionsResponse { return try await self.client.execute(operation: "ListActions", path: "/actions", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists your experiment templates. public func listExperimentTemplates(_ input: ListExperimentTemplatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListExperimentTemplatesResponse { return try await self.client.execute(operation: "ListExperimentTemplates", path: "/experimentTemplates", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists your experiments. public func listExperiments(_ input: ListExperimentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListExperimentsResponse { return try await self.client.execute(operation: "ListExperiments", path: "/experiments", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the tags for the specified resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse { return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{resourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Starts running an experiment from the specified experiment template. public func startExperiment(_ input: StartExperimentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StartExperimentResponse { return try await self.client.execute(operation: "StartExperiment", path: "/experiments", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Stops the specified experiment. public func stopExperiment(_ input: StopExperimentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> StopExperimentResponse { return try await self.client.execute(operation: "StopExperiment", path: "/experiments/{id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Applies the specified tags to the specified resource. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> TagResourceResponse { return try await self.client.execute(operation: "TagResource", path: "/tags/{resourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes the specified tags from the specified resource. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UntagResourceResponse { return try await self.client.execute(operation: "UntagResource", path: "/tags/{resourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the specified experiment template. public func updateExperimentTemplate(_ input: UpdateExperimentTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateExperimentTemplateResponse { return try await self.client.execute(operation: "UpdateExperimentTemplate", path: "/experimentTemplates/{id}", httpMethod: .PATCH, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
79.587629
704
0.737824
fb3ba992fda444f934242097628c48857b53d963
4,200
import Foundation import RealmSwift import UserNotifications public final class NotificationCategory: Object, UpdatableModel { public static let FallbackActionIdentifier = "_" @objc public dynamic var isServerControlled: Bool = false @objc public dynamic var serverIdentifier: String = "" @objc public dynamic var Name: String = "" @objc public dynamic var Identifier: String = "" @objc public dynamic var HiddenPreviewsBodyPlaceholder: String? // iOS 12+ only @objc public dynamic var CategorySummaryFormat: String? // Options @objc public dynamic var SendDismissActions: Bool = true @objc public dynamic var HiddenPreviewsShowTitle: Bool = false @objc public dynamic var HiddenPreviewsShowSubtitle: Bool = false // Maybe someday, HA will be on CarPlay (hey that rhymes!)... // @objc dynamic var AllowInCarPlay: Bool = false public var Actions = List<NotificationAction>() static func primaryKey(sourceIdentifier: String, serverIdentifier: String) -> String { #warning("multiserver - primary key duplication") return sourceIdentifier } override public static func primaryKey() -> String? { #keyPath(Identifier) } static func serverIdentifierKey() -> String { #keyPath(serverIdentifier) } public var options: UNNotificationCategoryOptions { var categoryOptions = UNNotificationCategoryOptions([]) if SendDismissActions { categoryOptions.insert(.customDismissAction) } #if os(iOS) if HiddenPreviewsShowTitle { categoryOptions.insert(.hiddenPreviewsShowTitle) } if HiddenPreviewsShowSubtitle { categoryOptions.insert(.hiddenPreviewsShowSubtitle) } #endif return categoryOptions } #if os(iOS) public var categories: [UNNotificationCategory] { [ UNNotificationCategory( identifier: Identifier.uppercased(), actions: Array(Actions.map(\.action)), intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: HiddenPreviewsBodyPlaceholder, categorySummaryFormat: CategorySummaryFormat, options: options ), ] } #endif public var exampleServiceCall: String { let urlStrings = Actions.map { "\"\($0.Identifier)\": \"http://example.com/url\"" } let indentation = "\n " return """ service: notify.mobile_app_#name_here data: push: category: \(Identifier.uppercased()) action_data: # see example trigger in action # value will be in fired event # url can be absolute path like: # "http://example.com/url" # or relative like: # "/lovelace/dashboard" # pick one of the following styles: # always open when opening notification url: "/lovelace/dashboard" # open a different url per action # use "\(Self.FallbackActionIdentifier)" as key for no action chosen url: "\(Self.FallbackActionIdentifier)": "http://example.com/fallback" \(urlStrings.joined(separator: indentation)) """ } static func didUpdate(objects: [NotificationCategory], server: Server, realm: Realm) {} static func willDelete(objects: [NotificationCategory], server: Server?, realm: Realm) {} static var updateEligiblePredicate: NSPredicate { .init(format: "isServerControlled == YES") } public func update(with object: MobileAppConfigPushCategory, server: Server, using realm: Realm) -> Bool { if self.realm == nil { Identifier = object.identifier.uppercased() } else { precondition(Identifier == object.identifier.uppercased()) } isServerControlled = true serverIdentifier = server.identifier.rawValue Name = object.name // TODO: update realm.delete(Actions) Actions.removeAll() Actions.append(objectsIn: object.actions.map { action in NotificationAction(action: action) }) return true } }
32.061069
110
0.640238
62d0830d8b68836259b62d40b92526657f619fec
146
// // BaseMJRefreshHeader.swift // FBusiness // // import UIKit import MJRefresh public class BaseMJRefreshHeader: MJRefreshNormalHeader { }
11.230769
57
0.753425
646fb3e8613a7ba57c3e841467b678a14a745deb
2,175
// // AppDelegate.swift // StyledTextField // // Created by Tobioka on 2017/11/11. // Copyright © 2017年 tnantoka. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.276596
285
0.756322
e475aa7a3fe2163793245b85a3b69397354c5801
3,610
// // UIView+ImageKit.swift // PHImageKit // // Copyright (c) 2016 Product Hunt (http://producthunt.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UIView { func ik_setConstraintsToSuperview() { guard let superview = superview else { return } self.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) superview.addConstraints([topConstraint, bottomConstraint, leftConstraint, rightConstraint]) } func ik_setConstraintsToSuperviewCenter(_ size: CGSize) { guard let superview = superview else { return } self.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.width) let heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.height) let centerXConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) let centerYConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) superview.addConstraints([widthConstraint, heightConstraint, centerXConstraint, centerYConstraint]) } }
59.180328
242
0.76759
1de027ddeef35bb67a6f61efdbbe6e363431d665
1,505
// // ColumnSchema.swift // SQLiteProtocol // // Created by Manuel Reich on 20.03.19. // import SQLite public protocol ColumnSchema { associatedtype Model associatedtype PrimaryKeyType: Value where PrimaryKeyType.Datatype: Equatable static var primaryColumn: PrimaryColumn<Model, Self, PrimaryKeyType> { get } static var columns: [Builder<Model, Self>] { get } init() static func buildTable(tableBuilder: TableBuilder) static func from(row: Row) -> Self } extension ColumnSchema { public static func buildTable(tableBuilder: TableBuilder) { self.primaryColumn.builder.createColumn(tableBuilder) for column in self.columns { column.createColumn(tableBuilder) } } public static func from(row: Row) -> Self { var columns = Self.init() self.primaryColumn.builder.addValue(row, &columns) for column in self.columns { column.addValue(row, &columns) } return columns } public static func getSetters(from model: Model) throws -> [Setter] { let primaryKeySetter = try self.primaryColumn.builder.buildSetter(model) let setters = try self.columns.map { column in try column.buildSetter(model) } return [primaryKeySetter] + setters } public static func primaryKeySelector(value: PrimaryKeyType) -> Expression<Bool> { let expression = Expression<PrimaryKeyType>(Self.primaryColumn.name) return expression == value } }
29.509804
86
0.67907
296120e343b49136d5074e1f01352b294a608f14
1,033
import Combine import Foundation public extension FS.Request.User { struct FetchById: FirestoreRequestProtocol { public typealias Entry = FSDocument public typealias Collection = FS.Collection.Users public typealias Response = FS.Document.User public struct Parameters: Codable { let id: String public init(id: String) { self.id = id } } public var parameters: Parameters public var testDataPath: URL? public var path: String { Collection.name self.parameters.id } public var entry: Entry { FirestoreManager.db.document(self.path) } public init(parameters: Parameters) { self.parameters = parameters } public func reguest( useTestData: Bool, parameters: Parameters ) -> AnyPublisher<FS.Document.User, Error> { self.entry.getDocument(Response.self) } } }
25.195122
57
0.575992
2fab8cd5220320dd591e0bf6fc2e353bf2df0828
4,799
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import AVFoundation import UIKit class ViewController: UIViewController, QRCodeReaderViewControllerDelegate { @IBOutlet weak var previewView: QRCodeReaderView! lazy var reader: QRCodeReader = QRCodeReader() lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: .back) $0.showTorchButton = true } return QRCodeReaderViewController(builder: builder) }() // MARK: - Actions private func checkScanPermissions() -> Bool { do { return try QRCodeReader.supportsMetadataObjectTypes() } catch let error as NSError { let alert: UIAlertController switch error.code { case -11852: alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(settingsURL) } } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) default: alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) } present(alert, animated: true, completion: nil) return false } } @IBAction func scanInModalAction(_ sender: AnyObject) { guard checkScanPermissions() else { return } readerVC.modalPresentationStyle = .formSheet readerVC.delegate = self readerVC.completionBlock = { (result: QRCodeReaderResult?) in if let result = result { print("Completion with result: \(result.value) of type \(result.metadataType)") } } present(readerVC, animated: true, completion: nil) } @IBAction func scanInPreviewAction(_ sender: Any) { guard checkScanPermissions(), !reader.isRunning else { return } previewView.setupComponents(showCancelButton: false, showSwitchCameraButton: false, showTorchButton: false, showOverlayView: true, reader: reader) reader.startScanning() reader.didFindCode = { result in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) } } // MARK: - QRCodeReader Delegate Methods func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { reader.stopScanning() dismiss(animated: true) { [weak self] in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self?.present(alert, animated: true, completion: nil) } } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { print("Switching capturing to: \(newCaptureDevice.device.localizedName)") } func readerDidCancel(_ reader: QRCodeReaderViewController) { reader.stopScanning() dismiss(animated: true, completion: nil) } }
36.356061
150
0.703897
1d260336d7a55ab48a5a7d47276f1e616388b7c0
4,891
// // PhysicsWorld.swift // Fiber2D // // Created by Andrey Volodin on 18.09.16. // Copyright © 2016 s1ddok. All rights reserved. // import SwiftMath import CChipmunk2D /** * @class PhysicsWorld * @brief An PhysicsWorld object simulates collisions and other physical properties. */ public class PhysicsWorld { /** A delegate that is called when two physics shapes come in contact with each other. */ public weak var contactDelegate: PhysicsContactDelegate? /** * Get the gravity value of this physics world. * * @return A Vec2 object. */ public var gravity: vec2 = vec2(0.0, -98.0) { didSet { cpSpaceSetGravity(chipmunkSpace, cpVect(gravity)) } } /** * Set the speed of this physics world. * * @attention if you set autoStep == false, this won't work. * @param speed A float number. Speed is the rate at which the simulation executes. default value is 1.0. */ public var speed: Float = 1.0 /** * The number of substeps in an update of the physics world. * * One physics update will be divided into several substeps to increase its accuracy. * @param steps An integer number, default value is 1. */ public var substeps: UInt = 1 { didSet { if substeps > 1 { updateRate = 1 } } } /** * Set the update rate of this physics world * * Update rate is the value of EngineUpdateTimes/PhysicsWorldUpdateTimes. * Set it higher can improve performance, set it lower can improve accuracy of physics world simulation. * @attention if you set autoStep == false, this won't work. * @param rate An float number, default value is 1.0. */ public var updateRate: Float = 1.0 /** * set the number of update of the physics world in a second. * 0 - disable fixed step system * default value is 0 */ public var fixedUpdateRate: UInt = 0 /** * The debug draw options of this physics world. * * This physics world will draw shapes and joints by DrawNode according to mask. */ public var debugDrawOptions = [DebugDrawOption]() /** * To control the step of physics. * * If you want control it by yourself( fixed-timestep for example ), you can set this to false and call step by yourself. * @attention If you set auto step to false, setSpeed setSubsteps and setUpdateRate won't work, you need to control the time step by yourself. * @param autoStep A bool object, default value is true. */ public var autoStep: Bool = true /** * The step for physics world. * * The times passing for simulate the physics. * @attention You need to setAutoStep(false) first before it can work. * @param delta A Time number. */ public func step(dt: Time) { guard !autoStep else { print("Cant step: You need to close auto step( autoStep = false ) first") return } updateDelaysIfNeeded() update(dt: dt, userCall: true) } /** * A root node that contains this physics world. * * @attention This value is initialized in constructor * @return A Node object reference. */ public let rootNode: Node internal(set) public var joints = [PhysicsJoint]() /** * Get all the bodies that in this physics world. * * @return A [PhysicsBody] that contains all bodies in this physics world. */ internal(set) public var bodies = [PhysicsBody]() public init(rootNode: Node) { self.rootNode = rootNode chipmunkSpace = cpHastySpaceNew() cpHastySpaceSetThreads(chipmunkSpace, 0) cpSpaceSetGravity(chipmunkSpace, cpVect(gravity)) let handler = cpSpaceAddDefaultCollisionHandler(chipmunkSpace)! handler.pointee.userData = Unmanaged.passRetained(self).toOpaque() handler.pointee.beginFunc = collisionBeginCallbackFunc handler.pointee.postSolveFunc = collisionPostSolveCallbackFunc handler.pointee.preSolveFunc = collisionPreSolveCallbackFunc handler.pointee.separateFunc = collisionSeparateCallbackFunc } // MARK: Internal stuff // MARK: Chipmunk vars internal var chipmunkSpace: UnsafeMutablePointer<cpSpace>! // MARK: Joints vars internal var delayRemoveJoints = [PhysicsJoint]() internal var delayAddJoints = [PhysicsJoint]() // MARK: Bodies vars internal var delayRemoveBodies = [PhysicsBody]() internal var delayAddBodies = [PhysicsBody]() // MARK: Other vars internal var updateTime: Time = 0.0 internal var updateRateCount = 0 // MARK: Destructor deinit { cpHastySpaceFree(chipmunkSpace) } }
31.554839
146
0.637293
f95c7a81d310e727be0cc5cbbfa095ba846a672c
13,559
// // CommonUtil.swift // ZCRMiOS // // Created by Vijayakrishna on 11/11/16. // Copyright © 2016 zohocrm. All rights reserved. // import Foundation let PhotoSupportedModules = ["Leads", "Contacts"] public enum ZCRMSDKError : Error { case UnAuthenticatedError(String) case InValidError(String) case ProcessingError(String) case MaxRecordCountExceeded(String) case FileSizeExceeded(String) case InternalError( String ) case ConnectionError( String ) } public enum SortOrder : String { case ASCENDING = "asc" case DESCENDING = "desc" } public enum AccessType : String { case PRODUCTION = "Production" case DEVELOPMENT = "Development" case SANDBOX = "Sandbox" } public enum PhotoSize : String { case STAMP = "stamp" case THUMB = "thumb" case ORIGINAL = "original" case FAVICON = "favicon" case MEDIUM = "medium" } internal extension Dictionary { func hasKey( forKey : Key ) -> Bool { return self[ forKey ] != nil } func hasValue(forKey : Key) -> Bool { return self[forKey] != nil && !(self[forKey] is NSNull) } func optValue(key: Key) -> Any? { if(self.hasValue(forKey: key)) { return self[key]! } else { return nil } } func optString(key : Key) -> String? { return optValue(key: key) as? String } func optInt(key : Key) -> Int? { return optValue(key: key) as? Int } func optInt64(key : Key) -> Int64? { guard let stringID = optValue(key: key) as? String else { return nil } return Int64(stringID) } func optDouble(key : Key) -> Double? { return optValue(key: key) as? Double } func optBoolean(key : Key) -> Bool? { return optValue(key: key) as? Bool } func optDictionary(key : Key) -> Dictionary<String, Any>? { return optValue(key: key) as? Dictionary<String, Any> } func optArray(key : Key) -> Array<Any>? { return optValue(key: key) as? Array<Any> } func optArrayOfDictionaries( key : Key ) -> Array< Dictionary < String, Any > >? { return ( optValue( key : key ) as? Array< Dictionary < String, Any > > ) } func getInt( key : Key ) -> Int { return optInt( key : key )! } func getInt64( key : Key ) -> Int64 { return optInt64( key : key )! } func getString( key : Key ) -> String { return optString( key : key )! } func getBoolean( key : Key ) -> Bool { return optBoolean( key : key )! } func getDouble( key : Key ) -> Double { return optDouble( key : key )! } func getArray( key : Key ) -> Array< Any > { return optArray( key : key )! } func getDictionary( key : Key ) -> Dictionary< String, Any > { return optDictionary( key : key )! } func getArrayOfDictionaries( key : Key ) -> Array< Dictionary < String, Any > > { return optArrayOfDictionaries( key : key )! } func convertToJSON() -> String { let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) let jsonString = String(data: jsonData!, encoding: String.Encoding.ascii) return jsonString! } func equateKeys( dictionary : [ String : Any ] ) -> Bool { let dictKeys = dictionary.keys var isEqual : Bool = true for key in self.keys { if dictKeys.index(of: key as! String) == nil { isEqual = false } } return isEqual } } public extension Array { func ArrayOfDictToStringArray () -> String { var stringArray: [String] = [] self.forEach { let dictionary = $0 as! Dictionary<String, Any> stringArray.append(dictionary.convertToJSON()) } let dup = stringArray.joined(separator: "-") return dup } } public extension String { func pathExtension() -> String { return self.nsString.pathExtension } func deleteLastPathComponent() -> String { return self.nsString.deletingLastPathComponent } func lastPathComponent( withExtension : Bool = true ) -> String { let lpc = self.nsString.lastPathComponent return withExtension ? lpc : lpc.nsString.deletingPathExtension } var nsString : NSString { return NSString( string : self ) } func boolValue() -> Bool { switch self { case "True", "true", "yes", "1" : return true case "False", "false", "no", "0" : return false default : return false } } var dateFromISO8601 : Date? { return Formatter.iso8601.date( from : self ) // "Nov 14, 2017, 10:22 PM" } var dateComponents : DateComponents { let date : Date = Formatter.iso8601.date( from : self )! return date.dateComponents } var millisecondsSince1970 : Double { let date : Date = Formatter.iso8601.date( from : self )! return date.millisecondsSince1970 } func convertToDictionary() -> [String: String]? { let data = self.data(using: .utf8) let anyResult = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) return anyResult as? [String: String] } func StringArrayToArrayOfDictionary () -> Array< Dictionary < String, Any > > { var arrayOfDic : Array< Dictionary < String, Any > > = [] let array : [String] = self.components(separatedBy: "-") array.forEach { let json = $0 let val = json.convertToDictionary() if(val != nil) { arrayOfDic.append(val!) } } return arrayOfDic } func toNSArray() throws -> NSArray { var nsarray = NSArray() if(self.isEmpty == true) { return nsarray } if let data = self.data(using: String.Encoding.utf8) { do { nsarray = try JSONSerialization.jsonObject(with: data, options: []) as! NSArray } } return nsarray } } extension Error { var code : Int { return ( self as NSError ).code } var description : String { return ( self as NSError ).localizedDescription } } extension Formatter { static let iso8601 : DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar( identifier : .iso8601 ) formatter.locale = Locale( identifier : "en_US_POSIX" ) formatter.timeZone = TimeZone( secondsFromGMT : 0 ) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" return formatter }() static let iso8601WithTimeZone : DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar( identifier : .iso8601 ) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX" return formatter }() } public extension Date { var iso8601 : String { return Formatter.iso8601WithTimeZone.string( from : self ).replacingOccurrences( of : "Z", with : "+00:00" ).replacingOccurrences( of : "z", with : "+00:00" ) } func millisecondsToISO( timeIntervalSince1970 : Double, timeZone : TimeZone ) -> String { let date = Date( timeIntervalSince1970 : timeIntervalSince1970 ) return self.dateToISO( date : date, timeZone : timeZone ) } func millisecondsToISO( timeIntervalSinceNow : Double, timeZone : TimeZone ) -> String { let date = Date( timeIntervalSinceNow : timeIntervalSinceNow ) return self.dateToISO( date : date, timeZone : timeZone ) } func millisecondsToISO( timeIntervalSinceReferenceDate : Double, timeZone : TimeZone ) -> String { let date = Date( timeIntervalSinceReferenceDate : timeIntervalSinceReferenceDate ) return self.dateToISO( date : date, timeZone : timeZone ) } private func dateToISO( date : Date, timeZone : TimeZone ) -> String { let formatter = Formatter.iso8601WithTimeZone formatter.timeZone = timeZone return formatter.string( from : date ).replacingOccurrences( of : "Z", with : "+00:00" ).replacingOccurrences( of : "z", with : "+00:00" ) } var millisecondsSince1970 : Double { return ( self.timeIntervalSince1970 * 1000.0 ) } var dateComponents : DateComponents { let calender = Calendar.current let components = calender.dateComponents( [ Calendar.Component.day, Calendar.Component.month, Calendar.Component.year, Calendar.Component.quarter, Calendar.Component.timeZone, Calendar.Component.weekOfMonth, Calendar.Component.weekOfYear, Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second ], from : self ) var dateComponents = DateComponents() dateComponents.day = components.day! dateComponents.month = components.month! dateComponents.year = components.year! dateComponents.timeZone = components.timeZone! dateComponents.weekOfMonth = components.weekOfMonth! dateComponents.quarter = components.quarter! dateComponents.weekOfYear = components.weekOfYear! dateComponents.hour = components.hour! dateComponents.minute = components.minute! dateComponents.second = components.second! return dateComponents } } internal extension Optional where Wrapped == String { var notNilandEmpty : Bool { if(self != nil && !(self?.isEmpty)!) { return true } return false ; } } public func getCurrentMillisecSince1970() -> Double { return Date().timeIntervalSince1970 * 1000 } public func getCurrentMillisecSinceNow() -> Double { return Date().timeIntervalSinceNow * 1000 } public func getCurrentMillisecSinceReferenceDate() -> Double { return Date().timeIntervalSinceReferenceDate * 1000 } public func getCurrentMillisec( date : Date ) -> Double { return Date().timeIntervalSince( date ) * 1000 } public func moveFile(sourceUrl: URL, destinationUrl: URL) { moveFile(filePath: sourceUrl.path, newFilePath: destinationUrl.path) } public func moveFile(filePath: String, newFilePath: String) { do { try FileManager.default.moveItem(atPath: filePath, toPath: newFilePath) } catch(let err) { print("Exception while moving file - \(err)") } } public func photoSupportedModuleCheck( moduleAPIName : String ) throws { if ( !PhotoSupportedModules.contains( moduleAPIName ) ) { throw ZCRMSDKError.InValidError( "Photo not supported for this module." ) } } public func fileDetailCheck( filePath : String ) throws { if ( FileManager.default.fileExists( atPath : filePath ) == false ) { throw ZCRMSDKError.InValidError( "File not found at given path : \( filePath )" ) } if ( getFileSize( filePath : filePath ) > 2097152 ) { throw ZCRMSDKError.FileSizeExceeded( "Cannot upload. File size should not exceed to 20MB" ) } } internal func getFileSize( filePath : String ) -> Int64 { do { let fileAttributes = try FileManager.default.attributesOfItem( atPath : filePath ) if let fileSize = fileAttributes[ FileAttributeKey.size ] { return ( fileSize as! NSNumber ).int64Value } else { print( "Failed to get a size attribute from path : \( filePath )" ) } } catch { print( "Failed to get file attributes for local path: \( filePath ) with error: \( error )" ) } return 0 } var APPTYPE : String = "ZCRM" var APIBASEURL : String = String() var APIVERSION : String = String() var COUNTRYDOMAIN : String = "com" let PHOTOURL : URL = URL( string : "https://profile.zoho.com/api/v1/user/self/photo" )! let BOUNDARY = String( format : "unique-consistent-string-%@", UUID.init().uuidString ) let LEADS : String = "Leads" let ACCOUNTS : String = "Accounts" let CONTACTS : String = "Contacts" let DEALS : String = "Deals" let QUOTES : String = "Quotes" let SALESORDERS : String = "SalesOrders" let INVOICES : String = "Invoices" let PURCHASEORDERS : String = "PurchaseOrders" let INVALID_ID_MSG : String = "The given id seems to be invalid." let INVALID_DATA : String = "INVALID_DATA" let API_MAX_RECORDS_MSG : String = "Cannot process more than 100 records at a time." let ACTION : String = "action" let DUPLICATE_FIELD : String = "duplicate_field" let MESSAGE : String = "message" let DATA : String = "data" let STATUS : String = "status" let CODE : String = "code" let CODE_ERROR : String = "error" let CODE_SUCCESS : String = "success" let INFO : String = "info" let DETAILS : String = "details" let PER_PAGE : String = "per_page" let PAGE : String = "page" let COUNT : String = "count" let MORE_RECORDS : String = "more_records" let REMAINING_COUNT_FOR_THIS_DAY : String = "X-RATELIMIT-LIMIT" let REMAINING_COUNT_FOR_THIS_WINDOW : String = "X-RATELIMIT-REMAINING" let REMAINING_TIME_FOR_THIS_WINDOW_RESET : String = "X-RATELIMIT-RESET"
26.638507
341
0.610148
8a11afa2e449b8f56a1243e7e14bde157437f3b8
2,202
// // AppDelegate.swift // ImageConstraintsLandscapePortrait // // Created by Bart van Kuik on 05/07/2018. // Copyright © 2018 DutchVirtual. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.851064
285
0.758401
1ef8f271f6de0e1db3a3d34aca37d9186bb0bf66
242
// // UsernameType.swift // GoldenHillHTTPLibrary // // Created by John Brayton on 3/5/17. // Copyright © 2017 John Brayton. All rights reserved. // import Foundation public enum UsernameType { case username case emailAddress }
16.133333
55
0.706612
1dbfe182e39f162ff7081d2230a10fe1e97176f9
150
extension Optional { public func toArray<T>(transform: (Wrapped) throws -> [T]) rethrows -> [T] { return try map(transform) ?? [] } }
25
80
0.586667
f4e8cf76584a230ece76b76e503529a5e7b37e05
3,724
import UIKit import AVFoundation extension MainViews { class AlertView: UIView { // MARK: - Views private lazy var backgroundView: UIView = { let view = UIView() let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.systemMaterialDark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) return view }() private lazy var alertImageView: UIImageView = UIImageView.defaultImageView( config: UIImageView.Config(image: UIImage()) ) private lazy var alertTitleLabel: UILabel = UILabel.defaultLabel( config: UILabel.Config( title: "", textColor: activeTheme.colors.blank, textAlignment: .center ) ) // MARK: - Variables private var detectActionHandler: (() -> Void)? // MARK: - Life Cycle init() { super.init(frame: .zero) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup func setupDetectActionHandler(_ handler: @escaping () -> Void) { detectActionHandler = handler } private func setupViews() { backgroundColor = .clear setupBackgroundView() setupAlertTitleLabel() setupAlertImageView() } private func setupBackgroundView() { addSubview(backgroundView) backgroundView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ backgroundView.topAnchor.constraint(equalTo: self.topAnchor), backgroundView.leadingAnchor.constraint(equalTo: self.leadingAnchor), backgroundView.trailingAnchor.constraint(equalTo: self.trailingAnchor), backgroundView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } private func setupAlertTitleLabel() { addSubview(alertTitleLabel) alertTitleLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ alertTitleLabel.topAnchor.constraint(equalTo: centerYAnchor, constant: 5), alertTitleLabel.leadingAnchor.constraint( equalTo: leadingAnchor, constant: 40 ), alertTitleLabel.trailingAnchor.constraint( equalTo: trailingAnchor, constant: -40 ), alertTitleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 30) ]) } private func setupAlertImageView() { addSubview(alertImageView) alertImageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ alertImageView.bottomAnchor.constraint(equalTo: centerYAnchor, constant: -5), alertImageView.centerXAnchor.constraint(equalTo: centerXAnchor), alertImageView.widthAnchor.constraint(equalToConstant: 50), alertImageView.heightAnchor.constraint(equalToConstant: 50) ]) } func updateAlertView(image: UIImage, title: String) { alertImageView.image = image alertTitleLabel.text = title } } }
37.24
93
0.583781
2fcebfe006cf6e377c03c84e7f242f8b0e8c3b77
4,711
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: google/protobuf/unittest_no_arena_import.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct Proto2ArenaUnittest_ImportNoArenaNestedMessage: SwiftProtobuf.Message { static let protoMessageName: String = _protobuf_package + ".ImportNoArenaNestedMessage" var d: Int32 { get {return _d ?? 0} set {_d = newValue} } /// Returns true if `d` has been explicitly set. var hasD: Bool {return self._d != nil} /// Clears the value of `d`. Subsequent reads from it will return its default value. mutating func clearD() {self._d = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} /// Used by the decoding initializers in the SwiftProtobuf library, not generally /// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding /// initializers are defined in the SwiftProtobuf library. See the Message and /// Message+*Additions` files. mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularInt32Field(value: &self._d) default: break } } } /// Used by the encoding methods of the SwiftProtobuf library, not generally /// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and /// other serializer methods are defined in the SwiftProtobuf library. See the /// `Message` and `Message+*Additions` files. func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._d { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } fileprivate var _d: Int32? = nil } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "proto2_arena_unittest" extension Proto2ArenaUnittest_ImportNoArenaNestedMessage: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "d"), ] func _protobuf_generated_isEqualTo(other: Proto2ArenaUnittest_ImportNoArenaNestedMessage) -> Bool { if self._d != other._d {return false} if unknownFields != other.unknownFields {return false} return true } }
42.827273
135
0.753131
6159c355f07ccde571fb72dcd39e86529fb17116
618
import Foundation public struct Consts { public static let cartfileName = "Cartfile" public static let mintfileName = "Mintfile" public static let podsDirectoryName = "Pods" public static let packageName = "Package.swift" public static let xcworkspaceExtension = "xcworkspace" public static let xcodeprojExtension = "xcodeproj" public static let prefix = "com.mono0926.LicensePlist" public static let outputPath = "\(prefix).Output" public static let configPath = "license_plist.yml" public static let version = "3.21.0" public static let encoding = String.Encoding.utf8 }
38.625
58
0.736246
fe620beb465a650b91759f1aca34010bdfbfcf3b
686
// // iVariantApp.swift // iVariant // // Created by Lakr Aream on 2021/9/24. // import SwiftUI @main struct iVariantApp: App { var body: some Scene { WindowGroup { ContentView() .frame(minWidth: 800, maxWidth: 5000, minHeight: 400, maxHeight: 5000) .toolbar { ToolbarItem { Button { NSWorkspace.shared.open(URL(string: "https://github.com/Co2333/iVariant")!) } label: { Image(systemName: "questionmark.circle.fill") } } } } } }
24.5
103
0.441691
fc33b93326c12fe19453bce2fb58391001ae41c6
7,166
// // MediaTableViewController.swift // TMDb // // Created by Santiago Rojas on 5/3/19. // Copyright © 2019 Santiago Rojas. All rights reserved. // import UIKit import Kingfisher import RxSwift import RxCocoa class MediaTableViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var categoriesSegmentedControl: UISegmentedControl! var viewModel = MediaTableViewModel() var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() viewModel.delegate = self let nib = UINib(nibName: "MediaCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: MediaCell.reusableIdentifier) tableView.delegate = self tableView.dataSource = self tableView.prefetchDataSource = self tableView.tableFooterView = UIView() tableView.contentInset.top += toolbar.bounds.height tableView.scrollIndicatorInsets.top += toolbar.bounds.height // SearchBar configuration parent?.definesPresentationContext = true parent?.navigationItem.searchController = UISearchController(searchResultsController: nil) parent?.navigationItem.searchController?.obscuresBackgroundDuringPresentation = false if let searchBar = parent?.navigationItem.searchController?.searchBar { searchBar.placeholder = parent is MoviesViewController ? "Filter movies".localizedString : "Filter TV shows".localizedString searchBar.tintColor = UIColor(named: "Main") searchBar.barStyle = .black searchBar.delegate = self searchBar.rx.text.bind(to: viewModel.searchText).disposed(by: disposeBag) } viewModel.searchText .throttle(.milliseconds(500), scheduler: MainScheduler.instance) .filter{ $0 != nil && $0!.count > 0 } .distinctUntilChanged() .subscribe(onNext: { self.categoriesSegmentedControl.isEnabled = false self.viewModel.isSearching = true self.viewModel.search(contains: $0!) self.tableView.reloadData() if !self.viewModel.searchResults.isEmpty { self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } }).disposed(by: disposeBag) viewModel.searchText .filter{ $0 == "" } .observeOn(MainScheduler.instance) .subscribe({_ in self.viewModel.searchResults = [] self.tableView.reloadData() }).disposed(by: disposeBag) viewModel.fetch(page: 1) } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.setValue(true, forKey: "hidesShadow") } override func viewDidDisappear(_ animated: Bool) { navigationController?.navigationBar.setValue(false, forKey: "hidesShadow") } @IBAction func changeCategory(_ sender: UISegmentedControl) { viewModel.category = TMDbCategory(rawValue: sender.selectedSegmentIndex)! viewModel.media.removeAll() viewModel.fetch(page: 1) if viewModel.totalCount > 0 { tableView.scrollToRow(at: IndexPath(item: 0, section: 0), at: .top, animated: false) } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. super.prepare(for: segue, sender: sender) switch segue.identifier ?? "" { case "Show Detail": guard let mediaDetailViewController = segue.destination as? MediaDetailViewController, let indexPath = sender as? IndexPath else { return } let page = (indexPath.row / 20) + 1 let item = indexPath.row % 20 mediaDetailViewController.viewModel.mediaData = viewModel.isSearching ? viewModel.searchResults[indexPath.row] : viewModel.media[page]?[item] mediaDetailViewController.viewModel.mediaType = viewModel.mediaType default: fatalError("Unidentified Segue") } } } extension MediaTableViewController: UITableViewDataSource, UITableViewDelegate, UITableViewDataSourcePrefetching { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if viewModel.isSearching { return viewModel.searchResults.count } else { return viewModel.totalCount } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: MediaCell.reusableIdentifier) as! MediaCell let page = (indexPath.row / 20) + 1 let item = indexPath.row % 20 if let media = viewModel.isSearching ? viewModel.searchResults[indexPath.row]: viewModel.media[page]?[item] { cell.configure(title: media.title ?? media.name ?? "" , score: media.voteAverage, overview: media.overview) cell.mediaImage.kf.setImage(with: URL(string: "https://image.tmdb.org/t/p/w500\(media.posterPath ?? "")"),placeholder: UIImage(named: "Media Placeholder")) } else { cell.loading() } return cell } func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { if !viewModel.isSearching, indexPaths.contains(where: { (indexPath) -> Bool in let page = (indexPath.row / 20) + 1 let item = indexPath.row % 20 return self.viewModel.media[page]?[item] == nil }) { viewModel.fetch(page: (indexPaths[0].row / 20) + 1) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "Show Detail", sender: indexPath) } } extension MediaTableViewController: MediaTableViewModelDelegate { func onFetchCompleted() { tableView.reloadData() } func onFetchFailed(with reason: String) { let title = "Warning".localizedString let action = UIAlertAction(title: "OK".localizedString, style: .default) let alertController = UIAlertController(title: title, message: reason, preferredStyle: .alert) alertController.addAction(action) self.present(alertController, animated: true) } } extension MediaTableViewController: UISearchBarDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { viewModel.isSearching = false categoriesSegmentedControl.isEnabled = true viewModel.searchResults.removeAll(keepingCapacity: false) tableView.reloadData() tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } }
41.421965
167
0.654759
e9733e7d28370afd9be54ffee40fd14262a0794e
505
// // SwifQLable+Delete.swift // SwifQL // // Created by Mihael Isaev on 26/11/2018. // import Foundation extension SwifQLable { public func delete(from table: SwifQLable) -> SwifQLable { var parts: [SwifQLPart] = self.parts parts.appendSpaceIfNeeded() parts.append(o: .delete) parts.append(o: .space) parts.append(o: .from) parts.append(o: .space) parts.append(contentsOf: table.parts) return SwifQLableParts(parts: parts) } }
22.954545
62
0.629703
33e5d456406987bbf74d265a50e8c5baa8c18d8a
19,392
// 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 // /**************** Immutable Ordered Set ****************/ open class NSOrderedSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, ExpressibleByArrayLiteral { internal var _storage: Set<NSObject> internal var _orderedStorage: [NSObject] open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { NSUnimplemented() } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { NSUnimplemented() } public static var supportsSecureCoding: Bool { return true } open override func isEqual(_ object: Any?) -> Bool { guard let orderedSet = object as? NSOrderedSet else { return false } return isEqual(to: orderedSet) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } for idx in _indices { aCoder.encode(__SwiftValue.store(self.object(at: idx)), forKey:"NS.object.\(idx)") } } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } var idx = 0 var objects : [AnyObject] = [] while aDecoder.containsValue(forKey: ("NS.object.\(idx)")) { guard let object = aDecoder.decodeObject(forKey: "NS.object.\(idx)") else { return nil } objects.append(object as! NSObject) idx += 1 } self.init(array: objects) } open var count: Int { return _storage.count } open func object(at idx: Int) -> Any { _validateSubscript(idx) return __SwiftValue.fetch(nonOptional: _orderedStorage[idx]) } open func index(of object: Any) -> Int { return _orderedStorage.index(of: __SwiftValue.store(object)) ?? NSNotFound } public convenience override init() { self.init(objects: [], count: 0) } public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) { _storage = Set<NSObject>() _orderedStorage = [NSObject]() super.init() _insertObjects(objects, count: cnt) } required public convenience init(arrayLiteral elements: Any...) { self.init(array: elements) } public convenience init(objects elements: Any...) { self.init(array: elements) } open subscript (idx: Int) -> Any { return object(at: idx) } fileprivate func _insertObject(_ object: Any) { let value = __SwiftValue.store(object) guard !contains(value) else { return } _storage.insert(value) _orderedStorage.append(value) } fileprivate func _insertObjects(_ objects: UnsafePointer<AnyObject>!, count cnt: Int) { let buffer = UnsafeBufferPointer(start: objects, count: cnt) for obj in buffer { _insertObject(obj) } } internal var allObjects: [Any] { if type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self { return _orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) } } else { return _indices.map { idx in return self[idx] } } } /// The range of indices that are valid for subscripting the ordered set. internal var _indices: Range<Int> { return 0..<count } /// Checks that an index is valid for subscripting: 0 ≤ `index` < `count`. internal func _validateSubscript(_ index: Int, file: StaticString = #file, line: UInt = #line) { precondition(_indices.contains(index), "\(self): Index out of bounds", file: file, line: line) } } extension NSOrderedSet : Sequence { /// Return a *generator* over the elements of this *sequence*. /// /// - Complexity: O(1). public typealias Iterator = NSEnumerator.Iterator public func makeIterator() -> Iterator { return self.objectEnumerator().makeIterator() } } extension NSOrderedSet { public func getObjects(_ objects: inout [AnyObject], range: NSRange) { for idx in range.location..<(range.location + range.length) { objects.append(_orderedStorage[idx]) } } /// Returns an array with the objects at the specified indexes in the /// ordered set. /// /// - Parameter indexes: The indexes. /// - Returns: An array of objects in the ascending order of their indexes /// in `indexes`. /// /// - Complexity: O(*n*), where *n* is the number of indexes in `indexes`. /// - Precondition: The indexes in `indexes` are within the /// bounds of the ordered set. open func objects(at indexes: IndexSet) -> [Any] { return indexes.map { object(at: $0) } } public var firstObject: Any? { if let value = _orderedStorage.first { return __SwiftValue.fetch(nonOptional: value) } else { return nil } } public var lastObject: Any? { if let value = _orderedStorage.last { return __SwiftValue.fetch(nonOptional: value) } else { return nil } } open func isEqual(to other: NSOrderedSet) -> Bool { if count != other.count { return false } for idx in _indices { if let value1 = object(at: idx) as? AnyHashable, let value2 = other.object(at: idx) as? AnyHashable { if value1 != value2 { return false } } } return true } open func contains(_ object: Any) -> Bool { return _storage.contains(__SwiftValue.store(object)) } open func intersects(_ other: NSOrderedSet) -> Bool { if count < other.count { return contains { obj in other.contains(obj) } } else { return other.contains { obj in contains(obj) } } } open func intersectsSet(_ set: Set<AnyHashable>) -> Bool { if count < set.count { return contains { obj in set.contains(obj) } } else { return set.contains { obj in contains(obj) } } } open func isSubset(of other: NSOrderedSet) -> Bool { for item in self { if !other.contains(item) { return false } } return true } open func isSubset(of set: Set<AnyHashable>) -> Bool { for item in self { if !set.contains(item as! AnyHashable) { return false } } return true } public func objectEnumerator() -> NSEnumerator { guard type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self else { NSRequiresConcreteImplementation() } return NSGeneratorEnumerator(_orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.makeIterator()) } public func reverseObjectEnumerator() -> NSEnumerator { guard type(of: self) === NSOrderedSet.self || type(of: self) === NSMutableOrderedSet.self else { NSRequiresConcreteImplementation() } return NSGeneratorEnumerator(_orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.reversed().makeIterator()) } /*@NSCopying*/ public var reversed: NSOrderedSet { return NSOrderedSet(array: _orderedStorage.map { __SwiftValue.fetch(nonOptional: $0) }.reversed()) } // These two methods return a facade object for the receiving ordered set, // which acts like an immutable array or set (respectively). Note that // while you cannot mutate the ordered set through these facades, mutations // to the original ordered set will "show through" the facade and it will // appear to change spontaneously, since a copy of the ordered set is not // being made. public var array: [Any] { NSUnimplemented() } public var set: Set<AnyHashable> { NSUnimplemented() } open func enumerateObjects(_ block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() } open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() } open func enumerateObjects(at s: IndexSet, options opts: NSEnumerationOptions = [], using block: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() } open func index(ofObjectPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } open func index(_ opts: NSEnumerationOptions = [], ofObjectPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } open func index(ofObjectAt s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } open func indexes(ofObjectsPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() } open func indexes(options opts: NSEnumerationOptions = [], ofObjectsPassingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() } open func indexes(ofObjectsAt s: IndexSet, options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet { NSUnimplemented() } open func index(of object: Any, inSortedRange range: NSRange, options opts: NSBinarySearchingOptions = [], usingComparator cmp: (Any, Any) -> ComparisonResult) -> Int { NSUnimplemented() } // binary search open func sortedArray(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { NSUnimplemented() } open func sortedArray(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { NSUnimplemented() } public func description(withLocale locale: Locale?) -> String { NSUnimplemented() } public func description(withLocale locale: Locale?, indent level: Int) -> String { NSUnimplemented() } } extension NSOrderedSet { public convenience init(object: Any) { self.init(array: [object]) } public convenience init(orderedSet set: NSOrderedSet) { self.init(orderedSet: set, copyItems: false) } public convenience init(orderedSet set: NSOrderedSet, copyItems flag: Bool) { self.init(orderedSet: set, range: NSRange(location: 0, length: set.count), copyItems: flag) } public convenience init(orderedSet set: NSOrderedSet, range: NSRange, copyItems flag: Bool) { // TODO: Use the array method here when available. self.init(array: Array(set), range: range, copyItems: flag) } public convenience init(array: [Any]) { let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: array.count) for (idx, element) in array.enumerated() { buffer.advanced(by: idx).initialize(to: __SwiftValue.store(element)) } self.init(objects: buffer, count: array.count) buffer.deinitialize(count: array.count) buffer.deallocate() } public convenience init(array set: [Any], copyItems flag: Bool) { self.init(array: set, range: NSRange(location: 0, length: set.count), copyItems: flag) } public convenience init(array set: [Any], range: NSRange, copyItems flag: Bool) { var objects = set if let range = Range(range), range.count != set.count || flag { objects = [Any]() for index in range.indices { let object = set[index] objects.append(flag ? (object as! NSObject).copy() : object) } } self.init(array: objects) } public convenience init(set: Set<AnyHashable>) { self.init(set: set, copyItems: false) } public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) { self.init(array: Array(set), copyItems: flag) } } /**************** Mutable Ordered Set ****************/ open class NSMutableOrderedSet : NSOrderedSet { open func insert(_ object: Any, at idx: Int) { precondition(idx <= count && idx >= 0, "\(self): Index out of bounds") let value = __SwiftValue.store(object) if contains(value) { return } _storage.insert(value) _orderedStorage.insert(value, at: idx) } open func removeObject(at idx: Int) { _validateSubscript(idx) _storage.remove(_orderedStorage[idx]) _orderedStorage.remove(at: idx) } open func replaceObject(at idx: Int, with obj: Any) { let value = __SwiftValue.store(obj) let objectToReplace = __SwiftValue.store(object(at: idx)) _orderedStorage[idx] = value _storage.remove(objectToReplace) _storage.insert(value) } public init(capacity numItems: Int) { super.init(objects: [], count: 0) } required public convenience init(arrayLiteral elements: Any...) { self.init(capacity: 0) addObjects(from: elements) } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } fileprivate func _removeObject(_ object: Any) { let value = __SwiftValue.store(object) guard contains(object) else { return } _storage.remove(value) _orderedStorage.remove(at: index(of: object)) } open override subscript(idx: Int) -> Any { get { return object(at: idx) } set { replaceObject(at: idx, with: newValue) } } } extension NSMutableOrderedSet { open func add(_ object: Any) { _insertObject(object) } open func add(_ objects: UnsafePointer<AnyObject>!, count: Int) { _insertObjects(objects, count: count) } open func addObjects(from array: [Any]) { for object in array { _insertObject(object) } } open func exchangeObject(at idx1: Int, withObjectAt idx2: Int) { let object1 = self.object(at: idx1) let object2 = self.object(at: idx2) _orderedStorage[idx1] = __SwiftValue.store(object2) _orderedStorage[idx2] = __SwiftValue.store(object1) } open func moveObjects(at indexes: IndexSet, to idx: Int) { var removedObjects = [Any]() for index in indexes.lazy.reversed() { let obj = object(at: index) removedObjects.append(obj) removeObject(at: index) } for removedObject in removedObjects { insert(removedObject, at: idx) } } open func insert(_ objects: [Any], at indexes: IndexSet) { for (indexLocation, index) in indexes.enumerated() { let object = objects[indexLocation] insert(object, at: index) } } /// Sets the object at the specified index of the mutable ordered set. /// /// - Parameters: /// - obj: The object to be set. /// - idx: The index. If the index is equal to `count`, then it appends /// the object. Otherwise it replaces the object at the index with the /// given object. open func setObject(_ obj: Any, at idx: Int) { if idx == count { insert(obj, at: idx) } else { replaceObject(at: idx, with: obj) } } open func replaceObjects(in range: NSRange, with objects: UnsafePointer<AnyObject>!, count: Int) { if let range = Range(range) { let buffer = UnsafeBufferPointer(start: objects, count: count) for (indexLocation, index) in range.indices.lazy.reversed().enumerated() { let object = buffer[indexLocation] replaceObject(at: index, with: object) } } } open func replaceObjects(at indexes: IndexSet, with objects: [Any]) { for (indexLocation, index) in indexes.enumerated() { let object = objects[indexLocation] replaceObject(at: index, with: object) } } open func removeObjects(in range: NSRange) { if let range = Range(range) { for index in range.indices.lazy.reversed() { removeObject(at: index) } } } open func removeObjects(at indexes: IndexSet) { for index in indexes.lazy.reversed() { removeObject(at: index) } } public func removeAllObjects() { _storage.removeAll() _orderedStorage.removeAll() } open func remove(_ val: Any) { let object = __SwiftValue.store(val) _storage.remove(object) _orderedStorage.remove(at: index(of: val)) } open func removeObjects(in array: [Any]) { array.forEach(remove) } open func intersect(_ other: NSOrderedSet) { for item in self where !other.contains(item) { remove(item) } } open func minus(_ other: NSOrderedSet) { for item in other where contains(item) { remove(item) } } open func union(_ other: NSOrderedSet) { other.forEach(add) } open func intersectSet(_ other: Set<AnyHashable>) { for case let item as AnyHashable in self where !other.contains(item) { remove(item) } } open func minusSet(_ other: Set<AnyHashable>) { for item in other where contains(item) { remove(item) } } open func unionSet(_ other: Set<AnyHashable>) { other.forEach(add) } open func sort(comparator cmptr: (Any, Any) -> ComparisonResult) { sortRange(NSRange(location: 0, length: count), options: [], usingComparator: cmptr) } open func sort(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) { sortRange(NSRange(location: 0, length: count), options: opts, usingComparator: cmptr) } open func sortRange(_ range: NSRange, options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) { // The sort options are not available. We use the Array's sorting algorithm. It is not stable neither concurrent. guard opts.isEmpty else { NSUnimplemented() } let swiftRange = Range(range)! _orderedStorage[swiftRange].sort { lhs, rhs in return cmptr(__SwiftValue.fetch(nonOptional: lhs), __SwiftValue.fetch(nonOptional: rhs)) == .orderedAscending } } }
33.902098
209
0.608395
08f47be40a187ea07b70be3cf5306d28da326c3f
3,666
// Copyright SIX DAY LLC. All rights reserved. import Foundation //TODO probably should have an ID which is really good for debugging open class Subscribable<T>: Hashable { public static func == (lhs: Subscribable<T>, rhs: Subscribable<T>) -> Bool { return lhs.uuid == rhs.uuid } public struct SubscribableKey: Hashable { let id = UUID() public static func == (lhs: SubscribableKey, rhs: SubscribableKey) -> Bool { return lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } } private var _value: T? private var _subscribers: [SubscribableKey: Subscription] = .init() private var _oneTimeSubscribers: [(T) -> Void] = [] open var value: T? { get { return _value } set { _value = newValue for (_, f) in _subscribers { if let q = f.queue { q.async { f.callback(newValue) } } else { f.callback(newValue) } } if let value = value { for f in _oneTimeSubscribers { f(value) } _oneTimeSubscribers = [] } } } private let uuid = UUID() public init(_ value: T?) { _value = value } private struct Subscription { let queue: DispatchQueue? let callback: (T?) -> Void } @discardableResult open func subscribe(_ subscribe: @escaping (T?) -> Void, on queue: DispatchQueue? = .none) -> SubscribableKey { if let value = _value { if let q = queue { q.async { subscribe(value) } } else { subscribe(value) } } let key = SubscribableKey() _subscribers[key] = Subscription(queue: queue, callback: subscribe) return key } static func merge<T>(_ elements: [Subscribable<T>], on queue: DispatchQueue? = .none) -> Subscribable<[T]> { let values = elements.compactMap { $0.value } let notifier = Subscribable<[T]>(values) for each in elements { each.subscribe { _ in if let queue = queue { queue.async { notifier.value = elements.compactMap { $0.value } } } else { notifier.value = elements.compactMap { $0.value } } } } return notifier } func map<V>(_ mapClosure: @escaping (T) -> V?, on queue: DispatchQueue? = .none) -> Subscribable<V> { let notifier = Subscribable<V>(nil) func updateNotifier(with value: T?, on queue: DispatchQueue?) { if let queue = queue { queue.async { notifier.value = value.flatMap { mapClosure($0) } } } else { notifier.value = value.flatMap { mapClosure($0) } } } subscribe { value in updateNotifier(with: value, on: queue) } return notifier } open func subscribeOnce(_ subscribe: @escaping (T) -> Void) { if let value = _value { subscribe(value) } else { _oneTimeSubscribers.append(subscribe) } } func unsubscribe(_ key: SubscribableKey) { _subscribers.removeValue(forKey: key) } func unsubscribeAll() { _subscribers.removeAll() } public func hash(into hasher: inout Hasher) { hasher.combine(uuid) } }
27.772727
134
0.511457
46eb56d091a4ac58f7f369bd7e6876680cd4577a
1,524
// 876_Middle of the Linked List // https://leetcode.com/problems/middle-of-the-linked-list/ // // Created by Honghao Zhang on 9/7/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a non-empty, singly linked list with head node head, return a middle node of linked list. // //If there are two middle nodes, return the second middle node. // // // //Example 1: // //Input: [1,2,3,4,5] //Output: Node 3 from this list (Serialization: [3,4,5]) //The returned node has value 3. (The judge's serialization of this node is [3,4,5]). //Note that we returned a ListNode object ans, such that: //ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. //Example 2: // //Input: [1,2,3,4,5,6] //Output: Node 4 from this list (Serialization: [4,5,6]) //Since the list has two middle nodes with values 3 and 4, we return the second one. // // //Note: // //The number of nodes in the given list will be between 1 and 100. // import Foundation // 找到linked list的中间点 class Num876 { // MARK: - 快慢pointer func middleNode(_ head: ListNode?) -> ListNode? { let root: ListNode? = ListNode(0) root?.next = head var slow = root var fast = root while fast?.next != nil { slow = slow?.next fast = fast?.next?.next } // if fast is just the last node, the slow is the last node of first half. // should return the next node, which is the head of the right part. if fast != nil { return slow?.next } return slow } }
26.736842
98
0.652231
f7beb1fbe7dd19978df09952432647a662dbdc8d
650
// // PinResponseModel.swift // // // Created by zunda on 2022/02/08. // import Foundation extension Sweet { internal struct PinResponse { public let pinned: Bool } } extension Sweet.PinResponse: Decodable { private enum DataCodingKeys: String, CodingKey { case data = "data" } private enum CodingKeys: String, CodingKey { case pinned } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: DataCodingKeys.self) let usersInfo = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .data) self.pinned = try usersInfo.decode(Bool.self, forKey: .pinned) } }
20.967742
87
0.696923
33477f5c7ec1a29b811c0f87dc057d5642775dad
2,167
// // AppDelegate.swift // DHCalendarDemo // // Created by mac on 2018/11/27. // Copyright © 2018 aiden. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.106383
285
0.754961
f8011c51efe374cb93a69d52fe878d0df58b29a1
5,777
/// Represents an N-dimensional [geometric ray] which projects a line from a /// starting point in a specified direction to infinity. /// /// [geometric ray]: https://en.wikipedia.org/wiki/Line_(geometry)#Ray public struct DirectionalRay<Vector: VectorFloatingPoint>: GeometricType { public typealias Scalar = Vector.Scalar /// The starting position of this ray public var start: Vector /// A unit vector relative to `start` which indicates the direction of this /// ray. /// /// Must have `length > 0`. @UnitVector public var direction: Vector /// Initializes a directional ray with a given start position and direction /// vectors. /// /// The direction will be normalized before initializing. /// /// - precondition: `direction.length > 0` @_transparent public init(start: Vector, direction: Vector) { self.start = start self.direction = direction } /// Initializes a directional ray with a given line's endpoints. /// /// The direction will be normalized before initializing. /// /// - precondition: `line.length > 0` @_transparent public init<Line: LineType>(_ line: Line) where Line.Vector == Vector { self.init(a: line.a, b: line.b) } /// Initializes a directional ray with a line passing through `a` and `b`. /// /// The ray's ``start`` point matches `a`. /// /// The direction will be normalized before initializing. /// /// - precondition: `line.length > 0` @_transparent public init(a: Vector, b: Vector) { self.init(start: a, direction: b - a) } } extension DirectionalRay: Equatable where Vector: Equatable, Scalar: Equatable { } extension DirectionalRay: Hashable where Vector: Hashable, Scalar: Hashable { } extension DirectionalRay: Encodable where Vector: Encodable, Scalar: Encodable { } extension DirectionalRay: Decodable where Vector: Decodable, Scalar: Decodable { } extension DirectionalRay: LineType { /// Equivalent to ``start``. @_transparent public var a: Vector { start } /// Equivalent to ``start`` + ``direction``. @_transparent public var b: Vector { start + direction } } public extension DirectionalRay where Vector: VectorAdditive { /// Returns a `Line` representation of this directional ray, where `line.a` /// matches ``start`` and `line.b` matches ``start`` + ``direction``. @_transparent var asLine: Line<Vector> { Line(a: start, b: b) } /// Returns a `Ray` representation of this directional ray, where `ray.start` /// matches ``start`` and `ray.b` matches ``start`` + ``direction``. @_transparent var asRay: Ray<Vector> { Ray(start: start, b: b) } } extension DirectionalRay: LineAdditive where Vector: VectorAdditive { /// Gets the slope of this directional ray. /// /// For directional rays this value always equates to `direction`. @_transparent public var lineSlope: Vector { direction } @_transparent public func offsetBy(_ vector: Vector) -> Self { Self(start: start + vector, direction: direction) } } extension DirectionalRay: LineMultiplicative where Vector: VectorMultiplicative { /// - precondition: `factor > Vector.zero` @_transparent public func withPointsScaledBy(_ factor: Vector) -> Self { Self(start: start * factor, direction: direction * factor) } } extension DirectionalRay: LineFloatingPoint & PointProjectableType & SignedDistanceMeasurableType where Vector: VectorFloatingPoint { /// Performs a vector projection of a given vector with respect to this /// directional ray, returning a scalar value representing the magnitude of /// the projected point laying on the infinite line defined by points /// `start <-> start + direction`. /// /// By multiplying the result of this function by ``direction`` and adding /// ``start``, the projected point as it lays on this directional ray line /// can be obtained. This can also be achieved by using /// ``projectedMagnitude(_:)``. /// /// ```swift /// let ray = DirectionalRay2D(x: 1, y: 1, dx: 1, dy: 0) /// /// print(ray.projectAsScalar(.init(x: 5, y: 0))) // Prints "4" /// ``` /// /// - seealso: ``projectedMagnitude(_:)`` @inlinable public func projectAsScalar(_ vector: Vector) -> Vector.Scalar { let relVec = vector - start let proj = relVec.dot(direction) return proj } /// Returns the result of creating a projection of this ray's start point /// projected in the direction of this ray's direction, with a total /// magnitude of `scalar`. /// /// ```swift /// let ray = DirectionalRay2D(x: 1, y: 1, dx: 1, dy: 0) /// /// print(ray.projectedMagnitude(4)) // Prints "(x: 5, y: 0)" /// ``` /// /// - seealso: ``projectAsScalar(_:)`` @inlinable public func projectedMagnitude(_ scalar: Vector.Scalar) -> Vector { start.addingProduct(direction, scalar) } /// Returns `true` for all positive scalar values, which describes a [ray]. /// /// [ray]: https://en.wikipedia.org/wiki/Line_(geometry)#Ray @_transparent public func containsProjectedNormalizedMagnitude(_ scalar: Vector.Scalar) -> Bool { scalar >= 0 } /// Returns a projected normalized magnitude that is guaranteed to be /// contained in this line. /// /// For ``DirectionalRay``, this is a clamped inclusive (0-∞ range. @_transparent public func clampProjectedNormalizedMagnitude(_ scalar: Vector.Scalar) -> Vector.Scalar { max(0, scalar) } }
33.982353
133
0.637874
eb4a733b064af4210170156fadd3206ad57e35ff
1,519
// // PresentationViewController.swift // EasyTransitions_Example // // Created by Marcos Griselli on 21/04/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class P: UIPresentationController { override var frameOfPresentedViewInContainerView: CGRect { return CGRect(x: 10, y: presentingViewController.view.bounds.height - 380, width: 355, height: 370) } } class PresentationViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! // Layouts private typealias Layout = (transform: CGAffineTransform, alpha: CGFloat) private let startLayout: Layout = (.init(translationX: 0, y: 30), 0.0) private let endLayout: Layout = (.identity, 1.0) init() { super.init(nibName: String(describing: PresentationViewController.self), bundle: Bundle(for: PresentationViewController.self)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.layer.cornerRadius = 16.0 set(layout: startLayout) } public func animations(presenting: Bool) { let layout = presenting ? endLayout : startLayout set(layout: layout) } private func set(layout: Layout) { imageView.transform = layout.transform imageView.alpha = layout.alpha } }
28.12963
80
0.635945
6a840bb5d8966662daa82fa8489f0616d379cced
232
@objc(AMapOffline) class Offline: NSObject { @objc static func requiresMainQueueSetup() -> Bool { false } @objc func removeListeners(_: Int) {} @objc func addListener(_: String) {} @objc func download(_: String) {} }
21.090909
54
0.672414
795ae5f920934fd614f5716ec45c9e60d65eabd6
2,181
// // AppDelegate.swift // Calculator Project // // Created by Willis Wang on 12/2/16. // Copyright © 2016 Willis Wang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.404255
285
0.755617
1aa7110805cae2664e559173dae0d5a2bbd0d7b5
818
// // CBFileTransfer.swift // Barcelona // // Created by Eric Rabil on 11/2/21. // import Foundation import IMCore /// Registers a file transfer with imagent for the given filename and path. /// The returned file transfer is ready to be sent by including its GUID in a message. public func CBInitializeFileTransfer(filename: String, path: URL) -> IMFileTransfer { let guid = IMFileTransferCenter.sharedInstance().guidForNewOutgoingTransfer(withLocalURL: path) let transfer = IMFileTransferCenter.sharedInstance().transfer(forGUID: guid)! transfer.transferredFilename = filename IMFileTransferCenter.sharedInstance().registerTransfer(withDaemon: guid) transfer.shouldForceArchive = true IMFileTransferCenter.sharedInstance().sendTransfer(transfer) return transfer }
31.461538
99
0.756724
87e7ee49fa76a2d5e92fffdba84ec866d0fe0dfc
241
// // InitialViewController.swift // SegueCoordinatorExample // // Created by Евгений Сафронов on 02/04/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit class InitialViewController: TestableController { }
17.214286
52
0.73444
091e0a3943f076cd20f8127a15abc4b10dc3970c
892
// MIT license. Copyright (c) 2019 RadiantKit. All rights reserved. import UIKit public struct RFStaticTextCellModel { var title: String = "" var value: String = "" } public class RFStaticTextCell: UITableViewCell { public var model: RFStaticTextCellModel public init(model: RFStaticTextCellModel) { self.model = model super.init(style: .value1, reuseIdentifier: nil) loadWithModel(model) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func loadWithModel(_ model: RFStaticTextCellModel) { selectionStyle = .none textLabel?.text = model.title detailTextLabel?.text = model.value } } @available(*, unavailable, renamed: "RFStaticTextCell") typealias StaticTextCell = RFStaticTextCell @available(*, unavailable, renamed: "RFStaticTextCellModel") typealias StaticTextCellModel = RFStaticTextCellModel
25.485714
67
0.765695
33a7f189dcefaad2f460af991423ec43624ff77d
2,997
// // JsonPlaceholerTestReactorView.swift // SpasiboRx // // Created by Pavel Grechikhin on 01/10/2018. // Copyright © 2018 Pavel Grechikhin. All rights reserved. // import ReactorKit import RxSwift import RxAlamofire let baseUrl = "http://jsonplaceholder.typicode.com/posts/" class JsonPlaceholerTestReactorView: Reactor { var bag = DisposeBag() enum Action { // actiom cases case addButtonTapped } enum Mutation { // mutation cases case showActivity, hideActivity case updateIdentifier(Int) case successWithData(ResponseObject), errorRequest } struct State: Equatable { //state var load: Bool = false var responseObject: [ResponseObject] = [] var currentIdentifier: Int = 0 var error: Bool = false var errorText = "" static func == (lhs: JsonPlaceholerTestReactorView.State, rhs: JsonPlaceholerTestReactorView.State) -> Bool { return lhs.responseObject == rhs.responseObject } } let initialState: State init() { initialState = State() } func mutate(action: Action) -> Observable<Mutation> { switch action { case .addButtonTapped: return Observable.concat([ Observable.just(Mutation.showActivity), Observable.just(Mutation.updateIdentifier(self.currentState.currentIdentifier + 1)), makeRequest(with: self.currentState.currentIdentifier + 1), Observable.just(Mutation.hideActivity) ]) } } func reduce(state: State, mutation: Mutation) -> State { var newState = state switch mutation { case .showActivity: newState.load = true case .hideActivity: newState.load = false case .updateIdentifier(let identifier): newState.currentIdentifier = identifier case .errorRequest: newState.error = true case .successWithData(let data): var items = state.responseObject items.append(data) newState.responseObject = items } return newState } //MARK: - Private private func makeRequest(with identifier:Int) -> Observable<Mutation> { let currentId = (identifier <= 0) && (identifier > 100) ? 1 : identifier return requestData(.get, "\(baseUrl)\(currentId)").map({ (response) -> Mutation in if (response.0.statusCode == 404) { return Mutation.errorRequest } else { let response = try! JSONDecoder().decode(ResponseObject.self, from: response.1) return Mutation.successWithData(response) } }) } } // model struct ResponseObject: Codable, Equatable { var userId: Int var title: String var body: String var id: Int }
28.542857
117
0.589256
ed40a6d877533e4b1163a73f4a91a05db70ed029
1,521
// // GetStartedViewController.swift // Carouselish // // Created by Michelle Harvey on 2/14/16. // Copyright © 2016 Michelle Venetucci Harvey. All rights reserved. // import UIKit class GetStartedViewController: UIViewController { @IBOutlet weak var task1: UIButton! @IBOutlet weak var task2: UIButton! @IBOutlet weak var task3: UIButton! let userDefaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() let task1Completed = userDefaults.boolForKey("task1_completed") let task2Completed = userDefaults.boolForKey("task2_completed") let task3Completed = userDefaults.boolForKey("task3_completed") task1.selected = task1Completed task2.selected = task2Completed task3.selected = task3Completed } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func dismissButtonDidPress(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
29.25
106
0.69165
e0a01d55e7c983b6607997530d6edd75b9ad9873
1,103
/** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func isValidBST(_ root: TreeNode?) -> Bool { // iterative inorder traversal var root = root var stack: [TreeNode] = [] var prev = Int.min while !stack.isEmpty || root != nil { while root != nil { stack.append(root!) root = root!.left } root = stack.popLast() if root!.val <= prev { return false } prev = root!.val root = root!.right } return true } }
26.902439
85
0.473255
1e5051ccbb651e7daf7f7b9250a7b2ae6d3d9037
14,001
import KsApi import Prelude import ReactiveSwift public protocol DeprecatedRewardCellViewModelInputs { func boundStyles() func configureWith(project: Project, rewardOrBacking: Either<Reward, Backing>) func tapped() } public protocol DeprecatedRewardCellViewModelOutputs { var allGoneHidden: Signal<Bool, Never> { get } var conversionLabelHidden: Signal<Bool, Never> { get } var conversionLabelText: Signal<String, Never> { get } var descriptionLabelHidden: Signal<Bool, Never> { get } var descriptionLabelText: Signal<String, Never> { get } var estimatedDeliveryDateLabelText: Signal<String, Never> { get } var footerLabelText: Signal<String, Never> { get } var footerStackViewHidden: Signal<Bool, Never> { get } var items: Signal<[String], Never> { get } var itemsContainerHidden: Signal<Bool, Never> { get } var manageButtonHidden: Signal<Bool, Never> { get } var minimumAndConversionLabelsColor: Signal<UIColor, Never> { get } var minimumLabelText: Signal<String, Never> { get } var notifyDelegateRewardCellWantsExpansion: Signal<(), Never> { get } var pledgeButtonHidden: Signal<Bool, Never> { get } var pledgeButtonTitleText: Signal<String, Never> { get } var shippingLocationsStackViewHidden: Signal<Bool, Never> { get } var shippingLocationsSummaryLabelText: Signal<String, Never> { get } var titleLabelHidden: Signal<Bool, Never> { get } var titleLabelText: Signal<String, Never> { get } var titleLabelTextColor: Signal<UIColor, Never> { get } var updateTopMarginsForIsBacking: Signal<Bool, Never> { get } var viewPledgeButtonHidden: Signal<Bool, Never> { get } var youreABackerLabelText: Signal<String, Never> { get } var youreABackerViewHidden: Signal<Bool, Never> { get } } public protocol DeprecatedRewardCellViewModelType { var inputs: DeprecatedRewardCellViewModelInputs { get } var outputs: DeprecatedRewardCellViewModelOutputs { get } } public final class DeprecatedRewardCellViewModel: DeprecatedRewardCellViewModelType, DeprecatedRewardCellViewModelInputs, DeprecatedRewardCellViewModelOutputs { public init() { let projectAndRewardOrBacking: Signal<(Project, Either<Reward, Backing>), Never> = self.projectAndRewardOrBackingProperty.signal.skipNil() let project: Signal<Project, Never> = projectAndRewardOrBacking.map(first) let reward: Signal<Reward, Never> = projectAndRewardOrBacking .map { project, rewardOrBacking -> Reward in rewardOrBacking.left ?? rewardOrBacking.right?.reward ?? backingReward(fromProject: project) ?? Reward.noReward } let projectAndReward = Signal.zip(project, reward) self.conversionLabelHidden = project.map(needsConversion(project:) >>> negate) self.conversionLabelText = projectAndRewardOrBacking .filter(first >>> needsConversion(project:)) .map { project, rewardOrBacking in let (country, rate) = zip( project.stats.currentCountry, project.stats.currentCurrencyRate ) ?? (.us, project.stats.staticUsdRate) switch rewardOrBacking { case let .left(reward): let min = minPledgeAmount(forProject: project, reward: reward) return Format.currency( max(1, Int(Float(min) * rate)), country: country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) case let .right(backing): return Format.currency( Int(ceil(Float(backing.amount) * rate)), country: country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) } } .map(Strings.About_reward_amount(reward_amount:)) self.minimumLabelText = projectAndRewardOrBacking .map { project, rewardOrBacking in switch rewardOrBacking { case let .left(reward): let min = minPledgeAmount(forProject: project, reward: reward) let currency = Format.currency( min, country: project.country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) return reward == Reward.noReward ? Strings.rewards_title_pledge_reward_currency_or_more(reward_currency: currency) : currency case let .right(backing): let backingAmount = formattedAmount(for: backing) return Format.formattedCurrency( backingAmount, country: project.country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) } } self.descriptionLabelText = reward .map { $0 == Reward.noReward ? "" : $0.description } self.minimumAndConversionLabelsColor = projectAndReward .map(minimumRewardAmountTextColor(project:reward:)) self.titleLabelHidden = reward .map { $0.title == nil && $0 != Reward.noReward } self.titleLabelText = projectAndReward .map(rewardTitle(project:reward:)) self.titleLabelTextColor = projectAndReward .map { project, reward in reward.remaining != 0 || userIsBacking(reward: reward, inProject: project) || project.state != .live ? .ksr_soft_black : .ksr_text_dark_grey_500 } let youreABacker = projectAndReward .map { project, reward in userIsBacking(reward: reward, inProject: project) } self.youreABackerViewHidden = youreABacker .map(negate) self.youreABackerLabelText = project .map { $0.personalization.backing?.reward == nil } .skipRepeats() .map { noRewardBacking in noRewardBacking ? Strings.Your_pledge() : Strings.Your_reward() } self.estimatedDeliveryDateLabelText = reward .map { reward in reward.estimatedDeliveryOn.map { Format.date(secondsInUTC: $0, template: DateFormatter.monthYear, timeZone: UTCTimeZone) } } .skipNil() let rewardItemsIsEmpty = reward .map { $0.rewardsItems.isEmpty } self.itemsContainerHidden = Signal.merge( reward.map { $0.remaining == 0 || $0.rewardsItems.isEmpty }, rewardItemsIsEmpty.takeWhen(self.tappedProperty.signal) ) .skipRepeats() self.items = reward .map { reward in reward.rewardsItems.map { rewardsItem in rewardsItem.quantity > 1 ? "(\(Format.wholeNumber(rewardsItem.quantity))) \(rewardsItem.item.name)" : rewardsItem.item.name } } let rewardIsCollapsed = projectAndReward .map { project, reward in shouldCollapse(reward: reward, forProject: project) } self.allGoneHidden = projectAndReward .map { project, reward in reward.remaining != 0 || userIsBacking(reward: reward, inProject: project) } let allGoneAndNotABacker = Signal.zip(reward, youreABacker) .map { reward, youreABacker in reward.remaining == 0 && !youreABacker } let isNoReward = reward .map { $0.isNoReward } self.footerStackViewHidden = Signal.merge( projectAndReward .map { project, reward in reward.estimatedDeliveryOn == nil || shouldCollapse(reward: reward, forProject: project) }, isNoReward.takeWhen(self.tappedProperty.signal) ) self.descriptionLabelHidden = Signal.merge( rewardIsCollapsed, self.tappedProperty.signal.mapConst(false) ) self.updateTopMarginsForIsBacking = Signal.combineLatest(youreABacker, self.boundStylesProperty.signal) .map(first) self.manageButtonHidden = Signal.zip(project, youreABacker) .map { project, youreABacker in project.state != .live || !youreABacker } self.viewPledgeButtonHidden = Signal.zip(project, youreABacker) .map { project, youreABacker in project.state == .live || !youreABacker } self.pledgeButtonHidden = Signal.zip(project, reward, youreABacker) .map { project, reward, youreABacker in project.state != .live || reward.remaining == 0 || youreABacker } self.pledgeButtonTitleText = project.map { $0.personalization.isBacking == true ? Strings.Select_this_reward_instead() : Strings.Select_this_reward() } self.shippingLocationsStackViewHidden = reward.map { $0.shipping.summary == nil } self.shippingLocationsSummaryLabelText = reward.map { $0.shipping.summary ?? "" } self.notifyDelegateRewardCellWantsExpansion = allGoneAndNotABacker .takeWhen(self.tappedProperty.signal) .filter(isTrue) .ignoreValues() .take(first: 1) self.footerLabelText = projectAndReward .map(footerString(project:reward:)) projectAndReward .takeWhen(self.notifyDelegateRewardCellWantsExpansion) .observeValues { project, reward in AppEnvironment.current.koala.trackExpandedUnavailableReward( reward, project: project, pledgeContext: pledgeContext(forProject: project, reward: reward) ) } } private let boundStylesProperty = MutableProperty(()) public func boundStyles() { self.boundStylesProperty.value = () } private let projectAndRewardOrBackingProperty = MutableProperty<(Project, Either<Reward, Backing>)?>(nil) public func configureWith(project: Project, rewardOrBacking: Either<Reward, Backing>) { self.projectAndRewardOrBackingProperty.value = (project, rewardOrBacking) } private let tappedProperty = MutableProperty(()) public func tapped() { self.tappedProperty.value = () } public let allGoneHidden: Signal<Bool, Never> public let conversionLabelHidden: Signal<Bool, Never> public let conversionLabelText: Signal<String, Never> public let descriptionLabelHidden: Signal<Bool, Never> public let descriptionLabelText: Signal<String, Never> public let estimatedDeliveryDateLabelText: Signal<String, Never> public let footerLabelText: Signal<String, Never> public let footerStackViewHidden: Signal<Bool, Never> public let items: Signal<[String], Never> public let itemsContainerHidden: Signal<Bool, Never> public let manageButtonHidden: Signal<Bool, Never> public let minimumAndConversionLabelsColor: Signal<UIColor, Never> public let minimumLabelText: Signal<String, Never> public let notifyDelegateRewardCellWantsExpansion: Signal<(), Never> public let pledgeButtonHidden: Signal<Bool, Never> public let pledgeButtonTitleText: Signal<String, Never> public let shippingLocationsStackViewHidden: Signal<Bool, Never> public let shippingLocationsSummaryLabelText: Signal<String, Never> public let titleLabelHidden: Signal<Bool, Never> public let titleLabelText: Signal<String, Never> public let titleLabelTextColor: Signal<UIColor, Never> public let updateTopMarginsForIsBacking: Signal<Bool, Never> public let viewPledgeButtonHidden: Signal<Bool, Never> public let youreABackerLabelText: Signal<String, Never> public let youreABackerViewHidden: Signal<Bool, Never> public var inputs: DeprecatedRewardCellViewModelInputs { return self } public var outputs: DeprecatedRewardCellViewModelOutputs { return self } } private func minimumRewardAmountTextColor(project: Project, reward: Reward) -> UIColor { if project.state != .successful && project.state != .live && reward.remaining == 0 { return .ksr_text_dark_grey_500 } else if project.state == .live && reward.remaining == 0 && userIsBacking(reward: reward, inProject: project) { return .ksr_green_700 } else if project.state != .live && reward.remaining == 0 && userIsBacking(reward: reward, inProject: project) { return .ksr_text_dark_grey_500 } else if (project.state == .live && reward.remaining == 0) || (project.state != .live && reward.remaining == 0) { return .ksr_text_dark_grey_400 } else if project.state == .live { return .ksr_green_700 } else if project.state != .live { return .ksr_soft_black } else { return .ksr_soft_black } } private func needsConversion(project: Project) -> Bool { return project.stats.needsConversion } private func backingReward(fromProject project: Project) -> Reward? { guard let backing = project.personalization.backing else { return nil } return project.rewards .filter { $0.id == backing.rewardId || $0.id == backing.reward?.id } .first .coalesceWith(.noReward) } private func rewardTitle(project: Project, reward: Reward) -> String { guard project.personalization.isBacking == true else { return reward == Reward.noReward ? Strings.Id_just_like_to_support_the_project() : (reward.title ?? "") } return reward.title ?? Strings.Thank_you_for_supporting_this_project() } private func footerString(project: Project, reward: Reward) -> String { var parts: [String] = [] if let endsAt = reward.endsAt, project.state == .live, endsAt > 0, endsAt >= AppEnvironment.current.dateType.init().timeIntervalSince1970 { let (time, unit) = Format.duration( secondsInUTC: min(endsAt, project.dates.deadline), abbreviate: true, useToGo: false ) parts.append(Strings.Time_left_left(time_left: time + " " + unit)) } if let remaining = reward.remaining, reward.limit != nil, project.state == .live { parts.append(Strings.Left_count_left(left_count: remaining)) } if let backersCount = reward.backersCount { parts.append(Strings.general_backer_count_backers(backer_count: backersCount)) } return parts .map { part in part.nonBreakingSpaced() } .joined(separator: " • ") } private func formattedAmount(for backing: Backing) -> String { let amount = backing.amount let backingAmount = floor(amount) == backing.amount ? String(Int(amount)) : String(format: "%.2f", backing.amount) return backingAmount } private func shouldCollapse(reward: Reward, forProject project: Project) -> Bool { return reward.remaining == .some(0) && !userIsBacking(reward: reward, inProject: project) && project.state == .live }
36.085052
108
0.697236
218253f03096fa794441f180660e1933072b7a78
761
// // EmittableOutput.swift // Rainbow // // Created by Pierre Felgines on 08/10/2019. // import Foundation import XCResultKit protocol EmittableOutput { var emittedOutput: String? { get } } extension ActivityLogUnitTestSection: EmittableOutput {} extension ActivityLogSection: EmittableOutput { var emittedOutput: String? { return "\(title)\n\n" + subsections .compactMap { $0.emittedOutput } .joined(separator: "\n") } } extension ActivityLogMajorSection: EmittableOutput { var emittedOutput: String? { return "\(title) - \(subtitle)\n\n" + unitTestSubsections .compactMap { $0.emittedOutput } .joined(separator: "\n") } }
20.026316
56
0.61498
695c5d00780587137fc61dfca5deaa301cf81301
1,832
// // MongoLabClient.swift // MongoLabKit // // Created by luca strazzullo on 12/03/16. // Copyright © 2016 ustwo. All rights reserved. // import Foundation open class MongoLabClient { // MARK: Typealiases typealias Completion = (_ result: Result) -> () // MARK: Types enum Result { case success(response: AnyObject) case failure(error: ErrorDescribable) } // MARK: Static properties static let sharedClient = MongoLabClient() // MARK: Public APIs func perform(_ request: URLRequest, completion: @escaping Completion) -> URLSessionTask { let session = dataTask(with: request, completion: completion) session.resume() return session } // MARK: Private helper methods private func dataTask(with request: URLRequest, completion: @escaping Completion) -> URLSessionTask { let dataTask = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in self?.parse(data, response: response, error: error, completion: completion) return } return dataTask } private func parse(_ data: Data?, response: URLResponse?, error: Error?, completion: @escaping Completion) { do { call(completion, withResult: Result.success(response: try MongoLabResponseParser().parse(data, response: response, error: error))) } catch let error as ErrorDescribable { call(completion, withResult: Result.failure(error: error)) } catch { call(completion, withResult: Result.failure(error: MongoLabError.parserError)) } } private func call(_ completion: @escaping Completion, withResult result: Result) { DispatchQueue.main.async { completion(result) } } }
24.756757
142
0.641921
2062ff7d7701f82c704196863e8ba44a407e34b9
2,640
// // ImageCreator.swift // // Copyright 2018-2021 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // http://www.mopub.com/legal/sdk-license-agreement/ // import Foundation import UIKit @objc(MPImageCreator) public final class ImageCreator: NSObject { /// Creates either an animated `UIImage` from a GIF, or a static `UIImage` from any other format. /// - Parameters: /// - data: The data to create the image from. /// - Returns: A `UIImage` if one could be created, or nil if not. @objc public static func image(with data: Data) -> UIImage? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return createAnimatedImage(from: source) ?? UIImage(data: data) } } // MARK: - Helpers private extension ImageCreator { struct Constants { // Specify the 0.1 as the default GIF delay time, which is the same // as the clamped delay time. static let defaultGIFDelay: TimeInterval = 0.1 } static func canCreateAnimatedImage(from source: CGImageSource) -> Bool { let frameCount = CGImageSourceGetCount(source) // CFDictionary is toll-free bridged with NSDictionary, but it's much // more expensive to cast to a native Swift dictionary. let properties: NSDictionary? = CGImageSourceCopyProperties(source, nil) // Only support GIFs for now. return properties?[kCGImagePropertyGIFDictionary] != nil && frameCount > 1 } static func createAnimatedImage(from source: CGImageSource) -> UIImage? { guard canCreateAnimatedImage(from: source) else { return nil } let frameCount = CGImageSourceGetCount(source) // Get the duration from the first frame. let frameProperties: NSDictionary? = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) let gifProperties = frameProperties?[kCGImagePropertyGIFDictionary] as? NSDictionary let delay: TimeInterval = gifProperties?[kCGImagePropertyGIFDelayTime] as? TimeInterval ?? Constants.defaultGIFDelay let duration: TimeInterval = TimeInterval(frameCount) * delay var frames: [UIImage] = [] for i in 0..<frameCount { guard let frame = CGImageSourceCreateImageAtIndex(source, i, nil) else { continue } let uiImage = UIImage(cgImage: frame) frames.append(uiImage) } return UIImage.animatedImage(with: frames, duration: duration) } }
35.675676
124
0.644318
9be75505f77165961fea608d4b851956beb781df
3,721
// // SettingsScreenNew.swift // SampleProject // // Created by Lokesh Sehgal on 13/08/21. // import SwiftUI import Neumorphic import BottomSheet struct SettingsScreenNew: View { let data = ["Language", "Notifications"] @State var showGreeting = false var body: some View { ZStack{ ARRRBackground() ScrollView { VStack { ForEach(data, id:\.self) { row in VStack { HStack{ Text(row).foregroundColor(.white) .frame(width: 230, height: 22,alignment: .leading) .foregroundColor(Color.white) .padding(.trailing, 50) .padding().onTapGesture { showGreeting.toggle() } } } } } .modifier(CardViewModifier()) } .background(Color.init(red: 33.0/255.0, green: 36.0/255.0, blue: 38.0/255.0)) }.bottomSheet(isPresented: $showGreeting, height: 600, topBarHeight: 0, topBarCornerRadius: 16, showTopIndicator: false) { SettingsScreen() } } } struct ColoredToggleStyle: ToggleStyle { var onColor = Color.init(red: 12.0/255.0, green: 38.0/255.0, blue: 48.0/255.0) var offColor = Color.init(red: 27.0/255.0, green: 30.0/255.0, blue: 32.0/255.0) var thumbOnColor = Color.init(red: 120.0/255.0, green: 176.0/255.0, blue: 193.0/255.0) var thumbOffColor = Color.init(red: 83.0/255.0, green: 94.0/255.0, blue: 97.0/255.0) func makeBody(configuration: Self.Configuration) -> some View { HStack { configuration.label // The text (or view) portion of the Toggle Spacer() RoundedRectangle(cornerRadius: 16, style: .circular) .fill(configuration.isOn ? onColor : offColor) .frame(width: 50, height: 29) .overlay( Circle() .fill(configuration.isOn ? thumbOnColor : thumbOffColor) .shadow(radius: 1, x: 0, y: 1) .padding(1.5) .offset(x: configuration.isOn ? 10 : -10)) .animation(Animation.easeInOut(duration: 0.2)) .onTapGesture { configuration.isOn.toggle() } } .font(.title) .padding(.horizontal) } } struct CardViewModifier: ViewModifier { var backgroundColor = Color(.systemBackground) func body(content: Content) -> some View { content .padding() .frame(maxWidth: .infinity) .background( RoundedRectangle(cornerRadius: 30).fill(Color.init(red: 29.0/255.0, green: 32.0/255.0, blue: 34.0/255.0)) .softInnerShadow(RoundedRectangle(cornerRadius: 30), darkShadow: Color.init(red: 0.06, green: 0.07, blue: 0.07), lightShadow: Color.init(red: 0.26, green: 0.27, blue: 0.3), spread: 0.05, radius: 2)) .padding() } } //RoundedRectangle(cornerRadius: 20).fill(Color.Neumorphic.main).softOuterShadow() struct SettingsScreenNew_Previews: PreviewProvider { static var previews: some View { SettingsScreenNew() } }
37.969388
214
0.487235
c1360d3b73cf889928925e9af3806b0b8838bc8c
3,161
// // ******************************************* // // IISearchBar.swift // impcloud_dev // // Created by Noah_Shan on 2019/2/28. // Copyright © 2018 Inpur. All rights reserved. // // ******************************************* // import UIKit import RxSwift import RxCocoa import SnapKit public protocol IISearchBarDelegate: NSObjectProtocol { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool func textFieldDidEndEditing(_ textField: UITextField) func textFieldShouldClear(_ textField: UITextField) -> Bool func textFieldShouldReturn(_ textField: UITextField) -> Bool func each5MillSecsTxtInfo(_ txtInfo: String) } /// 自定义search bar public class IISearchBar: UIView { public var field: UITextField = UITextField() public weak var del: IISearchBarDelegate? let leftImg = UIButton() /// 是否显示放大镜 public var showSearchIcon = false public init(frame: CGRect, showSearchIcon: Bool = false) { super.init(frame: frame) self.showSearchIcon = showSearchIcon createVw() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createVw() { self.addSubview(field) self.field.snp.makeConstraints { (make) in make.left.equalTo(0) make.right.equalTo(0) make.top.equalTo(0) make.bottom.equalTo(0) } self.layer.masksToBounds = true self.field.delegate = self field.textAlignment = .center field.font = UIFont.systemFont(ofSize: 13) field.textColor = UIColor(red: 51 / 255, green: 51 / 255, blue: 51 / 255, alpha: 1) field.backgroundColor = UIColor(red: 246 / 255, green: 246 / 255, blue: 246 / 255, alpha: 1) field.clearButtonMode = .whileEditing //left search img if self.showSearchIcon { field.leftView = leftImg leftImg.frame = CGRect(x: 3, y: 3, width: 22, height: 22) leftImg.contentEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3) leftImg.setImage(UIImage(named: "work_bench_searchvc_search"), for: UIControl.State.normal) field.leftViewMode = .always } //圆角 self.layer.cornerRadius = 5 _ = self.field.rx.text.orEmpty .throttle(0.5, scheduler: MainScheduler.instance) .subscribe { [weak self] events in self?.del?.each5MillSecsTxtInfo(events.element ?? "") } } } extension IISearchBar: UITextFieldDelegate { public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return self.del?.textFieldShouldBeginEditing(textField) ?? true } public func textFieldDidEndEditing(_ textField: UITextField) { self.del?.textFieldDidEndEditing(textField) } public func textFieldShouldClear(_ textField: UITextField) -> Bool { return self.del?.textFieldShouldClear(textField) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return self.del?.textFieldShouldReturn(textField) ?? true } }
29.820755
103
0.632395
1ad8109ed9723fde90885a5b4964dbc8971a1e13
2,149
// // ThemeColorTableViewController.swift // TipCalculator // // Created by Xiaofei Long on 12/30/15. // Copyright © 2015 Xiaofei Long. All rights reserved. // import UIKit class ThemeColorTableViewController: UITableViewController { private let themeColorNames: [String] = Array(Config.ThemeColor.optionsDict.keys).sort() private var checkmarkedCell: UITableViewCell? override func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = .SingleLine } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return themeColorNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier( "ThemeColorOptionCell", forIndexPath: indexPath ) cell.textLabel!.text = themeColorNames[indexPath.row] let currentThemeColorName = NSUserDefaults.standardUserDefaults().stringForKey("theme_color_name") if (cell.textLabel!.text == currentThemeColorName) { checkmarkedCell = cell cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } // MARK: table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { checkmarkedCell?.accessoryType = .None checkmarkedCell = tableView.cellForRowAtIndexPath(indexPath) checkmarkedCell?.accessoryType = .Checkmark NSUserDefaults.standardUserDefaults().setObject( checkmarkedCell?.textLabel!.text, forKey: "theme_color_name" ) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
30.7
96
0.665891
f7a3d7af65d086c8dd69f45eab5ed3ac188d10ac
776
// // PostResult.swift // HiPDA // // Created by leizh007 on 2017/5/17. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation enum PostError: Error { case parseError(String) case unKnown(String) } // MARK: - CustomStringConvertible extension PostError: CustomStringConvertible { var description: String { switch self { case let .parseError(errorString): return errorString case let .unKnown(errorString): return errorString } } } extension PostError: LocalizedError { var errorDescription: String? { return description } } typealias PostResult = HiPDA.Result<String, PostError> typealias PostListResult = HiPDA.Result<(title: String?, posts: [Post]), PostError>
20.972973
83
0.670103
ab9a5029206626b5d1556beec193951f9b99a576
669
// // EPUBArchiveService.swift // EPUBKit // // Created by Witek Bobrowski on 30/06/2018. // Copyright © 2018 Witek Bobrowski. All rights reserved. // import Foundation import Zip protocol EPUBArchiveService { func unarchive(archive url: URL) throws -> URL } class EPUBArchiveServiceImplementation: EPUBArchiveService { init() { Zip.addCustomFileExtension("epub") } func unarchive(archive url: URL) throws -> URL { var destination: URL do { destination = try Zip.quickUnzipFile(url) } catch { throw EPUBParserError.unzipFailed(reason: error) } return destination } }
20.272727
60
0.647235
b9c7da10be0302cb5c3dd71459275924c8c96815
1,275
// // Ice_and_Fire_WikiUITests.swift // Ice and Fire WikiUITests // // Created by Dubois Grayson on 8/30/18. // Copyright © 2018 Mellow Cobra. All rights reserved. // import XCTest class Ice_and_Fire_WikiUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.459459
182
0.668235
fb6e87d4e9dff8eae4f821b4b82cd788e59ce039
7,182
// RUN: %target-run-simple-swift-swift3 --stdlib-unittest-in-process | tee %t.txt // RUN: %FileCheck %s < %t.txt // note: remove the --stdlib-unittest-in-process once all the FileCheck tests // have been converted to StdlibUnittest // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("CollectionTests") /// An *iterator* that adapts a *collection* `C` and any *sequence* of /// its `Index` type to present the collection's elements in a /// permuted order. public struct PermutationGenerator< C: Collection, Indices: Sequence where C.Index == Indices.Iterator.Element > : IteratorProtocol, Sequence { var seq : C var indices : Indices.Iterator /// The type of element returned by `next()`. public typealias Element = C.Iterator.Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Element? { let result = indices.next() return result != nil ? seq[result!] : .none } /// Construct an *iterator* over a permutation of `elements` given /// by `indices`. /// /// - Precondition: `elements[i]` is valid for every `i` in `indices`. public init(elements: C, indices: Indices) { self.seq = elements self.indices = indices.makeIterator() } } var foobar = MinimalCollection(elements: "foobar".characters) // CHECK: foobar for a in foobar { print(a, terminator: "") } print("") // FIXME: separate r from the expression below pending // <rdar://problem/15772601> Type checking failure // CHECK: raboof let i = foobar.indices let r = i.lazy.reversed() for a in PermutationGenerator(elements: foobar, indices: r) { print(a, terminator: "") } print("") func isPalindrome0< S : BidirectionalCollection >(_ seq: S) -> Bool where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index { typealias Index = S.Index let a = seq.indices let i = seq.indices let ir = i.lazy.reversed() var b = ir.makeIterator() for i in a { if seq[i] != seq[b.next()!] { return false } } return true } // CHECK: false print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiImaLasagneHoG".characters))) // CHECK: true print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiimalaSagnaHoG".characters))) func isPalindrome1< S : BidirectionalCollection >(_ seq: S) -> Bool where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index { let a = PermutationGenerator(elements: seq, indices: seq.indices) var b = seq.lazy.reversed().makeIterator() for nextChar in a { if nextChar != b.next()! { return false } } return true } func isPalindrome1_5< S: BidirectionalCollection >(_ seq: S) -> Bool where S.Iterator.Element == S.Iterator.Element, S.Iterator.Element: Equatable { var b = seq.lazy.reversed().makeIterator() for nextChar in seq { if nextChar != b.next()! { return false } } return true } // CHECK: false print(isPalindrome1(MinimalBidirectionalCollection(elements: "MADAMINEDENIMWILLIAM".characters))) // CHECK: true print(isPalindrome1(MinimalBidirectionalCollection(elements: "MadamInEdEnImadaM".characters))) // CHECK: false print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeRemoteelF".characters))) // CHECK: true print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeReMoteelF".characters))) // Finally, one that actually uses indexing to do half as much work. // BidirectionalCollection traversal finally pays off! func isPalindrome2< S: BidirectionalCollection >(_ seq: S) -> Bool where S.Iterator.Element: Equatable { var b = seq.startIndex, e = seq.endIndex while (b != e) { e = seq.index(before: e) if (b == e) { break } if seq[b] != seq[e] { return false } b = seq.index(after: b) } return true } // Test even length // CHECK: false print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarRamireZ".characters))) // CHECK: true print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimaRRamireZ".characters))) // Test odd length // CHECK: false print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarORamireZ".characters))) // CHECK: true print(isPalindrome2(MinimalBidirectionalCollection(elements: "Zerimar-O-ramireZ".characters))) func isPalindrome4< S: BidirectionalCollection >(_ seq: S) -> Bool where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index { typealias Index = S.Index let a = PermutationGenerator(elements: seq, indices: seq.indices) // FIXME: separate ri from the expression below pending // <rdar://problem/15772601> Type checking failure let i = seq.indices let ri = i.lazy.reversed() var b = PermutationGenerator(elements: seq, indices: ri) for nextChar in a { if nextChar != b.next()! { return false } } return true } // Can't put these literals into string interpolations pending // <rdar://problem/16401145> hella-slow compilation let array = [1, 2, 3, 4] let dict = [0:0, 1:1, 2:2, 3:3, 4:4] func testCount() { // CHECK: testing count print("testing count") // CHECK-NEXT: random access: 4 print("random access: \(array.count)") // CHECK-NEXT: bidirectional: 5 print("bidirectional: \(dict.count)") } testCount() struct SequenceOnly<T : Sequence> : Sequence { var base: T func makeIterator() -> T.Iterator { return base.makeIterator() } } func testUnderestimatedCount() { // CHECK: testing underestimatedCount print("testing underestimatedCount") // CHECK-NEXT: random access: 4 print("random access: \(array.underestimatedCount)") // CHECK-NEXT: bidirectional: 5 print("bidirectional: \(dict.underestimatedCount)") // CHECK-NEXT: Sequence only: 0 let s = SequenceOnly(base: array) print("Sequence only: \(s.underestimatedCount)") } testUnderestimatedCount() CollectionTests.test("isEmptyFirstLast") { expectTrue((10..<10).isEmpty) expectFalse((10...10).isEmpty) expectEqual(10, (10..<100).first) expectEqual(10, (10...100).first) expectEqual(99, (10..<100).last) expectEqual(100, (10...100).last) } /// A `Collection` that vends just the default implementations for /// `CollectionType` methods. struct CollectionOnly<T: Collection> : Collection { var base: T var startIndex: T.Index { return base.startIndex } var endIndex: T.Index { return base.endIndex } func makeIterator() -> T.Iterator { return base.makeIterator() } subscript(position: T.Index) -> T.Iterator.Element { return base[position] } func index(after i: T.Index) -> T.Index { return base.index(after: i) } } // CHECK: all done. print("all done.") CollectionTests.test("first/performance") { // accessing `first` should not perform duplicate work on lazy collections var log: [Int] = [] let col_ = (0..<10).lazy.filter({ log.append($0); return (2..<8).contains($0) }) let col = CollectionOnly(base: col_) expectEqual(2, col.first) expectEqual([0, 1, 2], log) } runAllTests()
26.698885
103
0.701197
1422b1ab96eb11780eef5043281a762717aeb317
1,644
// // BusinessCell.swift // Yelp // // Created by Joseph Antongiovanni on 2/14/18. // Copyright © 2018 Timothy Lee. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var reviewsCountLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! var business: Business! { didSet{ nameLabel.text = business.name thumbImageView.setImageWith(business.imageURL!) categoriesLabel.text = business.categories addressLabel.text = business.address reviewsCountLabel.text = "\(business.reviewCount!) Reviews" ratingImageView.setImageWith(business.ratingImageURL!) distanceLabel.text = business.distance } } override func awakeFromNib() { super.awakeFromNib() // Initialization code thumbImageView.layer.cornerRadius = 5 thumbImageView.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
29.890909
71
0.659976
c15f5d52798d09378b97b8f91062c662212f49cc
20
struct Subclass { }
6.666667
17
0.7
4b5846a365a9164f2576e3d850eb6c561e4d2364
1,717
import Foundation // MARK: - Design protocol Iterator { associatedtype Element func first() -> Element func next() -> Element? func isDone() -> Bool func currentItem() -> Element } protocol Aggregate { associatedtype Iterator func createIterator() -> Iterator } class ConcreteAggregate { typealias Element = Any private var items = Array<Element>() var count: Int { return items.count } subscript(index: Int) -> Element { set { items.append(newValue) } get { return items[index] } } } extension ConcreteAggregate: Aggregate { typealias Iterator = ConcreteIterator func createIterator() -> ConcreteAggregate.Iterator { return ConcreteIterator(aggregate: self) } } class ConcreteIterator { private let aggregate: ConcreteAggregate private var current = 0 init(aggregate: ConcreteAggregate) { self.aggregate = aggregate } } extension ConcreteIterator: Iterator { typealias Element = Any func first() -> Any { return aggregate[0] } @discardableResult func next() -> Any? { current += 1 guard current < aggregate.count else { return nil } return aggregate[current] } func isDone() -> Bool { return current >= aggregate.count } func currentItem() -> Any { return aggregate[current] } } // MARK: - Test let aggregate = ConcreteAggregate() aggregate[0] = "A" aggregate[1] = "B" aggregate[2] = "C" let ite = aggregate.createIterator() while !ite.isDone() { print(ite.currentItem()) ite.next() }
18.868132
57
0.596971
f7f076aa5db09f79552f3e5c3225d3fa11aee8d5
2,139
// // AppDelegate.swift // TDC-FP // // Created by Trond Bordewich on 28.09.15. // Copyright © 2015 Trobe. 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.510638
285
0.753156
90b086a5b12e2294332aebc6af979813a0444f5a
2,174
// // AppDelegate.swift // SectionIndexViewDemo // // Created by 陈健 on 2018/3/13. // Copyright © 2018年 ChenJian. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.255319
285
0.75621
1dccfd02fa7e05f9c422e44c7788b11a96c019fa
6,535
import Foundation /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). public func equal<T: Equatable>(_ expectedValue: T?) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" let actualValue = try actualExpression.evaluate() let matches = actualValue == expectedValue && expectedValue != nil if expectedValue == nil || actualValue == nil { if expectedValue == nil { failureMessage.postfixActual = " (use beNil() to match nils)" } return false } return matches } } /// A Nimble matcher that succeeds when the actual value is equal to the expected value. /// Values can support equal by supporting the Equatable protocol. /// /// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). public func equal<T: Equatable, C: Equatable>(_ expectedValue: [T: C]?) -> NonNilMatcherFunc<[T: C]> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" let actualValue = try actualExpression.evaluate() if expectedValue == nil || actualValue == nil { if expectedValue == nil { failureMessage.postfixActual = " (use beNil() to match nils)" } return false } return expectedValue! == actualValue! } } /// A Nimble matcher that succeeds when the actual collection is equal to the expected collection. /// Items must implement the Equatable protocol. public func equal<T: Equatable>(_ expectedValue: [T]?) -> NonNilMatcherFunc<[T]> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" let actualValue = try actualExpression.evaluate() if expectedValue == nil || actualValue == nil { if expectedValue == nil { failureMessage.postfixActual = " (use beNil() to match nils)" } return false } return expectedValue! == actualValue! } } /// A Nimble matcher allowing comparison of collection with optional type public func equal<T: Equatable>(_ expectedValue: [T?]) -> NonNilMatcherFunc<[T?]> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" if let actualValue = try actualExpression.evaluate() { if expectedValue.count != actualValue.count { return false } for (index, item) in actualValue.enumerated() { let otherItem = expectedValue[index] if item == nil && otherItem == nil { continue } else if item == nil && otherItem != nil { return false } else if item != nil && otherItem == nil { return false } else if item! != otherItem! { return false } } return true } else { failureMessage.postfixActual = " (use beNil() to match nils)" } return false } } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. public func equal<T>(_ expectedValue: Set<T>?) -> NonNilMatcherFunc<Set<T>> { return equal(expectedValue, stringify: { stringify($0) }) } /// A Nimble matcher that succeeds when the actual set is equal to the expected set. public func equal<T: Comparable>(_ expectedValue: Set<T>?) -> NonNilMatcherFunc<Set<T>> { return equal(expectedValue, stringify: { if let set = $0 { return stringify(Array(set).sorted { $0 < $1 }) } else { return "nil" } }) } private func equal<T>(_ expectedValue: Set<T>?, stringify: @escaping (Set<T>?) -> String) -> NonNilMatcherFunc<Set<T>> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" if let expectedValue = expectedValue { if let actualValue = try actualExpression.evaluate() { failureMessage.actualValue = "<\(stringify(actualValue))>" if expectedValue == actualValue { return true } let missing = expectedValue.subtracting(actualValue) if missing.count > 0 { failureMessage.postfixActual += ", missing <\(stringify(missing))>" } let extra = actualValue.subtracting(expectedValue) if extra.count > 0 { failureMessage.postfixActual += ", extra <\(stringify(extra))>" } } } else { failureMessage.postfixActual = " (use beNil() to match nils)" } return false } } public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) { lhs.to(equal(rhs)) } public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) { lhs.toNot(equal(rhs)) } public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) { lhs.to(equal(rhs)) } public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) { lhs.toNot(equal(rhs)) } public func == <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) { lhs.to(equal(rhs)) } public func != <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) { lhs.toNot(equal(rhs)) } public func ==<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) { lhs.to(equal(rhs)) } public func !=<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) { lhs.toNot(equal(rhs)) } public func ==<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) { lhs.to(equal(rhs)) } public func !=<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) { lhs.toNot(equal(rhs)) } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func equalMatcher(_ expected: NSObject) -> NMBMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in return try! equal(expected).matches(actualExpression, failureMessage: failureMessage) } } } #endif
35.906593
120
0.60658
260a35e64361e3767899593066ac7d8cc52d2174
1,138
// // GlanceController.swift // WatchButton WatchKit Extension // // Created by Boris Bügling on 09/05/15. // Copyright (c) 2015 Boris Bügling. All rights reserved. // import Foundation import MMWormhole import WatchConnectivity import WatchKit class GlanceController: WKInterfaceController { let wormhole = MMWormhole(applicationGroupIdentifier: AppGroupIdentifier, optionalDirectory: DirectoryIdentifier) @IBOutlet weak var infoLabel: WKInterfaceLabel! func resetLabel() { infoLabel.setText("No beacons in range :(") } override func willActivate() { super.willActivate() resetLabel() wormhole.listenForMessageWithIdentifier(Reply.BeaconRanged.rawValue) { (data) in if let ranged = data as? Bool { if ranged { self.infoLabel.setText("Beacon in range, tap to buy.") } return } self.resetLabel() } WCSession.defaultSession().sendMessage([ CommandIdentifier: Command.Nothing.rawValue ], replyHandler: { (_) in }, errorHandler: nil) } }
27.095238
118
0.643234
dd7f3835674c36d53927d525597d1d17d6f4afa1
3,143
// ************************ // // FirestoreUserModel.swift // // ------------------------ // // Created by // // Oleksandr Kurtsev // // ------------------------ // // github: kurtsev0103 // // linkedin: kurtsev0103 // // facebook: kurtsev0103 // // ------------------------ // // Copyright © 2021 // // ************************ // import UIKit import FirebaseFirestore struct FirestoreUserModel: Hashable, Decodable { var firstName: String var lastName: String var email: String var bornDate: String var gender: String var phone: String var address: String var avatarStringURL: String var id: String init() { firstName = "" lastName = "" email = "" bornDate = "" gender = "" phone = "" address = "" avatarStringURL = "" id = "" } init?(document: DocumentSnapshot) { guard let data = document.data() else { return nil } guard let firstName = data["firstName"] as? String, let lastName = data["lastName"] as? String, let email = data["email"] as? String, let bornDate = data["bornDate"] as? String, let gender = data["gender"] as? String, let phone = data["phone"] as? String, let address = data["address"] as? String, let avatarStringURL = data["avatarStringURL"] as? String, let id = data["id"] as? String else { return nil } self.firstName = firstName self.lastName = lastName self.email = email self.bornDate = bornDate self.gender = gender self.phone = phone self.address = address self.avatarStringURL = avatarStringURL self.id = id } init?(document: QueryDocumentSnapshot) { let data = document.data() guard let firstName = data["firstName"] as? String, let lastName = data["lastName"] as? String, let email = data["email"] as? String, let bornDate = data["bornDate"] as? String, let gender = data["gender"] as? String, let phone = data["phone"] as? String, let address = data["address"] as? String, let avatarStringURL = data["avatarStringURL"] as? String, let id = data["id"] as? String else { return nil } self.firstName = firstName self.lastName = lastName self.email = email self.bornDate = bornDate self.gender = gender self.phone = phone self.address = address self.avatarStringURL = avatarStringURL self.id = id } var representation: [String: Any] { var rep = ["id": id] rep["firstName"] = firstName rep["lastName"] = lastName rep["email"] = email rep["bornDate"] = bornDate rep["gender"] = gender rep["phone"] = phone rep["address"] = address rep["avatarStringURL"] = avatarStringURL return rep } }
31.43
71
0.514158
081e4d92459b284053ff4ceeaac9756bc6bf11f2
1,511
// // Copyright © FINN.no AS, Inc. All rights reserved. // import UIKit class RoundedRectangleGiftView: UIImageView, AttachableView { var attach: UIAttachmentBehavior? // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") } // MARK: - Setup private func setup() { image = UIImage(named: .giftRoundedRectRed) contentMode = .scaleAspectFit isUserInteractionEnabled = true } // MARK: - Override methods override var collisionBoundsType: UIDynamicItemCollisionBoundsType { return .path } override var collisionBoundingPath: UIBezierPath { let path = createRoundedRectanglePath(from: frame) var translation = CGAffineTransform(translationX: -frame.width / 2, y: -frame.height / 2) guard let movedPath = path.copy(using: &translation) else { return UIBezierPath(cgPath: path) } let mask = UIBezierPath(cgPath: movedPath) return mask } // MARK: - Private methods private func createRoundedRectanglePath(from shapeFrame: CGRect) -> CGPath { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: shapeFrame.width, height: shapeFrame.height), byRoundingCorners: .topRight, cornerRadii: CGSize(width: shapeFrame.width * 2, height: shapeFrame.height * 2)) path.close() return path.cgPath } }
27.981481
227
0.655195
f8dc15e3e3e14e5e6f31658664a8295497c20b1d
1,146
import Foundation import UIKit import PromiseKit import Shared extension UIApplication { func backgroundTask<PromiseValue>( withName name: String, wrapping: (TimeInterval?) -> Promise<PromiseValue> ) -> Promise<PromiseValue> { HomeAssistantBackgroundTask.execute( withName: name, beginBackgroundTask: { name, expirationHandler in let identifier = self.beginBackgroundTask(withName: name, expirationHandler: expirationHandler) let remaining = self.backgroundTimeRemaining < 100 ? self.backgroundTimeRemaining : nil Current.Log.info { if let remaining = remaining { return "background time remaining \(remaining)" } else { return "background time remaining could not be determined" } } return (identifier == .invalid ? nil : identifier, remaining) }, endBackgroundTask: { identifier in self.endBackgroundTask(identifier) }, wrapping: wrapping ) } }
35.8125
111
0.588133
d518dccae3a62bd6f29c8a947fbe480d844e4ca9
2,798
// // HierarchicalList.swift // DemoEcommerce // // Created by Vladislav Fitc on 10/04/2021. // import Foundation import InstantSearch import SwiftUI public struct HierarchicalList: View { @ObservedObject var hierarchicalObservableController: HierarchicalObservableController public init(hierarchicalObservableController: HierarchicalObservableController) { self.hierarchicalObservableController = hierarchicalObservableController } public var body: some View { VStack(alignment: .leading, spacing: 5) { ForEach(hierarchicalObservableController.items.prefix(20), id: \.facet) { item in let (_, level, isSelected) = item let facet = self.facet(from: item) HStack(spacing: 10) { Image(systemName: isSelected ? "chevron.down" : "chevron.right") .font(.callout) Text("\(facet.value) (\(facet.count))") .fontWeight(isSelected ? .semibold : .regular) } .padding(.leading, CGFloat(level * 15)) .onTapGesture { hierarchicalObservableController.select(item.facet.value) } } } } func maxSelectedLevel(_ hierarchicalFacets: [HierarchicalFacet]) -> Int? { return hierarchicalFacets .filter { $0.isSelected } .max { (l, r) in l.level < r.level }? .level } func facet(from hierarchicalFacet: HierarchicalFacet) -> Facet { let value = hierarchicalFacet .facet .value .split(separator: ">") .map { $0.trimmingCharacters(in: .whitespaces) }[hierarchicalFacet.level] return Facet(value: value, count: hierarchicalFacet.facet.count, highlighted: nil) } } struct HierarchicalMenu_Preview: PreviewProvider { static var previews: some View { let controller: HierarchicalObservableController = .init() HierarchicalList(hierarchicalObservableController: controller) .onAppear { controller.setItem([ (Facet(value: "Category1", count: 10), 0, false), (Facet(value: "Category1 > Category1-1", count: 7), 1, false), (Facet(value: "Category1 > Category1-2", count: 2), 1, false), (Facet(value: "Category1 > Category1-3", count: 1), 1, false), (Facet(value: "Category2", count: 14), 0, true), (Facet(value: "Category2 > Category2-1", count: 8), 1, false), (Facet(value: "Category2 > Category2-2", count: 4), 1, true), (Facet(value: "Category2 > Category2-2 > Category2-2-1", count: 2), 2, false), (Facet(value: "Category2 > Category2-2 > Category2-2-2", count: 2), 2, true), (Facet(value: "Category2 > Category2-3", count: 2), 1, false), ]) } .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height, alignment: .leading) } }
34.54321
105
0.642959
3aaec88c95e0b2e54964be03c20c1b6f1e5f394d
2,988
// // SOTabBarItem.swift // SOTabBar // // Created by ahmad alsofi on 1/3/20. // Copyright © 2020 ahmad alsofi. All rights reserved. // import UIKit @available(iOS 10.0, *) class SOTabBarItem: UIView { let image: UIImage let title: String private lazy var titleLabel: UILabel = { let lbl = UILabel() lbl.text = self.title lbl.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold) lbl.textColor = UIColor.darkGray lbl.textAlignment = .center lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() private lazy var tabImageView: UIImageView = { let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() init(tabBarItem item: UITabBarItem) { guard let selecteImage = item.image else { fatalError("You should set image to all view controllers") } self.image = selecteImage self.title = item.title ?? "" super.init(frame: .zero) drawConstraints() } private func drawConstraints() { self.addSubview(titleLabel) self.addSubview(tabImageView) NSLayoutConstraint.activate([ tabImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor), tabImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor), tabImageView.heightAnchor.constraint(equalToConstant: SOTabBarSetting.tabBarSizeImage), tabImageView.widthAnchor.constraint(equalToConstant: SOTabBarSetting.tabBarSizeImage), titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: SOTabBarSetting.tabBarHeight), titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor), titleLabel.heightAnchor.constraint(equalToConstant: 26) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func animateTabSelected() { tabImageView.alpha = 1 titleLabel.alpha = 0 UIView.animate(withDuration: SOTabBarSetting.tabBarAnimationDurationTime) { [weak self] in self?.titleLabel.alpha = 1 self?.titleLabel.frame.origin.y = SOTabBarSetting.tabBarHeight / 1.8 self?.tabImageView.frame.origin.y = -5 self?.tabImageView.alpha = 0 } } internal func animateTabDeSelect() { tabImageView.alpha = 1 UIView.animate(withDuration: SOTabBarSetting.tabBarAnimationDurationTime) { [weak self] in self?.titleLabel.frame.origin.y = SOTabBarSetting.tabBarHeight self?.tabImageView.frame.origin.y = (SOTabBarSetting.tabBarHeight / 2) - CGFloat(SOTabBarSetting.tabBarSizeImage / 2) self?.tabImageView.alpha = 1 } } }
36.439024
129
0.660308
75f6661f4a8135f51dda5b7c3d87e3a02a98bb22
547
// // Stand.swift // Honolulu // // Created by mobapp12 on 29/01/2020. // Copyright © 2020 H3AR7B3A7. All rights reserved. // import Foundation import MapKit class Stand:NSObject, MKAnnotation{ var coordinate: CLLocationCoordinate2D var subtitle: String? var title: String? var cat: String? init(coordinate: CLLocationCoordinate2D, subtitle: String, name: String, cat: String) { self.coordinate = coordinate self.subtitle = subtitle self.title = name self.cat = cat } }
20.259259
91
0.650823
4b77c411c35ea3f6f7bc4c210244f2d2a9b084d8
2,052
// // MailView.swift // Petulia // // Created by Johandre Delgado on 03.12.2020. // Copyright © 2020 Johandre Delgado . All rights reserved. // import SwiftUI import UIKit import MessageUI struct MailView: UIViewControllerRepresentable { @Environment(\.presentationMode) var presentation @Binding var result: Result<MFMailComposeResult, Error>? var recipient = "" var subject = "Adoption Information" var message = "<p>I would like more information...</p>" class Coordinator: NSObject, MFMailComposeViewControllerDelegate { @Binding var presentation: PresentationMode @Binding var result: Result<MFMailComposeResult, Error>? init(presentation: Binding<PresentationMode>, result: Binding<Result<MFMailComposeResult, Error>?>) { _presentation = presentation _result = result } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { defer { $presentation.wrappedValue.dismiss() } guard error == nil else { self.result = .failure(error!) return } self.result = .success(result) } } func makeCoordinator() -> Coordinator { return Coordinator(presentation: presentation, result: $result) } func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController { let vc = MFMailComposeViewController() vc.setToRecipients([recipient]) vc.setSubject(subject) vc.setMessageBody(message, isHTML: true) vc.mailComposeDelegate = context.coordinator return vc } func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: UIViewControllerRepresentableContext<MailView>) { } }
31.569231
117
0.62768
38ac46482ce2d6b0e2cf9b74a7aa4eac80afd735
17,176
/* * Copyright 2015 Google Inc. 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 /** Delegate for position events that occur on a `Connection`. */ @objc(BKYConnectionPositionDelegate) public protocol ConnectionPositionDelegate { /** Event that is called immediately before the connection's `position` will change. - parameter connection: The connection whose `position` value will change. */ func willChangePosition(forConnection connection: Connection) /** Event that is called immediately after the connection's `position` has changed. - parameter connection: The connection whose `position` value has changed. */ func didChangePosition(forConnection connection: Connection) } /** Component used to create a connection between two `Block` instances. */ @objc(BKYConnection) @objcMembers public final class Connection : NSObject { // MARK: - Static Properties // NOTE: If OPPOSITE_TYPES is updated, also update ConnectionManager's matchingLists and // oppositeLists arrays. /// Specifies which `ConnectionType` a `ConnectionType` is compatible with. public static let OPPOSITE_TYPES: [ConnectionType] = [.nextStatement, .previousStatement, .outputValue, .inputValue] // MARK: - Constants /// Represents all possible types of connections. @objc(BKYConnectionType) public enum ConnectionType: Int { case /// Specifies the connection is a previous connection. previousStatement = 0, /// Specifies the connection is a next connection. nextStatement, /// Specifies the connection is an input connection. inputValue, /// Specifies the connection is an output connection. outputValue } /// Represents a combination of result codes when trying to connect two connections public struct CheckResult: OptionSet { public static let CanConnect = CheckResult(value: .canConnect) public static let ReasonSelfConnection = CheckResult(value: .reasonSelfConnection) public static let ReasonWrongType = CheckResult(value: .reasonWrongType) public static let ReasonMustDisconnect = CheckResult(value: .reasonMustDisconnect) public static let ReasonTargetNull = CheckResult(value: .reasonTargetNull) public static let ReasonShadowNull = CheckResult(value: .reasonShadowNull) public static let ReasonTypeChecksFailed = CheckResult(value: .reasonTypeChecksFailed) public static let ReasonCannotSetShadowForTarget = CheckResult(value: .reasonCannotSetShadowForTarget) public static let ReasonInferiorBlockShadowMismatch = CheckResult(value: .reasonInferiorBlockShadowMismatch) public static let ReasonSourceBlockNull = CheckResult(value: .reasonSourceBlockNull) /// Specific reasons why two connections are able or unable connect @objc(BKYConnectionCheckResultValue) public enum Value: Int { case canConnect = 1, reasonSelfConnection, reasonWrongType, reasonMustDisconnect, reasonTargetNull, reasonShadowNull, reasonTypeChecksFailed, reasonCannotSetShadowForTarget, reasonInferiorBlockShadowMismatch, reasonSourceBlockNull func errorMessage() -> String? { switch (self) { case .reasonSelfConnection: return "Cannot connect a block to itself." case .reasonWrongType: return "Cannot connect these types." case .reasonMustDisconnect: return "Must disconnect from current block before connecting to a new one." case .reasonTargetNull, .reasonShadowNull: return "Cannot connect to a null connection" case .reasonTypeChecksFailed: return "Cannot connect, `typeChecks` do not match." case .reasonCannotSetShadowForTarget: return "Cannot set `self.targetConnection` when the source or target block is a shadow." case .reasonInferiorBlockShadowMismatch: return "Cannot connect a non-shadow block to a shadow block when the non-shadow block " + "connection is of type `.OutputValue` or `.PreviousStatement`." case .reasonSourceBlockNull: return "One of the connections does not reference a source block" case .canConnect: // Connection can be made, no error message return nil } } } /// The underlying raw value for the `CheckResult`. public let rawValue : Int public init(rawValue: Int) { self.rawValue = rawValue } public init(value: Value) { self.init(rawValue: 1 << value.rawValue) } /** Checks whether the `CheckResult` intersects with another `CheckResult`. - parameter other: The other `CheckResult` to check. - returns: `true` if they intersect, `false` otherwise. */ public func intersectsWith(_ other: CheckResult) -> Bool { return intersection(other).rawValue != 0 } func errorMessage() -> String? { guard !intersectsWith(.CanConnect) else { return nil } var errorMessage = "" var i = 1 while let validValue = Value(rawValue: i) { if intersectsWith(CheckResult(value: validValue)), let message = validValue.errorMessage() { errorMessage += "\(message)\n" } i += 1 } return errorMessage } } // MARK: - Properties /// A globally unique identifier public let uuid: String /// The connection type public let type: ConnectionType /// The block that holds this connection 这个enm。。 public internal(set) weak var sourceBlock: Block? /// If this connection belongs to a value or statement input, this is its source public internal(set) weak var sourceInput: Input? /** The position of this connection in the workspace. NOTE: While this value *should* be stored in a Layout subclass, it's more efficient to simply store the absolute position here since it's the only relevant property needed. */ public fileprivate(set) var position: WorkspacePoint = WorkspacePoint.zero /// The connection that this one is connected to public fileprivate(set) weak var targetConnection: Connection? /// The shadow connection that this one is connected to public fileprivate(set) weak var shadowConnection: Connection? /// The source block of `self.targetConnection` public var targetBlock: Block? { return targetConnection?.sourceBlock } /// The source block of `self.shadowConnection` public var shadowBlock: Block? { return shadowConnection?.sourceBlock } /// `true` if `self.targetConnection` is non-nil. `false` otherwise. public var connected: Bool { return targetConnection != nil } /// `true` if `self.shadowConnection` is non-nil. `false` otherwise. public var shadowConnected: Bool { return shadowConnection != nil } /** The set of checks for this connection. Two Connections may be connected if one of them supports any connection (when this is null) or if they share at least one common check value. For example, {"Number", "Integer", "MyValueType"} and {"AnotherType", "Integer"} would be valid since they share "Integer" as a check. */ public var typeChecks: [String]? { didSet { // Disconnect connections that aren't compatible with the new `typeChecks` value. if let targetConnection = self.targetConnection, !typeChecksMatchWithConnection(targetConnection) { disconnect() } if let shadowConnection = self.shadowConnection, !typeChecksMatchWithConnection(shadowConnection) { disconnectShadow() } } } /// Whether the connection has high priority in the context of bumping connections away. public var highPriority: Bool { return (self.type == .inputValue || self.type == .nextStatement) } /// Flag determining if this connection has a value set for `positionDelegate`. /// It is used for performance purposes. private final var _hasPositionDelegate: Bool = false /// Connection position delegate public final weak var positionDelegate: ConnectionPositionDelegate? { didSet { _hasPositionDelegate = (positionDelegate != nil) } } /// This value is `true` if this connection is an "inferior" connection (ie. `.outputValue` or /// `.previousStatement`). Otherwise, this value is `false`. public var isInferior: Bool { return type == .outputValue || type == .previousStatement } // MARK: - Initializers /** Creates a `Connection`. - parameter type: The `ConnectionType` of this connection. - parameter sourceInput: [Optional] The source input for the `Connection`. Defaults to `nil`. */ public init(type: Connection.ConnectionType, sourceInput: Input? = nil) { self.uuid = UUID().uuidString self.type = type self.sourceInput = sourceInput } /** Sets `self.targetConnection` to a given connection, and vice-versa. - parameter connection: The other connection - throws: `BlocklyError`: Thrown if the connection could not be made, with error code `.ConnectionInvalid` */ public func connectTo(_ connection: Connection?) throws { if let newConnection = connection , newConnection == targetConnection { // Already connected return } if let errorMessage = canConnectWithReasonTo(connection).errorMessage() { throw BlocklyError(.connectionInvalid, errorMessage) } if let newConnection = connection { // Set targetConnection for both sides targetConnection = newConnection newConnection.targetConnection = self } } /** Sets `self.shadowConnection` to a given connection, and vice-versa. - parameter connection: The other connection - throws: `BlocklyError`: Thrown if the connection could not be made, with error code `.ConnectionInvalid` */ public func connectShadowTo(_ connection: Connection?) throws { if let newConnection = connection , newConnection == shadowConnection { // Already connected return } if let errorMessage = canConnectShadowWithReasonTo(connection).errorMessage() { throw BlocklyError(.connectionInvalid, errorMessage) } if let newConnection = connection { // Set shadowConnection for both sides shadowConnection = newConnection newConnection.shadowConnection = self } } /** Removes the connection between this and `self.targetConnection`. If `self.targetConnection` is `nil`, this method does nothing. */ public func disconnect() { guard let oldTargetConnection = targetConnection else { return } // Remove targetConnection for both sides targetConnection = nil oldTargetConnection.targetConnection = nil } /** Removes the connection between this and `self.shadowConnection`. If `self.shadowConnection` is `nil`, this method does nothing. */ public func disconnectShadow() { guard let oldShadowConnection = shadowConnection else { return } // Remove shadowConnection for both sides shadowConnection = nil oldShadowConnection.shadowConnection = nil } /** Check if this can be connected to the target connection. - parameter target: The connection to check. - returns: True if the target can be connected, false otherwise. */ public func canConnectTo(_ target: Connection) -> Bool { return canConnectWithReasonTo(target) == .CanConnect } /** Check if a given connection can be connected to the target connection, with a specific set of reasons. - parameter target: The `Connection` to check compatibility with. - returns: If the connection is legal, `[CheckResult.Value.CanConnect]` is returned. Otherwise, a set of all error codes are returned. */ public func canConnectWithReasonTo(_ target: Connection?) -> CheckResult { var checkResult = CheckResult(rawValue: 0) if let aTarget = target { if let targetSourceBlock = aTarget.sourceBlock { if targetSourceBlock == sourceBlock { checkResult.formUnion(.ReasonSelfConnection) } if targetSourceBlock.shadow { checkResult.formUnion(.ReasonCannotSetShadowForTarget) } } else { checkResult.formUnion(.ReasonSourceBlockNull) } if aTarget.type != Connection.OPPOSITE_TYPES[type.rawValue] { checkResult.formUnion(.ReasonWrongType) } if !typeChecksMatchWithConnection(aTarget) { checkResult.formUnion(.ReasonTypeChecksFailed) } } else { checkResult.formUnion(.ReasonTargetNull) } if targetConnection != nil { checkResult.formUnion(.ReasonMustDisconnect) } if let sourceBlock = self.sourceBlock { if sourceBlock.shadow { checkResult.formUnion(.ReasonCannotSetShadowForTarget) } } else { checkResult.formUnion(.ReasonSourceBlockNull) } if checkResult.rawValue == 0 { // All checks passed! Set it to .CanConnect checkResult.formUnion(.CanConnect) } return checkResult } /** Check if a given connection can be connected to the shadow connection, with a specific set of reasons. - parameter shadow: The `Connection` to check compatibility with. - returns: If the connection is legal, `[CheckResult.Value.CanConnect]` is returned. Otherwise, a set of all error codes are returned. */ public func canConnectShadowWithReasonTo(_ shadow: Connection?) -> CheckResult { var checkResult = CheckResult(rawValue: 0) if sourceBlock == nil { checkResult.formUnion(.ReasonSourceBlockNull) } if let aShadow = shadow { if aShadow.sourceBlock == nil { checkResult.formUnion(.ReasonSourceBlockNull) } if let sourceBlock = self.sourceBlock, let shadowSourceBlock = aShadow.sourceBlock { if sourceBlock == shadowSourceBlock { checkResult.formUnion(.ReasonSelfConnection) } let inferiorBlock = isInferior ? sourceBlock : shadowSourceBlock if !inferiorBlock.shadow { checkResult.formUnion(.ReasonInferiorBlockShadowMismatch) } } if aShadow.type != Connection.OPPOSITE_TYPES[type.rawValue] { checkResult.formUnion(.ReasonWrongType) } if !typeChecksMatchWithConnection(aShadow) { checkResult.formUnion(.ReasonTypeChecksFailed) } } else { checkResult.formUnion(.ReasonShadowNull) } if shadowConnection != nil { checkResult.formUnion(.ReasonMustDisconnect) } if checkResult.rawValue == 0 { // All checks passed! Set it to .CanConnect checkResult.formUnion(.CanConnect) } return checkResult } /** Returns the distance between this connection and another connection. - parameter other: The other `Connection` to measure the distance to. - returns: The distance between connections. */ public func distanceFromConnection(_ other: Connection) -> CGFloat { let xDiff = position.x - other.position.x let yDiff = position.y - other.position.y return sqrt(xDiff * xDiff + yDiff * yDiff) } /** Move the connection to a specific position. - parameter position: The position to move to. - parameter offset: An additional offset, usually the position of the parent view in the workspace view. */ public func moveToPosition( _ position: WorkspacePoint, withOffset offset: WorkspacePoint = WorkspacePoint.zero) { let newX = position.x + offset.x let newY = position.y + offset.y if self.position.x == newX && self.position.y == newY { return } if _hasPositionDelegate { positionDelegate?.willChangePosition(forConnection: self) } self.position.x = newX self.position.y = newY if _hasPositionDelegate { positionDelegate?.didChangePosition(forConnection: self) } } // MARK: - Internal - For testing only /** Returns if this connection is compatible with another connection with respect to the value type system. - parameter target: Connection to compare against. - returns: True if either connection's `typeChecks` value is nil, or if both connections share a common `typeChecks` value. False, otherwise. */ internal func typeChecksMatchWithConnection(_ target: Connection) -> Bool { if self.typeChecks == nil || target.typeChecks == nil { return true } // The list of checks is expected to be very small (1 or 2 items usually), so the // n^2 approach should be fine. for selfTypeCheck in self.typeChecks! { for targetTypeCheck in target.typeChecks! { if selfTypeCheck == targetTypeCheck { return true } } } return false } }
33.811024
100
0.699814
bf4f927ccaca978880deed6599a9b185461273db
1,807
/*   Copyright 2018-2021 Prebid.org, 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 Foundation typealias NativeAdLoadedHandler = (PBRNativeAd) -> Void typealias PrimaryAdServerWinHandler = () -> Void typealias InvalidNativeAdHandler = (Error) -> Void /// Immutable container for 3 mutually exclusive outcomes of an asynchronous native ad detection attempt. class NativeAdDetectionListener: NSObject, NSCopying { @objc public private(set) var onNativeAdLoaded: NativeAdLoadedHandler? @objc public private(set) var onPrimaryAdWin: PrimaryAdServerWinHandler? @objc public private(set) var onNativeAdInvalid: InvalidNativeAdHandler? @objc public required init(nativeAdLoadedHandler onNativeAdLoaded: NativeAdLoadedHandler?, onPrimaryAdWin: PrimaryAdServerWinHandler?, onNativeAdInvalid: InvalidNativeAdHandler?) { self.onNativeAdLoaded = onNativeAdLoaded self.onPrimaryAdWin = onPrimaryAdWin self.onNativeAdInvalid = onNativeAdInvalid } // MARK: - NSCopying @objc public func copy(with zone: NSZone? = nil) -> Any { return self } // MARK: - Private @available(*, unavailable) private override init() { fatalError("Init is unavailable.") } }
36.14
105
0.721638
1c41ea275eddd108de375a87b516af32e85b0cec
7,815
/* ViewController.swift AJRInterface Copyright © 2021, AJ Raftis and AJRFoundation authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of AJRInterface nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AJ RAFTIS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import AJRInterface import Cocoa import WebKit open class ViewController: NSViewController, WKNavigationDelegate, WKUIDelegate { // MARK: - Properties private func stopObservingWebView() -> Void { if let current = webView { current.removeObserver(self, forKeyPath: "estimatedProgress") current.removeObserver(self, forKeyPath: "URL") current.removeObserver(self, forKeyPath: "favoriteIcon") current.removeObserver(self, forKeyPath: "canGoBack") current.removeObserver(self, forKeyPath: "canGoForward") current.removeObserver(self, forKeyPath: "title") current.removeObserver(self, forKeyPath: "currentItem") } } @IBOutlet public var webView: AJRWebView! { willSet { stopObservingWebView() } didSet { if let current = webView { current.addObserver(self, forKeyPath: "estimatedProgress", options: [], context: nil) current.addObserver(self, forKeyPath: "URL", options: [], context: nil) current.addObserver(self, forKeyPath: "favoriteIcon", options: [], context: nil) current.addObserver(self, forKeyPath: "canGoBack", options: [], context: nil) current.addObserver(self, forKeyPath: "canGoForward", options: [], context: nil) current.addObserver(self, forKeyPath: "title", options: [], context: nil) current.addObserver(self, forKeyPath: "currentItem", options: [], context: nil) } } } public var urlField : AJRURLField! public var navigationSegments : NSSegmentedControl! // MARK: - Destruction deinit { stopObservingWebView() self.webView = nil } // MARK: - Utilities internal func updateNavigationSegments() -> Void { if let navigationSegments = navigationSegments { navigationSegments.setEnabled(webView.canGoBack, forSegment: 0) navigationSegments.setEnabled(webView.canGoForward, forSegment: 1) if let menu = webView.backForwardList.buildBackMenu(target: self, action: #selector(takeURLFrom(_:))) { navigationSegments.setMenu(menu, forSegment: 0) } if let menu = webView.backForwardList.buildForwardMenu(target: self, action: #selector(takeURLFrom(_:))) { navigationSegments.setMenu(menu, forSegment: 1) } } } // MARK: - NSViewController override open func viewDidLoad() { super.viewDidLoad() if webView.homeURL == nil { webView.homeURL = URL(string: "https://www.apple.com/startpage"); } } override open func viewDidAppear() { super.viewDidAppear() urlField = view.window?.toolbar?.toolbarItem(forItemIdentifier: "urlField")?.view as? AJRURLField navigationSegments = view.window?.toolbar?.toolbarItem(forItemIdentifier: "navigationSegments")?.view as? NSSegmentedControl updateNavigationSegments() urlField.urlValue = webView.url if webView.url == nil && !webView.isLoading { webView.goHome() } } override open var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: - Actions @IBAction open func takeURLFrom(_ sender: Any?) -> Void { if let menuItem = sender as? NSMenuItem { if let historyItem = menuItem.representedObject as? WKBackForwardListItem { webView.go(to: historyItem) } else if let url = menuItem.representedObject as? URL { webView.load(URLRequest(url: url)) } } else if let bookmarkBar = sender as? AJRBookmarksBar, let url = bookmarkBar.selectedBookmark?.url { webView.load(URLRequest(url: url)) } else if let url = (sender as? NSControl)?.urlValue { print("going to: \(url)") webView.load(URLRequest(url: url)) } } @IBAction open func openLocation(_ sender: Any?) -> Void { view.window?.makeFirstResponder(urlField) } @IBAction open func navigateBackOrForward(_ sender: NSSegmentedControl?) -> Void { if sender?.selectedSegment == 0 { webView.goBack() } else if sender?.selectedSegment == 1 { webView.goForward() } } // MARK: - WKNavigationDelegate public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("error: \(error)") } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("error: \(error)") } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // Not actually sufficient, for testing purposes now. ((view.window?.delegate as? WindowController)?.document as? Document)?.invalidateRestorableState() updateNavigationSegments() } // MARK: - Key/Value Observing open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "estimatedProgress" { if webView.estimatedProgress >= 1.0 { urlField?.noteProgressComplete() } else { urlField?.progress = webView.estimatedProgress } } else if keyPath == "URL" { urlField?.urlValue = webView.url } else if keyPath == "favoriteIcon" { urlField?.icon = webView.favoriteIcon } else if keyPath == "canGoBack" { updateNavigationSegments() } else if keyPath == "canGoForward" { updateNavigationSegments() } else if keyPath == "currentItem" { updateNavigationSegments() } else if keyPath == "title" { view.window?.title = webView.title ?? webView.url?.absoluteString ?? "Unknown" urlField?.titleForDrag = webView.title } } }
39.271357
156
0.644274