repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
steelwheels/KiwiScript
refs/heads/master
KiwiShell/Source/KHShellCompiler.swift
lgpl-2.1
1
/** * @file KHShellCompiler.swift * @brief Define KHShellCompiler class * @par Copyright * Copyright (C) 2019 Steel Wheels Project */ import KiwiLibrary import KiwiEngine import CoconutData import CoconutShell import JavaScriptCore import Foundation public class KHShellCompiler: KECompiler { open func compile(context ctxt: KEContext, readline readln: CNReadline, resource res: KEResource, processManager procmgr: CNProcessManager, terminalInfo terminfo: CNTerminalInfo, console cons: CNFileConsole, environment env: CNEnvironment, config conf: KEConfig) -> Bool { defineGlobalVariables(context: ctxt, readline: readln, console: cons) defineEnvironmentVariables(environment: env) defineBuiltinFunctions(context: ctxt, console: cons, processManager: procmgr, environment: env) importBuiltinLibrary(context: ctxt, console: cons, config: conf) return true } private func defineGlobalVariables(context ctxt: KEContext, readline readln: CNReadline, console cons: CNFileConsole){ let pref = KHPreference(context: ctxt) ctxt.set(name: "Preference", object: pref) let readobj = KLReadline(readline: readln, console: cons, context: ctxt) ctxt.set(name: "_readlineCore", object: readobj) } private func defineEnvironmentVariables(environment env: CNEnvironment) { let verstr = CNPreference.shared.systemPreference.version env.set(name: "JSH_VERSION", value: .stringValue(verstr)) } private func defineBuiltinFunctions(context ctxt: KEContext, console cons: CNConsole, processManager procmgr: CNProcessManager, environment env: CNEnvironment) { defineCdFunction(context: ctxt, console: cons, environment: env) defineCleanFunction(context: ctxt, console: cons, environment: env) defineHistoryFunction(context: ctxt, console: cons, environment: env) defineSetupFunction(context: ctxt, console: cons, environment: env) #if os(OSX) defineSystemFunction(context: ctxt, processManager: procmgr, environment: env) #endif } private func defineCdFunction(context ctxt: KEContext, console cons: CNConsole, environment env: CNEnvironment) { /* cd command */ let cdfunc: @convention(block) () -> JSValue = { () -> JSValue in let cdcmd = KLCdCommand(context: ctxt, console: cons, environment: env) return JSValue(object: cdcmd, in: ctxt) } ctxt.set(name: "cdcmd", function: cdfunc) } private func defineCleanFunction(context ctxt: KEContext, console cons: CNConsole, environment env: CNEnvironment) { /* clean command */ let cdfunc: @convention(block) () -> JSValue = { () -> JSValue in let cdcmd = KLCleanCommand(context: ctxt, console: cons, environment: env) return JSValue(object: cdcmd, in: ctxt) } ctxt.set(name: KLCleanCommand.builtinFunctionName, function: cdfunc) } private func defineHistoryFunction(context ctxt: KEContext, console cons: CNConsole, environment env: CNEnvironment) { /* history command */ let histfunc: @convention(block) () -> JSValue = { () -> JSValue in let cdcmd = KHHistoryCommand(context: ctxt, console: cons, environment: env) return JSValue(object: cdcmd, in: ctxt) } ctxt.set(name: KHHistoryCommandStatement.commandName, function: histfunc) } private func defineSetupFunction(context ctxt: KEContext, console cons: CNConsole, environment env: CNEnvironment) { /* setup command */ let setupfunc: @convention(block) () -> JSValue = { () -> JSValue in let cdcmd = KLInstallCommand(context: ctxt, console: cons, environment: env) return JSValue(object: cdcmd, in: ctxt) } ctxt.set(name: KLInstallCommand.builtinFunctionName, function: setupfunc) } private func importBuiltinLibrary(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) { let libnames = ["Readline", "ValueEditor"] do { for libname in libnames { if let url = CNFilePath.URLForResourceFile(fileName: libname, fileExtension: "js", subdirectory: "Library", forClass: KHShellCompiler.self) { let script = try String(contentsOf: url, encoding: .utf8) let _ = compileStatement(context: ctxt, statement: script, sourceFile: url, console: cons, config: conf) } else { cons.error(string: "Built-in script \"\(libname)\" is not found.") } } } catch { cons.error(string: "Failed to read built-in script in KiwiLibrary") } } /* Define "system" built-in command */ #if os(OSX) private func defineSystemFunction(context ctxt: KEContext, processManager procmgr: CNProcessManager, environment env: CNEnvironment) { /* system */ let systemfunc: @convention(block) (_ cmdval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue = { (_ cmdval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue in return KHShellCompiler.executeSystemCommand(processManager: procmgr, commandValue: cmdval, inputValue: inval, outputValue: outval, errorValue: errval, context: ctxt, environment: env) } ctxt.set(name: "system", function: systemfunc) } private static func executeSystemCommand(processManager procmgr: CNProcessManager, commandValue cmdval: JSValue, inputValue inval: JSValue, outputValue outval: JSValue, errorValue errval: JSValue, context ctxt: KEContext, environment env: CNEnvironment) -> JSValue { if let command = valueToString(value: cmdval), let ifile = valueToInputFile(value: inval), let ofile = valueToOutputFile(value: outval), let efile = valueToOutputFile(value: errval) { let process = CNProcess(processManager: procmgr, input: ifile, output: ofile, error: efile, environment: env, terminationHander: nil) let _ = procmgr.addProcess(process: process) process.execute(command: command) let procval = KLProcess(process: process, context: ctxt) return JSValue(object: procval, in: ctxt) } return JSValue(nullIn: ctxt) } private static func valueToString(value val: JSValue) -> String? { if val.isString { if let str = val.toString() { return str } } return nil } private static func valueToInputFile(value val: JSValue) -> CNFile? { if val.isObject { if let file = val.toObject() as? KLFile { return file.file } else if let pipe = val.toObject() as? KLPipe { return pipe.readerFile } } return nil } private static func valueToOutputFile(value val: JSValue) -> CNFile? { if val.isObject { if let file = val.toObject() as? KLFile { return file.file } else if let pipe = val.toObject() as? KLPipe { return pipe.writerFile } } return nil } private static func valueToFunction(value val: JSValue) -> JSValue? { if !(val.isNull || val.isUndefined) { return val } else { return nil } } #endif }
8c4d8cbbed4ac7e9a4e013ffea989f1b
38.660714
273
0.729101
false
false
false
false
daggmano/photo-management-studio
refs/heads/develop
src/Client/OSX/Photo Management Studio/Photo Management Studio/ImportPhotosRequestObject.swift
mit
1
// // ImportPhotosRequestObject.swift // Photo Management Studio // // Created by Darren Oster on 12/02/2016. // Copyright © 2016 Darren Oster. All rights reserved. // import Foundation class ImportPhotosRequestObject : NSObject, JsonProtocol { internal private(set) var photoPaths: [String]? init(photoPaths: [String]) { self.photoPaths = photoPaths } required init(json: [String: AnyObject]) { self.photoPaths = json["photoPaths"] as? [String] } func toJSON() -> [String: AnyObject] { var result = [String: AnyObject]() if let photoPaths = self.photoPaths { result["photoPaths"] = photoPaths } return result } }
c6edb8266a98e4d0fcaa35fa2fb04cc0
22.903226
58
0.609987
false
false
false
false
acevest/acecode
refs/heads/master
learn/FoodTracker/FoodTracker/MealViewController.swift
gpl-2.0
1
// // ViewController.swift // FoodTracker // // Created by Ace on 06/11/2016. // Copyright © 2016 Ace. All rights reserved. // import UIKit class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var mealNameLabel: UILabel! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal: Meal? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. nameTextField.delegate = self checkValidMealName() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Hide Keyboard textField.resignFirstResponder() return true; } func textFieldDidBeginEditing(_ textField: UITextField) { saveButton.isEnabled = false } func checkValidMealName() { let name = nameTextField.text ?? "" saveButton.isEnabled = !name.isEmpty } func textFieldDidEndEditing(_ textField: UITextField) { checkValidMealName() navigationItem.title = textField.text mealNameLabel.text = textField.text } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage photoImageView.image = selectedImage dismiss(animated: true, completion: nil) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let barButton = sender as? UIBarButtonItem { if saveButton === barButton { let name = nameTextField.text ?? "" let photo = photoImageView.image let rating = ratingControl.rating meal = Meal(name: name, photo: photo, rating: rating) } } } @IBAction func cancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } // MARK: Actions @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) { nameTextField.resignFirstResponder() let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .photoLibrary imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } @IBAction func setDefaultLabelText(_ sender: UIButton) { mealNameLabel.text = "Default Text" } }
306ef57bf1d45ecf069cf24ecdadc16d
27.761062
130
0.646154
false
false
false
false
garricn/CopyPaste
refs/heads/develop
CopyPaste/DebugFlow.swift
mit
1
// // DebugFlow.swift // CopyPaste // // Created by Garric Nahapetian on 4/1/18. // Copyright © 2018 SwiftCoders. All rights reserved. // import UIKit public final class DebugFlow { lazy var itemsContext: DataContext<[Item]> = AppContext.shared.itemsContext lazy var defaultsContext: DataContext<Defaults> = AppContext.shared.defaultsContext private var didGetItems: (([Item]) -> Void)? public func start(presenter: UIViewController) { let alert = UIAlertController(title: "DEBUG", message: nil, preferredStyle: .actionSheet) let dataTitle = "Load" let dataHandler: (UIAlertAction) -> Void = { _ in self.load() } let dataAction = UIAlertAction(title: dataTitle, style: .destructive, handler: dataHandler) dataAction.accessibilityLabel = "resetData" alert.addAction(dataAction) let defaultsTitle = "Reset" let defaultsHandler: (UIAlertAction) -> Void = { _ in self.presentReset(presenter: presenter) } let defaultsAction = UIAlertAction(title: defaultsTitle, style: .destructive, handler: defaultsHandler) defaultsAction.accessibilityLabel = "resetDefaults" alert.addAction(defaultsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) cancelAction.accessibilityLabel = "cancel" alert.addAction(cancelAction) presenter.present(alert, animated: true, completion: nil) } public func onGet(perform action: @escaping ([Item]) -> Void) { didGetItems = action } private func load() { let url = Bundle.main.url(forResource: "sampleItems", withExtension: "json")! let data = try! Data(contentsOf: url) let items = try! JSONDecoder().decode([Item].self, from: data) didGetItems?(items) } private func presentReset(presenter: UIViewController) { let alert = UIAlertController(title: "RESET", message: nil, preferredStyle: .actionSheet) let dataTitle = "Data" let dataHandler: (UIAlertAction) -> Void = { _ in self.itemsContext.reset() } let dataAction = UIAlertAction(title: dataTitle, style: .destructive, handler: dataHandler) dataAction.accessibilityLabel = "resetData" alert.addAction(dataAction) let defaultsTitle = "Defaults" let defaultsHandler: (UIAlertAction) -> Void = { _ in self.defaultsContext.reset() } let defaultsAction = UIAlertAction(title: defaultsTitle, style: .destructive, handler: defaultsHandler) defaultsAction.accessibilityLabel = "resetDefaults" alert.addAction(defaultsAction) let bothTitle = "Both" let bothHandler: (UIAlertAction) -> Void = { _ in self.itemsContext.reset(); self.defaultsContext.reset() } let bothAction = UIAlertAction(title: bothTitle, style: .destructive, handler: bothHandler) bothAction.accessibilityLabel = "resetDataAndDefaults" alert.addAction(bothAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) cancelAction.accessibilityLabel = "cancel" alert.addAction(cancelAction) presenter.present(alert, animated: true, completion: nil) } }
36da1208498a636b561ec965baf79091
41.75641
116
0.662969
false
false
false
false
phimage/Erik
refs/heads/master
ErikAppTest/TestErikOSX/ViewController.swift
mit
1
// // ViewController.swift // TestErikOSX // // Created by phimage on 13/12/15. // Copyright © 2015 phimage. All rights reserved. // import Cocoa import Erik import Kanna import WebKit class ViewController: NSViewController { var browser: Erik! var webView: WKWebView! @IBOutlet weak var mainView: NSView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: self.mainView.bounds, configuration: WKWebViewConfiguration()) self.webView.frame = self.mainView.bounds self.webView.translatesAutoresizingMaskIntoConstraints = false self.mainView.addSubview(self.webView) self.mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":self.webView])) self.mainView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":self.webView])) browser = Erik(webView: webView) browser.visit(url: googleURL) { object, error in if let e = error { print(String(describing: e)) } else if let doc = object { print(String(describing: doc)) } } } @IBAction func testAction(_ sender: AnyObject) { browser.currentContent { (d, r) in if let error = r { NSAlert(error: error).runModal() } else if let doc = d { if let input = doc.querySelector("input[name='q']") { print(input) input["value"] = "Erik swift" } if let form = doc.querySelector("form") as? Form { print(form) form.submit() } } } } @IBAction func reload(_ sender: AnyObject) { browser.visit(url: browser.url ?? googleURL) { (object, error) in if let e = error { print(String(describing: e)) } else if let doc = object { print(String(describing: doc)) } } } }
62dd38b851cbdd4d429024b176f5f7c4
30.520548
195
0.55628
false
false
false
false
tadija/AELog
refs/heads/master
Example/AELogDemo iOS/ViewController.swift
mit
1
/** * https://github.com/tadija/AELog * Copyright © 2016-2020 Marko Tadić * Licensed under the MIT license */ import UIKit import AELog class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() aelog() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) aelog() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) aelog() let text = "One two three four five" let x: CGFloat = 21 let y: CGFloat = 8 let size = CGSize(width: 19, height: 84) let rect = CGRect(x: x, y: y, width: size.width, height: size.height) let range = 1...5 aelog(text, x, y, size, rect, range, Log.shared, self) queue.async { aelog("This is coming from background thread.") } aelog("This will be logged to device console.", mode: .nsLog) } private let queue = DispatchQueue(label: "Custom") @IBAction func didTapButton(_ sender: UIButton) { let queue = DispatchQueue.global() queue.async { generateLogLines(count: Int.random(max: 1000)) DispatchQueue.main.async(execute: { aelog(sender) }) } } }
6ddab385b8c8f8c6f87506e0f927b2ab
24.415094
77
0.573868
false
false
false
false
mkrisztian95/iOS
refs/heads/master
Tardis/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // SideMenu // // Created by jonkykong on 12/23/2015. // Copyright (c) 2015 jonkykong. All rights reserved. // import UIKit import Firebase import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var table1:FirstDayTableViewController! = nil var table2:SecondDayTableViewController! = nil var window: UIWindow? override init() { // Firebase Init FIRApp.configure() GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID FIRDatabase.database().persistenceEnabled = true } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { /*var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") GIDSignIn.sharedInstance().delegate = self */ var configureError: NSError? // GMSServices.provideAPIKey("AIzaSyCEtkeXHgva5wSULamLxmU0ZYpSEZ-ln9w") // FIRApp.configure() GIDSignIn.sharedInstance().delegate = self return true } func application(application: UIApplication, openURL url: NSURL, options: [String: AnyObject]) -> Bool { if #available(iOS 9.0, *) { return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String, annotation: options[UIApplicationOpenURLOptionsAnnotationKey]) } else { // Fallback on earlier versions } return false } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { if #available(iOS 9.0, *) { var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!, UIApplicationOpenURLOptionsAnnotationKey: annotation!] } else { // Fallback on earlier versions } return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: sourceApplication, annotation: annotation) } func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) { if let error = error { print(error.localizedDescription) return } let authentication = user.authentication let credential = FIRGoogleAuthProvider.credentialWithIDToken(authentication.idToken, accessToken: authentication.accessToken) FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in // ... } // ... } func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!, withError error: NSError!) { // Perform any operations when the user disconnects from app here. // ... } 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:. } }
5bf1fe5defa79534c678f71f84c26fe5
38.241935
281
0.680436
false
true
false
false
YQqiang/Nunchakus
refs/heads/master
Nunchakus/Nunchakus/Services/API.swift
mit
1
// // API.swift // operation4ios // // Created by sungrow on 2017/2/17. // Copyright © 2017年 阳光电源股份有限公司. All rights reserved. // import Foundation import Moya import Result let API_PRO = "http://www.sjg8.com" /// 请求头--日志信息 private let deviceName = UIDevice.current.name //获取设备名称 例如:某某的手机 private let sysName = UIDevice.current.systemName //获取系统名称 例如:iPhone OS private let sysVersion = UIDevice.current.systemVersion //获取系统版本 例如:9.2 private let deviceUUID = UIDevice.current.identifierForVendor?.uuidString ?? "" //获取设备唯一标识符 例如:FBF2306E-A0D8-4F4B-BDED-9333B627D3E6 private let infoDic = Bundle.main.infoDictionary private let identifier = (infoDic?["CFBundleIdentifier"] as? String) ?? "" private let appVersion = (infoDic?["CFBundleShortVersionString"] as? String) ?? "" // 获取App的版本 private let appBuildVersion = (infoDic?["CFBundleVersion"] as? String) ?? "" // 获取App的build版本 private let appName = (infoDic?["CFBundleDisplayName"] as? String) ?? "" // 获取App的名称 private let system_info = "\(appName)/\(identifier)/\(appVersion)_\(appBuildVersion)/iOS(\(deviceName)|\(sysName)|\(sysVersion)|\(deviceUUID))" var headerFields: [String: String] = ["User-Agent": "sungrow-agent", "system": "iOS","sys_ver": String(UIDevice.version()), "system_info": system_info] /// 公共参数--(token 需要在每个接口中获取) var publicParameters: [String: String] = ["language": NSLocalizedString("Language", comment: "")] final class RequestCloudLoadingPlugin: PluginType { func willSend(_ request: RequestType, target: TargetType) { Hud.show(status: NSLocalizedString("正在加载", comment: "")) } func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) { Hud.dismissHUD() } }
2b09475e223705acc4069fbd7e20b2a6
44.837838
151
0.71934
false
false
false
false
adrianomazucato/CoreStore
refs/heads/master
CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV2.swift
mit
3
// // OrganismV2.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/21. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import Foundation import CoreData class OrganismV2: NSManagedObject, OrganismProtocol { @NSManaged var dna: Int64 @NSManaged var hasHead: Bool @NSManaged var hasTail: Bool @NSManaged var numberOfFlippers: Int32 // MARK: OrganismProtocol func mutate() { self.hasHead = arc4random_uniform(2) == 1 self.hasTail = arc4random_uniform(2) == 1 self.numberOfFlippers = Int32(arc4random_uniform(9) / 2 * 2) } }
5df72d30b0625a14fe2e670d22bcf739
22.888889
68
0.657364
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/HTTPCookieStorage.swift
apache-2.0
2
// 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 // import Dispatch import CoreFoundation /*! @enum HTTPCookie.AcceptPolicy @abstract Values for the different cookie accept policies @constant HTTPCookie.AcceptPolicy.always Accept all cookies @constant HTTPCookie.AcceptPolicy.never Reject all cookies @constant HTTPCookie.AcceptPolicy.onlyFromMainDocumentDomain Accept cookies only from the main document domain */ extension HTTPCookie { public enum AcceptPolicy : UInt { case always case never case onlyFromMainDocumentDomain } } /*! @class HTTPCookieStorage @discussion HTTPCookieStorage implements a singleton object (shared instance) which manages the shared cookie store. It has methods to allow clients to set and remove cookies, and get the current set of cookies. It also has convenience methods to parse and generate cookie-related HTTP header fields. */ open class HTTPCookieStorage: NSObject { /* both sharedStorage and sharedCookieStorages are synchronized on sharedSyncQ */ private static var sharedStorage: HTTPCookieStorage? private static var sharedCookieStorages: [String: HTTPCookieStorage] = [:] //for group storage containers private static let sharedSyncQ = DispatchQueue(label: "org.swift.HTTPCookieStorage.sharedSyncQ") /* only modified in init */ private var cookieFilePath: String! /* synchronized on syncQ, please don't use _allCookies directly outside of init/deinit */ private var _allCookies: [String: HTTPCookie] private var allCookies: [String: HTTPCookie] { get { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } return self._allCookies } set { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } self._allCookies = newValue } } private let syncQ = DispatchQueue(label: "org.swift.HTTPCookieStorage.syncQ") private init(cookieStorageName: String) { _allCookies = [:] cookieAcceptPolicy = .always super.init() let bundlePath = Bundle.main.bundlePath var bundleName = bundlePath.components(separatedBy: "/").last! if let range = bundleName.range(of: ".", options: .backwards, range: nil, locale: nil) { bundleName = String(bundleName[..<range.lowerBound]) } let cookieFolderPath = _CFXDGCreateDataHomePath()._swiftObject + "/" + bundleName cookieFilePath = filePath(path: cookieFolderPath, fileName: "/.cookies." + cookieStorageName, bundleName: bundleName) loadPersistedCookies() } private func loadPersistedCookies() { guard let cookiesData = try? Data(contentsOf: URL(fileURLWithPath: cookieFilePath)) else { return } guard let cookies = try? PropertyListSerialization.propertyList(from: cookiesData, format: nil) else { return } var cookies0 = cookies as? [String: [String: Any]] ?? [:] self.syncQ.sync { for key in cookies0.keys { if let cookie = createCookie(cookies0[key]!) { allCookies[key] = cookie } } } } private func directory(with path: String) -> Bool { guard !FileManager.default.fileExists(atPath: path) else { return true } do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch { return false } } private func filePath(path: String, fileName: String, bundleName: String) -> String { if directory(with: path) { return path + fileName } //if we were unable to create the desired directory, create the cookie file //in a subFolder (named after the bundle) of the `pwd` return FileManager.default.currentDirectoryPath + "/" + bundleName + fileName } open var cookies: [HTTPCookie]? { return Array(self.syncQ.sync { self.allCookies.values }) } /*! @method sharedHTTPCookieStorage @abstract Get the shared cookie storage in the default location. @result The shared cookie storage @discussion Starting in OS X 10.11, each app has its own sharedHTTPCookieStorage singleton, which will not be shared with other applications. */ open class var shared: HTTPCookieStorage { get { return sharedSyncQ.sync { if sharedStorage == nil { sharedStorage = HTTPCookieStorage(cookieStorageName: "shared") } return sharedStorage! } } } /*! @method sharedCookieStorageForGroupContainerIdentifier: @abstract Get the cookie storage for the container associated with the specified application group identifier @param identifier The application group identifier @result A cookie storage with a persistent store in the application group container @discussion By default, applications and associated app extensions have different data containers, which means that the sharedHTTPCookieStorage singleton will refer to different persistent cookie stores in an application and any app extensions that it contains. This method allows clients to create a persistent cookie storage that can be shared among all applications and extensions with access to the same application group. Subsequent calls to this method with the same identifier will return the same cookie storage instance. */ open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage { return sharedSyncQ.sync { guard let cookieStorage = sharedCookieStorages[identifier] else { let newCookieStorage = HTTPCookieStorage(cookieStorageName: identifier) sharedCookieStorages[identifier] = newCookieStorage return newCookieStorage } return cookieStorage } } /*! @method setCookie: @abstract Set a cookie @discussion The cookie will override an existing cookie with the same name, domain and path, if any. */ open func setCookie(_ cookie: HTTPCookie) { self.syncQ.sync { guard cookieAcceptPolicy != .never else { return } //add or override let key = cookie.domain + cookie.path + cookie.name if let _ = allCookies.index(forKey: key) { allCookies.updateValue(cookie, forKey: key) } else { allCookies[key] = cookie } //remove stale cookies, these may include the one we just added let expired = allCookies.filter { (_, value) in value.expiresDate != nil && value.expiresDate!.timeIntervalSinceNow < 0 } for (key,_) in expired { self.allCookies.removeValue(forKey: key) } updatePersistentStore() } } open override var description: String { return "<NSHTTPCookieStorage cookies count:\(cookies?.count ?? 0)>" } private func createCookie(_ properties: [String: Any]) -> HTTPCookie? { var cookieProperties: [HTTPCookiePropertyKey: Any] = [:] for (key, value) in properties { if key == "Expires" { guard let timestamp = value as? NSNumber else { continue } cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = Date(timeIntervalSince1970: timestamp.doubleValue) } else { cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = properties[key] } } return HTTPCookie(properties: cookieProperties) } private func updatePersistentStore() { if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { dispatchPrecondition(condition: DispatchPredicate.onQueue(self.syncQ)) } //persist cookies var persistDictionary: [String : [String : Any]] = [:] let persistable = self.allCookies.filter { (_, value) in value.expiresDate != nil && value.isSessionOnly == false && value.expiresDate!.timeIntervalSinceNow > 0 } for (key,cookie) in persistable { persistDictionary[key] = cookie.persistableDictionary() } let nsdict = __SwiftValue.store(persistDictionary) as! NSDictionary _ = nsdict.write(toFile: cookieFilePath, atomically: true) } /*! @method lockedDeleteCookie: @abstract Delete the specified cookie, for internal callers already on syncQ. */ private func lockedDeleteCookie(_ cookie: HTTPCookie) { let key = cookie.domain + cookie.path + cookie.name self.allCookies.removeValue(forKey: key) updatePersistentStore() } /*! @method deleteCookie: @abstract Delete the specified cookie */ open func deleteCookie(_ cookie: HTTPCookie) { self.syncQ.sync { self.lockedDeleteCookie(cookie) } } /*! @method removeCookiesSince: @abstract Delete all cookies from the cookie storage since the provided date. */ open func removeCookies(since date: Date) { self.syncQ.sync { let cookiesSinceDate = self.allCookies.values.filter { $0.properties![.created] as! Double > date.timeIntervalSinceReferenceDate } for cookie in cookiesSinceDate { lockedDeleteCookie(cookie) } updatePersistentStore() } } /*! @method cookiesForURL: @abstract Returns an array of cookies to send to the given URL. @param URL The URL for which to get cookies. @result an Array of HTTPCookie objects. @discussion The cookie manager examines the cookies it stores and includes those which should be sent to the given URL. You can use <tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array into a set of header fields to add to a request. */ open func cookies(for url: URL) -> [HTTPCookie]? { guard let host = url.host?.lowercased() else { return nil } return Array(self.syncQ.sync(execute: {allCookies}).values.filter{ $0.validFor(host: host) }) } /*! @method setCookies:forURL:mainDocumentURL: @abstract Adds an array cookies to the cookie store, following the cookie accept policy. @param cookies The cookies to set. @param URL The URL from which the cookies were sent. @param mainDocumentURL The main document URL to be used as a base for the "same domain as main document" policy. @discussion For mainDocumentURL, the caller should pass the URL for an appropriate main document, if known. For example, when loading a web page, the URL of the main html document for the top-level frame should be passed. To save cookies based on a set of response headers, you can use <tt>+[NSCookie cookiesWithResponseHeaderFields:forURL:]</tt> on a header field dictionary and then use this method to store the resulting cookies in accordance with policy settings. */ open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) { //if the cookieAcceptPolicy is `never` we don't have anything to do guard cookieAcceptPolicy != .never else { return } //if the urls don't have a host, we cannot do anything guard let urlHost = url?.host?.lowercased() else { return } if mainDocumentURL != nil && cookieAcceptPolicy == .onlyFromMainDocumentDomain { guard let mainDocumentHost = mainDocumentURL?.host?.lowercased() else { return } //the url.host must be a suffix of manDocumentURL.host, this is based on Darwin's behaviour guard mainDocumentHost.hasSuffix(urlHost) else { return } } //save only those cookies whose domain matches with the url.host let validCookies = cookies.filter { $0.validFor(host: urlHost) } for cookie in validCookies { setCookie(cookie) } } /*! @method cookieAcceptPolicy @abstract The cookie accept policy preference of the receiver. */ open var cookieAcceptPolicy: HTTPCookie.AcceptPolicy /*! @method sortedCookiesUsingDescriptors: @abstract Returns an array of all cookies in the store, sorted according to the key value and sorting direction of the NSSortDescriptors specified in the parameter. @param sortOrder an array of NSSortDescriptors which represent the preferred sort order of the resulting array. @discussion proper sorting of cookies may require extensive string conversion, which can be avoided by allowing the system to perform the sorting. This API is to be preferred over the more generic -[HTTPCookieStorage cookies] API, if sorting is going to be performed. */ open func sortedCookies(using sortOrder: [NSSortDescriptor]) -> [HTTPCookie] { NSUnimplemented() } } extension Notification.Name { /*! @const NSHTTPCookieManagerCookiesChangedNotification @abstract Notification sent when the set of cookies changes */ public static let NSHTTPCookieManagerCookiesChanged = Notification.Name(rawValue: "NSHTTPCookieManagerCookiesChangedNotification") } extension HTTPCookie { internal func validFor(host: String) -> Bool { // RFC6265 - HTTP State Management Mechanism // https://tools.ietf.org/html/rfc6265#section-5.1.3 // // 5.1.3. Domain Matching // A string domain-matches a given domain string if at least one of the // following conditions hold: // // 1) The domain string and the string are identical. (Note that both // the domain string and the string will have been canonicalized to // lower case at this point.) // // 2) All of the following conditions hold: // * The domain string is a suffix of the string. // * The last character of the string that is not included in the // domain string is a %x2E (".") character. // * The string is a host name (i.e., not an IP address). guard domain.hasPrefix(".") else { return host == domain } return host == domain.dropFirst() || host.hasSuffix(domain) } internal func persistableDictionary() -> [String: Any] { var properties: [String: Any] = [:] properties[HTTPCookiePropertyKey.name.rawValue] = name properties[HTTPCookiePropertyKey.path.rawValue] = path properties[HTTPCookiePropertyKey.value.rawValue] = _value properties[HTTPCookiePropertyKey.secure.rawValue] = _secure properties[HTTPCookiePropertyKey.version.rawValue] = _version properties[HTTPCookiePropertyKey.expires.rawValue] = _expiresDate?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 //OK? properties[HTTPCookiePropertyKey.domain.rawValue] = _domain if let commentURL = _commentURL { properties[HTTPCookiePropertyKey.commentURL.rawValue] = commentURL.absoluteString } if let comment = _comment { properties[HTTPCookiePropertyKey.comment.rawValue] = comment } properties[HTTPCookiePropertyKey.port.rawValue] = portList return properties } }
57feefd799b2b984562fe44ed9bcf222
41.912467
274
0.654036
false
false
false
false
JeremyJacquemont/SchoolProjects
refs/heads/master
IUT/iOS-Projects/TP-BDD-1/Task.swift
apache-2.0
1
// // Task.swift // TP-BDD-1 // // Created by iem on 01/04/2015. // Copyright (c) 2015 JeremyJacquemont. All rights reserved. // import Foundation import CoreData func == (lhs : Task , rhs : Task) -> Bool { return lhs.name == rhs.name && lhs.text == rhs.text && lhs.date == rhs.date && lhs.photo == rhs.photo } class Task: NSManagedObject { class var TABLE_NAME: String { return "Task" } class var FIELD_NAME: String { return "name" } class var FIELD_TEXT: String { return "text" } class var FIELD_DATE: String { return "date" } class var FIELD_PHOTO: String { return "photo" } class var FIELD_CATEGORY: String { return "category" } class var ALL_FIELDS: [String] { return [Task.FIELD_NAME, Task.FIELD_TEXT, Task.FIELD_DATE, Task.FIELD_PHOTO, Task.FIELD_CATEGORY] } @NSManaged var name: String @NSManaged var text: String? @NSManaged var date: NSDate? @NSManaged var photo: NSData @NSManaged var category: Category }
ca2a28cea32b345027cfdac8b835e32d
30.806452
136
0.657201
false
false
false
false
quran/quran-ios
refs/heads/main
Sources/QuranAudioKit/Downloads/AudioFilesDownloader.swift
apache-2.0
1
// // AudioFilesDownloader.swift // Quran // // Created by Mohamed Afifi on 5/15/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import BatchDownloader import Crashing import Foundation import PromiseKit import QuranKit class AudioFilesDownloader { private let gapplessAudioFileList: ReciterAudioFileListRetrieval private let gappedAudioFileList: ReciterAudioFileListRetrieval private let downloader: DownloadManager private let ayahDownloader: AyahsAudioDownloader private let fileSystem: FileSystem private var response: DownloadBatchResponse? init(gapplessAudioFileList: ReciterAudioFileListRetrieval, gappedAudioFileList: ReciterAudioFileListRetrieval, downloader: DownloadManager, ayahDownloader: AyahsAudioDownloader, fileSystem: FileSystem) { self.gapplessAudioFileList = gapplessAudioFileList self.gappedAudioFileList = gappedAudioFileList self.downloader = downloader self.ayahDownloader = ayahDownloader self.fileSystem = fileSystem } func cancel() { response?.cancel() response = nil } func needsToDownloadFiles(reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> Bool { let files = filesForReciter(reciter, from: start, to: end) return files.contains { !fileSystem.fileExists(at: FileManager.documentsURL.appendingPathComponent($0.destinationPath)) } } func getCurrentDownloadResponse() -> Guarantee<DownloadBatchResponse?> { if let response = response { return Guarantee.value(response) } else { return downloader.getOnGoingDownloads().map { batches -> DownloadBatchResponse? in let downloading = batches.first { $0.isAudio } self.createRequestWithDownloads(downloading) return self.response } } } func download(reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> Promise<DownloadBatchResponse?> { ayahDownloader .download(from: start, to: end, reciter: reciter) .map(on: .main) { responses -> DownloadBatchResponse? in // wrap the requests self.createRequestWithDownloads(responses) return self.response } } private func createRequestWithDownloads(_ batch: DownloadBatchResponse?) { guard let batch = batch else { return } response = batch response?.promise.ensure { [weak self] in self?.response = nil } .catch { error in crasher.recordError(error, reason: "Audio Download Promise failed.") } } private func filesForReciter(_ reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> [DownloadRequest] { let audioFileList = getAudioFileList(for: reciter) return audioFileList.get(for: reciter, from: start, to: end).map { DownloadRequest(url: $0.remote, destinationPath: $0.local) } } private func getAudioFileList(for reciter: Reciter) -> ReciterAudioFileListRetrieval { switch reciter.audioType { case .gapless: return gapplessAudioFileList case .gapped: return gappedAudioFileList } } }
6cd5683f29a8a8d9bfa17b46cc013407
35.074766
129
0.678756
false
false
false
false
devpunk/cartesian
refs/heads/master
cartesian/View/Gallery/VGallery.swift
mit
1
import UIKit class VGallery:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var controller:CGallery! private weak var spinner:VSpinner! private weak var viewBar:VGalleryBar! private weak var collectionView:VCollection! private let kBarTop:CGFloat = 70 private let kBarHeight:CGFloat = 45 private let kHeaderHeight:CGFloat = 45 private let kFooterHeight:CGFloat = 90 private let kCellHeight:CGFloat = 250 override init(controller:CController) { super.init(controller:controller) self.controller = controller as? CGallery let spinner:VSpinner = VSpinner() self.spinner = spinner let viewBar:VGalleryBar = VGalleryBar( controller:self.controller) viewBar.isHidden = true self.viewBar = viewBar let collectionView:VCollection = VCollection() collectionView.isHidden = true collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerHeader(header:VGalleryHeader.self) collectionView.registerFooter(footer:VGalleryFooterMine.self) collectionView.registerFooter(footer:VGalleryFooterOther.self) collectionView.registerCell(cell:VGalleryCell.self) collectionView.contentInset = UIEdgeInsets( top:kBarHeight, left:0, bottom:0, right:0) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight) flow.footerReferenceSize = CGSize(width:0, height:kFooterHeight) } addSubview(spinner) addSubview(collectionView) addSubview(viewBar) NSLayoutConstraint.equals( view:spinner, toView:self) NSLayoutConstraint.topToTop( view:viewBar, toView:self, constant:kBarTop) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.topToTop( view:collectionView, toView:self, constant:kBarTop) NSLayoutConstraint.bottomToBottom( view:collectionView, toView:self) NSLayoutConstraint.equalsHorizontal( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { collectionView.collectionViewLayout.invalidateLayout() super.layoutSubviews() } //MARK: private private func modelAtIndex(index:IndexPath) -> MGalleryItem { let item:MGalleryItem = controller.model.displayItems[index.section] return item } //MARK: public func startLoading() { spinner.startAnimating() viewBar.isHidden = true collectionView.isHidden = true } func stopLoading() { spinner.stopAnimating() viewBar.isHidden = false viewBar.refresh() collectionView.isHidden = false collectionView.reloadData() let count:Int = controller.model.displayItems.count if count > 0 { let indexPath:IndexPath = IndexPath( item:0, section:0) collectionView.scrollToItem( at:indexPath, at:UICollectionViewScrollPosition.top, animated:true) } } //MARK: collectionView delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let width:CGFloat = collectionView.bounds.maxX let size:CGSize = CGSize(width:width, height:kCellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { let count:Int = controller.model.displayItems.count return count } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView { let reusableView:UICollectionReusableView let item:MGalleryItem = modelAtIndex(index:indexPath) if kind == UICollectionElementKindSectionHeader { let header:VGalleryHeader = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VGalleryHeader.reusableIdentifier, for:indexPath) as! VGalleryHeader header.config(model:item) reusableView = header } else { let footer:VGalleryFooter = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: item.reusableIdentifier, for:indexPath) as! VGalleryFooter footer.config( controller:controller, model:item) reusableView = footer } return reusableView } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MGalleryItem = modelAtIndex(index:indexPath) let cell:VGalleryCell = collectionView.dequeueReusableCell( withReuseIdentifier: VGalleryCell.reusableIdentifier, for:indexPath) as! VGalleryCell cell.config(model:item) return cell } }
5c53c6fe3dd536eebe91c081e5c21bb0
30.155779
157
0.617742
false
false
false
false
farshidce/RKMultiUnitRuler
refs/heads/master
Example/RKMultiUnitRuler/ViewController.swift
mit
1
// // ViewController.swift // RKMultiUnitRulerDemo // // Created by Farshid Ghods on 12/29/16. // Copyright © 2016 Rekovery. All rights reserved. // import UIKit import RKMultiUnitRuler class ViewController: UIViewController, RKMultiUnitRulerDataSource, RKMultiUnitRulerDelegate { @IBOutlet weak var ruler: RKMultiUnitRuler? @IBOutlet weak var controlHConstraint: NSLayoutConstraint? @IBOutlet weak var colorSwitch: UISwitch? var backgroundColor: UIColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) @IBOutlet weak var directionSwitch: UISwitch? @IBOutlet weak var moreMarkersSwitch: UISwitch? var rangeStart = Measurement(value: 30.0, unit: UnitMass.kilograms) var rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) var colorOverridesEnabled = false var moreMarkers = false var direction: RKLayerDirection = .horizontal var segments = Array<RKSegmentUnit>() override func viewDidLoad() { super.viewDidLoad() self.colorSwitch?.addTarget(self, action: #selector(ViewController.colorSwitchValueChanged(sender:)), for: .valueChanged) self.directionSwitch?.addTarget(self, action: #selector(ViewController.directionSwitchValueChanged(sender:)), for: .valueChanged) self.moreMarkersSwitch?.addTarget(self, action: #selector(ViewController.moreMarkersSwitchValueChanged(sender:)), for: .valueChanged) ruler?.direction = direction ruler?.tintColor = UIColor(red: 0.15, green: 0.18, blue: 0.48, alpha: 1.0) controlHConstraint?.constant = 200.0 segments = self.createSegments() ruler?.delegate = self ruler?.dataSource = self let initialValue = (self.rangeForUnit(UnitMass.kilograms).location + self.rangeForUnit(UnitMass.kilograms).length) / 2 ruler?.measurement = NSMeasurement( doubleValue: Double(initialValue), unit: UnitMass.kilograms) self.view.layoutSubviews() // Do any additional setup after loading the view, typically from a nib. } private func createSegments() -> Array<RKSegmentUnit> { let formatter = MeasurementFormatter() formatter.unitStyle = .medium formatter.unitOptions = .providedUnit let kgSegment = RKSegmentUnit(name: "Kilograms", unit: UnitMass.kilograms, formatter: formatter) kgSegment.name = "Kilogram" kgSegment.unit = UnitMass.kilograms let kgMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 5.0) kgMarkerTypeMax.labelVisible = true kgSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 0.5), RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 1.0)] let lbsSegment = RKSegmentUnit(name: "Pounds", unit: UnitMass.pounds, formatter: formatter) let lbsMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 10.0) lbsSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 1.0)] if moreMarkers { kgSegment.markerTypes.append(kgMarkerTypeMax) lbsSegment.markerTypes.append(lbsMarkerTypeMax) } kgSegment.markerTypes.last?.labelVisible = true lbsSegment.markerTypes.last?.labelVisible = true return [kgSegment, lbsSegment] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func unitForSegmentAtIndex(index: Int) -> RKSegmentUnit { return segments[index] } var numberOfSegments: Int { get { return segments.count } set { } } func rangeForUnit(_ unit: Dimension) -> RKRange<Float> { let locationConverted = rangeStart.converted(to: unit as! UnitMass) let lengthConverted = rangeLength.converted(to: unit as! UnitMass) return RKRange<Float>(location: ceilf(Float(locationConverted.value)), length: ceilf(Float(lengthConverted.value))) } func styleForUnit(_ unit: Dimension) -> RKSegmentUnitControlStyle { let style: RKSegmentUnitControlStyle = RKSegmentUnitControlStyle() style.scrollViewBackgroundColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) let range = self.rangeForUnit(unit) if unit == UnitMass.pounds { style.textFieldBackgroundColor = UIColor.clear // color override location:location+40% red , location+60%:location.100% green } else { style.textFieldBackgroundColor = UIColor.red } if (colorOverridesEnabled) { style.colorOverrides = [ RKRange<Float>(location: range.location, length: 0.1 * (range.length)): UIColor.red, RKRange<Float>(location: range.location + 0.4 * (range.length), length: 0.2 * (range.length)): UIColor.green] } style.textFieldBackgroundColor = UIColor.clear style.textFieldTextColor = UIColor.white return style } func valueChanged(measurement: NSMeasurement) { print("value changed to \(measurement.doubleValue)") } func colorSwitchValueChanged(sender: UISwitch) { colorOverridesEnabled = sender.isOn ruler?.refresh() } func directionSwitchValueChanged(sender: UISwitch) { if sender.isOn { direction = .vertical controlHConstraint?.constant = 400 } else { direction = .horizontal controlHConstraint?.constant = 200 } ruler?.direction = direction ruler?.refresh() self.view.layoutSubviews() } func moreMarkersSwitchValueChanged(sender: UISwitch) { moreMarkers = sender.isOn if moreMarkers { self.rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) } else { self.rangeLength = Measurement(value: Double(130), unit: UnitMass.kilograms) } segments = self.createSegments() ruler?.refresh() self.view.layoutSubviews() } }
3cffe4cb363489e54438428b7649337d
38.90303
126
0.638366
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/c_function_pointers.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -verify %s | %FileCheck %s func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int { return arg } // CHECK-LABEL: sil hidden @_T019c_function_pointers6valuesS2iXCS2iXCF // CHECK: bb0(%0 : $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int @discardableResult func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden @_T019c_function_pointers5callsS3iXC_SitF // CHECK: bb0(%0 : $@convention(c) (Int) -> Int, %1 : $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] @discardableResult func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden @_T019c_function_pointers0B19_to_swift_functionsySiF func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @_T019c_function_pointers6globalS2iFTo // CHECK: apply {{.*}}([[GLOBAL_C]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiF5localL_S2iFTo // CHECK: apply {{.*}}([[LOCAL_C]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiFS2icfU_To // CHECK: apply {{.*}}([[CLOSURE_C]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @_T019c_function_pointers7no_argsSiyFTo // CHECK: apply {{.*}}([[NO_ARGS_C]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}} } // CHECK-LABEL: sil shared @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_ : $@convention(thin) () -> () { // CHECK-LABEL: sil shared [thunk] @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_To : $@convention(c) () -> () { struct StructWithInitializers { let fn1: @convention(c) () -> () = {} init(a: ()) {} init(b: ()) {} }
5618a98afe105aaa36096b51077e823c
35.415385
155
0.61597
false
false
false
false
NUKisZ/MyTools
refs/heads/master
MyTools/MyTools/ThirdLibrary/EZSwiftSources/UIImageViewExtensions.swift
mit
4
// // UIImageViewExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIImageView { /// EZSwiftExtensions public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, imageName: String) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) image = UIImage(named: imageName) } /// EZSwiftExtensions public convenience init(x: CGFloat, y: CGFloat, imageName: String, scaleToWidth: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: 0, height: 0)) image = UIImage(named: imageName) if image != nil { scaleImageFrameToWidth(width: scaleToWidth) } else { assertionFailure("EZSwiftExtensions Error: The imageName: '\(imageName)' is invalid!!!") } } /// EZSwiftExtensions public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, image: UIImage) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) self.image = image } /// EZSwiftExtensions public convenience init(x: CGFloat, y: CGFloat, image: UIImage, scaleToWidth: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: 0, height: 0)) self.image = image scaleImageFrameToWidth(width: scaleToWidth) } /// EZSwiftExtensions, scales this ImageView size to fit the given width public func scaleImageFrameToWidth(width: CGFloat) { guard let image = image else { print("EZSwiftExtensions Error: The image is not set yet!") return } let widthRatio = image.size.width / width let newWidth = image.size.width / widthRatio let newHeigth = image.size.height / widthRatio frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newWidth, height: newHeigth) } /// EZSwiftExtensions, scales this ImageView size to fit the given height public func scaleImageFrameToHeight(height: CGFloat) { guard let image = image else { print("EZSwiftExtensions Error: The image is not set yet!") return } let heightRatio = image.size.height / height let newHeight = image.size.height / heightRatio let newWidth = image.size.width / heightRatio frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newWidth, height: newHeight) } /// EZSwiftExtensions public func roundSquareImage() { self.clipsToBounds = true self.layer.cornerRadius = self.frame.size.width / 2 } /// EZSE: Initializes an UIImage from URL and adds into current ImageView public func image(url: String) { ez.requestImage(url, success: { (image) -> Void in if let img = image { DispatchQueue.main.async { self.image = img } } }) } /// EZSE: Initializes an UIImage from URL and adds into current ImageView with placeholder public func image(url: String, placeholder: UIImage) { self.image = placeholder image(url: url) } /// EZSE: Initializes an UIImage from URL and adds into current ImageView with placeholder public func image(url: String, placeholderNamed: String) { if let image = UIImage(named: placeholderNamed) { self.image(url: url, placeholder: image) } else { image(url: url) } } // MARK: Deprecated 1.8 /// EZSwiftExtensions @available(*, deprecated: 1.8, renamed: "image(url:)") public func imageWithUrl(url: String) { ez.requestImage(url, success: { (image) -> Void in if let img = image { DispatchQueue.main.async { self.image = img } } }) } /// EZSwiftExtensions @available(*, deprecated: 1.8, renamed: "image(url:placeholder:)") public func imageWithUrl(url: String, placeholder: UIImage) { self.image = placeholder imageWithUrl(url: url) } /// EZSwiftExtensions @available(*, deprecated: 1.8, renamed: "image(url:placeholderNamed:)") public func imageWithUrl(url: String, placeholderNamed: String) { if let image = UIImage(named: placeholderNamed) { imageWithUrl(url: url, placeholder: image) } else { imageWithUrl(url: url) } } }
7ce61952a5d3e9ca19391c05f702e8d0
33.984375
100
0.61054
false
false
false
false
gcharita/XMLMapper
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import XMLMapper class TableOfContentsSpec: QuickSpec { override func spec() { // describe("these will fail") { // it("can do maths") { // expect(1) == 2 // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } // } } }
b06c09d81eb83c261ed079aa3ec5852e
22.58
62
0.349449
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
refs/heads/master
UberGo/UberGo/SearchController.swift
mit
1
// // SearchController.swift // UberGo // // Created by Nghia Tran on 8/3/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import UberGoCore protocol SearchControllerDelegate: class { func didSelectPlace(_ placeObj: PlaceObj) func shouldUpdateLayoutState(_ newState: MapViewLayoutState) } class SearchController: NSViewController { // MARK: - Variable fileprivate var viewModel: SearchViewModelProtocol! public weak var delegate: SearchControllerDelegate? // MARK: - View fileprivate lazy var collectionView: SearchCollectionView = self.lazyInitSearchCollectionView() fileprivate lazy var searchBarView: SearchBarView = self.lazyInitSearchBarView() // MARK: - Init init?(viewModel: SearchViewModelProtocol) { self.viewModel = viewModel super.init(nibName: "SearchController", bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Cycle override func viewDidLoad() { super.viewDidLoad() initCommon() // Setup searchBarView.setupViewModel(viewModel) collectionView.setupViewModel(viewModel) } public func resetTextSearch() { searchBarView.resetTextSearch() } } // MARK: - Private extension SearchController { fileprivate func initCommon() { view.backgroundColor = NSColor.clear view.translatesAutoresizingMaskIntoConstraints = false } fileprivate func lazyInitSearchBarView() -> SearchBarView { let searchView = SearchBarView.viewFromNib(with: BundleType.app)! searchView.delegate = self view.addSubview(searchView) searchView.configureView(with: view) return searchView } fileprivate func lazyInitSearchCollectionView() -> SearchCollectionView { let collectionView = SearchCollectionView.viewFromNib(with: BundleType.app)! collectionView.delegate = self self.view.addSubview(collectionView) collectionView.configureView(parenView: view, searchBarView: searchBarView) return collectionView } } // MARK: - Layout extension SearchController { public func configureContainerController(_ controller: NSViewController, containerView: NSView) { controller.addChildViewController(self) containerView.addSubview(view) containerView.edges(to: view) } public func updateState(_ state: MapViewLayoutState) { searchBarView.layoutState = state collectionView.layoutStateChanged(state) } } // MARK: - SearchBarViewDelegate extension SearchController: SearchBarViewDelegate { func searchBar(_ sender: SearchBarView, layoutStateDidChanged state: MapViewLayoutState) { delegate?.shouldUpdateLayoutState(state) } } // MARK: - SearchCollectionViewDelegate extension SearchController: SearchCollectionViewDelegate { func searchCollectionViewSearchPersonalPlace(_ placeObj: PlaceObj) { viewModel.input.enableFullSearchModePublisher.onNext(true) delegate?.shouldUpdateLayoutState(.searchFullScreen) } func searchCollectionViewDidSelectPlace(_ placeObj: PlaceObj) { delegate?.didSelectPlace(placeObj) delegate?.shouldUpdateLayoutState(.minimal) } }
b762bd5cc8354a220f00270eeb5e78ac
28.300885
101
0.715494
false
false
false
false
Poligun/NihonngoSwift
refs/heads/master
Nihonngo/FetchWordViewController.swift
mit
1
// // FetchWordViewController.swift // Nihonngo // // Created by ZhaoYuhan on 15/1/10. // Copyright (c) 2015年 ZhaoYuhan. All rights reserved. // import UIKit class FetchWordViewController: BaseViewController, UISearchBarDelegate, UIAlertViewDelegate, UITableViewDataSource, UITableViewDelegate { private var searchBar: UISearchBar! private var tableView: UITableView! private var fetchedWords = [FetchedWord]() private var exists = [Bool]() enum FetchingState { case Normal case Fetching case NoResult } private var pendingSearchText: String? private var fetchingState = FetchingState.Normal private lazy var wordFetcher: WordFetcher = { let fetcher = WordFetcher() return fetcher }() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "在线查询" searchBar = addSearchBar(placeHolder: "输入待查单词或假名") tableView = addTableView(heightStyle: .Dynamic(60.0), cellClasses: FetchedWordCell.self, LoadingCell.self, LabelCell.self) addConstraints("V:|-0-[searchBar]-0-[tableView]-0-|", "H:|-0-[searchBar]-0-|", "H:|-0-[tableView]-0-|") } override func viewWillAppear(animated: Bool) { if let searchText = pendingSearchText { searchBar.text = searchText searchBar.becomeFirstResponder() pendingSearchText = nil } else { searchBar.resignFirstResponder() } for var i = 0; i < fetchedWords.count; i++ { exists[i] = DataStore.sharedInstance.hasWord(fetchedWords[i].word, kana: fetchedWords[i].kana) } tableView.reloadData() } func setSearchText(searchText: String) { pendingSearchText = searchText } // SearchBar Delegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() if fetchingState != .Fetching { fetchingState = .Fetching wordFetcher.fetchWord(searchBar.text, wordHandler: {(words: [FetchedWord]) -> Void in dispatch_async(dispatch_get_main_queue(), { self.fetchedWords = words self.fetchingState = words.count == 0 ? .NoResult : .Normal self.exists.removeAll(keepCapacity: true) for word in words { self.exists.append(DataStore.sharedInstance.hasWord(word.word, kana: word.kana)) } self.tableView.reloadData() }) }) tableView.reloadData() } } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = "" searchBar.resignFirstResponder() } // TableView DataSource & Delegate func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch fetchingState { case .Normal: return fetchedWords.count case .Fetching: return 1 case .NoResult: return 1 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch fetchingState { case .Normal: let cell = tableView.dequeueReusableCellWithIdentifier(FetchedWordCell.defaultReuseIdentifier, forIndexPath: indexPath) as FetchedWordCell cell.setFetchedWord(fetchedWords[indexPath.row]) cell.setState(exists[indexPath.row] ? "单词已存在" : "") return cell case .Fetching: let cell = tableView.dequeueReusableCellWithIdentifier(LoadingCell.defaultReuseIdentifier, forIndexPath: indexPath) as LoadingCell cell.setLoadingText("在线查询中", animating: true) return cell case .NoResult: let cell = tableView.dequeueReusableCellWithIdentifier(LabelCell.defaultReuseIdentifier, forIndexPath: indexPath) as LabelCell cell.setLabelText("未找到相关的词条", textAlignment: .Center) return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if fetchingState == .Normal { let alertView = UIAlertView(title: "确认添加单词(\(fetchedWords[indexPath.row].word))吗", message: "单词将被加入离线词库", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确认") alertView.tag = indexPath.row alertView.show() } } // AlertView Delegate func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex == 1 { let wordViewController = WordViewController() wordViewController.word = DataStore.sharedInstance.addWordFromFetched(fetchedWords[alertView.tag]) DataStore.sharedInstance.saveContext() DataStore.sharedInstance.updateAllWords() searchBar.text = "" searchBar.resignFirstResponder() navigationController?.pushViewController(wordViewController, animated: true) } } }
9b4ea960fd2418226c0859fcd5264e10
34.414966
150
0.625816
false
false
false
false
Pretz/SwiftGraphics
refs/heads/develop
SwiftGraphics/BezierCurve/BezierCurveChain.swift
bsd-2-clause
3
// // BezierCurveChain.swift // SwiftGraphics // // Created by Jonathan Wight on 1/16/15. // Copyright (c) 2015 schwa.io. All rights reserved. // import CoreGraphics public struct BezierCurveChain { // TODO: This isn't really an accurate representaiton of what we want. // TODO: Control points should be shared (and mirrored) between neighbouring curves. public let curves: [BezierCurve] public init(curves: [BezierCurve]) { var previousCurve: BezierCurve? self.curves = curves.map() { (curve: BezierCurve) -> BezierCurve in var newCurve = curve if let previousEndPoint = previousCurve?.end, let start = curve.start { assert(previousEndPoint == start) newCurve = BezierCurve(controls: curve.controls, end: curve.end) } previousCurve = curve return newCurve } } } extension BezierCurveChain: CustomStringConvertible { public var description: String { return curves.map({ $0.description }).joinWithSeparator(", ") } } extension BezierCurveChain: Drawable { public func drawInContext(context: CGContextRef) { // Stroke all curves as a single path let start = curves[0].start CGContextMoveToPoint(context, start!.x, start!.y) for curve in curves { context.addToPath(curve) } CGContextStrokePath(context) } } // TODO: Transformable protocol? public func * (lhs: BezierCurveChain, rhs: CGAffineTransform) -> BezierCurveChain { let transformedCurves = lhs.curves.map() { return $0 * rhs } return BezierCurveChain(curves: transformedCurves) }
d34fd2989ae16d1cde0b16f9be3e673a
25.65625
88
0.643025
false
false
false
false
blstream/AugmentedSzczecin_iOS
refs/heads/master
AugmentedSzczecin/AugmentedSzczecin/ASCategoryPickerViewController.swift
apache-2.0
1
// // ASCategoryPickerViewController.swift // AugmentedSzczecin // // Created by Grzegorz Pawlowicz on 03.06.2015. // Copyright (c) 2015 BLStream. All rights reserved. // import UIKit class ASCategoryPickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var doneBarButtonItem: UIBarButtonItem! @IBOutlet weak var categoryPickerView: UIPickerView! var categoryPickerDataSource = [String]() var selectedCategory: String! var changeBlock:((text: String) -> ())? override func viewDidLoad() { super.viewDidLoad() categoryPickerDataSource = ["SCHOOL", "HOSPITAL", "PARK", "MONUMENT", "MUSEUM", "OFFICE", "BUS_STATION", "TRAIN_STATION", "POST_OFFICE", "CHURCH"] categoryPickerView.delegate = self categoryPickerView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func doneBarButtonItemTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } // MARK: - UIPickerView func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return categoryPickerDataSource.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return categoryPickerDataSource[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedCategory = categoryPickerDataSource[row] self.changeBlock?(text: selectedCategory) } /* // 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. } */ }
7bfebdcd903a3d679ab4a5bfdf1a40f1
32.373134
154
0.686494
false
false
false
false
JorritO/Zeeguu-API-iOS
refs/heads/master
ZeeguuAPI/ZeeguuAPI/Feed.swift
mit
2
// // Feed.swift // ZeeguuAPI // // Created by Jorrit Oosterhof on 18-01-16. // Copyright © 2015 Jorrit Oosterhof. // // 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 /// Adds support for comparing `Feed` objects using the equals operator (`==`) /// /// - parameter lhs: The left `Feed` operand of the `==` operator (left hand side) <pre><b>lhs</b> == rhs</pre> /// - parameter rhs: The right `Feed` operand of the `==` operator (right hand side) <pre>lhs == <b>rhs</b></pre> /// - returns: A `Bool` that states whether the two `Feed` objects are equal public func ==(lhs: Feed, rhs: Feed) -> Bool { return lhs.title == rhs.title && lhs.url == rhs.url && lhs.feedDescription == rhs.feedDescription && lhs.language == rhs.language && lhs.imageURL == rhs.imageURL } /// The `Feed` class represents an RSS feed. It holds the `id`, `title`, `url`, `feedDescription`, `language` and more about the feed. public class Feed: CustomStringConvertible, Equatable, ZGSerializable { // MARK: Properties - /// The id of this feed public var id: String? /// The title of this feed public var title: String /// The url of this feed public var url: String /// The description of this feed public var feedDescription: String /// The language of this feed public var language: String private var imageURL: String private var image: UIImage? /// The description of this `Feed` object. The value of this property will be used whenever the system tries to print this `Feed` object or when the system tries to convert this `Feed` object to a `String`. public var description: String { return "Feed: {\n\tid: \"\(id)\",\n\ttitle: \"\(title)\",\n\turl: \"\(url)\",\n\tdescription: \"\(feedDescription)\",\n\tlanguage: \"\(language)\",\n\timageURL: \"\(imageURL)\"\n}" } // MARK: Constructors - /** Construct a new `Feed` object. - parameter id: The id of this feed - parameter title: The title of the feed - parameter url: The url of the feed - parameter description: The description of the feed - parameter language: The language of the feed - parameter imageURL: The url for the image of the feed */ public init(id: String? = nil, title: String, url: String, description: String, language: String, imageURL: String) { self.id = id self.title = title self.url = url self.feedDescription = description self.language = language self.imageURL = imageURL } /** Construct a new `Feed` object from the data in the dictionary. - parameter dictionary: The dictionary that contains the data from which to construct an `Feed` object. */ @objc public required init?(dictionary dict: [String : AnyObject]) { guard let title = dict["title"] as? String, url = dict["url"] as? String, feedDescription = dict["feedDescription"] as? String, language = dict["language"] as? String, imageURL = dict["imageURL"] as? String else { return nil } self.id = dict["id"] as? String self.title = title self.url = url self.feedDescription = feedDescription self.language = language self.imageURL = imageURL self.image = dict["image"] as? UIImage } // MARK: Methods - /** The dictionary representation of this `Feed` object. - returns: A dictionary that contains all data of this `Feed` object. */ @objc public func dictionaryRepresentation() -> [String: AnyObject] { var dict = [String: AnyObject]() dict["id"] = self.id dict["title"] = self.title dict["url"] = self.url dict["feedDescription"] = self.feedDescription dict["language"] = self.language dict["imageURL"] = self.imageURL dict["image"] = self.image return dict } /** Get the image of this feed. This method will make sure that the image url is cached within this `Feed` object, so calling this method again will not retrieve the image again, but will return the cached version instead. - parameter completion: A closure that will be called once the image has been retrieved. If there was no image to retrieve, `image` is `nil`. Otherwise, it contains the feed image. */ public func getImage(completion: (image: UIImage?) -> Void) { if let imURL = NSURL(string: self.imageURL) { let request = NSMutableURLRequest(URL: imURL) ZeeguuAPI.sharedAPI().sendAsynchronousRequestWithDataResponse(request) { (data, error) -> Void in if let res = data { completion(image: UIImage(data: res)) } else { if ZeeguuAPI.sharedAPI().enableDebugOutput { print("Could not get image with url '\(self.imageURL)', error: \(error)") } completion(image: nil) } } } else { completion(image: nil) } } }
b54e1802a271f731f0f9a52cbcb634a6
37.664384
219
0.699026
false
false
false
false
wess/Appendix
refs/heads/master
Sources/shared/URLRequest+Appendix.swift
mit
1
// // URLRequest+Appendix.swift // Appendix // // Created by Wess Cope on 1/25/19. // import Foundation extension URLRequest { public enum Method:String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } init(_ urlString:String, method:URLRequest.Method = .get) { self.init(url: URL(string: urlString)!) self.httpMethod = method.rawValue } }
86ad25124af0b8fecd622acaf071805b
18.551724
61
0.594356
false
false
false
false
onurersel/anim
refs/heads/master
examples/message/view controllers/MessageListViewController.swift
mit
1
// // MessageListViewController.swift // anim // // Created by Onur Ersel on 2017-03-14. // Copyright (c) 2017 Onur Ersel. All rights reserved. import UIKit import anim // MARK: - View Controller class MessageListViewController: UIViewController { fileprivate var scrollView: BubbleScrollView! private(set) var bubbleTransitionFrame: CGRect? private var animatingBubble: ConversationBubble? // MARK: View Controller Overrides override func viewDidLoad() { self.view.backgroundColor = UIColor.white self.automaticallyAdjustsScrollViewInsets = false scrollView = BubbleScrollView.create() self.view.addSubview(scrollView) scrollView.size(withMainView: self.view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addListeners() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removeListeners() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) animatingBubble?.restoreAnimateDown() animatingBubble = nil } // MARK: Listeners private func addListeners() { NotificationCenter.default.addObserver(self, selector: #selector(self.navigateToConversationHandler), name: AnimEvent.navigateToConversation, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.navigateToProfileHandler), name: AnimEvent.navigateToProfile, object: nil) } private func removeListeners() { NotificationCenter.default.removeObserver(self) } @objc func navigateToConversationHandler(notification: Notification) { guard animatingBubble == nil else { return } guard let bubble = notification.object as? ConversationBubble else { return } bubbleTransitionFrame = scrollView.bubbleContainer.convert(bubble.frame, to: self.view) animatingBubble = bubble bubble.animateDown { self.navigationController?.pushViewController(MessageDialogueViewController(), animated: true) } } @objc func navigateToProfileHandler(notification: Notification) { self.navigationController?.pushViewController(ProfileListViewController(), animated: true) self.navigationController?.viewControllers.remove(at: 0) } } // MARK: - View Controller Transition Animations extension MessageListViewController: AnimatedViewController { var estimatedInAnimationDuration: TimeInterval { return 0.5 } var estimatedOutAnimationDuration: TimeInterval { return 0.6 } func animateIn(_ completion: @escaping ()->Void) { NotificationCenter.default.post(name: AnimEvent.menuShow, object: nil) anim { (settings) -> (animClosure) in settings.duration = 0.6 settings.ease = .easeInQuint return { NavigationBarController.shared.hide() } } self.scrollView.animateIn() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(Int(estimatedInAnimationDuration*1000))) { completion() } } func animateOut(_ completion: @escaping ()->Void) { self.scrollView.animateOut() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(Int(estimatedOutAnimationDuration*1000))) { completion() } } func prepareForAnimateIn() { self.scrollView.prepareAnimateIn() } func prepareForAnimateOut() {} } // MARK: - Bubble Scroll View class BubbleScrollView: UIScrollView, UIScrollViewDelegate { static fileprivate let bubbleCount = 13 static fileprivate let inAnimationDelayBetweenBubbles = 0.08 static fileprivate let outAnimationDelayBetweenBubbles = 0.04 private(set) var bubbleContainer: UIView! private var previousOffset: CGPoint? private var velocity: CGPoint = CGPoint.zero private var bubbles: [ConversationBubble]? var bubblesInScreen: [ConversationBubble] { guard let bubbles = bubbles else { return [ConversationBubble]() } var array = [ConversationBubble]() for bubble in bubbles { if !(bubble.frame.origin.y+bubble.frame.size.height < contentOffset.y || bubble.frame.origin.y > contentOffset.y+frame.size.height) { array.append(bubble) } } return array } class func create() -> BubbleScrollView { let view = BubbleScrollView() view.delegate = view view.bounces = false view.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0) view.bubbleContainer = UIView() view.bubbleContainer.translatesAutoresizingMaskIntoConstraints = false view.addSubview(view.bubbleContainer) view.bubbles = [ConversationBubble]() var lastBubble: ConversationBubble? = nil for _ in 0..<bubbleCount { let bubble = ConversationBubble.create() bubble.position(on: view.bubbleContainer, under: lastBubble) bubble.animateFloating() view.bubbles?.append(bubble) lastBubble = bubble } return view } func size(withMainView mainView: UIView) { self.snapEdges(to: mainView) guard let lastBubble = bubbles?.last else { return } mainView.addConstraints([ NSLayoutConstraint(item: bubbleContainer, attribute: .width, relatedBy: .equal, toItem: mainView, attribute: .width, multiplier: 1, constant: 0) ]) self.addConstraints([ NSLayoutConstraint(item: bubbleContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: bubbleContainer, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: bubbleContainer, attribute: .bottom, relatedBy: .equal, toItem: lastBubble, attribute: .bottom, multiplier: 1, constant: 0) ]) } // MARK: View Overrides override func layoutSubviews() { super.layoutSubviews() guard let containerFrame = subviews.first?.frame else { return } contentSize = containerFrame.size } // MARK: Scroll View Delegates func scrollViewDidScroll(_ scrollView: UIScrollView) { defer { previousOffset = contentOffset } guard let previousOffset = previousOffset else { return } if contentOffset.y <= 0 || contentOffset.y + scrollView.frame.size.height - contentInset.bottom >= contentSize.height { NotificationCenter.default.post(name: AnimEvent.conversationScroll, object: nil, userInfo: ["velocity": velocity]) } let currentVelocity = contentOffset - previousOffset velocity = CGPoint.lerp(current: velocity, target: currentVelocity, t: 0.5) } // MARK: Position / Animate func prepareAnimateIn() { bubbles?.forEach { (bubble) in bubble.prepareAnimateIn() } } func animateIn() { guard let bubbles = bubbles else { return } for (index, bubble) in bubbles.enumerated() { bubble.animateIn(delay: Double(index) * BubbleScrollView.inAnimationDelayBetweenBubbles) } } func animateOut() { let bubblesReverseEnumerated = bubblesInScreen.reversed().enumerated() for (index, bubble) in bubblesReverseEnumerated { bubble.animateOut(delay: Double(index) * BubbleScrollView.outAnimationDelayBetweenBubbles) } } } // MARK: - Conversation Bubble class ConversationBubble: UIButton { static fileprivate let outAnimationDuration: TimeInterval = 0.35 static fileprivate let inAnimationDuration: TimeInterval = 1 private(set) var positionConstraints: BubbleConstraints! private(set) var floatingContainer: UIView! private var animation: anim? class func create() -> ConversationBubble { let view = ConversationBubble() view.floatingContainer = UIView() view.addSubview(view.floatingContainer) view.floatingContainer.backgroundColor = Color.lightGray view.floatingContainer.isUserInteractionEnabled = false view.positionConstraints = BubbleConstraints(for: view) view.backgroundColor = UIColor.clear view.addTarget(view, action: #selector(self.tapAction), for: .touchUpInside) NotificationCenter.default.addObserver(view, selector: #selector(self.scrollHandler), name: AnimEvent.conversationScroll, object: nil) return view } func position(on parent: UIView, under: ConversationBubble? = nil) { positionConstraints.place(at: parent, under: under) } // MARK: View Overrides override func layoutSubviews() { super.layoutSubviews() positionConstraints.updateCornerRadius() } // MARK: Floating Animation func animateFloating() { self.floatToNewPosition() } private func floatToNewPosition() { guard let parent = positionConstraints.parent else { return } let randomPosition = CGFloat(10).randomPointWithRadius let randomDuration = DoubleRange(min: 1.2, max: 3.3).random let randomDelay = DoubleRange(min: 0, max: 0.2).random animation = anim(constraintParent: parent) { (settings) -> animClosure in settings.ease = .easeInOutSine settings.duration = randomDuration settings.delay = randomDelay settings.isUserInteractionsEnabled = true settings.completion = self.floatToNewPosition return { self.positionConstraints.positionFloatingContainer(x: randomPosition.x, y: randomPosition.y) } } } // MARK: Position / Animate (Shared) func stopAnimation() { animation?.stop() animation = nil } // MARK: Bounce On Edge Animation private func bounceOnEndScroll(withVelocity velocity: CGFloat) { guard let parent = positionConstraints.parent else { return } stopAnimation() let initialDuration = DoubleRange(min: 0.18, max: 0.28).random let initialHorizontalDrift = DoubleRange(min: -0.4, max: 0.4).random.cgFloat let initialVelocityMultiplier = DoubleRange(min: 2.1, max: 2.9).random.cgFloat animation = anim(constraintParent: parent) { (settings) -> animClosure in settings.ease = .easeOutQuad settings.duration = initialDuration settings.isUserInteractionsEnabled = true return { self.positionConstraints.positionFloatingContainer(x: velocity*initialHorizontalDrift, y: -velocity*initialVelocityMultiplier) } } .then(constraintParent: parent, { (settings) -> animClosure in settings.ease = .easeInOutQuad settings.duration = 0.4 settings.isUserInteractionsEnabled = true return { self.positionConstraints.positionFloatingContainer(x: 0, y: velocity*0.3) } }) .then(constraintParent: parent, { (settings) -> animClosure in settings.ease = .easeInOutSine settings.duration = 0.5 settings.isUserInteractionsEnabled = true return { self.positionConstraints.positionFloatingContainer(x: 0, y: 0) } }) .callback { self.animateFloating() } } // MARK: In Animation func prepareAnimateIn() { stopAnimation() self.positionConstraints.positionFloatingContainer(x: 0, y: 200) self.alpha = 0 } func animateIn(delay: TimeInterval) { guard let parent = positionConstraints.parent else { return } anim { (settings) -> (animClosure) in settings.duration = 0.4 settings.delay = delay return { self.alpha = 1 } } anim(constraintParent: parent) { (settings) -> animClosure in settings.duration = ConversationBubble.inAnimationDuration * 0.5 settings.ease = .easeOutQuint settings.delay = delay return { self.positionConstraints.positionFloatingContainer(x: 0, y: -10) } } .then(constraintParent: parent, { (settings) -> animClosure in settings.duration = ConversationBubble.inAnimationDuration * 0.5 settings.ease = .easeInOutQuad return { self.positionConstraints.positionFloatingContainer(x: 0, y: 0) } }) .callback { self.animateFloating() } } // MARK: Out Animation func animateOut(delay: TimeInterval) { guard let parent = positionConstraints.parent else { return } stopAnimation() anim { (settings) -> (animClosure) in settings.duration = ConversationBubble.outAnimationDuration settings.ease = .easeInQuint settings.delay = delay return { self.alpha = 0 } } anim(constraintParent: parent) { (settings) -> animClosure in settings.duration = ConversationBubble.outAnimationDuration settings.ease = .easeInQuint settings.delay = delay return { self.positionConstraints.positionFloatingContainer(x: 0, y: 200) } } } // MARK: Down Animation func animateDown(_ completion: @escaping ()->Void) { anim { (settings) -> (animClosure) in settings.duration = 0.15 settings.ease = .easeOutQuint return { self.transform = CGAffineTransform.identity.scaledBy(x: 0.93, y: 0.93) self.floatingContainer.backgroundColor = Color.midGray } } .callback { completion() } } func restoreAnimateDown() { self.transform = CGAffineTransform.identity self.floatingContainer.backgroundColor = Color.lightGray } // MARK: Actions / Handlers @objc func tapAction() { NotificationCenter.default.post(name: AnimEvent.navigateToConversation, object: self) } @objc func scrollHandler(notification: Notification) { guard let velocity = notification.userInfo?["velocity"] as? CGPoint else { return } let limit: CGFloat = 28 let velocityY = max(min(velocity.y, limit), -limit) bounceOnEndScroll(withVelocity: velocityY) } deinit { NotificationCenter.default.removeObserver(self) removeTarget(self, action: #selector(self.tapAction), for: .touchUpInside) } }
fc63d697bd307abac339bb7f1313c413
30.524752
162
0.609108
false
false
false
false
zcrome/taxi-app-client-end-point
refs/heads/master
taxi-app-client-end-point/taxi-app-client-end-point/Controllers/Register/RegisterViewController.swift
mit
1
// // RegisterViewController.swift // taxi-app-client-end-point // // Created by zcrome on 10/14/17. // Copyright © 2017 zcrome. All rights reserved. // import UIKit class RegisterViewController: UIViewController { //************************************** //**** MARK: - Constraints outlets //************************************** //************************************** //**** MARK: - View outlets //************************************** @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! //************************************** //**** MARK: - Local constans and variables //************************************** //************************************** //**** MARK: - ViewController override definitions //************************************** override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } //************************************** //**** MARK: - Actions and other outlets remaining //************************************** @IBAction func executeRegister(_ sender: UIButton) { guard let name = nameTextField.text, let lastName = lastNameTextField.text, let phone = phoneTextField.text, let email = emailTextField.text, let password = passwordTextField.text else{ print("error con textfield") return } let parameters = ["name": name, "lastName": lastName, "phone": phone, "email": email, "password": password, "state": "normal"] Services.sharedInstance.executeRegistrationOf(Client: parameters) { (response) in if response.status, let _ = response.clientId{ self.performSegue(withIdentifier: "toLoginAfterRegister", sender: self) }else{ print("ERROR register") } } } //************************************** //**** MARK: - Additional functions that may be require //************************************** }
a965f70e8d81e39dfcd80903deaaa1bc
26.358696
85
0.501391
false
false
false
false
iAugux/iBBS-Swift
refs/heads/master
iBBS/loadmore/RefreshFooterView.swift
mit
1
// // File.swift // RefreshExample // // Created by SunSet on 14-6-23. // Copyright (c) 2014 zhaokaiyuan. All rights reserved. // import UIKit class RefreshFooterView: RefreshBaseView { class func footer()->RefreshFooterView{ let footer:RefreshFooterView = RefreshFooterView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, CGFloat(RefreshViewHeight))) return footer } var lastRefreshCount:Int = 0 override func willMoveToSuperview(newSuperview: UIView!) { super.willMoveToSuperview(newSuperview) if (self.superview != nil){ self.superview!.removeObserver(self, forKeyPath: RefreshContentSize as String,context:nil) } if (newSuperview != nil) { newSuperview.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil) // 重新调整frame adjustFrameWithContentSize() } } //重写调整frame func adjustFrameWithContentSize(){ let contentHeight:CGFloat = self.scrollView.contentSize.height// let scrollHeight:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom var rect:CGRect = self.frame; rect.origin.y = contentHeight > scrollHeight ? contentHeight : scrollHeight self.frame = rect; } //监听UIScrollView的属性 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (!self.userInteractionEnabled || self.hidden){ return } if RefreshContentSize.isEqualToString(keyPath!){ adjustFrameWithContentSize() }else if RefreshContentOffset.isEqualToString(keyPath!) { if self.State == RefreshState.Refreshing{ return } adjustStateWithContentOffset() } } func adjustStateWithContentOffset() { let currentOffsetY:CGFloat = self.scrollView.contentOffset.y let happenOffsetY:CGFloat = self.happenOffsetY() if currentOffsetY <= happenOffsetY { return } if self.scrollView.dragging { let normal2pullingOffsetY = happenOffsetY + self.frame.size.height if self.State == RefreshState.Normal && currentOffsetY > normal2pullingOffsetY { self.State = RefreshState.Pulling; } else if (self.State == RefreshState.Pulling && currentOffsetY <= normal2pullingOffsetY) { self.State = RefreshState.Normal; } } else if (self.State == RefreshState.Pulling) { self.State = RefreshState.Refreshing } } override var State:RefreshState { willSet { if State == newValue{ return; } oldState = State setState(newValue) } didSet{ switch State{ case .Normal: if (RefreshState.Refreshing == oldState) { self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: { self.scrollView.contentInset.bottom = self.scrollViewOriginalInset.bottom }) } else { UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: { self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)); }) } let deltaH:CGFloat = self.heightForContentBreakView() let currentCount:Int = self.totalDataCountInScrollView() if (RefreshState.Refreshing == oldState && deltaH > 0 && currentCount != self.lastRefreshCount) { var offset:CGPoint = self.scrollView.contentOffset; offset.y = self.scrollView.contentOffset.y self.scrollView.contentOffset = offset; } break case .Pulling: UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: { self.arrowImage.transform = CGAffineTransformIdentity }) break case .Refreshing: self.lastRefreshCount = self.totalDataCountInScrollView(); UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: { var bottom:CGFloat = self.frame.size.height + self.scrollViewOriginalInset.bottom let deltaH:CGFloat = self.heightForContentBreakView() if deltaH < 0 { bottom = bottom - deltaH } var inset:UIEdgeInsets = self.scrollView.contentInset; inset.bottom = bottom; self.scrollView.contentInset = inset; }) break default: break } } } func totalDataCountInScrollView()->Int { var totalCount:Int = 0 if self.scrollView is UITableView { let tableView:UITableView = self.scrollView as! UITableView for i in 0 ..< tableView.numberOfSections { totalCount = totalCount + tableView.numberOfRowsInSection(i) } } else if self.scrollView is UICollectionView{ let collectionView:UICollectionView = self.scrollView as! UICollectionView for i in 0 ..< collectionView.numberOfSections() { totalCount = totalCount + collectionView.numberOfItemsInSection(i) } } return totalCount } func heightForContentBreakView()->CGFloat { let h:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; return self.scrollView.contentSize.height - h; } func happenOffsetY()->CGFloat { let deltaH:CGFloat = self.heightForContentBreakView() if deltaH > 0 { return deltaH - self.scrollViewOriginalInset.top; } else { return -self.scrollViewOriginalInset.top; } } func addState(state:RefreshState){ self.State = state } }
af095eed3b9cb03b3d3521e60290c623
36.556818
157
0.583296
false
false
false
false
mathiasquintero/Sweeft
refs/heads/master
Example/Sweeft/Movie.swift
mit
1
// // Movie.swift // Sweeft // // Created by Mathias Quintero on 12/26/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Sweeft final class Movie: Observable { let title: String let vote: Double let id: Int let overview: String let date: Date var poster: UIImage? var listeners = [Listener]() init(title: String, vote: Double, id: Int, overview: String, date: Date, poster: UIImage? = nil) { self.title = title self.vote = vote self.id = id self.overview = overview self.date = date self.poster = poster } func fetchImage(with path: String) { MovieImageAPI.fetchImage(with: path).onSuccess { image in self.poster = image self.hasChanged() } } /// Says whether or not a movie was released close enough to the date for it to be relevant. func isRelevant(for date: Date) -> Bool { return abs((date - self.date).weeks) <= 12 } } extension Movie: ValueComparable { var comparable: Double { return vote } } extension Movie: Hashable { var hashValue: Int { return id } } func ==(_ lhs: Movie, _ rhs: Movie) -> Bool { return lhs.id == rhs.id } extension Movie: Deserializable { convenience init?(from json: JSON) { guard let title = json["title"].string, let vote = json["vote_average"].double, let overview = json["overview"].string, let id = json["id"].int, let date = json["release_date"].date(using: "yyyy-MM-dd") else { return nil } self.init(title: title, vote: vote, id: id, overview: overview, date: date) json["poster_path"].string | fetchImage } } extension Movie { static func movie(with id: Int, using api: MoviesAPI = .shared) -> Movie.Result { return get(using: api, at: .movie, arguments: ["id": id]) } static func movies(with ids: [Int], using api: MoviesAPI = .shared) -> Movie.Results { return api.doBulkObjectRequest(to: .movie, arguments: ids => { ["id": $0] }) } static func featured(using api: MoviesAPI = .shared) -> Movie.Results { return api.doFlatBulkObjectRequest(to: [.nowPlaying, .upcoming, .popular], at: ["results"]) .map { $0 |> { $0.vote >= 5.0 } } .map { $0 |> Movie.isRelevant ** .now } .map { $0.noDuplicates } } } extension Movie { func getRoles(using api: MoviesAPI = .shared) -> Role.Results { return Role.getAll(using: api, at: .credits, arguments: ["id": id], for: "cast") } func getSimilar(using api: MoviesAPI = .shared) -> Movie.Results { return Movie.getAll(using: api, at: .similar, arguments: ["id": id], for: "results") } }
9322d7657d242510e22cb9386095a9ab
25.477876
102
0.55381
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionData/Core/Network/Clients/APIClient.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import Errors import FeatureTransactionDomain import MoneyKit import NetworkKit import PlatformKit import ToolKit typealias FeatureTransactionDomainClientAPI = CustodialQuoteAPI & OrderCreationClientAPI & AvailablePairsClientAPI & TransactionLimitsClientAPI & OrderFetchingClientAPI & OrderUpdateClientAPI & CustodialTransferClientAPI & BitPayClientAPI & BlockchainNameResolutionClientAPI & BankTransferClientAPI & WithdrawalLocksCheckClientAPI /// FeatureTransactionDomain network client final class APIClient: FeatureTransactionDomainClientAPI { fileprivate enum Parameter { static let minor = "minor" static let currency = "currency" static let inputCurrency = "inputCurrency" static let fromAccount = "fromAccount" static let outputCurrency = "outputCurrency" static let toAccount = "toAccount" static let product = "product" static let paymentMethod = "paymentMethod" static let orderDirection = "orderDirection" static let payment = "payment" static let simpleBuy = "SIMPLEBUY" static let swap = "SWAP" static let sell = "SELL" static let `default` = "DEFAULT" } private enum Path { static let quote = ["custodial", "quote"] static let createOrder = ["custodial", "trades"] static let availablePairs = ["custodial", "trades", "pairs"] static let fetchOrder = createOrder static let limits = ["trades", "limits"] static let crossBorderLimits = ["limits", "crossborder", "transaction"] static let transfer = ["payments", "withdrawals"] static let bankTransfer = ["payments", "banktransfer"] static let transferFees = ["payments", "withdrawals", "fees"] static let domainResolution = ["explorer-gateway", "resolution", "resolve"] static let reverseResolution = ["explorer-gateway", "resolution", "reverse"] static let withdrawalLocksCheck = ["payments", "withdrawals", "locks", "check"] static func updateOrder(transactionID: String) -> [String] { createOrder + [transactionID] } } private enum BitPay { static let url: String = "https://bitpay.com/" enum Paramter { static let invoice: String = "i/" } } private let retailNetworkAdapter: NetworkAdapterAPI private let retailRequestBuilder: RequestBuilder private let defaultNetworkAdapter: NetworkAdapterAPI private let defaultRequestBuilder: RequestBuilder init( retailNetworkAdapter: NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail), retailRequestBuilder: RequestBuilder = DIKit.resolve(tag: DIKitContext.retail), defaultNetworkAdapter: NetworkAdapterAPI = DIKit.resolve(), defaultRequestBuilder: RequestBuilder = DIKit.resolve() ) { self.retailNetworkAdapter = retailNetworkAdapter self.retailRequestBuilder = retailRequestBuilder self.defaultNetworkAdapter = defaultNetworkAdapter self.defaultRequestBuilder = defaultRequestBuilder } } // MARK: - AvailablePairsClientAPI extension APIClient { var availableOrderPairs: AnyPublisher<AvailableTradingPairsResponse, NabuNetworkError> { let request = retailRequestBuilder.get( path: Path.availablePairs, authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - CustodialQuoteAPI extension APIClient { func fetchQuoteResponse( with request: OrderQuoteRequest ) -> AnyPublisher<OrderQuoteResponse, NabuNetworkError> { let request = retailRequestBuilder.post( path: Path.quote, body: try? request.encode(), authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - OrderCreationClientAPI extension APIClient { func create( direction: OrderDirection, quoteIdentifier: String, volume: MoneyValue, destinationAddress: String?, refundAddress: String? ) -> AnyPublisher<SwapActivityItemEvent, NabuNetworkError> { create( direction: direction, quoteIdentifier: quoteIdentifier, volume: volume, destinationAddress: destinationAddress, refundAddress: refundAddress, ccy: nil ) } func create( direction: OrderDirection, quoteIdentifier: String, volume: MoneyValue, ccy: String? ) -> AnyPublisher<SwapActivityItemEvent, NabuNetworkError> { create( direction: direction, quoteIdentifier: quoteIdentifier, volume: volume, destinationAddress: nil, refundAddress: nil, ccy: ccy ) } private func create( direction: OrderDirection, quoteIdentifier: String, volume: MoneyValue, destinationAddress: String?, refundAddress: String?, ccy: String? ) -> AnyPublisher<SwapActivityItemEvent, NabuNetworkError> { let body = OrderCreationRequest( direction: direction, quoteId: quoteIdentifier, volume: volume, destinationAddress: destinationAddress, refundAddress: refundAddress, ccy: ccy ) let request = retailRequestBuilder.post( path: Path.createOrder, body: try? body.encode(), authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - OrderUpdateClientAPI extension APIClient { func updateOrder( with transactionId: String, success: Bool ) -> AnyPublisher<Void, NabuNetworkError> { let payload = OrderUpdateRequest(success: success) let request = retailRequestBuilder.post( path: Path.updateOrder(transactionID: transactionId), body: try? payload.encode(), authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - OrderFetchingClientAPI extension APIClient { func fetchTransaction( with transactionId: String ) -> AnyPublisher<SwapActivityItemEvent, NabuNetworkError> { let request = retailRequestBuilder.get( path: Path.fetchOrder + [transactionId], authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - CustodialTransferClientAPI extension APIClient { func send( transferRequest: CustodialTransferRequest ) -> AnyPublisher<CustodialTransferResponse, NabuNetworkError> { let headers = [HttpHeaderField.blockchainOrigin: HttpHeaderValue.simpleBuy] let request = retailRequestBuilder.post( path: Path.transfer, body: try? transferRequest.encode(), headers: headers, authenticated: true )! return retailNetworkAdapter.perform(request: request) } func custodialTransferFeesForProduct( _ product: Product ) -> AnyPublisher<CustodialTransferFeesResponse, NabuNetworkError> { let parameters: [URLQueryItem] = [ URLQueryItem(name: Parameter.product, value: product.rawValue), URLQueryItem(name: Parameter.paymentMethod, value: Parameter.default) ] let request = retailRequestBuilder.get( path: Path.transferFees, parameters: parameters, authenticated: false )! return retailNetworkAdapter.perform(request: request) } func custodialTransferFees() -> AnyPublisher<CustodialTransferFeesResponse, NabuNetworkError> { let headers = [HttpHeaderField.blockchainOrigin: HttpHeaderValue.simpleBuy] let parameters: [URLQueryItem] = [ URLQueryItem(name: Parameter.product, value: Parameter.simpleBuy), URLQueryItem(name: Parameter.paymentMethod, value: Parameter.default) ] let request = retailRequestBuilder.get( path: Path.transferFees, parameters: parameters, headers: headers, authenticated: false )! return retailNetworkAdapter.perform(request: request) } } // MARK: - BankTransferClientAPI extension APIClient { func startBankTransfer( id: String, amount: MoneyValue ) -> AnyPublisher<BankTranferPaymentResponse, NabuNetworkError> { let model = BankTransferPaymentRequest( amountMinor: amount.minorString, currency: amount.code, attributes: nil ) let request = retailRequestBuilder.post( path: Path.bankTransfer + [id] + [Parameter.payment], body: try? model.encode(), authenticated: true )! return retailNetworkAdapter.perform(request: request) } func createWithdrawOrder(id: String, amount: MoneyValue) -> AnyPublisher<Void, NabuNetworkError> { let headers = [HttpHeaderField.blockchainOrigin: HttpHeaderValue.simpleBuy] let body = WithdrawRequestBody( beneficiary: id, currency: amount.code, amount: amount.minorString ) let request = retailRequestBuilder.post( path: Path.transfer, body: try? body.encode(), headers: headers, authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - BitPayClientAPI extension APIClient { func bitpayPaymentRequest( invoiceId: String, currency: CryptoCurrency ) -> AnyPublisher<BitpayPaymentRequestResponse, NetworkError> { let payload = ["chain": currency.code] let headers = [ HttpHeaderField.xPayProVersion: HttpHeaderValue.xPayProVersion, HttpHeaderField.contentType: HttpHeaderValue.bitpayPaymentRequest, HttpHeaderField.bitpayPartner: HttpHeaderValue.bitpayPartnerName, HttpHeaderField.bitpayPartnerVersion: HttpHeaderValue.bitpayPartnerVersion ] let url = URL(string: BitPay.url + BitPay.Paramter.invoice + invoiceId)! let request = NetworkRequest( endpoint: url, method: .post, body: try? JSONEncoder().encode(payload), headers: headers ) return retailNetworkAdapter.perform(request: request) } func verifySignedTransaction( invoiceId: String, currency: CryptoCurrency, transactionHex: String, transactionSize: Int ) -> AnyPublisher<Void, NetworkError> { let transaction = BitPayPaymentRequest.Transaction( tx: transactionHex, weightedSize: transactionSize ) let payload = BitPayPaymentRequest( chain: currency.code, transactions: [transaction] ) let headers = [ HttpHeaderField.xPayProVersion: HttpHeaderValue.xPayProVersion, HttpHeaderField.contentType: HttpHeaderValue.bitpayPaymentVerification, HttpHeaderField.bitpayPartner: HttpHeaderValue.bitpayPartnerName, HttpHeaderField.bitpayPartnerVersion: HttpHeaderValue.bitpayPartnerVersion ] let url = URL(string: BitPay.url + BitPay.Paramter.invoice + invoiceId)! let request = NetworkRequest( endpoint: url, method: .post, body: try? JSONEncoder().encode(payload), headers: headers ) return retailNetworkAdapter.perform(request: request) } func postPayment( invoiceId: String, currency: CryptoCurrency, transactionHex: String, transactionSize: Int ) -> AnyPublisher<BitPayMemoResponse, NetworkError> { let transaction = BitPayPaymentRequest.Transaction( tx: transactionHex, weightedSize: transactionSize ) let payload = BitPayPaymentRequest( chain: currency.code, transactions: [transaction] ) let headers = [ HttpHeaderField.xPayProVersion: HttpHeaderValue.xPayProVersion, HttpHeaderField.contentType: HttpHeaderValue.bitpayPayment, HttpHeaderField.bitpayPartner: HttpHeaderValue.bitpayPartnerName, HttpHeaderField.bitpayPartnerVersion: HttpHeaderValue.bitpayPartnerVersion ] let url = URL(string: BitPay.url + BitPay.Paramter.invoice + invoiceId)! let request = NetworkRequest( endpoint: url, method: .post, body: try? JSONEncoder().encode(payload), headers: headers ) return retailNetworkAdapter.perform(request: request) } } // MARK: - TransactionLimitsClientAPI extension APIClient { func fetchTradeLimits( currency: CurrencyType, product: TransactionLimitsProduct ) -> AnyPublisher<TradeLimitsResponse, NabuNetworkError> { var parameters: [URLQueryItem] = [ URLQueryItem( name: Parameter.currency, value: currency.code ), URLQueryItem( name: Parameter.minor, value: "true" ) ] switch product { case .swap(let orderDirection): parameters.append( URLQueryItem(name: Parameter.product, value: Parameter.swap) ) parameters.append( URLQueryItem(name: Parameter.orderDirection, value: orderDirection.rawValue) ) case .sell(let orderDirection): parameters.append( URLQueryItem(name: Parameter.product, value: Parameter.sell) ) parameters.append( URLQueryItem(name: Parameter.orderDirection, value: orderDirection.rawValue) ) case .simplebuy: parameters.append( URLQueryItem(name: Parameter.product, value: Parameter.simpleBuy) ) } let request = retailRequestBuilder.get( path: Path.limits, parameters: parameters, authenticated: true )! return retailNetworkAdapter.perform(request: request) } func fetchCrossBorderLimits( source: LimitsAccount, destination: LimitsAccount, limitsCurrency: CurrencyType ) -> AnyPublisher<CrossBorderLimitsResponse, NabuNetworkError> { let parameters: [URLQueryItem] = [ URLQueryItem(name: Parameter.currency, value: limitsCurrency.code), URLQueryItem(name: Parameter.inputCurrency, value: source.currency.code), URLQueryItem(name: Parameter.fromAccount, value: source.accountType.rawValue), URLQueryItem(name: Parameter.outputCurrency, value: destination.currency.code), URLQueryItem(name: Parameter.toAccount, value: destination.accountType.rawValue) ] let request = retailRequestBuilder.get( path: Path.crossBorderLimits, parameters: parameters, authenticated: true )! return retailNetworkAdapter.perform(request: request) } } // MARK: - BlockchainNameResolutionClientAPI extension APIClient { func resolve( domainName: String, currency: String ) -> AnyPublisher<DomainResolutionResponse, NetworkError> { let payload = DomainResolutionRequest(currency: currency, name: domainName) let request = defaultRequestBuilder.post( path: Path.domainResolution, body: try? JSONEncoder().encode(payload) )! return defaultNetworkAdapter.perform(request: request) } func reverseResolve( address: String ) -> AnyPublisher<ReverseResolutionResponse, NetworkError> { let payload = ReverseResolutionRequest(address: address) let request = defaultRequestBuilder.post( path: Path.reverseResolution, body: try? JSONEncoder().encode(payload) )! return defaultNetworkAdapter.perform(request: request) } } // MARK: - TransactionLimitsClientAPI extension APIClient { func fetchWithdrawalLocksCheck( paymentMethod: String, currencyCode: String ) -> AnyPublisher<WithdrawalLocksCheckResponse, NabuNetworkError> { let body = [ "paymentMethod": paymentMethod, "currency": currencyCode ] let request = retailRequestBuilder.post( path: Path.withdrawalLocksCheck, body: try? body.data(), authenticated: true )! return retailNetworkAdapter.perform(request: request) } }
bdee05e155986676b6335a1f4af5d31c
33.004008
102
0.641796
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Application/AppLaunchUtil.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Shared import Storage import Account import Glean // A convinient mapping, `Profile.swift` can't depend // on `PlacesMigrationConfiguration` directly since // the FML is only usable from `Client` at the moment extension PlacesMigrationConfiguration { func into() -> HistoryMigrationConfiguration { switch self { case .disabled: return .disabled case .dryRun: return .dryRun case .real: return .real } } } extension PlacesApiConfiguration { func into() -> HistoryAPIConfiguration { switch self { case .old: return .old case .new: return .new } } } class AppLaunchUtil { private var log: RollingFileLogger private var adjustHelper: AdjustHelper private var profile: Profile init(log: RollingFileLogger = Logger.browserLogger, profile: Profile) { self.log = log self.profile = profile self.adjustHelper = AdjustHelper(profile: profile) } func setUpPreLaunchDependencies() { // If the 'Save logs to Files app on next launch' toggle // is turned on in the Settings app, copy over old logs. if DebugSettingsBundleOptions.saveLogsToDocuments { Logger.copyPreviousLogsToDocuments() } // Now roll logs. DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } TelemetryWrapper.shared.setup(profile: profile) // Need to get "settings.sendUsageData" this way so that Sentry can be initialized // before getting the Profile. let sendUsageData = NSUserDefaultsPrefs(prefix: "profile").boolForKey(AppConstants.PrefSendUsageData) ?? true SentryIntegration.shared.setup(sendUsageData: sendUsageData) setUserAgent() KeyboardHelper.defaultHelper.startObserving() DynamicFontHelper.defaultHelper.startObserving() MenuHelper.defaultHelper.setItems() let logDate = Date() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) Logger.browserLogger.newLogWithDate(logDate) // Initialize the feature flag subsystem. // Among other things, it toggles on and off Nimbus, Contile, Adjust. // i.e. this must be run before initializing those systems. FeatureFlagsManager.shared.initializeDeveloperFeatures(with: profile) FeatureFlagUserPrefsMigrationUtility(with: profile).attemptMigration() // Migrate wallpaper folder LegacyWallpaperMigrationUtility(with: profile).attemptMigration() WallpaperManager().migrateLegacyAssets() // Start initializing the Nimbus SDK. This should be done after Glean // has been started. initializeExperiments() NotificationCenter.default.addObserver(forName: .FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL { let title = (userInfo["Title"] as? String) ?? "" self.profile.readingList.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name) } } SystemUtils.onFirstRun() RustFirefoxAccounts.startup(prefs: profile.prefs).uponQueue(.main) { _ in print("RustFirefoxAccounts started") } } func setUpPostLaunchDependencies() { let persistedCurrentVersion = InstallType.persistedCurrentVersion() let introScreen = profile.prefs.intForKey(PrefsKeys.IntroSeen) // upgrade install - Intro screen shown & persisted current version does not match if introScreen != nil && persistedCurrentVersion != AppInfo.appVersion { InstallType.set(type: .upgrade) InstallType.updateCurrentVersion(version: AppInfo.appVersion) } // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if introScreen == nil { // fresh install - Intro screen not yet shown InstallType.set(type: .fresh) InstallType.updateCurrentVersion(version: AppInfo.appVersion) // Profile setup profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } else if profile.prefs.boolForKey(PrefsKeys.KeySecondRun) == nil { profile.prefs.setBool(true, forKey: PrefsKeys.KeySecondRun) } updateSessionCount() adjustHelper.setupAdjust() } private func setUserAgent() { let firefoxUA = UserAgent.getUserAgent() // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } private func initializeExperiments() { // We initialize the generated FxNimbus singleton very early on with a lazily // constructed singleton. FxNimbus.shared.initialize(with: { Experiments.shared }) // We also make sure that any cache invalidation happens after each applyPendingExperiments(). NotificationCenter.default.addObserver(forName: .nimbusExperimentsApplied, object: nil, queue: nil) { _ in FxNimbus.shared.invalidateCachedValues() self.runEarlyExperimentDependencies() } let defaults = UserDefaults.standard let nimbusFirstRun = "NimbusFirstRun" let isFirstRun = defaults.object(forKey: nimbusFirstRun) == nil defaults.set(false, forKey: nimbusFirstRun) Experiments.customTargetingAttributes = ["isFirstRun": "\(isFirstRun)"] let initialExperiments = Bundle.main.url(forResource: "initial_experiments", withExtension: "json") let serverURL = Experiments.remoteSettingsURL let savedOptions = Experiments.getLocalExperimentData() let options: Experiments.InitializationOptions switch (savedOptions, isFirstRun, initialExperiments, serverURL) { // QA testing case: experiments come from the Experiments setting screen. case (let payload, _, _, _) where payload != nil: log.info("Nimbus: Loading from experiments provided by settings screen") options = Experiments.InitializationOptions.testing(localPayload: payload!) // First startup case: case (nil, true, let file, _) where file != nil: log.info("Nimbus: Loading from experiments from bundle, at first startup") options = Experiments.InitializationOptions.preload(fileUrl: file!) // Local development case: load from the bundled initial_experiments.json case (_, _, let file, let url) where file != nil && url == nil: log.info("Nimbus: Loading from experiments from bundle, with no URL") options = Experiments.InitializationOptions.preload(fileUrl: file!) case (_, _, _, let url) where url != nil: log.info("Nimbus: server exists") options = Experiments.InitializationOptions.normal default: log.info("Nimbus: server does not exist") options = Experiments.InitializationOptions.normal } Experiments.intialize(options) } private func updateSessionCount() { var sessionCount: Int32 = 0 // Get the session count from preferences if let currentSessionCount = profile.prefs.intForKey(PrefsKeys.SessionCount) { sessionCount = currentSessionCount } // increase session count value profile.prefs.setInt(sessionCount + 1, forKey: PrefsKeys.SessionCount) } private func runEarlyExperimentDependencies() { runAppServicesHistoryMigration() } // MARK: - Application Services History Migration private func runAppServicesHistoryMigration() { let placesHistory = FxNimbus.shared.features.placesHistory.value() FxNimbus.shared.features.placesHistory.recordExposure() guard placesHistory.migration != .disabled else { log.info("Migration disabled, won't run migration") return } let browserProfile = self.profile as? BrowserProfile let migrationRanKey = "PlacesHistoryMigrationRan" + placesHistory.migration.rawValue let migrationRan = UserDefaults.standard.bool(forKey: migrationRanKey) UserDefaults.standard.setValue(true, forKey: migrationRanKey) if !migrationRan { if placesHistory.api == .new { browserProfile?.historyApiConfiguration = .new // We set a user default so users with new configuration never go back UserDefaults.standard.setValue(true, forKey: PrefsKeys.NewPlacesAPIDefaultKey) } log.info("Migrating Application services history") let id = GleanMetrics.PlacesHistoryMigration.duration.start() // We mark that the migration started // this will help us identify how often the migration starts, but never ends // additionally, we have a seperate metric for error rates GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToNumerator(1) GleanMetrics.PlacesHistoryMigration.migrationErrorRate.addToNumerator(1) browserProfile?.migrateHistoryToPlaces( migrationConfig: placesHistory.migration.into(), callback: { result in self.log.info("Successful Migration took \(result.totalDuration / 1000) seconds") // We record various success metrics here GleanMetrics.PlacesHistoryMigration.duration.stopAndAccumulate(id) GleanMetrics.PlacesHistoryMigration.numMigrated.set(Int64(result.numSucceeded)) self.log.info("Migrated \(result.numSucceeded) entries") GleanMetrics.PlacesHistoryMigration.numToMigrate.set(Int64(result.numTotal)) GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToDenominator(1) }, errCallback: { err in let errDescription = err?.localizedDescription ?? "Unknown error during History migration" self.log.error(errDescription) GleanMetrics.PlacesHistoryMigration.duration.cancel(id) GleanMetrics.PlacesHistoryMigration.migrationEndedRate.addToDenominator(1) GleanMetrics.PlacesHistoryMigration.migrationErrorRate.addToDenominator(1) // We also send the error to sentry SentryIntegration.shared.sendWithStacktrace(message: "Error executing application services history migration", tag: SentryTag.rustPlaces, severity: .error, description: errDescription) }) } else { log.info("History Migration skipped, already migrated") } } }
8490aedb20c25de4d6097f576a019aaf
43.256705
200
0.671284
false
false
false
false
CodaFi/swift
refs/heads/master
stdlib/public/core/OutputStream.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Input/Output interfaces //===----------------------------------------------------------------------===// /// A type that can be the target of text-streaming operations. /// /// You can send the output of the standard library's `print(_:to:)` and /// `dump(_:to:)` functions to an instance of a type that conforms to the /// `TextOutputStream` protocol instead of to standard output. Swift's /// `String` type conforms to `TextOutputStream` already, so you can capture /// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of /// logging it to standard output. /// /// var s = "" /// for n in 1...5 { /// print(n, terminator: "", to: &s) /// } /// // s == "12345" /// /// Conforming to the TextOutputStream Protocol /// =========================================== /// /// To make your custom type conform to the `TextOutputStream` protocol, /// implement the required `write(_:)` method. Functions that use a /// `TextOutputStream` target may call `write(_:)` multiple times per writing /// operation. /// /// As an example, here's an implementation of an output stream that converts /// any input to its plain ASCII representation before sending it to standard /// output. /// /// struct ASCIILogger: TextOutputStream { /// mutating func write(_ string: String) { /// let ascii = string.unicodeScalars.lazy.map { scalar in /// scalar == "\n" /// ? "\n" /// : scalar.escaped(asASCII: true) /// } /// print(ascii.joined(separator: ""), terminator: "") /// } /// } /// /// The `ASCIILogger` type's `write(_:)` method processes its string input by /// escaping each Unicode scalar, with the exception of `"\n"` line returns. /// By sending the output of the `print(_:to:)` function to an instance of /// `ASCIILogger`, you invoke its `write(_:)` method. /// /// let s = "Hearts ♡ and Diamonds ♢" /// print(s) /// // Prints "Hearts ♡ and Diamonds ♢" /// /// var asciiLogger = ASCIILogger() /// print(s, to: &asciiLogger) /// // Prints "Hearts \u{2661} and Diamonds \u{2662}" public protocol TextOutputStream { mutating func _lock() mutating func _unlock() /// Appends the given string to the stream. mutating func write(_ string: String) mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) } extension TextOutputStream { public mutating func _lock() {} public mutating func _unlock() {} public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { write(String._fromASCII(buffer)) } } /// A source of text-streaming operations. /// /// Instances of types that conform to the `TextOutputStreamable` protocol can /// write their value to instances of any type that conforms to the /// `TextOutputStream` protocol. The Swift standard library's text-related /// types, `String`, `Character`, and `Unicode.Scalar`, all conform to /// `TextOutputStreamable`. /// /// Conforming to the TextOutputStreamable Protocol /// ===================================== /// /// To add `TextOutputStreamable` conformance to a custom type, implement the /// required `write(to:)` method. Call the given output stream's `write(_:)` /// method in your implementation. public protocol TextOutputStreamable { /// Writes a textual representation of this instance into the given output /// stream. func write<Target: TextOutputStream>(to target: inout Target) } /// A type with a customized textual representation. /// /// Types that conform to the `CustomStringConvertible` protocol can provide /// their own representation to be used when converting an instance to a /// string. The `String(describing:)` initializer is the preferred way to /// convert an instance of *any* type to a string. If the passed instance /// conforms to `CustomStringConvertible`, the `String(describing:)` /// initializer and the `print(_:)` function use the instance's custom /// `description` property. /// /// Accessing a type's `description` property directly or using /// `CustomStringConvertible` as a generic constraint is discouraged. /// /// Conforming to the CustomStringConvertible Protocol /// ================================================== /// /// Add `CustomStringConvertible` conformance to your custom types by defining /// a `description` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(p) /// // Prints "Point(x: 21, y: 30)" /// /// After implementing the `description` property and declaring /// `CustomStringConvertible` conformance, the `Point` type provides its own /// custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(p) /// // Prints "(21, 30)" public protocol CustomStringConvertible { /// A textual representation of this instance. /// /// Calling this property directly is discouraged. Instead, convert an /// instance of any type to a string by using the `String(describing:)` /// initializer. This initializer works with any type, and uses the custom /// `description` property for types that conform to /// `CustomStringConvertible`: /// /// struct Point: CustomStringConvertible { /// let x: Int, y: Int /// /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(describing: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `description` property. var description: String { get } } /// A type that can be represented as a string in a lossless, unambiguous way. /// /// For example, the integer value 1050 can be represented in its entirety as /// the string "1050". /// /// The description property of a conforming type must be a value-preserving /// representation of the original value. As such, it should be possible to /// re-create an instance from its string representation. public protocol LosslessStringConvertible: CustomStringConvertible { /// Instantiates an instance of the conforming type from a string /// representation. init?(_ description: String) } /// A type with a customized textual representation suitable for debugging /// purposes. /// /// Swift provides a default debugging textual representation for any type. /// That default representation is used by the `String(reflecting:)` /// initializer and the `debugPrint(_:)` function for types that don't provide /// their own. To customize that representation, make your type conform to the /// `CustomDebugStringConvertible` protocol. /// /// Because the `String(reflecting:)` initializer works for instances of *any* /// type, returning an instance's `debugDescription` if the value passed /// conforms to `CustomDebugStringConvertible`, accessing a type's /// `debugDescription` property directly or using /// `CustomDebugStringConvertible` as a generic constraint is discouraged. /// /// - Note: Calling the `dump(_:_:_:_:)` function and printing in the debugger /// uses both `String(reflecting:)` and `Mirror(reflecting:)` to collect /// information about an instance. If you implement /// `CustomDebugStringConvertible` conformance for your custom type, you may /// want to consider providing a custom mirror by implementing /// `CustomReflectable` conformance, as well. /// /// Conforming to the CustomDebugStringConvertible Protocol /// ======================================================= /// /// Add `CustomDebugStringConvertible` conformance to your custom types by /// defining a `debugDescription` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing the /// `debugDescription` property, `Point` provides its own custom debugging /// representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" public protocol CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. /// /// Calling this property directly is discouraged. Instead, convert an /// instance of any type to a string by using the `String(reflecting:)` /// initializer. This initializer works with any type, and uses the custom /// `debugDescription` property for types that conform to /// `CustomDebugStringConvertible`: /// /// struct Point: CustomDebugStringConvertible { /// let x: Int, y: Int /// /// var debugDescription: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(reflecting: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `debugDescription` property. var debugDescription: String { get } } //===----------------------------------------------------------------------===// // Default (ad-hoc) printing //===----------------------------------------------------------------------===// @_silgen_name("swift_EnumCaseName") internal func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>? @_silgen_name("swift_OpaqueSummary") internal func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>? /// Do our best to print a value that cannot be printed directly. @_semantics("optimize.sil.specialize.generic.never") internal func _adHocPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream, isDebugPrint: Bool ) { func printTypeName(_ type: Any.Type) { // Print type names without qualification, unless we're debugPrint'ing. target.write(_typeName(type, qualified: isDebugPrint)) } if let displayStyle = mirror.displayStyle { switch displayStyle { case .optional: if let child = mirror._children.first { _debugPrint_unlocked(child.1, &target) } else { _debugPrint_unlocked("nil", &target) } case .tuple: target.write("(") var first = true for (label, value) in mirror._children { if first { first = false } else { target.write(", ") } if let label = label { if !label.isEmpty && label[label.startIndex] != "." { target.write(label) target.write(": ") } } _debugPrint_unlocked(value, &target) } target.write(")") case .struct: printTypeName(mirror.subjectType) target.write("(") var first = true for (label, value) in mirror._children { if let label = label { if first { first = false } else { target.write(", ") } target.write(label) target.write(": ") _debugPrint_unlocked(value, &target) } } target.write(")") case .enum: if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { // Write the qualified type name in debugPrint. if isDebugPrint { printTypeName(mirror.subjectType) target.write(".") } target.write(caseName) } else { // If the case name is garbage, just print the type name. printTypeName(mirror.subjectType) } if let (_, value) = mirror._children.first { if Mirror(reflecting: value).displayStyle == .tuple { _debugPrint_unlocked(value, &target) } else { target.write("(") _debugPrint_unlocked(value, &target) target.write(")") } } default: target.write(_typeName(mirror.subjectType)) } } else if let metatypeValue = value as? Any.Type { // Metatype printTypeName(metatypeValue) } else { // Fall back to the type or an opaque summary of the kind if let cString = _opaqueSummary(mirror.subjectType), let opaqueSummary = String(validatingUTF8: cString) { target.write(opaqueSummary) } else { target.write(_typeName(mirror.subjectType, qualified: true)) } } } @usableFromInline @_semantics("optimize.sil.specialize.generic.never") internal func _print_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ target: inout TargetStream ) { // Optional has no representation suitable for display; therefore, // values of optional type should be printed as a debug // string. Check for Optional first, before checking protocol // conformance below, because an Optional value is convertible to a // protocol if its wrapped type conforms to that protocol. // Note: _isOptional doesn't work here when T == Any, hence we // use a more elaborate formulation: if _openExistential(type(of: value as Any), do: _isOptional) { let debugPrintable = value as! CustomDebugStringConvertible debugPrintable.debugDescription.write(to: &target) return } if let string = value as? String { target.write(string) return } if case let streamableObject as TextOutputStreamable = value { streamableObject.write(to: &target) return } if case let printableObject as CustomStringConvertible = value { printableObject.description.write(to: &target) return } if case let debugPrintableObject as CustomDebugStringConvertible = value { debugPrintableObject.debugDescription.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false) } //===----------------------------------------------------------------------===// // `debugPrint` //===----------------------------------------------------------------------===// @_semantics("optimize.sil.specialize.generic.never") @inline(never) public func _debugPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ target: inout TargetStream ) { if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } @_semantics("optimize.sil.specialize.generic.never") internal func _dumpPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream ) { if let displayStyle = mirror.displayStyle { // Containers and tuples are always displayed in terms of their element // count switch displayStyle { case .tuple: let count = mirror._children.count target.write(count == 1 ? "(1 element)" : "(\(count) elements)") return case .collection: let count = mirror._children.count target.write(count == 1 ? "1 element" : "\(count) elements") return case .dictionary: let count = mirror._children.count target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs") return case .`set`: let count = mirror._children.count target.write(count == 1 ? "1 member" : "\(count) members") return default: break } } if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } if let displayStyle = mirror.displayStyle { switch displayStyle { case .`class`, .`struct`: // Classes and structs without custom representations are displayed as // their fully qualified type name target.write(_typeName(mirror.subjectType, qualified: true)) return case .`enum`: target.write(_typeName(mirror.subjectType, qualified: true)) if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { target.write(".") target.write(caseName) } return default: break } } _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } //===----------------------------------------------------------------------===// // OutputStreams //===----------------------------------------------------------------------===// internal struct _Stdout: TextOutputStream { internal init() {} internal mutating func _lock() { _swift_stdlib_flockfile_stdout() } internal mutating func _unlock() { _swift_stdlib_funlockfile_stdout() } internal mutating func write(_ string: String) { if string.isEmpty { return } var string = string _ = string.withUTF8 { utf8 in _swift_stdlib_fwrite_stdout(utf8.baseAddress!, 1, utf8.count) } } } extension String: TextOutputStream { /// Appends the given string to this string. /// /// - Parameter other: A string to append. public mutating func write(_ other: String) { self += other } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { self._guts.append(_StringGuts(buffer, isASCII: true)) } } //===----------------------------------------------------------------------===// // Streamables //===----------------------------------------------------------------------===// extension String: TextOutputStreamable { /// Writes the string into the given output stream. /// /// - Parameter target: An output stream. @inlinable public func write<Target: TextOutputStream>(to target: inout Target) { target.write(self) } } extension Character: TextOutputStreamable { /// Writes the character into the given output stream. /// /// - Parameter target: An output stream. public func write<Target: TextOutputStream>(to target: inout Target) { target.write(String(self)) } } extension Unicode.Scalar: TextOutputStreamable { /// Writes the textual representation of the Unicode scalar into the given /// output stream. /// /// - Parameter target: An output stream. public func write<Target: TextOutputStream>(to target: inout Target) { target.write(String(Character(self))) } } /// A hook for playgrounds to print through. public var _playgroundPrintHook: ((String) -> Void)? = nil internal struct _TeeStream< L: TextOutputStream, R: TextOutputStream >: TextOutputStream { internal init(left: L, right: R) { self.left = left self.right = right } internal var left: L internal var right: R /// Append the given `string` to this stream. internal mutating func write(_ string: String) { left.write(string); right.write(string) } internal mutating func _lock() { left._lock(); right._lock() } internal mutating func _unlock() { right._unlock(); left._unlock() } }
cf6a293b10fc888b23b837342b4fb65b
33.041118
80
0.615548
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Persistence/WBPreferences.swift
agpl-3.0
2
// // WBPreferences.swift // SmartReceipts // // Created by Bogdan Evsenev on 25/02/2018. // Copyright © 2018 Will Baumann. All rights reserved. // typealias LanguageAlias = (name: String, identifier: String) private let LAST_OPENED_TRIP_KEY = "LastOpenedTripKey" extension WBPreferences { static func prefferedPDFSize() -> PDFPageSize { if let index = Int(string: preferredRawPDFSize()) { return PDFPageSize.pdfPageSizeBy(index: index) } return PDFPageSize(rawValue: preferredRawPDFSize())! } static func setPrefferedPDFSize(_ pdfSize: PDFPageSize) { setPreferredRawPDFSize(pdfSize.rawValue) } @objc static func isPDFFooterUnlocked() -> Bool { return PurchaseService.hasValidSubscriptionValue } static var languages: [LanguageAlias] = { return Bundle.main.localizations .map { identifier -> LanguageAlias? in guard let name = (Locale.current as NSLocale).displayName(forKey: .identifier, value: identifier) else { return nil } return LanguageAlias(name, identifier) }.compactMap { $0 } }() static func languageBy(identifier: String) -> LanguageAlias? { return WBPreferences.languages.first { identifier == $0.identifier } } static func languageBy(name: String) -> LanguageAlias? { return WBPreferences.languages.first { name == $0.name } } @objc class func localized(key: String, comment: String = "") -> String { var result = key if let path = Bundle.main.path(forResource: WBPreferences.preferredReportLanguage(), ofType: "lproj") { if let enBundle = Bundle(path: path) { result = NSLocalizedString(key, bundle: enBundle, comment: comment) if result == key { result = NSLocalizedString(key, tableName: "SharedLocalizable", bundle: enBundle, comment: comment) } } } return result } @objc class func localized(key: String) -> String { return WBPreferences.localized(key: key, comment: "") } static func markLastOpened(trip: WBTrip) { UserDefaults.standard.set(trip.name, forKey: LAST_OPENED_TRIP_KEY) } static var lastOpenedTrip: WBTrip? { guard let tripName = UserDefaults.standard.value(forKey: LAST_OPENED_TRIP_KEY) as? String else { return nil } return Database.sharedInstance().tripWithName(tripName) } } enum PDFPageSize: String { case A4 = "A4" case letter = "Letter" func size(portrait: Bool) -> CGSize { var width: CGFloat = 0 var height: CGFloat = 0 switch self { case .A4: width = 595.0 height = 842.0 case .letter: width = 612.001 height = 792.0 } return portrait ? CGSize(width: width, height: height) : CGSize(width: height, height: width) } static func pdfPageSizeBy(index: Int) -> PDFPageSize { let sizes: [PDFPageSize] = [.A4, .letter] return sizes[index] } } extension WBPreferences { static func importModel(settings: SettingsModel) { if let value = settings.tripDuration { setDefaultTripDuration(Int32(value)) } if let value = settings.isocurr { setDefaultCurrency(value) } if let value = settings.dateformat { setDateFormat(value) } if let value = settings.trackcostcenter { setTrackCostCenter(value) } if let value = settings.predictCategories { setPredictCategories(value) } if let value = settings.matchNameCategories { setMatchNameToCategory(value) } if let value = settings.matchCommentCategories { setMatchCommentToCategory(value) } if let value = settings.onlyIncludeExpensable { setOnlyIncludeReimbursableReceiptsInReports(value) } if let value = settings.expensableDefault { setExpensableDefault(value) } if let value = settings.includeTaxField { setIncludeTaxField(value) } if let value = settings.taxPercentage { setDefaultTaxPercentage(value) } if let value = settings.preTax { setEnteredPricePreTax(value) } if let value = settings.enableAutoCompleteSuggestions { setAutocompleteEnabled(value) } if let value = settings.minReceiptPrice { setMinimumReceiptPriceToIncludeInReports(value) } if let value = settings.defaultToFirstReportDate { setDefaultToFirstReportDate(value) } if let value = settings.showReceiptID { setShowReceiptID(value) } if let value = settings.useFullPage { setAssumeFullPage(value) } if let value = settings.usePaymentMethods { setUsePaymentMethods(value) } if let value = settings.printByIDPhotoKey { setPrintReceiptIDByPhoto(value) } if let value = settings.printCommentByPhoto { setPrintCommentByPhoto(value) } if let value = settings.emailTo { setDefaultEmailRecipient(value) } if let value = settings.emailCC { setDefaultEmailCC(value) } if let value = settings.emailBCC { setDefaultEmailBCC(value) } if let value = settings.emailSubject { setDefaultEmailSubject(value) } if let value = settings.saveBW { setCameraSaveImagesBlackAndWhite(value) } if let value = settings.layoutIncludeReceiptDate { setLayoutShowReceiptDate(value) } if let value = settings.layoutIncludeReceiptCategory { setLayoutShowReceiptCategory(value) } if let value = settings.layoutIncludeReceiptPicture { setLayoutShowReceiptAttachmentMarker(value) } if let value = settings.mileageTotalInReport { setTheDistancePriceBeIncludedInReports(value) } if let value = settings.mileageRate { setDistanceRateDefaultValue(value) } if let value = settings.mileagePrintTable { setPrintDistanceTable(value) } if let value = settings.mileageAddToPDF { setPrintDailyDistanceValues(value) } if let value = settings.pdfFooterString { setPDFFooterString(value) } } static var settingsModel: SettingsModel { return .init( tripDuration: Int(defaultTripDuration()), isocurr: defaultCurrency(), dateformat: dateFormat(), trackcostcenter: trackCostCenter(), predictCategories: predictCategories(), matchNameCategories: matchNameToCategory(), matchCommentCategories: matchCommentToCategory(), onlyIncludeExpensable: onlyIncludeReimbursableReceiptsInReports(), expensableDefault: expensableDefault(), includeTaxField: includeTaxField(), taxPercentage: defaultTaxPercentage(), preTax: enteredPricePreTax(), enableAutoCompleteSuggestions: isAutocompleteEnabled(), minReceiptPrice: minimumReceiptPriceToIncludeInReports(), defaultToFirstReportDate: defaultToFirstReportDate(), showReceiptID: showReceiptID(), useFullPage: assumeFullPage(), usePaymentMethods: usePaymentMethods(), printByIDPhotoKey: printReceiptIDByPhoto(), printCommentByPhoto: printCommentByPhoto(), emailTo: defaultEmailRecipient(), emailCC: defaultEmailCC(), emailBCC: defaultEmailBCC(), emailSubject: defaultEmailSubject(), saveBW: cameraSaveImagesBlackAndWhite(), layoutIncludeReceiptDate: layoutShowReceiptDate(), layoutIncludeReceiptCategory: layoutShowReceiptCategory(), layoutIncludeReceiptPicture: layoutShowReceiptAttachmentMarker(), mileageTotalInReport: isTheDistancePriceBeIncludedInReports(), mileageRate: distanceRateDefaultValue(), mileagePrintTable: printDistanceTable(), mileageAddToPDF: printDailyDistanceValues(), pdfFooterString: pdfFooterString() ) } }
1a21e85dc90c6f80ee13ac9b2b9483d5
45.180233
133
0.668891
false
false
false
false
pavankataria/SwiftDataTables
refs/heads/master
SwiftDataTables/Classes/Models/DataTableConfiguration.swift
mit
1
// // DataTableConfiguration.swift // SwiftDataTables // // Created by Pavan Kataria on 28/02/2017. // Copyright © 2017 Pavan Kataria. All rights reserved. // import Foundation import UIKit public enum DataStyles { public enum Colors { public static var highlightedFirstColor: UIColor = { return setupColor(normalColor: UIColor(red: 0.941, green: 0.941, blue: 0.941, alpha: 1), darkColor: UIColor(red: 0.16, green: 0.16, blue: 0.16, alpha: 1), defaultColor: UIColor(red: 0.941, green: 0.941, blue: 0.941, alpha: 1)) }() public static var highlightedSecondColor: UIColor = { return setupColor(normalColor: UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1), darkColor: UIColor(red: 0.13, green: 0.13, blue: 0.13, alpha: 1), defaultColor: UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1)) }() public static var unhighlightedFirstColor: UIColor = { return setupColor(normalColor: UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1), darkColor: UIColor(red: 0.06, green: 0.06, blue: 0.06, alpha: 1), defaultColor: UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1)) }() public static var unhighlightedSecondColor: UIColor = { return setupColor(normalColor: .white, darkColor: UIColor(red: 0.03, green: 0.03, blue: 0.03, alpha: 1), defaultColor: .white) }() } } public let Style = DataStyles.self private func setupColor(normalColor: UIColor, darkColor: UIColor, defaultColor: UIColor) -> UIColor { if #available(iOS 13, *) { return UIColor.init { (trait) -> UIColor in if trait.userInterfaceStyle == .dark { return darkColor } else { return normalColor } } } else { return defaultColor } } public struct DataTableColumnOrder: Equatable { //MARK: - Properties let index: Int let order: DataTableSortType public init(index: Int, order: DataTableSortType){ self.index = index self.order = order } } public struct DataTableConfiguration: Equatable { public var defaultOrdering: DataTableColumnOrder? = nil public var heightForSectionFooter: CGFloat = 44 public var heightForSectionHeader: CGFloat = 44 public var heightForSearchView: CGFloat = 60 public var heightOfInterRowSpacing: CGFloat = 1 public var shouldShowFooter: Bool = true public var shouldShowSearchSection: Bool = true public var shouldSearchHeaderFloat: Bool = false public var shouldSectionFootersFloat: Bool = true public var shouldSectionHeadersFloat: Bool = true public var shouldContentWidthScaleToFillFrame: Bool = true public var shouldShowVerticalScrollBars: Bool = true public var shouldShowHorizontalScrollBars: Bool = false public var sortArrowTintColor: UIColor = UIColor.blue public var shouldSupportRightToLeftInterfaceDirection: Bool = true public var highlightedAlternatingRowColors = [ DataStyles.Colors.highlightedFirstColor, DataStyles.Colors.highlightedSecondColor ] public var unhighlightedAlternatingRowColors = [ DataStyles.Colors.unhighlightedFirstColor, DataStyles.Colors.unhighlightedSecondColor ] public var fixedColumns: DataTableFixedColumnType? = nil public init(){ } }
c465251198c484b6f2123bb6509442d9
35.284314
104
0.626047
false
false
false
false
pkkup/Pkkup-iOS
refs/heads/master
Pkkup/views/SportsCollectionViewCell.swift
mit
1
// // SportsCollectionViewCell.swift // Pkkup // // Created by Deepak on 10/9/14. // Copyright (c) 2014 Pkkup. All rights reserved. // import UIKit protocol SportsCellDelegate { func sportWasSelected(sportCell: SportsCollectionViewCell, sportName: String) -> Void } class SportsCollectionViewCell: UICollectionViewCell { @IBOutlet weak private var sportButton: UIButton! @IBOutlet weak private var buttonSelectedView: UIView! var themeColor = UIColor(hexString: "#0DB14B", alpha: 1) var delegate: SportsCellDelegate? var sport: PkkupSport! { willSet(newSport) { sportButton.setTitle(newSport.name, forState: UIControlState.Normal) if newSport.isSelected != nil && newSport.isSelected! { buttonSelectedView.backgroundColor = self.themeColor } else { buttonSelectedView.backgroundColor = UIColor.clearColor() } } didSet(oldSport) { } } @IBAction func didSelect(sender: UIButton) { NSLog("Button was Selected \(sender.currentTitle!)") if(self.buttonSelectedView.backgroundColor == self.themeColor) { self.buttonSelectedView.backgroundColor = UIColor.clearColor() } else { self.buttonSelectedView.backgroundColor = self.themeColor } delegate?.sportWasSelected(self, sportName: sender.currentTitle!) } }
9404c1bbf1d5795e4aa173250c623323
30.195652
89
0.65993
false
false
false
false
jbennett/Bugology
refs/heads/master
Bugology/SifterProject.swift
mit
1
// // SifterProject.swift // Bugology // // Created by Jonathan Bennett on 2016-01-20. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import Foundation public struct SifterProject: Project { public let name: String public let apiURL: NSURL public let issuesURL: NSURL public init(name: String, apiURL: NSURL, issuesURL: NSURL) { self.name = name self.apiURL = apiURL self.issuesURL = issuesURL } public init(data: [String: AnyObject]) throws { guard let apiURLString = data["api_url"] as? String, apiURL = NSURL(string: apiURLString), issuesURLString = data["api_issues_url"] as? String, issuesURL = NSURL(string: issuesURLString) else { throw NSError(domain: "com.jbennett.parseError", code: 1, userInfo: nil) } self.name = data["name"] as? String ?? "" self.apiURL = apiURL self.issuesURL = issuesURL } }
54a4cee0fc7e05396b46588a9db98bb7
24.138889
80
0.670718
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/Spaces/SpaceMembers/MemberList/SpaceMemberListCoordinator.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh Spaces/SpaceMembers/MemberList ShowSpaceMemberList /* Copyright 2021 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class SpaceMemberListCoordinator: SpaceMemberListCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private let spaceId: String private var spaceMemberListViewModel: SpaceMemberListViewModelType private let spaceMemberListViewController: SpaceMemberListViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SpaceMemberListCoordinatorDelegate? // MARK: - Setup init(session: MXSession, spaceId: String) { self.session = session self.spaceId = spaceId let spaceMemberListViewModel = SpaceMemberListViewModel(session: self.session, spaceId: self.spaceId) let spaceMemberListViewController = SpaceMemberListViewController.instantiate(with: spaceMemberListViewModel) self.spaceMemberListViewModel = spaceMemberListViewModel self.spaceMemberListViewController = spaceMemberListViewController } // MARK: - Public methods func start() { self.spaceMemberListViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.spaceMemberListViewController } } // MARK: - SpaceMemberListViewModelCoordinatorDelegate extension SpaceMemberListCoordinator: SpaceMemberListViewModelCoordinatorDelegate { func spaceMemberListViewModel(_ viewModel: SpaceMemberListViewModelType, didSelect member: MXRoomMember, from sourceView: UIView?) { self.delegate?.spaceMemberListCoordinator(self, didSelect: member, from: sourceView) } func spaceMemberListViewModelDidCancel(_ viewModel: SpaceMemberListViewModelType) { self.delegate?.spaceMemberListCoordinatorDidCancel(self) } func spaceMemberListViewModelShowInvite(_ viewModel: SpaceMemberListViewModelType) { self.delegate?.spaceMemberListCoordinatorShowInvite(self) } }
f85a9348e0936ff42af2881b227b3502
34.311688
136
0.746598
false
false
false
false
MrLSPBoy/LSPDouYu
refs/heads/master
LSPDouYuTV/LSPDouYuTV/Classes/Main/View/LSBaseCollectionViewCell.swift
mit
1
// // LSBaseCollectionViewCell.swift // LSPDouYuTV // // Created by lishaopeng on 17/3/1. // Copyright © 2017年 lishaopeng. All rights reserved. // import UIKit class LSBaseCollectionViewCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor : LSAnchorModel? { didSet{ //0.校验模型是否有值 guard let anchor = anchor else { return } //1.取出在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000{ onlineStr = "\(Int(anchor.online / 10000))万在线" }else{ onlineStr = "\(Int(anchor.online))在线" } onlineBtn .setTitle(onlineStr, for: .normal) //2.昵称 nickNameLabel.text = anchor.nickname //4.设置封面图片 guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
c7daba4f6112ce8d057b1b5f7f0a78ac
25.222222
71
0.516949
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
OneBusAway/ui/themes/DrawerApplicationUI.swift
apache-2.0
2
// // DrawerApplicationUI.swift // OneBusAway // // Created by Aaron Brethorst on 2/17/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import FirebaseAnalytics import OBAKit @objc class DrawerApplicationUI: NSObject { var application: OBAApplication let tabBarController = UITabBarController.init() // MARK: - Map Tab var mapTableController: MapTableViewController var mapPulley: PulleyViewController let mapPulleyNav: UINavigationController var mapController: OBAMapViewController let drawerNavigation: UINavigationController // MARK: - Recents Tab let recentsController = OBARecentStopsViewController.init() lazy var recentsNavigation: UINavigationController = { return UINavigationController.init(rootViewController: recentsController) }() // MARK: - Bookmarks Tab let bookmarksController = OBABookmarksViewController.init() lazy var bookmarksNavigation: UINavigationController = { return UINavigationController.init(rootViewController: bookmarksController) }() // MARK: - Info Tab let infoController = OBAInfoViewController.init() lazy var infoNavigation: UINavigationController = { return UINavigationController.init(rootViewController: infoController) }() // MARK: - Init required init(application: OBAApplication) { self.application = application let useStopDrawer = application.userDefaults.bool(forKey: OBAUseStopDrawerDefaultsKey) mapTableController = MapTableViewController.init(application: application) drawerNavigation = UINavigationController(rootViewController: mapTableController) drawerNavigation.setNavigationBarHidden(true, animated: false) mapController = OBAMapViewController(application: application) mapController.standaloneMode = !useStopDrawer mapController.delegate = mapTableController mapPulley = PulleyViewController(contentViewController: mapController, drawerViewController: drawerNavigation) mapPulley.defaultCollapsedHeight = DrawerApplicationUI.calculateCollapsedHeightForCurrentDevice() mapPulley.initialDrawerPosition = .collapsed mapPulley.title = mapTableController.title mapPulley.tabBarItem.image = mapTableController.tabBarItem.image mapPulley.tabBarItem.selectedImage = mapTableController.tabBarItem.selectedImage mapPulleyNav = UINavigationController(rootViewController: mapPulley) super.init() mapPulley.delegate = self tabBarController.viewControllers = [mapPulleyNav, recentsNavigation, bookmarksNavigation, infoNavigation] tabBarController.delegate = self } } // MARK: - Pulley Delegate extension DrawerApplicationUI: PulleyDelegate { func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat) { mapTableController.collectionView.isScrollEnabled = drawer.drawerPosition == .open } private static func calculateCollapsedHeightForCurrentDevice() -> CGFloat { let height = UIScreen.main.bounds.height var totalDrawerHeight: CGFloat if #available(iOS 11.0, *) { totalDrawerHeight = 0.0 } else { // PulleyLib seems to have a few layout bugs on iOS 10. // Given the very small number of users on this platform, I am not // super-excited about the prospect of debugging this issue and am // choosing instead to just work around it. totalDrawerHeight = 40.0 } if height >= 812.0 { // X, Xs, iPad, etc. totalDrawerHeight += 200.0 } else if height >= 736.0 { // Plus totalDrawerHeight += 150.0 } else if height >= 667.0 { // 6, 7, 8 totalDrawerHeight += 150.0 } else { // iPhone SE, etc. totalDrawerHeight += 120.0 } return totalDrawerHeight } } // MARK: - OBAApplicationUI extension DrawerApplicationUI: OBAApplicationUI { private static let kOBASelectedTabIndexDefaultsKey = "OBASelectedTabIndexDefaultsKey" public var rootViewController: UIViewController { return tabBarController } func performAction(for shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { var navigationTargetType: OBANavigationTargetType = .undefined var parameters: [AnyHashable: Any]? if shortcutItem.type == kApplicationShortcutRecents { navigationTargetType = .recentStops if let stopIDs = shortcutItem.userInfo?["stopIds"] as? NSArray, let firstObject = stopIDs.firstObject { parameters = [OBAStopIDNavigationTargetParameter: firstObject] } else if let stopID = shortcutItem.userInfo?["stopID"] as? String { parameters = [OBAStopIDNavigationTargetParameter: stopID] } } let target = OBANavigationTarget.init(navigationTargetType, parameters: parameters) self.navigate(toTargetInternal: target) completionHandler(true) } func applicationDidBecomeActive() { var selectedIndex = application.userDefaults.object(forKey: DrawerApplicationUI.kOBASelectedTabIndexDefaultsKey) as? Int ?? 0 // Users sometimes email us confused about what happened to their map. There really isn't any value // in having the user returned to the info tab when they reopen the app, so let's just stop persisting // it as a possible option. Instead, if the user has navigated to the info tab, we'll just default them // back to the map. // See: https://github.com/OneBusAway/onebusaway-iphone/issues/1410 if selectedIndex == 3 { selectedIndex = 0 } tabBarController.selectedIndex = selectedIndex let startingTab = [0: "OBAMapViewController", 1: "OBARecentStopsViewController", 2: "OBABookmarksViewController"][selectedIndex] ?? "Unknown" OBAAnalytics.shared().reportEvent(withCategory: OBAAnalyticsCategoryAppSettings, action: "startup", label: "Startup View: \(startingTab)", value: nil) Analytics.logEvent(OBAAnalyticsStartupScreen, parameters: ["startingTab": startingTab]) } func navigate(toTargetInternal navigationTarget: OBANavigationTarget) { let viewController: (UIViewController & OBANavigationTargetAware) let topController: UIViewController switch navigationTarget.target { case .map, .searchResults: viewController = mapTableController topController = mapPulleyNav case .recentStops: viewController = recentsController topController = recentsNavigation case .bookmarks: viewController = bookmarksController topController = bookmarksNavigation case .contactUs: viewController = infoController topController = infoNavigation case .undefined: // swiftlint:disable no_fallthrough_only fallthrough fallthrough // swiftlint:enable no_fallthrough_only fallthrough default: DDLogError("Unhandled target in #file #line: \(navigationTarget.target)") return } tabBarController.selectedViewController = topController viewController.setNavigationTarget(navigationTarget) if navigationTarget.parameters["stop"] != nil, let stopID = navigationTarget.parameters["stopID"] as? String { let vc = StopViewController.init(stopID: stopID) let nav = mapPulley.navigationController ?? drawerNavigation nav.pushViewController(vc, animated: true) } // update kOBASelectedTabIndexDefaultsKey, otherwise -applicationDidBecomeActive: will switch us away. if let selected = tabBarController.selectedViewController { tabBarController(tabBarController, didSelect: selected) } } } // MARK: - UITabBarControllerDelegate extension DrawerApplicationUI: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { application.userDefaults.set(tabBarController.selectedIndex, forKey: DrawerApplicationUI.kOBASelectedTabIndexDefaultsKey) } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { guard let selectedController = tabBarController.selectedViewController, let controllers = tabBarController.viewControllers else { return true } let oldIndex = controllers.firstIndex(of: selectedController) let newIndex = controllers.firstIndex(of: viewController) if newIndex == 0 && oldIndex == 0 { mapController.recenterMap() } return true } }
8a36927e0068f0c4066776482148afb6
38.697368
158
0.691857
false
false
false
false
nearfri/Strix
refs/heads/main
Sources/Strix/Error/ErrorMessageWriter.swift
mit
1
import Foundation struct ErrorMessageWriter<Target: ErrorOutputStream> { let input: String? let position: String.Index? let errorSplitter: ParseErrorSplitter init(input: String, position: String.Index, errors: [ParseError]) { self.input = input self.position = position self.errorSplitter = ParseErrorSplitter(errors) } init(errors: [ParseError]) { self.input = nil self.position = nil self.errorSplitter = ParseErrorSplitter(errors) } func write(to target: inout Target) { writePositionIfPossible(to: &target) writeExpectedErrors(to: &target) writeUnexpectedErrors(to: &target) writeGenericErrors(to: &target) writeCompoundErrors(to: &target) writeNestedErrors(to: &target) if !errorSplitter.hasErrors { print("Unknown Error(s)", to: &target) } } // MARK: - Position private func writePositionIfPossible(to target: inout Target) { if let input = input, let position = position { PositionWriter(input: input, position: position).write(to: &target) } } // MARK: - Expected, unexpected error private func writeExpectedErrors(to target: inout Target) { var writer = MessageListWriter(title: "Expecting: ", lastSeparator: "or") errorSplitter.expectedErrors.forEach({ writer.appendMessage($0) }) errorSplitter.expectedStringErrors.forEach({ writer.appendMessage(withStringError: $0) }) errorSplitter.compoundErrors.forEach({ writer.appendMessage($0.label) }) writer.write(to: &target) } private func writeUnexpectedErrors(to target: inout Target) { var writer = MessageListWriter(title: "Unexpected: ", lastSeparator: "and") errorSplitter.unexpectedErrors.forEach({ writer.appendMessage($0) }) errorSplitter.unexpectedStringErrors.forEach({ writer.appendMessage(withStringError: $0) }) writer.write(to: &target) } // MARK: - Generic error private func writeGenericErrors(to target: inout Target) { if errorSplitter.genericErrors.isEmpty { return } let shouldIndent = errorSplitter.hasExpectedErrors || errorSplitter.hasUnexpectedErrors if shouldIndent { print("Other error messages:", to: &target) target.indent.level += 1 } for message in errorSplitter.genericErrors { print(message, to: &target) } if shouldIndent { target.indent.level -= 1 } } // MARK: - Compound, nested error private func writeCompoundErrors(to target: inout Target) { for error in errorSplitter.compoundErrors { print("", to: &target) print("\(error.label) could not be parsed because:", to: &target) writeNestedErrors(error.errors, at: error.position, to: &target) } } private func writeNestedErrors(to target: inout Target) { for error in errorSplitter.nestedErrors { print("", to: &target) print("The parser backtracked after:", to: &target) writeNestedErrors(error.errors, at: error.position, to: &target) } } private func writeNestedErrors(_ errors: [ParseError], at position: String.Index, to target: inout Target) { let nestedWriter: ErrorMessageWriter = { guard let input = input else { return ErrorMessageWriter(errors: errors) } return ErrorMessageWriter(input: input, position: position, errors: errors) }() target.indent.level += 1 nestedWriter.write(to: &target) target.indent.level -= 1 } } // MARK: - Position writer extension ErrorMessageWriter { private struct PositionWriter { let input: String let position: String.Index let line: Int let column: Int init(input: String, position: String.Index) { let textPosition = TextPosition(string: input, index: position) self.input = input self.position = position self.line = textPosition.line self.column = textPosition.column } func write(to target: inout Target) { print("Error at line \(line), column \(column)", to: &target) let substringTerminator = input[lineRange].last?.isNewline == true ? "" : "\n" print(input[lineRange], terminator: substringTerminator, to: &target) columnMarker.map({ print($0, to: &target) }) note.map({ print("Note: \($0)", to: &target) }) } private var lineRange: Range<String.Index> { return input.lineRange(for: position..<position) } private var columnMarker: String? { let tab: Character = "\t" let printableASCIIRange: ClosedRange<Character> = " "..."~" var result = "" for character in input[lineRange].prefix(column - 1) { // ASCII 외의 문자는 프린트 시 폭이 다를 수 있으므로 nil을 리턴한다 guard character.isASCII else { return nil } switch character { case tab: result.append(tab) case printableASCIIRange: result.append(" ") default: // 그 외 제어 문자는 프린트 되지 않으므로 아무 것도 더하지 않는다 break } } result.append("^") return result } private var note: String? { if position == input.endIndex { return "The error occurred at the end of the input stream." } if input[position].isNewline { if input[lineRange].count == 1 { return "The error occurred on an empty line." } return "The error occurred at the end of the line." } return nil } } } // MARK: - Message list writer extension ErrorMessageWriter { private struct MessageListWriter { let title: String let lastSeparator: String private var messages: [String] = [] init(title: String, lastSeparator: String) { self.title = title self.lastSeparator = lastSeparator } mutating func appendMessage(_ message: String) { messages.append(message) } mutating func appendMessage(withStringError error: (string: String, caseSensitive: Bool)) { let message = "'\(error.string)'" + (error.caseSensitive ? "" : " (case-insensitive)") appendMessage(message) } func write(to target: inout Target) { if messages.isEmpty { return } print(title, terminator: "", to: &target) for message in messages.dropLast(2) { print(message, terminator: ", ", to: &target) } if let secondToLast = messages.dropLast().last { if messages.count > 2 { print("\(secondToLast), \(lastSeparator) ", terminator: "", to: &target) } else { print("\(secondToLast) \(lastSeparator) ", terminator: "", to: &target) } } if let last = messages.last { print(last, to: &target) } } } }
bf1bcf2ab663f4cfc716e34baaecc76f
32.213389
99
0.54006
false
false
false
false
cemolcay/DeserializableSwiftGenerator
refs/heads/master
DeserializableSwiftGenerator/AppDelegate.swift
mit
2
// // AppDelegate.swift // DeserializableSwiftGenerator // // Created by Cem Olcay on 14/11/14. // Copyright (c) 2014 Cem Olcay. All rights reserved. // import Cocoa import Foundation import AppKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) { let testCamel = "hello_world" Swift.print(testCamel.camelCasedString) } func applicationWillTerminate(aNotification: NSNotification) { } func testGenerator () { print("test starting") let p1 = SWProperty (name: "name", type: "String") let p2 = SWProperty (name: "surname", type: "String") let p3 = SWProperty (name: "age", type: "Int") let c = SWClass (name: "Person", superName: "TestSuper", properties: [p1, p2, p3]) let gen = ObjectMapperGenerator () let save = gen.saveToDesktop(c) print("did save \(save)") } }
5055cd41c5eda86e6e1fd6b0b6c0fbf9
23.952381
90
0.633588
false
true
false
false
fhchina/EasyIOS-Swift
refs/heads/master
Pod/Classes/Extend/EUI/EUIParse.swift
mit
3
// // EZUI.swift // medical // // Created by zhuchao on 15/4/30. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit import SnapKit class EUIParse: NSObject { class func ParseHtml(html:String) -> [ViewProperty]{ var data = ObjectiveGumbo.parseDocumentWithString(html) var body = data.elementsWithTag(GUMBO_TAG_BODY).first as! OGElement var viewArray = [ViewProperty]() for element in body.children { if element.isKindOfClass(OGElement) { if let pro = self.loopElement(element as! OGElement) { viewArray.append(pro) } } } return viewArray } // 对子节点进行递归解析 class func loopElement(pelement:OGElement) -> ViewProperty?{ var tagProperty:ViewProperty? var type:String? switch (pelement.tag.value){ case GUMBO_TAG_IMG.value : type = "UIImageView" case GUMBO_TAG_SPAN.value : type = "UILabel" case GUMBO_TAG_BUTTON.value : type = "UIButton" case GUMBO_TAG_INPUT.value : type = "UITextField" default : type = self.string(pelement,key:"type") } if let atype = type { switch (atype){ case "UIScrollView","scroll": tagProperty = ScrollViewProperty() case "UITableView","table": tagProperty = TableViewProperty() case "UICollectionView","collection": tagProperty = CollectionViewProperty() case "UIImageView","imageView": tagProperty = ImageProperty() case "UILabel","label": tagProperty = LabelProperty() case "UIButton","button": tagProperty = ButtonProperty() case "UITextField","field": tagProperty = TextFieldProperty() default : tagProperty = ViewProperty() } }else{ tagProperty = ViewProperty() } if tagProperty != nil { tagProperty!.renderTag(pelement) } return tagProperty } class func string (element:OGElement,key:String) ->String?{ if let str = element.attributes?[key] as? String { return str } return nil } class func getStyleProperty (element:OGElement,key:String) -> Array<Constrain>? { if element.attributes?[key] == nil { return nil } var style = Array<Constrain>() var origin = element.attributes?[key] as! String var firstArray = origin.trimArrayBy(";") for str in firstArray { var secondArray = str.trimArrayBy(":") if secondArray.count == 2 { var raw = secondArray[0] as String let rawKey = CSS(rawValue: key+"-"+raw.trim) if rawKey == nil { continue } var values = secondArray[1].trimArray if key == "align" { switch rawKey! { case .AlignTop,.AlignBottom,.AlignLeft,.AlignRight,.AlignCenterX,.AlignCenterY: if values.count == 1 { style.append(Constrain(name:rawKey!,value: values[0].trim.floatValue)) }else if(values.count >= 2){ style.append(Constrain(name:rawKey!,value: values[0].trim.floatValue,target:values[1].trim)) } case .AlignCenter: if values.count >= 1 { style.append(Constrain(name:.AlignCenterX,value: values[0].trim.floatValue)) } if values.count >= 2 { style.append(Constrain(name:.AlignCenterY,value: values[1].trim.floatValue)) } case .AlignEdge: if values.count >= 1 && values[0].trim != "*" { style.append(Constrain(name:.AlignTop,value: values[0].trim.floatValue)) } if values.count >= 2 && values[1].trim != "*" { style.append(Constrain(name:.AlignLeft,value: values[1].trim.floatValue)) } if values.count >= 3 && values[2].trim != "*" { style.append(Constrain(name:.AlignBottom,value: values[2].trim.floatValue)) } if values.count >= 4 && values[3].trim != "*" { style.append(Constrain(name:.AlignRight,value: values[3].trim.floatValue)) } default : println(raw.trim + " is jumped") } }else if key == "margin" { switch rawKey! { case .MarginTop,.MarginBottom,.MarginLeft,.MarginRight: if values.count == 1 { style.append(Constrain(name:rawKey!,value: values[0].trim.floatValue)) }else if(values.count >= 2){ style.append(Constrain(name:rawKey!,value: values[0].trim.floatValue,target:values[1].trim)) } default : println(raw.trim + " is jumped") } } }else if secondArray.count == 1 && key == "align" { var values = secondArray[0].trimArray if values.count >= 1 && values[0].trim != "*" { style.append(Constrain(name:.AlignTop,value: values[0].trim.floatValue)) } if values.count >= 2 && values[1].trim != "*" { style.append(Constrain(name:.AlignLeft,value: values[1].trim.floatValue)) } if values.count >= 3 && values[2].trim != "*" { style.append(Constrain(name:.AlignBottom,value: values[2].trim.floatValue)) } if values.count >= 4 && values[3].trim != "*" { style.append(Constrain(name:.AlignRight,value: values[3].trim.floatValue)) } } } return style } }
ce19eb09d0eff5eb03140ba6eacff727
38.79878
120
0.478474
false
false
false
false
0359xiaodong/CYFastImage
refs/heads/master
CYFastImage/CYFastImage/CYImageDownloader.swift
mit
3
// // CYImageDownloader.swift // CYFastImage // // Created by jason on 14-6-19. // Copyright (c) 2014 chenyang. All rights reserved. // import Foundation import UIKit extension CYFastImage { class CYImageDownloader { var operationQueue: NSOperationQueue! var concurrentCount: Int init(concurrentCount: Int) { self.concurrentCount = concurrentCount operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = concurrentCount } convenience init() { self.init(concurrentCount: 1) } // MARK: public func downloadImage(url: String, callback: DownloadCallback) { var operation = CYDownloadOperation() operation.urlString = url operation.finishCallback = callback operationQueue.addOperation(operation) } func cancel(url: String!) { for operation : AnyObject in operationQueue.operations { if let downloadOperation = operation as? CYDownloadOperation { if url == downloadOperation.urlString && downloadOperation.executing { downloadOperation.cancel() } } } } func isDownloadingImage(url: String!) -> Bool { for operation : AnyObject in operationQueue.operations { if let downloadOperation = operation as? CYDownloadOperation { if url == downloadOperation.urlString { return true } } } return false } } }
4b09522c1c2dfdd145c99f06f2ff6fbc
29.910714
90
0.554015
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Sources/AST/Declaration/VariableDeclaration.swift
apache-2.0
2
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ public class VariableDeclaration : ASTNode, Declaration { public enum Body { case initializerList([PatternInitializer]) case codeBlock(Identifier, TypeAnnotation, CodeBlock) case getterSetterBlock(Identifier, TypeAnnotation, GetterSetterBlock) case getterSetterKeywordBlock( Identifier, TypeAnnotation, GetterSetterKeywordBlock) case willSetDidSetBlock( Identifier, TypeAnnotation?, Expression?, WillSetDidSetBlock) } public let attributes: Attributes public let modifiers: DeclarationModifiers public private(set) var body: Body private init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], body: Body ) { self.attributes = attributes self.modifiers = modifiers self.body = body } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], initializerList: [PatternInitializer] ) { self.init(attributes: attributes, modifiers: modifiers, body: .initializerList(initializerList)) } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], variableName: Identifier, typeAnnotation: TypeAnnotation, codeBlock: CodeBlock ) { self.init(attributes: attributes, modifiers: modifiers, body: .codeBlock(variableName, typeAnnotation, codeBlock)) } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], variableName: Identifier, typeAnnotation: TypeAnnotation, getterSetterBlock: GetterSetterBlock ) { self.init(attributes: attributes, modifiers: modifiers, body: .getterSetterBlock(variableName, typeAnnotation, getterSetterBlock)) } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], variableName: Identifier, typeAnnotation: TypeAnnotation, getterSetterKeywordBlock: GetterSetterKeywordBlock ) { self.init(attributes: attributes, modifiers: modifiers, body: .getterSetterKeywordBlock( variableName, typeAnnotation, getterSetterKeywordBlock)) } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], variableName: Identifier, initializer: Expression, willSetDidSetBlock: WillSetDidSetBlock ) { self.init( attributes: attributes, modifiers: modifiers, body: .willSetDidSetBlock( variableName, nil, initializer, willSetDidSetBlock)) } public convenience init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], variableName: Identifier, typeAnnotation: TypeAnnotation, initializer: Expression? = nil, willSetDidSetBlock: WillSetDidSetBlock ) { self.init(attributes: attributes, modifiers: modifiers, body: .willSetDidSetBlock( variableName, typeAnnotation, initializer, willSetDidSetBlock)) } // MARK: - Node Mutations public func replaceBody(with newBody: Body) { body = newBody } // MARK: - ASTTextRepresentable override public var textDescription: String { let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) " let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) " return "\(attrsText)\(modifiersText)var \(body.textDescription)" } } extension VariableDeclaration.Body : ASTTextRepresentable { public var textDescription: String { switch self { case .initializerList(let inits): return inits.map({ $0.textDescription }).joined(separator: ", ") case let .codeBlock(name, typeAnnotation, codeBlock): return "\(name)\(typeAnnotation) \(codeBlock.textDescription)" case let .getterSetterBlock(name, typeAnnotation, block): return "\(name)\(typeAnnotation) \(block.textDescription)" case let .getterSetterKeywordBlock(name, typeAnnotation, block): return "\(name)\(typeAnnotation) \(block.textDescription)" case let .willSetDidSetBlock(name, typeAnnotation, initExpr, block): let typeAnnoStr = typeAnnotation?.textDescription ?? "" let initStr = initExpr.map({ " = \($0.textDescription)" }) ?? "" return "\(name)\(typeAnnoStr)\(initStr) \(block.textDescription)" } } }
68a939332679c68ee789b8b9e486ccdb
32.489796
85
0.713996
false
false
false
false
blstream/mEatUp
refs/heads/master
mEatUp/mEatUp/RestaurantListViewController.swift
apache-2.0
1
// // RestaurantListViewController.swift // mEatUp // // Created by Krzysztof Przybysz on 21/04/16. // Copyright © 2016 BLStream. All rights reserved. // import UIKit class RestaurantListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let cloudKitHelper = CloudKitHelper() let searchController = UISearchController(searchResultsController: nil) var restaurants = [Restaurant]() var filteredRestaurants = [Restaurant]() var saveRestaurant: ((Restaurant) -> Void)? lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(handleManualRefresh(_:)), forControlEvents: .ValueChanged) return refreshControl }() override func viewDidLoad() { super.viewDidLoad() self.searchController.loadViewIfNeeded() tableView.addSubview(self.refreshControl) refreshControl.beginRefreshing() tableView.delegate = self tableView.dataSource = self self.navigationController?.navigationBar.translucent = false searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false tableView.tableHeaderView = searchController.searchBar } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadRestaurants() } @IBAction func cancellButtonTapped(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } func loadRestaurants() { refreshControl.beginRefreshing() cloudKitHelper.loadRestaurantRecords({ [weak self] restaurants in self?.restaurants = restaurants self?.tableView.reloadData() self?.refreshControl.endRefreshing() }, errorHandler: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? RestaurantViewController { destination.saveRestaurant = self.saveRestaurant } } func handleManualRefresh(refreshControl: UIRefreshControl) { loadRestaurants() } } extension RestaurantListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchController.gotContentAndActive() ? filteredRestaurants.count : restaurants.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("RestaurantCell", forIndexPath: indexPath) let restaurant = searchController.gotContentAndActive() ? filteredRestaurants[indexPath.row] : restaurants[indexPath.row] if let cell = cell as? RestaurantTableViewCell { cell.configureWithRestaurant(restaurant) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let restaurant = searchController.gotContentAndActive() ? filteredRestaurants[indexPath.row] : restaurants[indexPath.row] self.searchController.active = false dismissViewControllerAnimated(true) { [unowned self] in self.saveRestaurant?(restaurant) } } } extension RestaurantListViewController: UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { if let text = searchController.searchBar.text { filterContentForSearchText(text) } } func filterContentForSearchText(searchText: String) { filteredRestaurants = restaurants.filter { restaurant in guard let name = restaurant.name else { return false } return name.lowercaseString.containsString(searchText.lowercaseString) } tableView.reloadData() } }
77559aa8932e5ddd72b5101d3c85c118
36.423423
129
0.702937
false
false
false
false
Solfanto/GoForIt
refs/heads/master
GoForIt/Authentication.swift
mit
1
// // Authentication.swift // GoForIt // // Created by Lidner on 14/9/20. // Copyright (c) 2014 Solfanto. All rights reserved. // import UIKit private let _authenticationInstance = Authentication() class Authentication { private var _uuid: String! class var sharedInstance: Authentication { return _authenticationInstance } init() { } func uuid() -> String { if _uuid != nil { return _uuid } _uuid = NSUserDefaults.standardUserDefaults().valueForKey("uuid") as? String if _uuid != nil { return _uuid } _uuid = NSUUID().UUIDString setUuid(_uuid) return _uuid } func setUuid(value: String) { NSUserDefaults.standardUserDefaults().setValue(value, forKey: "uuid") NSUserDefaults.standardUserDefaults().synchronize() } }
ae54ac5c7e48d451d8bb813772e792a6
21.475
84
0.589087
false
false
false
false
JoeLago/MHGDB-iOS
refs/heads/master
MHGDB/Common/TableAbstraction/Sections/MultiCellSection.swift
mit
1
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit class MultiCellSection: DetailSection { private var cells = [UITableViewCell]() override init() { super.init() populateCells() numberOfRows = cells.count showCountMinRows = -1 } func addCell(_ cell: UITableViewCell) { cells.append(cell) cell.selectionStyle = .none } func addDetail(label: String?, text: String?) { guard let text = text else { return } addCell(SingleDetailCell(label: label, text: text)) } func addDetail(label: String?, value: Int?) { addDetail(label: label, text: value == nil ? nil : "\(value ?? 0)") } func populateCells() { } override func cell(row: Int) -> UITableViewCell? { return cells[row] } }
eac0169c3009fffedc093d0611a39dfb
20.463415
75
0.563636
false
false
false
false
chanhx/Octogit
refs/heads/master
iGithub/ViewModels/SearchViewModel.swift
gpl-3.0
2
// // SearchViewModel.swift // iGithub // // Created by Chan Hocheung on 8/16/16. // Copyright © 2016 Hocheung. All rights reserved. // import Foundation import RxSwift import RxMoya import ObjectMapper class SearchViewModel { enum SearchObject { case repository case user } let repoTVM = RepositoriesSearchViewModel() let userTVM = UsersSearchViewModel() var searchObject: SearchObject = .repository func search(query: String) { switch searchObject { case .repository: repoTVM.query = query repoTVM.isLoading = true repoTVM.dataSource.value.removeAll() repoTVM.refresh() case .user: userTVM.query = query userTVM.isLoading = true userTVM.dataSource.value.removeAll() userTVM.refresh() } } @objc func fetchNextPage() { switch searchObject { case .repository: repoTVM.fetchData() case .user: userTVM.fetchData() } } func clean() { repoTVM.query = nil userTVM.query = nil repoTVM.dataSource.value = [] userTVM.dataSource.value = [] } } // MARK: SubViewModels class RepositoriesSearchViewModel: BaseTableViewModel<Repository> { var query: String? var sort: RepositoriesSearchSort = .bestMatch var language = "All Languages" var isLoading = false let sortOptions: [RepositoriesSearchSort] = [ .bestMatch, .stars, .forks, .updated ] var token: GitHubAPI { var q = query! switch sort { case .stars: q += " sort:stars" case .forks: q += " sort:forks" case .updated: q += " sort:updated" default: break } let lan = languagesDict[language]! if lan.count > 0 { q += " language:\(lan)" } return GitHubAPI.searchRepositories(query: q, after: endCursor) } override func fetchData() { GitHubProvider .request(token) .filterSuccessfulStatusCodes() .mapJSON() .subscribe(onSuccess: { [unowned self] in guard let json = ($0 as? [String: [String: Any]])?["data"]?["search"], let connection = Mapper<EntityConnection<Repository>>().map(JSONObject: json), let newRepos = connection.nodes else { // deal with error return } self.hasNextPage = connection.pageInfo!.hasNextPage! if self.endCursor == nil { self.dataSource.value = newRepos } else { self.dataSource.value.append(contentsOf: newRepos) } self.endCursor = connection.pageInfo?.endCursor }) .disposed(by: disposeBag) } } class UsersSearchViewModel: BaseTableViewModel<User> { var query: String? var sort: UsersSearchSort = .bestMatch var isLoading = false let sortOptions: [UsersSearchSort] = [ .bestMatch, .followers, .repositories, .joined ] var token: GitHubAPI { return GitHubAPI.searchUsers(q: query!, sort: sort, page: page) } override func fetchData() { GitHubProvider .request(token) .do(onNext: { [unowned self] in self.isLoading = false if let headers = $0.response?.allHeaderFields { self.hasNextPage = (headers["Link"] as? String)?.range(of: "rel=\"next\"") != nil } }) .mapJSON() .subscribe(onSuccess: { [unowned self] in if let results = Mapper<User>().mapArray(JSONObject: ($0 as! [String: Any])["items"]) { if self.page == 1 { self.dataSource.value = results } else { self.dataSource.value.append(contentsOf: results) } self.page += 1 } else { // deal with error } }) .disposed(by: disposeBag) } }
f7524fa877b9e2a20d35026c80c9f74b
26.420732
103
0.501001
false
false
false
false
EZ-NET/CodePiece
refs/heads/Rev2
CodePiece/Windows/Timeline/ContentsController/MyTweetsContentsController.swift
gpl-3.0
1
// // MyTweetsContentsController.swift // CodePiece // // Created by Tomohiro Kumagai on 2020/02/04. // Copyright © 2020 Tomohiro Kumagai. All rights reserved. // import Cocoa import ESTwitter import Swim import Ocean final class MyTweetsContentsController : TimelineContentsController, NotificationObservable { override var kind: TimelineKind { return .myTweets } var dataSource = ManagedByTweetContentsDataSource() override var tableViewDataSource: TimelineTableDataSource { return dataSource } override func activate() { super.activate() observe(PostCompletelyNotification.self) { [unowned self] notification in delegate?.timelineContentsNeedsUpdate?(self) } } override func timelineViewDidAppear() { super.timelineViewDidAppear() delegate?.timelineContentsNeedsUpdate?(self) } override func updateContents(callback: @escaping (UpdateResult) -> Void) { let options = API.TimelineOptions( sinceId: dataSource.lastTweetId ) NSApp.twitterController.timeline(options: options) { result in switch result { case .success(let statuses): callback(.success((statuses, []))) case .failure(let error): callback(.failure(error)) } } } override func estimateCellHeight(of row: Int) -> CGFloat { guard let tableView = tableView else { return 0 } let item = dataSource.items[row] return item.timelineCellType.estimateCellHeightForItem(item: item, tableView: tableView) } override func appendTweets(tweets: [Status]) { let newTweets = tweets .orderByNewCreationDate() .toTimelineTweetItems(hashtags: []) .timelineItemsAppend(items: dataSource.items) .prefix(maxTimelineRows) dataSource.items = Array(newTweets) } }
f9d4648cc9a4e92d1b9ed852de9063c8
19.37931
93
0.719684
false
false
false
false
glock45/swifter
refs/heads/master
Sources/TLS/SHA256.swift
bsd-3-clause
1
// // SHA256.swift // Swifter // // Copyright © 2016 Damian Kołakowski. All rights reserved. // #if os(Linux) import Glibc #else import Foundation #endif public struct SHA256 { public static func hash(_ input: [UInt8]) -> [UInt8] { // Alghorithm from: https://en.wikipedia.org/wiki/SHA-2 // http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf var message = input var h0 = UInt32(littleEndian: 0x6a09e667) var h1 = UInt32(littleEndian: 0xbb67ae85) var h2 = UInt32(littleEndian: 0x3c6ef372) var h3 = UInt32(littleEndian: 0xa54ff53a) var h4 = UInt32(littleEndian: 0x510e527f) var h5 = UInt32(littleEndian: 0x9b05688c) var h6 = UInt32(littleEndian: 0x1f83d9ab) var h7 = UInt32(littleEndian: 0x5be0cd19) // ml = message length in bits (always a multiple of the number of bits in a character). let ml = UInt64(message.count * 8) // append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits. message.append(0x80) // append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512) let padBytesCount = ( message.count + 8 ) % 64 message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount)) // append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits. var mlBigEndian = ml.bigEndian withUnsafePointer(to: &mlBigEndian) { message.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 8))) } // Process the message in successive 512-bit chunks ( 64 bytes chunks ): for chunkStart in 0..<message.count/64 { var words = [UInt32](repeating: 0, count: 64) let chunk = message[chunkStart*64..<chunkStart*64+64] // Break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15 for i in 0...15 { let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>(OpaquePointer($0.baseAddress! + (i*4))).pointee}) words[i] = value.bigEndian } // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array: for i in 16..<words.count { let s0 = (rotateRight(words[i-15], 7)) ^ (rotateRight(words[i-15], 18)) ^ (words[i-15] >> 3 ) let s1 = (rotateRight(words[i-2 ], 17)) ^ (rotateRight(words[i-2 ], 19)) ^ (words[i-2 ] >> 10) words[i] = words[i-16] &+ s0 &+ words[i-7] &+ s1 } // Initialize hash value for this chunk: var a = h0 var b = h1 var c = h2 var d = h3 var e = h4 var f = h5 var g = h6 var h = h7 for i in 0...63 { let S0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22) let S1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25) let ch = (e & f) ^ ((~e) & g) let maj = (a & b) ^ (a & c) ^ (b & c) let temp1 = h &+ S1 &+ ch &+ K[i] &+ words[i] let temp2 = S0 &+ maj h = g g = f f = e e = d &+ temp1 d = c c = b b = a a = temp1 &+ temp2 } // Add this chunk's hash to result so far: h0 = ( h0 &+ a ) h1 = ( h1 &+ b ) h2 = ( h2 &+ c ) h3 = ( h3 &+ d ) h4 = ( h4 &+ e ) h5 = ( h5 &+ f ) h6 = ( h6 &+ g ) h7 = ( h7 &+ h ) } // Produce the final hash value (big-endian): var digest = [UInt8]() [h0, h1, h2, h3, h4, h5, h6, h7].forEach { value in var bigEndianVersion = value.bigEndian withUnsafePointer(to: &bigEndianVersion) { digest.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 4))) } } return digest } private static func rotateRight(_ v : UInt32, _ n: UInt32) -> UInt32 { return (v >> n) | (v << (32 - n)) } private static func rotateLeft(_ v: UInt32, _ n: UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } private static var K: [UInt32] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ] } extension String { public func sha256() -> String { return self.sha256().hex() } public func sha256() -> [UInt8] { return SHA256.hash([UInt8](self.utf8)) } }
23be3785db7f663e1026095f8e50ee6c
35.814815
131
0.522803
false
false
false
false
mityung/XERUNG
refs/heads/master
IOS/Xerung/Xerung/CityViewController.swift
apache-2.0
1
// // CityViewController.swift // Xerung // // Created by mityung on 20/03/17. // Copyright © 2017 mityung. All rights reserved. // import UIKit import XLPagerTabStrip class CityViewController: UIViewController , UITableViewDelegate , UITableViewDataSource , IndicatorInfoProvider { public func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "City") } @IBOutlet weak var tableView: UITableView! // var groupId:String! var data = [String]() var groupType = [String]() var groupCount = [String]() override func viewDidLoad() { super.viewDidLoad() // self.getOffLineData() // print(data) // self.saveData() self.findBloodGroup() //tableView.backgroundView = UIImageView(image: UIImage(named: "backScreen.png")) // tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.separatorStyle = .none self.tableView.estimatedRowHeight = 170; self.tableView.rowHeight = UITableViewAutomaticDimension; /* let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupAbout cell.dirtectoryType.text = selectedGroupCalled cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "user.png") } tableView.tableHeaderView = cell*/ // Do any additional setup after loading the view. self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) } // set tab title func indicatorInfoForPagerTabStrip(_ pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "City") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupCount.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BloodCell", for: indexPath) as! BloodCell cell.bloodGroup.text = groupType[indexPath.row].uppercaseFirst cell.groupCount.text = groupCount[indexPath.row] cell.selectionStyle = .none cell.backgroundColor = UIColor.clear return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } /* func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupAbout cell.dirtectoryType.text = selectedGroupCalled cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "user.png") } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 88 }*/ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "MemberDetailViewController") as! MemberDetailViewController viewController.type = "city" if groupType[indexPath.row] == "Unknown" { viewController.query = "-1" }else{ viewController.query = groupType[indexPath.row] } self.navigationController?.pushViewController(viewController, animated: true) } /* func getOffLineData(){ let databasePath = NSUserDefaults.standardUserDefaults().URLForKey("DataBasePath")! let contactDB = FMDatabase(path: String(databasePath)) if contactDB.open() { let querySQL = "SELECT * FROM DirectoryMember where groupId = '\(groupId)'" let results:FMResultSet? = contactDB.executeQuery(querySQL,withArgumentsInArray: nil) while((results?.next()) == true){ self.data.append(results!.stringForColumn("GroupData")!) } contactDB.close() } else { print("Error: \(contactDB.lastErrorMessage())") } }*/ func findBloodGroup(){ let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")! let contactDB = FMDatabase(path: String(describing: databasePath)) if (contactDB?.open())! { let querySQL = "SELECT count(*) as Num_row , city FROM GroupData GROUP BY city " let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil) while((results?.next()) == true){ print(results!.string(forColumn: "city")!) if results!.string(forColumn: "city")! == "-1" { groupType.append("Unknown") }else{ groupType.append(results!.string(forColumn: "city")!) } groupCount.append(results!.string(forColumn: "Num_row")!) } tableView.reloadData() contactDB?.close() } else { print("Error: \(contactDB?.lastErrorMessage())") } } /*func saveData(){ let databasePath = NSUserDefaults.standardUserDefaults().URLForKey("DataBasePath")! let contactDB = FMDatabase(path: String(databasePath)) if contactDB.open() { let querySQL = "DELETE FROM GroupData " _ = contactDB!.executeUpdate(querySQL, withArgumentsInArray: nil) for i in 0 ..< data.count { var info = data[i].componentsSeparatedByString("|") var city = "-1" if info[6] != "" && info[6] != " "{ city = info[6] } let insertSQL = "INSERT INTO GroupData (name,number,flag,address,UID,bloodGroup,city,profession,Date) VALUES ('\(info[0])', '\(info[1])','\(info[2])', '\(info[3])', '\(info[4])','\(info[5])', '\(city)', '\(info[7])', '\(info[8])')" let result = contactDB.executeUpdate(insertSQL , withArgumentsInArray: nil) if !result { print("Error: \(contactDB.lastErrorMessage())") } } } else { print("Error: \(contactDB.lastErrorMessage())") } }*/ /* // 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. } */ }
19ad154793490871906c0d582ad8d645
38.288372
247
0.611696
false
false
false
false
artyom-stv/TextInputKit
refs/heads/develop
TextInputKit/TextInputKit/Code/TextInputFormat/TextInputFormat+TransformValue.swift
mit
1
// // TextInputFormat+TransformValue.swift // TextInputKit // // Created by Artem Starosvetskiy on 27/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Foundation public extension TextInputFormat { typealias DirectValueTransform<Result> = (Value) throws -> Result typealias ReverseValueTransform<Result> = (Result) -> Value /// Creates a `TextInputFormat` which transforms the values produced by the source serializer /// (the serializer of the callee format). /// /// - Parameters: /// - directTransform: The transformation from a source value to a resulting value. /// - reverseTransform: The transformation from a resulting value to a source value. /// - Returns: The created `TextInputFormatter`. func transformValue<Result>( direct directTransform: @escaping DirectValueTransform<Result>, reverse reverseTransform: @escaping ReverseValueTransform<Result>) -> TextInputFormat<Result> { return TextInputFormat.from( serializer.map(direct: directTransform, reverse: reverseTransform), formatter) } } public extension TextInputFormat { typealias NonThrowingDirectValueTransform<Result> = (Value) -> Result? /// Creates a `TextInputFormat` which transforms the values produced by the source serializer /// (the serializer of the callee format). /// /// - Parameters: /// - directTransform: The transformation from a source value to a resulting value. /// - reverseTransform: The transformation from a resulting value to a source value. /// - Returns: The created `TextInputFormatter`. func transformValue<Result>( direct nonThrowingDirectTransform: @escaping NonThrowingDirectValueTransform<Result>, reverse reverseTransform: @escaping ReverseValueTransform<Result>) -> TextInputFormat<Result> { let directTransform: DirectValueTransform<Result> = { value in guard let result = nonThrowingDirectTransform(value) else { throw TextInputKitError.unknown } return result } return TextInputFormat.from( serializer.map(direct: directTransform, reverse: reverseTransform), formatter) } }
fa53fd60516161f602ecf6e899c46e6e
36.442623
103
0.695271
false
false
false
false
slavapestov/swift
refs/heads/master
test/1_stdlib/Reflection_objc.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir %t // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/a.out // RUN: %S/timeout.sh 360 %target-run %t/a.out %S/Inputs/shuffle.jpg | FileCheck %s // REQUIRES: executable_test // FIXME: timeout wrapper is necessary because the ASan test runs for hours // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // // XFAIL: linux import Swift import Foundation #if os(OSX) import AppKit typealias OSImage = NSImage typealias OSColor = NSColor typealias OSBezierPath = NSBezierPath #endif #if os(iOS) || os(tvOS) || os(watchOS) import UIKit typealias OSImage = UIImage typealias OSColor = UIColor typealias OSBezierPath = UIBezierPath #endif // Check ObjC mirror implementation. // CHECK-LABEL: ObjC: print("ObjC:") // CHECK-NEXT: <NSObject: {{0x[0-9a-f]+}}> dump(NSObject()) // CHECK-LABEL: ObjC subclass: print("ObjC subclass:") // CHECK-NEXT: woozle wuzzle dump("woozle wuzzle" as NSString) // Test a mixed Swift-ObjC hierarchy. class NSGood : NSObject { let x: Int = 22 } class NSBetter : NSGood { let y: String = "333" } // CHECK-LABEL: Swift ObjC subclass: // CHECK-NEXT: <Reflection.NSBetter: {{0x[0-9a-f]+}}> #0 // CHECK-NEXT: super: Reflection.NSGood // CHECK-NEXT: super: NSObject print("Swift ObjC subclass:") dump(NSBetter()) // CHECK-LABEL: ObjC quick look objects: print("ObjC quick look objects:") // CHECK-LABEL: ObjC enums: print("ObjC enums:") // CHECK-NEXT: We cannot reflect NSComparisonResult yet print("We cannot reflect \(NSComparisonResult.OrderedAscending) yet") // Don't crash when introspecting framework types such as NSURL. // <rdar://problem/16592777> // CHECK-LABEL: NSURL: // CHECK-NEXT: file:///Volumes/ // CHECK-NEXT: - super: NSObject print("NSURL:") dump(NSURL(fileURLWithPath: "/Volumes", isDirectory: true)) // -- Check that quick look Cocoa objects get binned correctly to their // associated enum tag. // CHECK-NEXT: got the expected quick look text switch PlaygroundQuickLook(reflecting: "woozle wuzzle" as NSString) { case .Text("woozle wuzzle"): print("got the expected quick look text") case _: print("got something else") } // CHECK-NEXT: foobar let somesubclassofnsstring = ("foo" + "bar") as NSString switch PlaygroundQuickLook(reflecting: somesubclassofnsstring) { case .Text(let text): print(text) default: print("not the expected quicklook") } // CHECK-NEXT: got the expected quick look attributed string let astr = NSAttributedString(string: "yizzle pizzle") switch PlaygroundQuickLook(reflecting: astr as NSAttributedString) { case .AttributedString(let astr2 as NSAttributedString) where astr === astr2: print("got the expected quick look attributed string") case _: print("got something else") } // CHECK-NEXT: got the expected quick look int switch PlaygroundQuickLook(reflecting: Int.max as NSNumber) { case .Int(+Int64(Int.max)): print("got the expected quick look int") case _: print("got something else") } // CHECK-NEXT: got the expected quick look uint switch PlaygroundQuickLook(reflecting: NSNumber(unsignedLongLong: UInt64.max)) { case .UInt(UInt64.max): print("got the expected quick look uint") case _: print("got something else") } // CHECK-NEXT: got the expected quick look double switch PlaygroundQuickLook(reflecting: 22.5 as NSNumber) { case .Double(22.5): print("got the expected quick look double") case _: print("got something else") } // CHECK-NEXT: got the expected quick look float switch PlaygroundQuickLook(reflecting: Float32(1.25)) { case .Float(1.25): print("got the expected quick look float") case _: print("got something else") } // CHECK-NEXT: got the expected quick look image // CHECK-NEXT: got the expected quick look color // CHECK-NEXT: got the expected quick look bezier path let image = OSImage(contentsOfFile:Process.arguments[1])! switch PlaygroundQuickLook(reflecting: image) { case .Image(let image2 as OSImage) where image === image2: print("got the expected quick look image") case _: print("got something else") } let color = OSColor.blackColor() switch PlaygroundQuickLook(reflecting: color) { case .Color(let color2 as OSColor) where color === color2: print("got the expected quick look color") case _: print("got something else") } let path = OSBezierPath() switch PlaygroundQuickLook(reflecting: path) { case .BezierPath(let path2 as OSBezierPath) where path === path2: print("got the expected quick look bezier path") case _: print("got something else") } // CHECK-LABEL: Reflecting NSArray: // CHECK-NEXT: [ 1 2 3 4 5 ] print("Reflecting NSArray:") let intNSArray : NSArray = [1 as NSNumber,2 as NSNumber,3 as NSNumber,4 as NSNumber,5 as NSNumber] let arrayMirror = Mirror(reflecting: intNSArray) var buffer = "[ " for i in arrayMirror.children { buffer += "\(i.1) " } buffer += "]" print(buffer) // CHECK-LABEL: Reflecting NSSet: // CHECK-NEXT: NSSet reflection working fine print("Reflecting NSSet:") let numset = NSSet(objects: 1,2,3,4) let numsetMirror = Mirror(reflecting: numset) var numsetNumbers = Set<Int>() for i in numsetMirror.children { if let number = i.1 as? Int { numsetNumbers.insert(number) } } if numsetNumbers == Set([1, 2, 3, 4]) { print("NSSet reflection working fine") } else { print("NSSet reflection broken: here are the numbers we got: \(numsetNumbers)") } // CHECK-NEXT: (3.0, 6.0) // CHECK-NEXT: x: 3.0 // CHECK-NEXT: y: 6.0 dump(CGPoint(x: 3,y: 6)) // CHECK-NEXT: (30.0, 60.0) // CHECK-NEXT: width: 30.0 // CHECK-NEXT: height: 60.0 dump(CGSize(width: 30, height: 60)) // CHECK-NEXT: (50.0, 60.0, 100.0, 150.0) // CHECK-NEXT: origin: (50.0, 60.0) // CHECK-NEXT: x: 50.0 // CHECK-NEXT: y: 60.0 // CHECK-NEXT: size: (100.0, 150.0) // CHECK-NEXT: width: 100.0 // CHECK-NEXT: height: 150.0 dump(CGRect(x: 50, y: 60, width: 100, height: 150)) // rdar://problem/18513769 -- Make sure that QuickLookObject lookup correctly // manages memory. @objc class CanaryBase { deinit { print("\(self.dynamicType) overboard") } required init() { } } var CanaryHandle = false class IsDebugQLO : CanaryBase, CustomStringConvertible { @objc var description: String { return "I'm a QLO" } } class HasDebugQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { return IsDebugQLO() } } class HasNumberQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let number = NSNumber(integer: 97210) return number } } class HasAttributedQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSAttributedString(string: "attributed string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } class HasStringQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSString(string: "plain string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } func testQLO<T : CanaryBase>(type: T.Type) { autoreleasepool { _ = PlaygroundQuickLook(reflecting: type.init()) } } testQLO(IsDebugQLO.self) // CHECK-NEXT: IsDebugQLO overboard testQLO(HasDebugQLO.self) // CHECK-NEXT: HasDebugQLO overboard // CHECK-NEXT: IsDebugQLO overboard testQLO(HasNumberQLO.self) // CHECK-NEXT: HasNumberQLO overboard // TODO: tagged numbers are immortal, so we can't reliably check for // cleanup here testQLO(HasAttributedQLO.self) // CHECK-NEXT: HasAttributedQLO overboard // CHECK-NEXT: CanaryBase overboard testQLO(HasStringQLO.self) // CHECK-NEXT: HasStringQLO overboard // CHECK-NEXT: CanaryBase overboard // CHECK-LABEL: and now our song is done print("and now our song is done")
fefaa360f5496388db8b55d41bc6b0d4
26.387543
125
0.70777
false
false
false
false
almazrafi/Metatron
refs/heads/master
Sources/Types/FileStream.swift
mit
1
// // FileStream.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public class FileStream: Stream { // MARK: Instance Properties private var handle: FileHandle? public let filePath: String // MARK: public private(set) var isReadable: Bool public private(set) var isWritable: Bool public var isOpen: Bool { return (self.handle != nil) } // MARK: public var offset: UInt64 { if let handle = self.handle { return handle.offsetInFile } return 0 } public var length: UInt64 { if let handle = self.handle { let offset = handle.offsetInFile let length = handle.seekToEndOfFile() handle.seek(toFileOffset: offset) return length } else { if let attributes = try? FileManager.default.attributesOfItem(atPath: self.filePath) { if let length = attributes[FileAttributeKey.size] as? NSNumber { return length.uint64Value } } return 0 } } public var bufferLength: Int // MARK: Initializers public init(filePath: String) { self.filePath = filePath self.isReadable = false self.isWritable = false self.bufferLength = 1024 } // MARK: Deinitializer deinit { if let handle = self.handle { handle.synchronizeFile() handle.closeFile() } } // MARK: Instance Methods @discardableResult public func openForReading() -> Bool { guard !self.isOpen else { return false } guard let handle = FileHandle(forReadingAtPath: self.filePath) else { return false } self.handle = handle self.isReadable = true self.isWritable = false return true } @discardableResult public func openForUpdating(truncate: Bool) -> Bool { guard !self.isOpen else { return false } if !FileManager.default.fileExists(atPath: self.filePath) { let pathCharacters = [Character](self.filePath.characters) let directoryPath = String(pathCharacters.prefix(pathCharacters.lastIndex(of: "/") ?? 0)) if !directoryPath.isEmpty { try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true) } guard FileManager.default.createFile(atPath: self.filePath, contents: nil) else { return false } } guard let handle = FileHandle(forUpdatingAtPath: self.filePath) else { return false } if truncate { handle.truncateFile(atOffset: 0) } self.handle = handle self.isReadable = true self.isWritable = true return true } @discardableResult public func openForWriting(truncate: Bool) -> Bool { guard !self.isOpen else { return false } if !FileManager.default.fileExists(atPath: self.filePath) { let pathCharacters = [Character](self.filePath.characters) let directoryPath = String(pathCharacters.prefix(pathCharacters.lastIndex(of: "/") ?? 0)) if !directoryPath.isEmpty { try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true) } guard FileManager.default.createFile(atPath: self.filePath, contents: nil) else { return false } } guard let handle = FileHandle(forWritingAtPath: self.filePath) else { return false } if truncate { handle.truncateFile(atOffset: 0) } self.handle = handle self.isReadable = false self.isWritable = true return true } public func synchronize() { if let handle = self.handle { handle.synchronizeFile() } } public func close() { if let handle = self.handle { handle.synchronizeFile() handle.closeFile() self.handle = nil self.isReadable = false self.isWritable = false } } // MARK: @discardableResult public func seek(offset: UInt64) -> Bool { guard let handle = self.handle else { return false } guard offset <= self.length else { return false } handle.seek(toFileOffset: offset) return true } public func read(maxLength: Int) -> [UInt8] { guard self.isReadable && (maxLength > 0) else { return [] } guard let handle = self.handle else { return [] } return [UInt8](handle.readData(ofLength: maxLength)) } @discardableResult public func write(data: [UInt8]) -> Int { guard self.isWritable && (data.count > 0) else { return 0 } guard let handle = self.handle else { return 0 } let offset = handle.offsetInFile let length = min(UInt64.max - offset, UInt64(data.count)) handle.write(Data(data.prefix(Int(length)))) return Int(handle.offsetInFile - offset) } @discardableResult public func truncate(length: UInt64) -> Bool { guard self.isWritable else { return false } guard let handle = self.handle else { return false } guard length < self.length else { return false } let offset = min(handle.offsetInFile, length) handle.truncateFile(atOffset: length) handle.seek(toFileOffset: offset) return true } @discardableResult public func insert(data: [UInt8]) -> Bool { guard self.isReadable && self.isWritable else { return false } guard let handle = self.handle else { return false } guard data.count > 0 else { return true } let maxBufferLength = UInt64(max(self.bufferLength, data.count)) let offset = handle.offsetInFile let length = self.length let shift = UInt64(data.count) var count = length - offset handle.truncateFile(atOffset: length + shift) while count > 0 { let bufferLength = min(count, maxBufferLength) let bufferOffset = offset + count - bufferLength handle.seek(toFileOffset: bufferOffset) let buffer = handle.readData(ofLength: Int(bufferLength)) guard buffer.count == Int(bufferLength) else { handle.seek(toFileOffset: offset) return false } handle.seek(toFileOffset: bufferOffset + shift) handle.write(buffer) count -= bufferLength } handle.seek(toFileOffset: offset) handle.write(Data(data)) return true } @discardableResult public func remove(length: UInt64) -> Bool { guard self.isReadable && self.isWritable else { return false } guard let handle = self.handle else { return false } guard length > 0 else { return true } let maxBufferLength = UInt64(max(self.bufferLength, 1)) let offset = handle.offsetInFile let margin = self.length - offset guard length <= margin else { return false } var count = margin - length while count > 0 { let bufferLength = min(count, maxBufferLength) let bufferOffset = offset + margin - count handle.seek(toFileOffset: bufferOffset) let buffer = handle.readData(ofLength: Int(bufferLength)) guard buffer.count == Int(bufferLength) else { handle.seek(toFileOffset: offset) return false } handle.seek(toFileOffset: bufferOffset - length) handle.write(buffer) count -= bufferLength } handle.truncateFile(atOffset: handle.offsetInFile) handle.seek(toFileOffset: offset) return true } }
6d6f1f557bc556a2a4193b9657d45008
24.349333
114
0.584052
false
false
false
false
csnu17/My-Blognone-apps
refs/heads/master
myblognone/Modules/NewsList/User Interface/WireFrame/NewsListWireFrame.swift
mit
1
// // NewsListWireFrame.swift // myblognone // // Created by Kittisak Phetrungnapha on 12/18/2559. // Copyright © 2559 Kittisak Phetrungnapha. All rights reserved. // import Foundation import UIKit import SafariServices class NewsListWireFrame: NewsListWireFrameProtocol { static let NewsListViewControllerIdentifier = "NewsListViewController" static let StoryboardIdentifier = "NewsList" // MARK: - NewsListWireFrameProtocol class func setNewsListInterface(to window: AnyObject) { let storyboard = UIStoryboard(name: StoryboardIdentifier, bundle: Bundle.main) // Generating module components let view = storyboard.instantiateViewController(withIdentifier: NewsListViewControllerIdentifier) as! NewsListViewController let presenter: NewsListPresenterProtocol & NewsListInteractorOutputProtocol = NewsListPresenter() let interactor: NewsListInteractorInputProtocol = NewsListInteractor() let apiDataManager: NewsListAPIDataManagerInputProtocol = NewsListAPIDataManager() let wireFrame: NewsListWireFrameProtocol = NewsListWireFrame() // Connecting view.presenter = presenter presenter.view = view presenter.wireFrame = wireFrame presenter.interactor = interactor interactor.presenter = presenter interactor.apiDataManager = apiDataManager // set to root navigation controller if let window = window as? UIWindow, let nav = window.rootViewController as? UINavigationController { nav.viewControllers = [view] } } func pushToNewsDetailInterface(news: News, viewController: AnyObject?) { guard let view = viewController as? UIViewController, let url = URL(string: news.link) else { return } let svc = SFSafariViewController(url: url, entersReaderIfAvailable: true) if #available(iOS 10.0, *) { svc.preferredBarTintColor = UIColor(hexString: UIColor.navigationBarBackground) ?? UIColor.defaultNavigationBarColor() svc.preferredControlTintColor = UIColor.white } else { UIApplication.shared.statusBarStyle = .default } view.present(svc, animated: true, completion: nil) } func pushToAboutInterface(fromView view: AnyObject) { AboutWireFrame.presentAboutModule(fromView: view) } }
3708c7c5b05e7febf74a24b838f5de3a
37.746032
132
0.697665
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Controllers/Editorials/EditorialsViewController.swift
mit
1
//// /// EditorialsViewController.swift // class EditorialsViewController: StreamableViewController { override func trackerName() -> String? { return "Editorials" } override func trackerProps() -> [String: Any]? { return nil } override func trackerStreamInfo() -> (String, String?)? { return nil } private var _mockScreen: EditorialsScreenProtocol? var screen: EditorialsScreenProtocol { set(screen) { _mockScreen = screen } get { return fetchScreen(_mockScreen) } } var generator: EditorialsGenerator! typealias Usage = HomeViewController.Usage private let usage: Usage init(usage: Usage) { self.usage = usage super.init(nibName: nil, bundle: nil) title = InterfaceString.Editorials.NavbarTitle generator = EditorialsGenerator( currentUser: currentUser, destination: self ) streamViewController.streamKind = generator.streamKind streamViewController.initialLoadClosure = { [weak self] in self?.loadEditorials() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didSetCurrentUser() { super.didSetCurrentUser() generator.currentUser = currentUser } override func loadView() { let screen = EditorialsScreen(usage: usage) screen.delegate = self if usage == .loggedIn { screen.navigationBar.leftItems = [.burger] } screen.navigationBar.title = "" view = screen viewContainer = screen.streamContainer } override func viewDidLoad() { super.viewDidLoad() streamViewController.showLoadingSpinner() streamViewController.loadInitialPage() } private func updateInsets() { updateInsets(navBar: screen.navigationBar) } override func showNavBars(animated: Bool) { super.showNavBars(animated: animated) positionNavBar( screen.navigationBar, visible: true, withConstraint: screen.navigationBarTopConstraint, animated: animated ) updateInsets() } override func hideNavBars(animated: Bool) { super.hideNavBars(animated: animated) positionNavBar( screen.navigationBar, visible: false, withConstraint: screen.navigationBarTopConstraint, animated: animated ) updateInsets() } } extension EditorialsViewController: EditorialCellResponder { func editorialTapped(cellContent: EditorialCellContent) { guard let jsonable = streamViewController.jsonable(forCell: cellContent.editorialCell), let editorial = jsonable as? Editorial else { return } switch editorial.kind { case .internal: guard let url = editorial.url else { return } postNotification(InternalWebNotification, value: url.absoluteString) case .external, .sponsored: guard let url = editorial.url else { return } postNotification(ExternalWebNotification, value: url.absoluteString) case .post: guard let post = editorial.post else { return } postTapped(post) case .postStream, .invite, .join, .unknown: break } } } extension EditorialsViewController: EditorialPostStreamResponder { func editorialTapped(index: Int, cell: EditorialCell) { guard let jsonable = streamViewController.jsonable(forCell: cell), let editorialPosts = (jsonable as? Editorial)?.posts, let post = editorialPosts.safeValue(index) else { return } postTapped(post) } } extension EditorialsViewController: EditorialToolsResponder { func submitInvite(cell: UICollectionViewCell, emails emailString: String) { guard let jsonable = streamViewController.jsonable(forCell: cell), let editorial = jsonable as? Editorial else { return } editorial.invite = (emails: "", sent: Globals.now) let emails: [String] = emailString.replacingOccurrences(of: "\n", with: ",").split(",").map { $0.trimmed() } InviteService().sendInvitations(emails).ignoreErrors() } func submitJoin(cell: UICollectionViewCell, email: String, username: String, password: String) { guard currentUser == nil else { return } if Validator.hasValidSignUpCredentials(email: email, username: username, password: password, isTermsChecked: true) { UserService().join( email: email, username: username, password: password ) .done { user in Tracker.shared.joinSuccessful() self.appViewController?.showOnboardingScreen(user) } .catch { error in Tracker.shared.joinFailed() self.showJoinViewController( email: email, username: username, password: password ) } } else { showJoinViewController(email: email, username: username, password: password) } } func showJoinViewController(email: String, username: String, password: String) { let vc = JoinViewController(email: email, username: username, password: password) navigationController?.pushViewController(vc, animated: true) } func lovesTapped(post: Post, cell: EditorialPostCell) { streamViewController.postbarController?.toggleLove(cell, post: post, via: "editorial") } func commentTapped(post: Post, cell: EditorialPostCell) { postTapped(post) } func repostTapped(post: Post, cell: EditorialPostCell) { postTapped(post) } func shareTapped(post: Post, cell: EditorialPostCell) { streamViewController.postbarController?.shareButtonTapped(post: post, sourceView: cell) } } extension EditorialsViewController: StreamDestination { var isPagingEnabled: Bool { get { return streamViewController.isPagingEnabled } set { streamViewController.isPagingEnabled = newValue } } func loadEditorials() { streamViewController.isPagingEnabled = false generator.load() } func replacePlaceholder( type: StreamCellType.PlaceholderType, items: [StreamCellItem], completion: @escaping Block ) { if type == .pageHeader, let pageHeader = items.compactMap({ $0.jsonable as? PageHeader }).first, let trackingPostToken = pageHeader.postToken { let trackViews: ElloAPI = .promotionalViews(tokens: [trackingPostToken]) ElloProvider.shared.request(trackViews).ignoreErrors() } streamViewController.replacePlaceholder(type: type, items: items) { if self.streamViewController.hasCellItems(for: .pageHeader) && !self.streamViewController.hasCellItems(for: .editorials) { self.streamViewController.replacePlaceholder( type: .editorials, items: [StreamCellItem(type: .streamLoading)] ) } completion() } if type == .editorials { streamViewController.doneLoading() } else { streamViewController.hideLoadingSpinner() } } func setPlaceholders(items: [StreamCellItem]) { streamViewController.clearForInitialLoad(newItems: items) } func setPrimary(jsonable: Model) { } func setPagingConfig(responseConfig: ResponseConfig) { streamViewController.responseConfig = responseConfig } func primaryModelNotFound() { self.showGenericLoadFailure() self.streamViewController.doneLoading() } } extension EditorialsViewController: EditorialsScreenDelegate { func scrollToTop() { streamViewController.scrollToTop(animated: true) } }
b11ec215885e5b363687b9cb101e7110
30.910853
122
0.622616
false
false
false
false
ProcedureKit/ProcedureKit
refs/heads/development
Sources/ProcedureKitNetwork/NetworkSupport.swift
mit
2
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // #if SWIFT_PACKAGE import ProcedureKit import Foundation #endif // MARK: - URLSession public protocol URLSessionTaskProtocol { func resume() func cancel() } public protocol NetworkDataTask: URLSessionTaskProtocol { } public protocol NetworkDownloadTask: URLSessionTaskProtocol { } public protocol NetworkUploadTask: URLSessionTaskProtocol { } public protocol NetworkSession { func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> NetworkDataTask func downloadTask(with request: URLRequest, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> NetworkDownloadTask func uploadTask(with request: URLRequest, from bodyData: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> NetworkUploadTask } extension URLSessionTask: URLSessionTaskProtocol { } extension URLSessionDataTask: NetworkDataTask {} extension URLSessionDownloadTask: NetworkDownloadTask { } extension URLSessionUploadTask: NetworkUploadTask { } extension URLSession: NetworkSession { public func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> NetworkDataTask { let task: URLSessionDataTask = dataTask(with: request, completionHandler: completionHandler) return task } public func downloadTask(with request: URLRequest, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> NetworkDownloadTask { let task: URLSessionDownloadTask = downloadTask(with: request, completionHandler: completionHandler) return task } public func uploadTask(with request: URLRequest, from bodyData: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> NetworkUploadTask { let task: URLSessionUploadTask = uploadTask(with: request, from: bodyData, completionHandler: completionHandler) return task } } extension URL: ExpressibleByStringLiteral { public init(unicodeScalarLiteral value: String) { self.init(string: value)! } public init(extendedGraphemeClusterLiteral value: String) { self.init(string: value)! } public init(stringLiteral value: String) { self.init(string: value)! } } // MARK: - Input & Output wrapper types public protocol HTTPPayloadResponseProtocol: Equatable { associatedtype Payload: Equatable var payload: Payload? { get } var response: HTTPURLResponse { get } } public struct HTTPPayloadResponse<Payload: Equatable>: HTTPPayloadResponseProtocol { public var payload: Payload? public var response: HTTPURLResponse public init(payload: Payload, response: HTTPURLResponse) { self.payload = payload self.response = response } } public struct HTTPPayloadRequest<Payload: Equatable>: Equatable { public var request: URLRequest public var payload: Payload? public init(payload: Payload? = nil, request: URLRequest) { self.payload = payload self.request = request } } // MARK: - Error Handling public struct ProcedureKitNetworkError: Error { public let underlyingError: Error public var errorCode: Int { return (underlyingError as NSError).code } public var isTransientError: Bool { switch errorCode { case NSURLErrorNetworkConnectionLost: return true default: return false } } public var isTimeoutError: Bool { guard let procedureKitError = underlyingError as? ProcedureKitError else { return false } guard case .timedOut(with: _) = procedureKitError.context else { return false } return true } var waitForReachabilityChangeBeforeRetrying: Bool { switch errorCode { case NSURLErrorNotConnectedToInternet, NSURLErrorInternationalRoamingOff, NSURLErrorCallIsActive, NSURLErrorDataNotAllowed: return true default: return false } } init(error: Error) { self.underlyingError = error } } public struct ProcedureKitNetworkResponse { public let response: HTTPURLResponse? public let error: ProcedureKitNetworkError? public var httpStatusCode: HTTPStatusCode? { return response?.code } public init(response: HTTPURLResponse? = nil, error: Error? = nil) { self.response = response self.error = error.map { ProcedureKitNetworkError(error: $0) } } } public protocol NetworkOperation { var error: Error? { get } var urlResponse: HTTPURLResponse? { get } } public enum HTTPStatusCode: Int, CustomStringConvertible { case `continue` = 100 case switchingProtocols = 101 case processing = 102 case checkpoint = 103 case ok = 200 case created = 201 case accepted = 202 case nonAuthoritativeInformation = 203 case noContent = 204 case resetContent = 205 case partialContent = 206 case multiStatus = 207 case alreadyReported = 208 case imUsed = 226 case multipleChoices = 300 case movedPermenantly = 301 case found = 302 case seeOther = 303 case notModified = 304 case useProxy = 305 case temporaryRedirect = 307 case permanentRedirect = 308 case badRequest = 400 case unauthorized = 401 case paymentRequired = 402 case forbidden = 403 case notFound = 404 case methodNotAllowed = 405 case notAcceptable = 406 case proxyAuthenticationRequired = 407 case requestTimeout = 408 case conflict = 409 case gone = 410 case lengthRequired = 411 case preconditionFailed = 412 case payloadTooLarge = 413 case uriTooLong = 414 case unsupportedMediaType = 415 case rangeNotSatisfiable = 416 case expectationFailed = 417 case imATeapot = 418 case misdirectedRequest = 421 case unprocesssableEntity = 422 case locked = 423 case failedDependency = 424 case urpgradeRequired = 426 case preconditionRequired = 428 case tooManyRequests = 429 case requestHeadersFieldTooLarge = 431 case iisLoginTimeout = 440 case nginxNoResponse = 444 case iisRetryWith = 449 case blockedByWindowsParentalControls = 450 case unavailableForLegalReasons = 451 case nginxSSLCertificateError = 495 case nginxHTTPToHTTPS = 497 case tokenExpired = 498 case nginxClientClosedRequest = 499 case internalServerError = 500 case notImplemented = 501 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeout = 504 case httpVersionNotSupported = 505 case variantAlsoNegotiates = 506 case insufficientStorage = 507 case loopDetected = 508 case bandwidthLimitExceeded = 509 case notExtended = 510 case networkAuthenticationRequired = 511 case siteIsFrozen = 530 public var isInformational: Bool { switch rawValue { case 100..<200: return true default: return false } } public var isSuccess: Bool { switch rawValue { case 200..<300: return true default: return false } } public var isRedirection: Bool { switch rawValue { case 300..<400: return true default: return false } } public var isClientError: Bool { switch rawValue { case 400..<500: return true default: return false } } public var isServerError: Bool { switch rawValue { case 500..<600: return true default: return false } } public var localizedReason: String { return HTTPURLResponse.localizedString(forStatusCode: rawValue) } public var description: String { return "\(rawValue) \(localizedReason)" } } // MARK: - Extensions public extension HTTPURLResponse { var code: HTTPStatusCode? { return HTTPStatusCode(rawValue: statusCode) } } public extension NetworkOperation { func makeNetworkResponse() -> ProcedureKitNetworkResponse { return ProcedureKitNetworkResponse(response: urlResponse, error: error) } } extension NetworkOperation where Self: OutputProcedure, Self.Output: HTTPPayloadResponseProtocol { public var urlResponse: HTTPURLResponse? { return output.success?.response } }
e66d8e65bfd64ff25fb1ec0dbd03a7f8
26.844884
165
0.692426
false
false
false
false
kzaher/RxFeedback
refs/heads/master
Examples/Examples/Todo+UI.swift
mit
1
// // Todo+UI.swift // RxFeedback // // Created by Krunoslav Zaher on 5/11/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxFeedback fileprivate enum Row { case task(Version<Task>) case new } class TodoViewController: UIViewController { @IBOutlet weak var tableView: UITableView? @IBOutlet weak var editDone: UIBarButtonItem? private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // this dependency would be ideally injected in some way let synchronize: (Task) -> Single<SyncState> = { task in return Single<SyncState>.create { single in let state: SingleEvent<SyncState> = arc4random_uniform(3) != 0 ? .success(.success) : .failure(SystemError("")) single(state) return Disposables.create() } .delaySubscription(.milliseconds(Int.random(in: 50...2000)), scheduler: MainScheduler.instance) } let tasks = [ Task.create(title: "Write RxSwift", date: Date()), Task.create(title: "Give a lecture", date: Date()), Task.create(title: "Enjoy", date: Date()), Task.create(title: "Let's stop at Enjoy", date: Date()), ] + (1 ... 10).map { Task.create(title: "Task \($0)", date: Date()) } Todo.system( initialState: Todo.for(tasks: tasks), ui: bindings, synchronizeTask: synchronize) .drive() .disposed(by: disposeBag) self.tableView!.rx.setDelegate(self) .disposed(by: disposeBag) } } extension TodoViewController { var bindings: Todo.Feedback { let bindCell: (Int, Row, UITableViewCell) -> () = { index, element, cell in cell.textLabel?.attributedText = element.title cell.detailTextLabel?.attributedText = element.detail } let promptForTask = UIAlertController.prompt(message: "Please enter task name", title: "Adding task", actions: [AlertAction.ok, AlertAction.cancel], parent: self) { controller in controller.addTextField(configurationHandler: nil) } .flatMapLatest { (controller, action) -> Observable<Todo.Event> in guard case .ok = action else { return Observable.empty() } let task = Version(Task.create(title: controller.textFields?.first?.text ?? "", date: Date())) return Observable.just(Todo.Event.created(task)) } let tableView = self.tableView! let editDone = self.editDone! return bind { state in let tasks = state.map { [Row.new] + ($0.unfinishedTasks + $0.completedTasks).map(Row.task) } let editing = state.map { $0.isEditing } let editButtonTitle = editing.map { $0 ? "Done" : "Edit" } let subscriptions = [ tasks.drive(tableView.rx.items(cellIdentifier: "Cell"))(bindCell), editing.drive(tableView.rx.isEditing), editButtonTitle.drive(editDone.rx.title) ] let events = [ editDone.rx.tap.asSignal().map { _ in Todo.Event.toggleEditingMode }, tableView.rx.modelSelected(Row.self).asSignal() .flatMapLatest { row in row.selectedEvent(prompt: promptForTask) }, tableView.rx.itemDeleted.asSignal() .flatMapLatest { (try! tableView.rx.model(at: $0) as Row).deletedEvent }, tableView.rx.itemInserted.asSignal() .flatMapLatest { _ in return promptForTask.asSignal(onErrorSignalWith: Signal.empty()) } ] return Bindings(subscriptions: subscriptions, events: events) } } } extension TodoViewController: UITableViewDelegate { internal func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { let row: Row = try! tableView.rx.model(at: indexPath) return row.editingStyle } } extension Version where Value == Task { var syncTitle: NSAttributedString { return NSAttributedString(string: { switch self.state { case .failed: return "🔥" case .success: return "✔️" case .syncing: return "↻" } }()) } var title: NSAttributedString { return [self.value.title, " ", self.value.isCompleted ? " ✅" : ""].joinedAttributed(separator: "") } var detail: NSAttributedString { return [self.syncTitle,].joinedAttributed(separator: "") } } extension Row { var editingStyle: UITableViewCell.EditingStyle { switch self { case .new: return .insert case .task: return .delete } } var title: NSAttributedString { switch self { case .new: return "New".attributedString case .task(let task): return task.title } } var detail: NSAttributedString { switch self { case .new: return "".attributedString case .task(let task): return task.detail } } func selectedEvent(prompt: Observable<Todo.Event>) -> Signal<Todo.Event> { switch self { case .new: return prompt.asSignal(onErrorSignalWith: Signal.empty()) case .task(let task): return Signal.just(Todo.Event.toggleCompleted(task)) } } var deletedEvent: Signal<Todo.Event> { get { switch self { case .new: return Signal.empty() case .task(let task): return Signal.just(Todo.Event.archive(task)) } } } }
c15e86c76413dd5632553219dde3ca10
33.97619
186
0.581688
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/GroundStation/GroundStation_Paginator.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 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. import SotoCore // MARK: Paginators extension GroundStation { /// Returns a list of Config objects. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listConfigsPaginator<Result>( _ input: ListConfigsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListConfigsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listConfigs, tokenKey: \ListConfigsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listConfigsPaginator( _ input: ListConfigsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListConfigsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listConfigs, tokenKey: \ListConfigsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of contacts. If statusList contains AVAILABLE, the request must include groundStation, missionprofileArn, and satelliteArn. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listContactsPaginator<Result>( _ input: ListContactsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListContactsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listContacts, tokenKey: \ListContactsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listContactsPaginator( _ input: ListContactsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListContactsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listContacts, tokenKey: \ListContactsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of DataflowEndpoint groups. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDataflowEndpointGroupsPaginator<Result>( _ input: ListDataflowEndpointGroupsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDataflowEndpointGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDataflowEndpointGroups, tokenKey: \ListDataflowEndpointGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDataflowEndpointGroupsPaginator( _ input: ListDataflowEndpointGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDataflowEndpointGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDataflowEndpointGroups, tokenKey: \ListDataflowEndpointGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of ground stations. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listGroundStationsPaginator<Result>( _ input: ListGroundStationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListGroundStationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listGroundStations, tokenKey: \ListGroundStationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listGroundStationsPaginator( _ input: ListGroundStationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListGroundStationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroundStations, tokenKey: \ListGroundStationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of mission profiles. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listMissionProfilesPaginator<Result>( _ input: ListMissionProfilesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListMissionProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listMissionProfiles, tokenKey: \ListMissionProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listMissionProfilesPaginator( _ input: ListMissionProfilesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListMissionProfilesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMissionProfiles, tokenKey: \ListMissionProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of satellites. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSatellitesPaginator<Result>( _ input: ListSatellitesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSatellitesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSatellites, tokenKey: \ListSatellitesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSatellitesPaginator( _ input: ListSatellitesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSatellitesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSatellites, tokenKey: \ListSatellitesResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension GroundStation.ListConfigsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListConfigsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension GroundStation.ListContactsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListContactsRequest { return .init( endTime: self.endTime, groundStation: self.groundStation, maxResults: self.maxResults, missionProfileArn: self.missionProfileArn, nextToken: token, satelliteArn: self.satelliteArn, startTime: self.startTime, statusList: self.statusList ) } } extension GroundStation.ListDataflowEndpointGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListDataflowEndpointGroupsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension GroundStation.ListGroundStationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListGroundStationsRequest { return .init( maxResults: self.maxResults, nextToken: token, satelliteId: self.satelliteId ) } } extension GroundStation.ListMissionProfilesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListMissionProfilesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension GroundStation.ListSatellitesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> GroundStation.ListSatellitesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } }
099f44e4a5eae9ed0075ddecd8becf5b
41.590206
168
0.642602
false
false
false
false
TurfDb/Turf
refs/heads/master
Turf/Extensions/SecondaryIndex/ObservableCollection+IndexedCollection.swift
mit
1
// extension ObservableCollection where TCollection: IndexedCollection { //TODO Threading // MARK: Public methods /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. */ public func values(where clause: WhereClause) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { return self.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func values(where clause: WhereClause, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { var previous: [TCollection.Value] = [] return self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) previous = newValues return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. */ public func indexableValues(where clause: WhereClause) -> IndexableObservable<[TCollection.Value]> { return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) }) } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func indexableValues(where clause: WhereClause, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> { var previous: [TCollection.Value] = [] let observable = self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) -> [TCollection.Value] in let newValues = collection.findValues(where: clause) previous = newValues return newValues } return IndexableObservable(observable: observable) } // MARK: Prepared query /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. */ public func values(where clause: PreparedValuesWhereQuery<Collections>) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { return self.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func values(where clause: PreparedValuesWhereQuery<Collections>, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { var previous: [TCollection.Value] = [] return self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) previous = newValues return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. */ public func indexableValues(where clause: PreparedValuesWhereQuery<Collections>) -> IndexableObservable<[TCollection.Value]> { return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) }) } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter where: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func indexableValues(where clause: PreparedValuesWhereQuery<Collections>, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> { var previous: [TCollection.Value] = [] let observable = self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) -> [TCollection.Value] in let newValues = collection.findValues(where: clause) previous = newValues return newValues } return IndexableObservable(observable: observable) } // MARK: Raw SQL query /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter matchingRawSql: Secondary indexed query to execute on collection change. */ public func values(matchingRawSql clause: String) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { return self.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter matchingRawSql: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func values(matchingRawSql clause: String, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> { var previous: [TCollection.Value] = [] return self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) in let newValues = collection.findValues(where: clause) previous = newValues return TransactionalValue(transaction: collection.readTransaction, value: newValues) } } /** Observe the values returned by `predicate` after every collection change. - note: - Thread safe. - parameter matchingRawSql: Secondary indexed query to execute on collection change. */ public func indexableValues(matchingRawSql clause: String) -> IndexableObservable<[TCollection.Value]> { return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) }) } /** Observe the values returned by `predicate` after a collection change. If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`. - note: - Thread safe. - parameter matchingRawSql: Secondary indexed query to execute on collection change. - parameter prefilter: Executed before querying the collection to determine if the query is required. */ public func indexableValues(matchingRawSql clause: String, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> { var previous: [TCollection.Value] = [] let observable = self.filterChangeSet { (changeSet) -> Bool in return prefilter(changeSet, previous) }.map { (collection, changeSet) -> [TCollection.Value] in let newValues = collection.findValues(where: clause) previous = newValues return newValues } return IndexableObservable(observable: observable) } }
60c8f61df3a2580d9bd0578407345c2d
47.339901
247
0.677367
false
false
false
false
JGiola/swift
refs/heads/main
test/Distributed/Inputs/BadDistributedActorSystems.swift
apache-2.0
9
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Distributed // ==== Fake Address ----------------------------------------------------------- public struct ActorAddress: Hashable, Sendable, Codable { public let address: String public init(parse address: String) { self.address = address } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.address = try container.decode(String.self) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.address) } } // ==== Fake Systems ----------------------------------------------------------- public struct MissingRemoteCallVoidActorSystem: DistributedActorSystem { public typealias ActorID = ActorAddress public typealias InvocationDecoder = FakeInvocationDecoder public typealias InvocationEncoder = FakeInvocationEncoder public typealias SerializationRequirement = Codable // just so that the struct does not become "trivial" let someValue: String = "" let someValue2: String = "" let someValue3: String = "" let someValue4: String = "" init() { print("Initialized new FakeActorSystem") } public func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act? where Act: DistributedActor, Act.ID == ActorID { nil } public func assignID<Act>(_ actorType: Act.Type) -> ActorID where Act: DistributedActor, Act.ID == ActorID { ActorAddress(parse: "xxx") } public func actorReady<Act>(_ actor: Act) where Act: DistributedActor, Act.ID == ActorID { } public func resignID(_ id: ActorID) { } public func makeInvocationEncoder() -> InvocationEncoder { .init() } public func remoteCall<Act, Err, Res>( on actor: Act, target: RemoteCallTarget, invocation invocationEncoder: inout InvocationEncoder, throwing: Err.Type, returning: Res.Type ) async throws -> Res where Act: DistributedActor, Act.ID == ActorID, Err: Error, Res: SerializationRequirement { throw ExecuteDistributedTargetError(message: "\(#function) not implemented.") } // func remoteCallVoid<Act, Err>( // on actor: Act, // target: RemoteCallTarget, // invocation invocationEncoder: inout InvocationEncoder, // throwing: Err.Type // ) async throws // where Act: DistributedActor, // Act.ID == ActorID, // Err: Error { // throw ExecuteDistributedTargetError(message: "\(#function) not implemented.") // } } // ==== Fake Roundtrip Transport ----------------------------------------------- // TODO(distributed): not thread safe... public final class FakeRoundtripActorSystem: DistributedActorSystem, @unchecked Sendable { public typealias ActorID = ActorAddress public typealias InvocationEncoder = FakeInvocationEncoder public typealias InvocationDecoder = FakeInvocationDecoder public typealias SerializationRequirement = Codable var activeActors: [ActorID: any DistributedActor] = [:] public init() {} public func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act? where Act: DistributedActor { print("| resolve \(id) as remote // this system always resolves as remote") return nil } public func assignID<Act>(_ actorType: Act.Type) -> ActorID where Act: DistributedActor { let id = ActorAddress(parse: "<unique-id>") print("| assign id: \(id) for \(actorType)") return id } public func actorReady<Act>(_ actor: Act) where Act: DistributedActor, Act.ID == ActorID { print("| actor ready: \(actor)") self.activeActors[actor.id] = actor } public func resignID(_ id: ActorID) { print("X resign id: \(id)") } public func makeInvocationEncoder() -> InvocationEncoder { .init() } private var remoteCallResult: Any? = nil private var remoteCallError: Error? = nil public func remoteCall<Act, Err, Res>( on actor: Act, target: RemoteCallTarget, invocation: inout InvocationEncoder, throwing errorType: Err.Type, returning returnType: Res.Type ) async throws -> Res where Act: DistributedActor, Act.ID == ActorID, Err: Error, Res: SerializationRequirement { print(" >> remoteCall: on:\(actor), target:\(target), invocation:\(invocation), throwing:\(String(reflecting: errorType)), returning:\(String(reflecting: returnType))") guard let targetActor = activeActors[actor.id] else { fatalError("Attempted to call mock 'roundtrip' on: \(actor.id) without active actor") } func doIt<A: DistributedActor>(active: A) async throws -> Res { guard (actor.id) == active.id as! ActorID else { fatalError("Attempted to call mock 'roundtrip' on unknown actor: \(actor.id), known: \(active.id)") } let resultHandler = FakeRoundtripResultHandler { value in self.remoteCallResult = value self.remoteCallError = nil } onError: { error in self.remoteCallResult = nil self.remoteCallError = error } try await executeDistributedTarget( on: active, target: target, invocationDecoder: invocation.makeDecoder(), handler: resultHandler ) switch (remoteCallResult, remoteCallError) { case (.some(let value), nil): print(" << remoteCall return: \(value)") return remoteCallResult! as! Res case (nil, .some(let error)): print(" << remoteCall throw: \(error)") throw error default: fatalError("No reply!") } } return try await _openExistential(targetActor, do: doIt) } public func remoteCallVoid<Act, Err>( on actor: Act, target: RemoteCallTarget, invocation: inout InvocationEncoder, throwing errorType: Err.Type ) async throws where Act: DistributedActor, Act.ID == ActorID, Err: Error { print(" >> remoteCallVoid: on:\(actor), target:\(target), invocation:\(invocation), throwing:\(String(reflecting: errorType))") guard let targetActor = activeActors[actor.id] else { fatalError("Attempted to call mock 'roundtrip' on: \(actor.id) without active actor") } func doIt<A: DistributedActor>(active: A) async throws { guard (actor.id) == active.id as! ActorID else { fatalError("Attempted to call mock 'roundtrip' on unknown actor: \(actor.id), known: \(active.id)") } let resultHandler = FakeRoundtripResultHandler { value in self.remoteCallResult = value self.remoteCallError = nil } onError: { error in self.remoteCallResult = nil self.remoteCallError = error } try await executeDistributedTarget( on: active, target: target, invocationDecoder: invocation.makeDecoder(), handler: resultHandler ) switch (remoteCallResult, remoteCallError) { case (.some, nil): return case (nil, .some(let error)): print(" << remoteCall throw: \(error)") throw error default: fatalError("No reply!") } } try await _openExistential(targetActor, do: doIt) } } public struct FakeInvocationEncoder : DistributedTargetInvocationEncoder { public typealias SerializationRequirement = Codable var genericSubs: [Any.Type] = [] var arguments: [Any] = [] var returnType: Any.Type? = nil var errorType: Any.Type? = nil public mutating func recordGenericSubstitution<T>(_ type: T.Type) throws { print(" > encode generic sub: \(String(reflecting: type))") genericSubs.append(type) } public mutating func recordArgument<Value: SerializationRequirement>(_ argument: RemoteCallArgument<Value>) throws { print(" > encode argument name:\(argument.effectiveLabel), argument: \(argument.value)") arguments.append(argument) } public mutating func recordErrorType<E: Error>(_ type: E.Type) throws { print(" > encode error type: \(String(reflecting: type))") self.errorType = type } public mutating func recordReturnType<R: SerializationRequirement>(_ type: R.Type) throws { print(" > encode return type: \(String(reflecting: type))") self.returnType = type } public mutating func doneRecording() throws { print(" > done recording") } public func makeDecoder() -> FakeInvocationDecoder { return .init( args: arguments, substitutions: genericSubs, returnType: returnType, errorType: errorType ) } } // === decoding -------------------------------------------------------------- public class FakeInvocationDecoder : DistributedTargetInvocationDecoder { public typealias SerializationRequirement = Codable var genericSubs: [Any.Type] = [] var arguments: [Any] = [] var returnType: Any.Type? = nil var errorType: Any.Type? = nil var argumentIndex: Int = 0 fileprivate init( args: [Any], substitutions: [Any.Type] = [], returnType: Any.Type? = nil, errorType: Any.Type? = nil ) { self.arguments = args self.genericSubs = substitutions self.returnType = returnType self.errorType = errorType } public func decodeGenericSubstitutions() throws -> [Any.Type] { print(" > decode generic subs: \(genericSubs)") return genericSubs } public func decodeNextArgument<Argument: SerializationRequirement>() throws -> Argument { guard argumentIndex < arguments.count else { fatalError("Attempted to decode more arguments than stored! Index: \(argumentIndex), args: \(arguments)") } let anyArgument = arguments[argumentIndex] guard let argument = anyArgument as? Argument else { fatalError("Cannot cast argument\(anyArgument) to expected \(Argument.self)") } print(" > decode argument: \(argument)") argumentIndex += 1 return argument } public func decodeErrorType() throws -> Any.Type? { print(" > decode return type: \(errorType.map { String(describing: $0) } ?? "nil")") return self.errorType } public func decodeReturnType() throws -> Any.Type? { print(" > decode return type: \(returnType.map { String(describing: $0) } ?? "nil")") return self.returnType } } @available(SwiftStdlib 5.5, *) public struct FakeRoundtripResultHandler: DistributedTargetInvocationResultHandler { public typealias SerializationRequirement = Codable let storeReturn: (any Any) -> Void let storeError: (any Error) -> Void init(_ storeReturn: @escaping (Any) -> Void, onError storeError: @escaping (Error) -> Void) { self.storeReturn = storeReturn self.storeError = storeError } // FIXME(distributed): can we return void here? public func onReturn<Success: SerializationRequirement>(value: Success) async throws { print(" << onReturn: \(value)") storeReturn(value) } public func onThrow<Err: Error>(error: Err) async throws { print(" << onThrow: \(error)") storeError(error) } } // ==== Helpers ---------------------------------------------------------------- @_silgen_name("swift_distributed_actor_is_remote") func __isRemoteActor(_ actor: AnyObject) -> Bool
44471484c5e0de7c7c30834213ad5062
30.784153
173
0.644632
false
false
false
false
xuzhuoxi/SearchKit
refs/heads/master
Source/cs/cacheconfig/CacheInfo.swift
mit
1
// // CacheInfo.swift // SearchKit // // Created by 许灼溪 on 15/12/18. // // import Foundation /** * 缓存信息 * * @author xuzhuoxi * */ public struct CacheInfo { /** * cache名称 */ public let cacheName : String /** * 缓存实例的反射信息 */ public let cacheReflectionInfo: ReflectionInfo /** * 是否为单例<br> * 是:实例化后加入到缓存池中。{@link CachePool}<br> * 否:实例化后不加入到缓存池中。<br> */ public let isSingleton : Bool /** * 哈希表初始容量 */ public let initialCapacity : UInt /** * 缓存初始化时使用资源的路径 多个资源可使用""相隔 */ public let resourceURLs : [URL]? /** * 字符文件编码类型,如UTF-8等 */ public let charsetName : String? /** * 资源的值实例的反射信息 */ public let valueCodingReflectionInfo: ReflectionInfo? /** * @return 是否需要资源作为初始化,当resourcePath{@link #resourcePath}无效时返回false。 */ public let isNeedResource : Bool public init(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingType: ValueCodingType?) { self.cacheName = cacheName self.cacheReflectionInfo = ReflectionInfo(className: cacheClassName) self.isSingleton = isSingleton self.initialCapacity = initialCapacity self.resourceURLs = resourceURLs self.charsetName = charsetName self.valueCodingReflectionInfo = nil == valueCodingType ? nil : ReflectionInfo(className: valueCodingType!.associatedClassName) self.isNeedResource = nil != resourceURLs && !resourceURLs!.isEmpty } public init(_ cacheName: String, _ cacheClassName: String, _ isSingleton: Bool, _ initialCapacity: UInt, _ resourceURLs: [URL]?, _ charsetName: String?, valueCodingClassName: String?) { self.cacheName = cacheName self.cacheReflectionInfo = ReflectionInfo(className: cacheClassName) self.isSingleton = isSingleton self.initialCapacity = initialCapacity self.resourceURLs = resourceURLs self.charsetName = charsetName self.valueCodingReflectionInfo = nil == valueCodingClassName ? nil : ReflectionInfo(className: valueCodingClassName!) self.isNeedResource = nil != resourceURLs && !resourceURLs!.isEmpty } public init(cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, valueCodingType: ValueCodingType?) { self.init(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, "UTF-8", valueCodingType: valueCodingType) } public init(cacheName: String, reflectClassName: String, isSingleton: Bool, initialCapacity: UInt, resourceURLs: [URL]?, valueCodingClassName: String?) { self.init(cacheName, reflectClassName, isSingleton, initialCapacity, resourceURLs, "UTF-8", valueCodingClassName: valueCodingClassName) } }
ddd78a093fc8c2d27f2cad2102a15b56
32.05618
194
0.667233
false
false
false
false
tectijuana/patrones
refs/heads/master
Bloque1SwiftArchivado/PracticasSwift/Guerrero Martinez Daniel/Practicas1.swift
gpl-3.0
2
/* Guerrero Martinez Daniel 13211399 */ /* Patrones de diseño */ /* Imprimir una tabla de valores para y = a^(x) */ /* Declaración de variables */ var x = 1.0 var a = 2.0 print("\tx\t|\ta\t|\ty = a^(x)\t") print("----------------------------------------------------") /* Ciclo while que realiza la tabla */ while x <= 15 { /* Calcular el valor de y */ var y = pow(a,x) /* Imprime los resultados */ print("\t\(x)\t|\t\(a)\t|\t\(y)\t") /* Suma al valor de x una unidad */ x = x + 1 }
8d5b4a15052fe61a04628978ef306332
11.333333
61
0.49323
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/TextKit/ImageAttachment.swift
gpl-2.0
2
import Foundation import UIKit /// Custom text attachment. /// open class ImageAttachment: MediaAttachment { /// Attachment Alignment /// open var alignment: Alignment? { willSet { if newValue != alignment { glyphImage = nil } } } /// Attachment Size /// open var size: Size = .none { willSet { if newValue != size { glyphImage = nil } } } /// Creates a new attachment /// /// - Parameters: /// - identifier: An unique identifier for the attachment /// - url: the url that represents the image /// required public init(identifier: String, url: URL? = nil) { super.init(identifier: identifier, url: url) } /// Required Initializer /// required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if aDecoder.containsValue(forKey: EncodeKeys.alignment.rawValue) { let alignmentRaw = aDecoder.decodeInteger(forKey: EncodeKeys.alignment.rawValue) if let alignment = Alignment(rawValue:alignmentRaw) { self.alignment = alignment } } if aDecoder.containsValue(forKey: EncodeKeys.size.rawValue) { let sizeRaw = aDecoder.decodeInteger(forKey: EncodeKeys.size.rawValue) if let size = Size(rawValue:sizeRaw) { self.size = size } } } /// Required Initializer /// required public init(data contentData: Data?, ofType uti: String?) { super.init(data: contentData, ofType: uti) } // MARK: - NSCoder Support override open func encode(with aCoder: NSCoder) { super.encode(with: aCoder) if let alignmentValue = alignment?.rawValue { aCoder.encode(alignmentValue, forKey: EncodeKeys.alignment.rawValue) } aCoder.encode(size.rawValue, forKey: EncodeKeys.size.rawValue) } private enum EncodeKeys: String { case alignment case size case caption } // MARK: - Image Metrics /// Returns the x position for the image, for the specified container width. /// override func imagePositionX(for containerWidth: CGFloat) -> CGFloat { let imageWidth = onScreenWidth(for: containerWidth) let alignmentValue = alignment ?? .none switch alignmentValue { case .center: return CGFloat(floor((containerWidth - imageWidth) / 2)) case .right: return CGFloat(floor(containerWidth - imageWidth)) default: return 0 } } /// Returns the Image Width, for the specified container width. /// override func imageWidth(for containerWidth: CGFloat) -> CGFloat { guard let image = image else { return 0 } switch size { case .full, .none: return floor(min(image.size.width, containerWidth)) default: return floor(min(min(image.size.width,size.width), containerWidth)) } } } // MARK: - NSCopying // extension ImageAttachment { override public func copy(with zone: NSZone? = nil) -> Any { guard let clone = super.copy(with: nil) as? ImageAttachment else { fatalError() } clone.size = size clone.alignment = alignment return clone } } // MARL: - Nested Types // extension ImageAttachment { /// Alignment /// public enum Alignment: Int { case none case left case center case right func htmlString() -> String { switch self { case .center: return "aligncenter" case .left: return "alignleft" case .right: return "alignright" case .none: return "alignnone" } } func textAlignment() -> NSTextAlignment { switch self { case .center: return .center case .left: return .left case .right: return .right case .none: return .natural } } private static let mappedValues:[String: Alignment] = [ Alignment.none.htmlString():.none, Alignment.left.htmlString():.left, Alignment.center.htmlString():.center, Alignment.right.htmlString():.right ] public static func fromHTML(string value: String) -> Alignment? { return mappedValues[value] } } /// Size Onscreen! /// public enum Size: Int { case thumbnail case medium case large case full case none var shouldResizeAsset: Bool { return width != Settings.maximum } func htmlString() -> String { switch self { case .thumbnail: return "size-thumbnail" case .medium: return "size-medium" case .large: return "size-large" case .full: return "size-full" case .none: return "" } } private static let mappedValues: [String: Size] = [ Size.thumbnail.htmlString():.thumbnail, Size.medium.htmlString():.medium, Size.large.htmlString():.large, Size.full.htmlString():.full, Size.none.htmlString():.none ] public static func fromHTML(string value: String) -> Size? { return mappedValues[value] } var width: CGFloat { switch self { case .thumbnail: return Settings.thumbnail case .medium: return Settings.medium case .large: return Settings.large case .full: return Settings.maximum case .none: return Settings.maximum } } fileprivate struct Settings { static let thumbnail = CGFloat(135) static let medium = CGFloat(270) static let large = CGFloat(360) static let maximum = CGFloat.greatestFiniteMagnitude } } }
68d1e17b3c4db8fb7da83fc09b66c669
25.427386
92
0.538546
false
false
false
false
not4mj/think
refs/heads/master
Think Golf/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // Think Golf // // Created by Mohsin Jamadar on 15/02/17. // Copyright © 2017 Vogcalgary App Developer. All rights reserved. // import UIKit import CoreData import IQKeyboardManagerSwift @available(iOS 10.0, *) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. application.statusBarStyle = UIStatusBarStyle.lightContent //Enable Keyboard manager IQKeyboardManager.sharedManager().enable = true 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Think_Golf") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
57f23b832d4e97745949d0379fb85c09
47.158416
285
0.686061
false
false
false
false
pcperini/Thrust
refs/heads/master
Thrust/Source/HTTP.swift
mit
1
// // HTTP.swift // Thrust // // Created by Patrick Perini on 8/13/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation // MARK: - Extensions extension Dictionary { /// Returns a representation of the dictionary using percent escapes necessary to convert the key-value pairs into a legal URL string. var urlSerializedString: String { get { var serializedString: String = "" for (key, value) in self { let encodedKey = "\(key)".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) let encodedValue = "\(value)".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) if !serializedString.hasContent { serializedString = "\(encodedKey)=\(encodedValue)" } else { serializedString += "&\(encodedKey)=\(encodedValue)" } } return serializedString } } } class HTTP { // MARK: - Responses struct Response: DebugPrintable { // MARK: - Properties // MARK: Request Information /// The original request URL, with query parameters. var requestURL: NSURL /// The original request body. var requestBody: NSData // MARK: Response Information /// The response's HTTP status code. var status: Int? /// The response's binary data. var data: NSData? /// The response's data as a UTF8-string. var string: String? { return NSString(data: self.data!, encoding: NSUTF8StringEncoding) as String } /// The responses's data as a JSON container. var object: JSONContainer? { return self.string?.jsonObject } var debugDescription: String { return "\(self.requestURL) - \(self.status ?? 0)\n\t\(self.string ?? String())" } } // MARK: - Requests private struct Request { // MARK: Required Properties var url: NSURL var method: Method // MARK: Optional Properties var headers: [String: String]? var params: [String: String]? var payload: JSONContainer? var block: ((Response) -> Void)? // MARK: Request Operations func asyncRequest() { on (Queue.background) { let response: Response = self.syncRequest() on (Queue.main) { self.block?(response) } } } func syncRequest() -> Response { // Setup variables var urlString: String = self.url.absoluteString! let requestBody: NSData = self.payload?.jsonString?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) ?? NSData() // Add parameters if params != nil { urlString += "?\(params!.urlSerializedString)" } // Build request let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)) urlRequest.HTTPMethod = method.toRaw() urlRequest.HTTPBody = requestBody // ... add headers urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") if headers != nil { for (key, value) in headers! { urlRequest.setValue(value, forHTTPHeaderField: key) } } // Build response var urlResponse: NSURLResponse? let responseBody: NSData? = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &urlResponse, error: nil) var response: Response = Response(requestURL: NSURL(string: urlString), requestBody: requestBody, status: nil, data: nil) if let httpURLResponse = urlResponse as? NSHTTPURLResponse { response.data = responseBody response.status = httpURLResponse.statusCode } return response } } struct RequestBatch { // MARK: Properties private var requests: [Request] = [] var requestCount: Int { return self.requests.count } // MARK: Mutators mutating func addGETRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) { self.addRequest(url, method: Method.GET, headers: headers, params: params, payload: nil) } mutating func addPUTRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { self.addRequest(url, method: Method.PUT, headers: headers, params: params, payload: payload) } mutating func addPOSTRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { self.addRequest(url, method: Method.POST, headers: headers, params: params, payload: payload) } mutating func addDELETERequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) { self.addRequest(url, method: Method.DELETE, headers: headers, params: params, payload: nil) } private mutating func addRequest(url: NSURL, method: Method, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { let request: Request = Request(url: url, method: method, headers: headers, params: params, payload: payload, block: nil) var requests: [Request] = self.requests requests.append(request) self.requests = requests } // MARK: Performers mutating func performRequests(block: ([Response]) -> Void) { let requestQueue: Queue = Queue(label: "Thrust.Swift.RequestBatch.performRequests") on (requestQueue) { var responses: [Response] = [] for request: Request in self.requests { let response: Response = request.syncRequest() responses.append(response) } self.requests = [] on (Queue.main) { block(responses) } } } } // MARK: - Methods private enum Method: String { case GET = "GET" case PUT = "PUT" case POST = "POST" case DELETE = "DELETE" } // MARK: - Requests /** Executes an HTTP GET request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func get(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: block) request.asyncRequest() } /** Executes an HTTP GET request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :returns: The HTTP.Response object representing the request's response. */ class func get(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) -> Response { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: nil) return request.syncRequest() } /** Executes an HTTP PUT request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func put(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.PUT, headers: headers, params: params, payload: payload, block: block) request.asyncRequest() } /** Executes an HTTP PUT request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :returns: The HTTP.Response object representing the request's response. */ class func put(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) -> Response { let request: Request = Request(url: url, method: Method.PUT, headers: headers, params: params, payload: payload, block: nil) return request.syncRequest() } /** Executes an HTTP POST request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func post(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.POST, headers: headers, params: params, payload: payload, block: block) request.asyncRequest() } /** Executes an HTTP POST request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :returns: The HTTP.Response object representing the request's response. */ class func post(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) -> Response { let request: Request = Request(url: url, method: Method.POST, headers: headers, params: params, payload: payload, block: nil) return request.syncRequest() } /** Executes an HTTP DELETE request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func delete(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: block) request.asyncRequest() } /** Executes an HTTP DELETE request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :returns: The HTTP.Response object representing the request's response. */ class func delete(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) -> Response { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: nil) return request.syncRequest() } }
1113b649c32638d8ec7143e6a7fc1576
33.787634
162
0.558423
false
false
false
false
jegumhon/URWeatherView
refs/heads/master
URWeatherView/Filter/URWaveWarpFilter.swift
mit
1
// // URWaveWarpFilter.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 8.. // Copyright © 2017년 zigbang. All rights reserved. // import Foundation let URKernelShaderkWaveWarp: String = "URKernelShaderWaveWarp.cikernel.fsh" open class URWaveWarpFilter: URFilter { var roiRatio: CGFloat = 1.0 required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required public init(frame: CGRect, cgImage: CGImage, inputValues: [Any]) { fatalError("init(frame:cgImage:inputValues:) has not been implemented") } required public init(frame: CGRect, imageView: UIImageView, inputValues: [Any]) { fatalError("init(frame:imageView:inputValues:) has not been implemented") } /** Initialize CIFilter with **CGImage** and CIKernel shader params - parameters: - frame: The frame rectangle for the input image, measured in points. - cgImage: Core Image of the input image - inputValues: attributes for CIKernel. The format is like below. [sampler: CISampler, progress: TimeInterval, velocity: Double, wRatio: Double, hRatio: Double] - roiRatio: Rect area ratio of Interest. */ public init(frame: CGRect, cgImage: CGImage, inputValues: [Any], roiRatio: CGFloat = 1.0) { super.init(frame: frame, cgImage: cgImage, inputValues: inputValues) self.roiRatio = roiRatio self.loadCIKernel(from: URKernelShaderkWaveWarp) guard inputValues.count == 5 else { return } self.customAttributes = inputValues self.customAttributes?.append(Double.pi) } /** Initialize CIFilter with **CGImage** and CIKernel shader params - parameters: - frame: The frame rectangle for the input image, measured in points. - imageView: The UIImageView of the input image - inputValues: attributes for CIKernel. The format is like below. [sampler: CISampler, progress: TimeInterval, velocity: Double, wRatio: Double, hRatio: Double] - roiRatio: Rect area ratio of Interest. */ public init(frame: CGRect, imageView: UIImageView, inputValues: [Any], roiRatio: CGFloat = 1.0) { super.init(frame: frame, imageView: imageView, inputValues: inputValues) self.roiRatio = roiRatio self.loadCIKernel(from: URKernelShaderkWaveWarp) guard inputValues.count == 5 else { return } self.customAttributes = inputValues self.customAttributes?.append(Double.pi) } override func applyFilter() -> CIImage { // let inputWidth: CGFloat = self.inputImage!.extent.size.width; // let k: CGFloat = inputWidth / ( 1.0 - 1.0 / UIScreen.main.scale ) // let center: CGFloat = self.inputImage!.extent.origin.x + inputWidth / 2.0; let samplerROI = CGRect(x: 0, y: 0, width: self.inputImage!.extent.width, height: self.inputImage!.extent.height) let ROICallback: (Int32, CGRect) -> CGRect = { (samplerIndex, destination) in if samplerIndex == 1 { return samplerROI } // let destROI: CGRect = self.region(of: destination, center: center, k: k) // return destROI return destination } guard let resultImage: CIImage = self.customKernel?.apply(extent: self.extent, roiCallback: ROICallback, arguments: self.customAttributes!) else { fatalError("Filtered Image merging is failed!!") } return resultImage } }
4c97489e4602a8b6fb698ffc4b1ff984
37.354839
154
0.656013
false
false
false
false
quadro5/swift3_L
refs/heads/master
Swift_api.playground/Pages/Hashable Protocol.xcplaygroundpage/Contents.swift
unlicense
1
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) class MyClass: Hashable { var val: Int = 0 var hashValue: Int { get { return val } } static func ==(left: MyClass, right: MyClass) -> Bool { return left === right } } let class0 = MyClass() let class1 = MyClass() class1.val = 10 let class2 = MyClass() class2.val = 20 var set = Set<MyClass>() set.insert(class0) set.insert(class1) set.insert(class2) //set.forEach { (element) in // print(element, element.hashValue) //} func addSet<T: Hashable>(with elements: [T]) -> Set<T> { var set = Set<T>() elements.forEach { (element) in set.insert(element) } set.forEach { (element) in print("addSet: \(element.hashValue)") } print("\n") return set } let array = addSet(with: [class0, class1, class2, class0, class2])
e41d90a4cd5d20b7cda24c2ffd95422a
14.080645
66
0.580749
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/Expand/Extension/NSString+PinYin.swift
mit
2
// // NSString+PinYin.swift // CWWeChat // // Created by chenwei on 16/6/23. // Copyright © 2016年 chenwei. All rights reserved. // import Foundation import UIKit extension String { // 拼音 var pinYingString: String { let str = NSMutableString(string: self) as CFMutableString CFStringTransform(str, nil, kCFStringTransformToLatin, false) CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false) let string = str as String return string.capitalized.trimWhitespace() } // 首字母 var pinyingInitial: String { let array = self.capitalized.components(separatedBy: " ") var pinYing = "" for temp in array { if temp.characters.count == 0 {continue} let index = temp.index(temp.startIndex, offsetBy: 1) pinYing += temp[..<index] } return pinYing } var fistLetter: String { if self.characters.count == 0 {return self} let index = self.index(self.startIndex, offsetBy: 1) return String(self[..<index]) } }
de543ac8b3a870533f1b6ba00f693ecd
25.452381
77
0.610261
false
false
false
false
yulingtianxia/Spiral
refs/heads/master
Spiral/ShapeReapState.swift
apache-2.0
1
// // ShapeReapState.swift // Spiral // // Created by 杨萧玉 on 15/10/6. // Copyright © 2015年 杨萧玉. All rights reserved. // import GameplayKit class ShapeReapState: ShapeState { override init(scene s: MazeModeScene, entity e: Entity) { super.init(scene: s, entity: e) } // MARK: - GKState Life Cycle override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass == ShapeDefeatedState.self } override func didEnter(from previousState: GKState?) { // Set the shape sprite to its normal appearance, undoing any changes that happened in other states. if let component = entity.component(ofType: SpriteComponent.self) { component.useNormalAppearance() } } override func update(deltaTime seconds: TimeInterval) { // If the shape has reached its target, choose a new target. let position = entity.gridPosition var path = [GKGraphNode]() var nearest = Int.max for shape in scene.shapes { if let aiComponent = shape.component(ofType: IntelligenceComponent.self), let state = aiComponent.stateMachine.currentState , state.isKind(of: ShapeDefeatedState.self) || state.isKind(of: ShapeRespawnState.self) { continue } let expectPath: [GKGraphNode] if let cachePath = scene.pathCache[line_int4(pa: position, pb: shape.gridPosition)] { expectPath = cachePath } else if let sourceNode = scene.map.pathfindingGraph.node(atGridPosition: position), let targetNode = scene.map.pathfindingGraph.node(atGridPosition: shape.gridPosition) { expectPath = scene.map.pathfindingGraph.findPath(from: sourceNode, to: targetNode) scene.pathCache[line_int4(pa: position, pb: shape.gridPosition)] = (expectPath as! [GKGridGraphNode]) if expectPath.count < nearest { path = expectPath nearest = expectPath.count } } } startFollowingPath(path as? [GKGridGraphNode]) } }
3d5ec0d6b414c89395ad31af22d4f168
35.380952
121
0.59075
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/different-ways-to-add-parentheses.swift
mit
1
class Solution { /// - Complexity: /// - Time: O(2 ^ n), n = number of operator in expression. Since, at each operator, we could split the expr there or not. /// - Space: O(m), m = possible result for current expression. func diffWaysToCompute(_ expression: String) -> [Int] { if let num = Int(expression) { return [num] } var result = [Int]() for index in expression.indices { if "+-*".contains(expression[index]) { let left = diffWaysToCompute(String(expression[..<index])) let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex])) if expression[index] == Character("+") { for l in left { for r in right { result.append(l + r) } } } else if expression[index] == Character("-") { for l in left { for r in right { result.append(l - r) } } } else if expression[index] == Character("*") { for l in left { for r in right { result.append(l * r) } } } } } // print(expression, result) return result } } class Solution { /// Recursive solution with memorization. private var memo: [String : [Int]]! func diffWaysToCompute(_ expression: String) -> [Int] { memo = [String : [Int]]() return helper(expression) } private func helper(_ expression: String) -> [Int] { if let ret = self.memo[expression] { return ret } if let num = Int(expression) { return [num] } var result = [Int]() for index in expression.indices { if "+-*".contains(expression[index]) { let left = diffWaysToCompute(String(expression[..<index])) let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex])) if expression[index] == Character("+") { for l in left { for r in right { result.append(l + r) } } } else if expression[index] == Character("-") { for l in left { for r in right { result.append(l - r) } } } else if expression[index] == Character("*") { for l in left { for r in right { result.append(l * r) } } } } } self.memo[expression] = result return result } }
90a62fd0e224e93f39b54634901bc4a8
34.067416
130
0.416854
false
false
false
false
glock45/swiftX
refs/heads/master
Source/http/multipart.swift
bsd-3-clause
1
// // multipart.swift // swiftx // // Copyright © 2016 kolakowski. All rights reserved. // public extension Request { public func parseUrlencodedForm() -> [(String, String)] { guard let contentTypeHeader = headers.filter({ $0.0 == "content-type" }).first?.1 else { return [] } let contentTypeHeaderTokens = contentTypeHeader.components(separatedBy: ";").map { $0.trimmingCharacters(in: .whitespaces) } guard let contentType = contentTypeHeaderTokens.first, contentType == "application/x-www-form-urlencoded" else { return [] } return self.body.split(separator: .ampersand).map { param -> (String, String) in let tokens = param.split(separator: 61) if let name = tokens.first, let value = tokens.last { let nameString = String(bytes: name, encoding: .ascii)?.removingPercentEncoding ?? "" let valueString = tokens.count >= 2 ? (String(bytes: value, encoding: .ascii)?.removingPercentEncoding ?? "") : "" return (nameString.replacingOccurrences(of: "+", with: " "), valueString.replacingOccurrences(of: "+", with: " ")) } return ("","") } } subscript(name: String) -> String? { get { let fields = parseUrlencodedForm() return fields.filter({ $0.0 == name }).first?.1 } set(newValue) { } } }
58b969313bd803463e1fb18901396d13
36.225
132
0.562122
false
false
false
false
lionheart/LionheartExtensions
refs/heads/master
Pod/Classes/TitleButton.swift
apache-2.0
1
// // TitleButton.swift // LionheartExtensions // // Created by Dan Loewenherz on 4/10/18. // import Foundation public protocol TitleButtonThemeProtocol { static var normalColor: UIColor { get } static var highlightedColor: UIColor { get } static var subtitleColor: UIColor { get } } extension TitleButtonThemeProtocol { static var centeredParagraphStyle: NSParagraphStyle { let style = NSMutableParagraphStyle() style.setParagraphStyle(.default) style.alignment = .center return style } static var normalAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: Self.normalColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } static var highlightedAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: Self.highlightedColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } static var subtitleAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: Self.subtitleColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } } public final class TitleButton<T>: UIButton where T: TitleButtonThemeProtocol { public var enableTitleCopy = false public override var canBecomeFirstResponder: Bool { return true } public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return enableTitleCopy && action == #selector(UIApplication.copy(_:)) } public override func copy(_ sender: Any?) { UIPasteboard.general.string = titleLabel?.text } @objc public convenience init() { self.init(frame: .zero) } } // MARK: - CustomButtonType extension TitleButton: CustomButtonType { public func setTitle(title: String) { setTitle(title: title, subtitle: nil) } public func setTitle(title: String, subtitle: String?) { let normalString = NSMutableAttributedString(string: title, attributes: T.normalAttributes) let highlightedString = NSMutableAttributedString(string: title, attributes: T.highlightedAttributes) if let subtitle = subtitle { normalString.append(NSAttributedString(string: "\n" + subtitle, attributes: T.subtitleAttributes)) highlightedString.append(NSAttributedString(string: "\n" + subtitle, attributes: T.subtitleAttributes)) titleLabel?.lineBreakMode = .byWordWrapping } else { titleLabel?.lineBreakMode = .byTruncatingTail } setAttributedTitle(normalString, for: .normal) setAttributedTitle(highlightedString, for: .highlighted) sizeToFit() } public func startAnimating() { fatalError() } public func stopAnimating() { fatalError() } }
a5cd7d0de5aecec68568271ed908bfb2
31.39604
115
0.666565
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/Extensions/UIView+Borders.swift
gpl-2.0
2
extension UIView { @discardableResult func addTopBorder(withColor bgColor: UIColor) -> UIView { let borderView = makeBorderView(withColor: bgColor) NSLayoutConstraint.activate([ borderView.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth), borderView.topAnchor.constraint(equalTo: topAnchor), borderView.centerXAnchor.constraint(equalTo: centerXAnchor), borderView.widthAnchor.constraint(equalTo: widthAnchor) ]) return borderView } @discardableResult func addBottomBorder(withColor bgColor: UIColor) -> UIView { let borderView = makeBorderView(withColor: bgColor) NSLayoutConstraint.activate([ borderView.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth), borderView.bottomAnchor.constraint(equalTo: bottomAnchor), borderView.centerXAnchor.constraint(equalTo: centerXAnchor), borderView.widthAnchor.constraint(equalTo: widthAnchor) ]) return borderView } @discardableResult func addBottomBorder(withColor bgColor: UIColor, leadingMargin: CGFloat) -> UIView { let borderView = makeBorderView(withColor: bgColor) NSLayoutConstraint.activate([ borderView.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth), borderView.bottomAnchor.constraint(equalTo: bottomAnchor), borderView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: leadingMargin), borderView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) return borderView } private func makeBorderView(withColor: UIColor) -> UIView { let borderView = UIView() borderView.backgroundColor = withColor borderView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(borderView) return borderView } } extension CGFloat { static var hairlineBorderWidth: CGFloat { return 1.0 / UIScreen.main.scale } }
9bd412468a57f0037e6d877f9b4119dc
36.6
97
0.692456
false
false
false
false
izeni-team/retrolux
refs/heads/master
RetroluxTests/AfterSerializationDeserializationTests.swift
mit
1
// // AfterSerializationDeserializationTests.swift // Retrolux // // Created by Bryan Henderson on 7/16/17. // Copyright © 2017 Bryan. All rights reserved. // import Foundation import Retrolux import XCTest class AfterSerializationDeserializationTests: XCTestCase { class Test1: Reflection { var test_one = "" } class Test2: Reflection { var test_two = "" } class ResultsResponse<T: Reflection>: Reflection { var results: [T] = [] override func afterDeserialization(remoteData: [String : Any]) throws { results = try Reflector.shared.convert(fromArray: remoteData["results"] as? [[String: Any]] ?? [], to: T.self) as! [T] } override func afterSerialization(remoteData: inout [String: Any]) throws { remoteData["results"] = try Reflector.shared.convertToArray(from: results) } override class func config(_ c: PropertyConfig) { c["results"] = [.ignored] } } func testAfterSerializationAndDeserialization() { let builder = Builder.dry() let request1 = builder.makeRequest(method: .get, endpoint: "", args: ResultsResponse<Test2>(), response: ResultsResponse<Test1>.self) { let data = "{\"results\":[{\"test_one\":\"SUCCESS_1\"}]}".data(using: .utf8)! return ClientResponse(url: $0.2.url!, data: data, headers: [:], status: 200, error: nil) } let body2 = ResultsResponse<Test2>() let test2 = Test2() test2.test_two = "SEND_2" body2.results = [ test2 ] let response1 = request1(body2).perform() XCTAssert(response1.request.httpBody == "{\"results\":[{\"test_two\":\"SEND_2\"}]}".data(using: .utf8)!) XCTAssert(response1.body?.results.first?.test_one == "SUCCESS_1") let request2 = builder.makeRequest(method: .get, endpoint: "", args: ResultsResponse<Test1>(), response: ResultsResponse<Test2>.self) { let data = "{\"results\":[{\"test_two\":\"SUCCESS_2\"}]}".data(using: .utf8)! return ClientResponse(url: $0.2.url!, data: data, headers: [:], status: 200, error: nil) } let body1 = ResultsResponse<Test1>() let test1 = Test1() test1.test_one = "SEND_1" body1.results = [ test1 ] let response2 = request2(body1).perform() XCTAssert(response2.request.httpBody == "{\"results\":[{\"test_one\":\"SEND_1\"}]}".data(using: .utf8)!) XCTAssert(response2.body?.results.first?.test_two == "SUCCESS_2") } }
d9e45414d2dff9abf177af485b6ca0bf
37.231884
143
0.58605
false
true
false
false
MAARK/Charts
refs/heads/master
Pods/Charts/Source/Charts/Utils/ViewPortHandler.swift
apache-2.0
3
// // ViewPortHandler.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// Class that contains information about the charts current viewport settings, including offsets, scale & translation levels, ... @objc(ChartViewPortHandler) open class ViewPortHandler: NSObject { /// matrix used for touch events private var _touchMatrix = CGAffineTransform.identity /// this rectangle defines the area in which graph values can be drawn private var _contentRect = CGRect() private var _chartWidth = CGFloat(0.0) private var _chartHeight = CGFloat(0.0) /// minimum scale value on the y-axis private var _minScaleY = CGFloat(1.0) /// maximum scale value on the y-axis private var _maxScaleY = CGFloat.greatestFiniteMagnitude /// minimum scale value on the x-axis private var _minScaleX = CGFloat(1.0) /// maximum scale value on the x-axis private var _maxScaleX = CGFloat.greatestFiniteMagnitude /// contains the current scale factor of the x-axis private var _scaleX = CGFloat(1.0) /// contains the current scale factor of the y-axis private var _scaleY = CGFloat(1.0) /// current translation (drag distance) on the x-axis private var _transX = CGFloat(0.0) /// current translation (drag distance) on the y-axis private var _transY = CGFloat(0.0) /// offset that allows the chart to be dragged over its bounds on the x-axis private var _transOffsetX = CGFloat(0.0) /// offset that allows the chart to be dragged over its bounds on the x-axis private var _transOffsetY = CGFloat(0.0) /// Constructor - don't forget calling setChartDimens(...) @objc public init(width: CGFloat, height: CGFloat) { super.init() setChartDimens(width: width, height: height) } @objc open func setChartDimens(width: CGFloat, height: CGFloat) { let offsetLeft = self.offsetLeft let offsetTop = self.offsetTop let offsetRight = self.offsetRight let offsetBottom = self.offsetBottom _chartHeight = height _chartWidth = width restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } @objc open var hasChartDimens: Bool { if _chartHeight > 0.0 && _chartWidth > 0.0 { return true } else { return false } } @objc open func restrainViewPort(offsetLeft: CGFloat, offsetTop: CGFloat, offsetRight: CGFloat, offsetBottom: CGFloat) { _contentRect.origin.x = offsetLeft _contentRect.origin.y = offsetTop _contentRect.size.width = _chartWidth - offsetLeft - offsetRight _contentRect.size.height = _chartHeight - offsetBottom - offsetTop } @objc open var offsetLeft: CGFloat { return _contentRect.origin.x } @objc open var offsetRight: CGFloat { return _chartWidth - _contentRect.size.width - _contentRect.origin.x } @objc open var offsetTop: CGFloat { return _contentRect.origin.y } @objc open var offsetBottom: CGFloat { return _chartHeight - _contentRect.size.height - _contentRect.origin.y } @objc open var contentTop: CGFloat { return _contentRect.origin.y } @objc open var contentLeft: CGFloat { return _contentRect.origin.x } @objc open var contentRight: CGFloat { return _contentRect.origin.x + _contentRect.size.width } @objc open var contentBottom: CGFloat { return _contentRect.origin.y + _contentRect.size.height } @objc open var contentWidth: CGFloat { return _contentRect.size.width } @objc open var contentHeight: CGFloat { return _contentRect.size.height } @objc open var contentRect: CGRect { return _contentRect } @objc open var contentCenter: CGPoint { return CGPoint(x: _contentRect.origin.x + _contentRect.size.width / 2.0, y: _contentRect.origin.y + _contentRect.size.height / 2.0) } @objc open var chartHeight: CGFloat { return _chartHeight } @objc open var chartWidth: CGFloat { return _chartWidth } // MARK: - Scaling/Panning etc. /// Zooms by the specified zoom factors. @objc open func zoom(scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform { return _touchMatrix.scaledBy(x: scaleX, y: scaleY) } /// Zooms around the specified center @objc open func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) -> CGAffineTransform { var matrix = _touchMatrix.translatedBy(x: x, y: y) matrix = matrix.scaledBy(x: scaleX, y: scaleY) matrix = matrix.translatedBy(x: -x, y: -y) return matrix } /// Zooms in by 1.4, x and y are the coordinates (in pixels) of the zoom center. @objc open func zoomIn(x: CGFloat, y: CGFloat) -> CGAffineTransform { return zoom(scaleX: 1.4, scaleY: 1.4, x: x, y: y) } /// Zooms out by 0.7, x and y are the coordinates (in pixels) of the zoom center. @objc open func zoomOut(x: CGFloat, y: CGFloat) -> CGAffineTransform { return zoom(scaleX: 0.7, scaleY: 0.7, x: x, y: y) } /// Zooms out to original size. @objc open func resetZoom() -> CGAffineTransform { return zoom(scaleX: 1.0, scaleY: 1.0, x: 0.0, y: 0.0) } /// Sets the scale factor to the specified values. @objc open func setZoom(scaleX: CGFloat, scaleY: CGFloat) -> CGAffineTransform { var matrix = _touchMatrix matrix.a = scaleX matrix.d = scaleY return matrix } /// Sets the scale factor to the specified values. x and y is pivot. @objc open func setZoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) -> CGAffineTransform { var matrix = _touchMatrix matrix.a = 1.0 matrix.d = 1.0 matrix = matrix.translatedBy(x: x, y: y) matrix = matrix.scaledBy(x: scaleX, y: scaleY) matrix = matrix.translatedBy(x: -x, y: -y) return matrix } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. @objc open func fitScreen() -> CGAffineTransform { _minScaleX = 1.0 _minScaleY = 1.0 return CGAffineTransform.identity } /// Translates to the specified point. @objc open func translate(pt: CGPoint) -> CGAffineTransform { let translateX = pt.x - offsetLeft let translateY = pt.y - offsetTop let matrix = _touchMatrix.concatenating(CGAffineTransform(translationX: -translateX, y: -translateY)) return matrix } /// Centers the viewport around the specified position (x-index and y-value) in the chart. /// Centering the viewport outside the bounds of the chart is not possible. /// Makes most sense in combination with the setScaleMinima(...) method. @objc open func centerViewPort(pt: CGPoint, chart: ChartViewBase) { let translateX = pt.x - offsetLeft let translateY = pt.y - offsetTop let matrix = _touchMatrix.concatenating(CGAffineTransform(translationX: -translateX, y: -translateY)) refresh(newMatrix: matrix, chart: chart, invalidate: true) } /// call this method to refresh the graph with a given matrix @objc @discardableResult open func refresh(newMatrix: CGAffineTransform, chart: ChartViewBase, invalidate: Bool) -> CGAffineTransform { _touchMatrix = newMatrix // make sure scale and translation are within their bounds limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) chart.setNeedsDisplay() return _touchMatrix } /// limits the maximum scale and X translation of the given matrix private func limitTransAndScale(matrix: inout CGAffineTransform, content: CGRect?) { // min scale-x is 1 _scaleX = min(max(_minScaleX, matrix.a), _maxScaleX) // min scale-y is 1 _scaleY = min(max(_minScaleY, matrix.d), _maxScaleY) var width: CGFloat = 0.0 var height: CGFloat = 0.0 if content != nil { width = content!.width height = content!.height } let maxTransX = -width * (_scaleX - 1.0) _transX = min(max(matrix.tx, maxTransX - _transOffsetX), _transOffsetX) let maxTransY = height * (_scaleY - 1.0) _transY = max(min(matrix.ty, maxTransY + _transOffsetY), -_transOffsetY) matrix.tx = _transX matrix.a = _scaleX matrix.ty = _transY matrix.d = _scaleY } /// Sets the minimum scale factor for the x-axis @objc open func setMinimumScaleX(_ xScale: CGFloat) { var newValue = xScale if newValue < 1.0 { newValue = 1.0 } _minScaleX = newValue limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } /// Sets the maximum scale factor for the x-axis @objc open func setMaximumScaleX(_ xScale: CGFloat) { var newValue = xScale if newValue == 0.0 { newValue = CGFloat.greatestFiniteMagnitude } _maxScaleX = newValue limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } /// Sets the minimum and maximum scale factors for the x-axis @objc open func setMinMaxScaleX(minScaleX: CGFloat, maxScaleX: CGFloat) { var newMin = minScaleX var newMax = maxScaleX if newMin < 1.0 { newMin = 1.0 } if newMax == 0.0 { newMax = CGFloat.greatestFiniteMagnitude } _minScaleX = newMin _maxScaleX = maxScaleX limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } /// Sets the minimum scale factor for the y-axis @objc open func setMinimumScaleY(_ yScale: CGFloat) { var newValue = yScale if newValue < 1.0 { newValue = 1.0 } _minScaleY = newValue limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } /// Sets the maximum scale factor for the y-axis @objc open func setMaximumScaleY(_ yScale: CGFloat) { var newValue = yScale if newValue == 0.0 { newValue = CGFloat.greatestFiniteMagnitude } _maxScaleY = newValue limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } @objc open func setMinMaxScaleY(minScaleY: CGFloat, maxScaleY: CGFloat) { var minScaleY = minScaleY, maxScaleY = maxScaleY if minScaleY < 1.0 { minScaleY = 1.0 } if maxScaleY == 0.0 { maxScaleY = CGFloat.greatestFiniteMagnitude } _minScaleY = minScaleY _maxScaleY = maxScaleY limitTransAndScale(matrix: &_touchMatrix, content: _contentRect) } @objc open var touchMatrix: CGAffineTransform { return _touchMatrix } // MARK: - Boundaries Check @objc open func isInBoundsX(_ x: CGFloat) -> Bool { return isInBoundsLeft(x) && isInBoundsRight(x) } @objc open func isInBoundsY(_ y: CGFloat) -> Bool { return isInBoundsTop(y) && isInBoundsBottom(y) } @objc open func isInBounds(x: CGFloat, y: CGFloat) -> Bool { return isInBoundsX(x) && isInBoundsY(y) } @objc open func isInBoundsLeft(_ x: CGFloat) -> Bool { return _contentRect.origin.x <= x + 1.0 } @objc open func isInBoundsRight(_ x: CGFloat) -> Bool { let x = floor(x * 100.0) / 100.0 return (_contentRect.origin.x + _contentRect.size.width) >= x - 1.0 } @objc open func isInBoundsTop(_ y: CGFloat) -> Bool { return _contentRect.origin.y <= y } @objc open func isInBoundsBottom(_ y: CGFloat) -> Bool { let normalizedY = floor(y * 100.0) / 100.0 return (_contentRect.origin.y + _contentRect.size.height) >= normalizedY } /// The current x-scale factor @objc open var scaleX: CGFloat { return _scaleX } /// The current y-scale factor @objc open var scaleY: CGFloat { return _scaleY } /// The minimum x-scale factor @objc open var minScaleX: CGFloat { return _minScaleX } /// The minimum y-scale factor @objc open var minScaleY: CGFloat { return _minScaleY } /// The minimum x-scale factor @objc open var maxScaleX: CGFloat { return _maxScaleX } /// The minimum y-scale factor @objc open var maxScaleY: CGFloat { return _maxScaleY } /// The translation (drag / pan) distance on the x-axis @objc open var transX: CGFloat { return _transX } /// The translation (drag / pan) distance on the y-axis @objc open var transY: CGFloat { return _transY } /// if the chart is fully zoomed out, return true @objc open var isFullyZoomedOut: Bool { return isFullyZoomedOutX && isFullyZoomedOutY } /// `true` if the chart is fully zoomed out on it's y-axis (vertical). @objc open var isFullyZoomedOutY: Bool { return !(_scaleY > _minScaleY || _minScaleY > 1.0) } /// `true` if the chart is fully zoomed out on it's x-axis (horizontal). @objc open var isFullyZoomedOutX: Bool { return !(_scaleX > _minScaleX || _minScaleX > 1.0) } /// Set an offset in pixels that allows the user to drag the chart over it's bounds on the x-axis. @objc open func setDragOffsetX(_ offset: CGFloat) { _transOffsetX = offset } /// Set an offset in pixels that allows the user to drag the chart over it's bounds on the y-axis. @objc open func setDragOffsetY(_ offset: CGFloat) { _transOffsetY = offset } /// `true` if both drag offsets (x and y) are zero or smaller. @objc open var hasNoDragOffset: Bool { return _transOffsetX <= 0.0 && _transOffsetY <= 0.0 } /// `true` if the chart is not yet fully zoomed out on the x-axis @objc open var canZoomOutMoreX: Bool { return _scaleX > _minScaleX } /// `true` if the chart is not yet fully zoomed in on the x-axis @objc open var canZoomInMoreX: Bool { return _scaleX < _maxScaleX } /// `true` if the chart is not yet fully zoomed out on the y-axis @objc open var canZoomOutMoreY: Bool { return _scaleY > _minScaleY } /// `true` if the chart is not yet fully zoomed in on the y-axis @objc open var canZoomInMoreY: Bool { return _scaleY < _maxScaleY } }
be8a5352ea720de3f866f95dea6179fc
27.330922
139
0.593604
false
false
false
false
ngquerol/Diurna
refs/heads/master
App/Sources/Views/CommentCellView.swift
mit
1
// // CommentTableCellView.swift // Diurna // // Created by Nicolas Gaulard-Querol on 26/01/2016. // Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved. // import AppKit import HackerNewsAPI class CommentCellView: NSTableCellView { // MARK: Outlets @IBOutlet var replyArrowTextField: ClickableTextField! { didSet { replyArrowTextField.toolTip = "Go to parent comment" } } @IBOutlet var authorTextField: NSTextField! @IBOutlet var opBadgeView: LightColoredBadgeView! { didSet { opBadgeView.toolTip = "Story author" } } @IBOutlet var timeTextField: NSTextField! @IBOutlet var repliesButton: DisclosureButtonView! { didSet { repliesButton.isHidden = true } } @IBOutlet var repliesTextField: NSTextField! { didSet { repliesTextField.isHidden = true } } @IBOutlet var textView: MarkupTextView! @IBOutlet var trailingSpacingConstraint: NSLayoutConstraint! // MARK: Properties override var objectValue: Any? { didSet { guard let comment = objectValue as? Comment else { return } timeTextField.stringValue = comment.time.timeIntervalString timeTextField.toolTip = comment.time.description(with: .autoupdatingCurrent) guard comment.deleted != true else { replyArrowTextField.textColor = .disabledControlTextColor opBadgeView.isHidden = true authorTextField.isEnabled = false authorTextField.stringValue = "[deleted]" authorTextField.textColor = .disabledControlTextColor authorTextField.toolTip = "This comment was deleted" timeTextField.textColor = .disabledControlTextColor textView.attributedStringValue = .empty return } replyArrowTextField.textColor = .secondaryLabelColor authorTextField.textColor = .labelColor timeTextField.textColor = .secondaryLabelColor if let author = comment.by { authorTextField.stringValue = author authorTextField.isEnabled = true authorTextField.toolTip = "See \(author)'s profile" } else { authorTextField.stringValue = "unknown" authorTextField.isEnabled = false authorTextField.toolTip = nil } textView.attributedStringValue = comment.text?.parseMarkup() ?? .empty } } var isExpandable: Bool = false { didSet { repliesButton.isHidden = !isExpandable repliesTextField.isHidden = !isExpandable } } var isExpanded: Bool = false { didSet { repliesButton.isExpanded = isExpandable && isExpanded repliesTextField.isHidden = !isExpandable || isExpanded } } private lazy var userDetailsPopover: NSPopover = { let userDetailsPopoverViewController = UserDetailsPopoverViewController( nibName: .userDetailsPopover, bundle: nil ) let popover = NSPopover() popover.behavior = .transient popover.animates = true popover.delegate = userDetailsPopoverViewController popover.contentViewController = userDetailsPopoverViewController return popover }() // MARK: Actions @IBAction private func toggleReplies(_: NSButton) { let toggleChildren = NSEvent.modifierFlags.contains(.option) isExpanded.toggle() NotificationCenter.default.post( name: .toggleCommentRepliesNotification, object: self, userInfo: [ "toggleChildren": toggleChildren ] ) } @IBAction private func goToParentComment(_: ClickableTextField) { guard let comment = objectValue as? Comment else { return } NotificationCenter.default.post( name: .goToParentCommentNotification, object: self, userInfo: [ "childComment": comment ] ) } @IBAction private func showUserDetailsPopover(_: NSTextField) { guard let user = (objectValue as? Comment)?.by, let userDetailsPopoverViewController = userDetailsPopover.contentViewController as? UserDetailsPopoverViewController else { return } userDetailsPopover.show( relativeTo: authorTextField.bounds, of: authorTextField, preferredEdge: .maxY ) userDetailsPopoverViewController.show(user) } } // MARK: - Notifications extension Notification.Name { static let toggleCommentRepliesNotification = Notification .Name("ToggleCommentRepliesNotification") static let goToParentCommentNotification = Notification.Name("GoToParentCommentNotification") } // MARK: - NSUserInterfaceItemIdentifier extension NSUserInterfaceItemIdentifier { static let commentCell = NSUserInterfaceItemIdentifier("CommentCell") }
7c6650eaa3263b1588d7be2a05d86e6c
28.426966
97
0.622375
false
false
false
false
shajrawi/swift
refs/heads/master
stdlib/public/Platform/Platform.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims import SwiftOverlayShims #if os(Windows) import ucrt #endif #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public var noErr: OSStatus { return 0 } /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. @_fixed_layout public struct DarwinBoolean : ExpressibleByBooleanLiteral { @usableFromInline var _value: UInt8 @_transparent public init(_ value: Bool) { self._value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. @_transparent public var boolValue: Bool { return _value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension DarwinBoolean : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension DarwinBoolean : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension DarwinBoolean : Equatable { @_transparent public static func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool { return lhs.boolValue == rhs.boolValue } } @_transparent public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } @_transparent public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool { return x.boolValue } #endif //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// public var errno : Int32 { get { return _swift_stdlib_getErrno() } set(val) { return _swift_stdlib_setErrno(val) } } //===----------------------------------------------------------------------===// // stdio.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var stdin : UnsafeMutablePointer<FILE> { get { return __stdinp } set { __stdinp = newValue } } public var stdout : UnsafeMutablePointer<FILE> { get { return __stdoutp } set { __stdoutp = newValue } } public var stderr : UnsafeMutablePointer<FILE> { get { return __stderrp } set { __stderrp = newValue } } public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in vdprintf(Int32(fd), format, va_args) } } public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in return vsnprintf(ptr, len, format, va_args) } } #elseif os(Windows) public var stdin: UnsafeMutablePointer<FILE> { return __acrt_iob_func(0) } public var stdout: UnsafeMutablePointer<FILE> { return __acrt_iob_func(1) } public var stderr: UnsafeMutablePointer<FILE> { return __acrt_iob_func(2) } public var STDIN_FILENO: Int32 { return _fileno(stdin) } public var STDOUT_FILENO: Int32 { return _fileno(stdout) } public var STDERR_FILENO: Int32 { return _fileno(stderr) } #endif //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_stdlib_open(path, oflag, 0) } #if os(Windows) public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: Int32 ) -> Int32 { return _swift_stdlib_open(path, oflag, mode) } #else public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_stdlib_open(path, oflag, mode) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_stdlib_openat(fd, path, oflag, 0) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_stdlib_openat(fd, path, oflag, mode) } public func fcntl( _ fd: Int32, _ cmd: Int32 ) -> Int32 { return _swift_stdlib_fcntl(fd, cmd, 0) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ value: Int32 ) -> Int32 { return _swift_stdlib_fcntl(fd, cmd, value) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ ptr: UnsafeMutableRawPointer ) -> Int32 { return _swift_stdlib_fcntlPtr(fd, cmd, ptr) } // !os(Windows) #endif #if os(Windows) public var S_IFMT: Int32 { return Int32(0xf000) } public var S_IFREG: Int32 { return Int32(0x8000) } public var S_IFDIR: Int32 { return Int32(0x4000) } public var S_IFCHR: Int32 { return Int32(0x2000) } public var S_IFIFO: Int32 { return Int32(0x1000) } public var S_IREAD: Int32 { return Int32(0x0100) } public var S_IWRITE: Int32 { return Int32(0x0080) } public var S_IEXEC: Int32 { return Int32(0x0040) } #else public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_IFWHT: mode_t { return mode_t(0o160000) } #endif public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_ISTXT: mode_t { return S_ISVTX } public var S_IREAD: mode_t { return S_IRUSR } public var S_IWRITE: mode_t { return S_IWUSR } public var S_IEXEC: mode_t { return S_IXUSR } #endif #endif //===----------------------------------------------------------------------===// // ioctl.h //===----------------------------------------------------------------------===// #if !os(Windows) public func ioctl( _ fd: CInt, _ request: UInt, _ value: CInt ) -> CInt { return _swift_stdlib_ioctl(fd, request, value) } public func ioctl( _ fd: CInt, _ request: UInt, _ ptr: UnsafeMutableRawPointer ) -> CInt { return _swift_stdlib_ioctlPtr(fd, request, ptr) } public func ioctl( _ fd: CInt, _ request: UInt ) -> CInt { return _swift_stdlib_ioctl(fd, request, 0) } // !os(Windows) #endif //===----------------------------------------------------------------------===// // unistd.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func fork() -> Int32 { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func vfork() -> Int32 { fatalError("unavailable function can't be called") } #endif //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) } #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Haiku) public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Cygwin) public typealias sighandler_t = _sig_func_ptr public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Windows) public var SIG_DFL: _crt_signal_t? { return nil } public var SIG_IGN: _crt_signal_t { return unsafeBitCast(1, to: _crt_signal_t.self) } public var SIG_ERR: _crt_signal_t { return unsafeBitCast(-1, to: _crt_signal_t.self) } #else internal var _ignore = _UnsupportedPlatformError() #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// #if !os(Windows) /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: UnsafeMutablePointer<sem_t>? { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS. return UnsafeMutablePointer<sem_t>(bitPattern: -1) #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) #else _UnsupportedPlatformError() #endif } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32 ) -> UnsafeMutablePointer<sem_t>? { return _stdlib_sem_open2(name, oflag) } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t>? { return _stdlib_sem_open4(name, oflag, mode, value) } #endif //===----------------------------------------------------------------------===// // Misc. //===----------------------------------------------------------------------===// // Some platforms don't have `extern char** environ` imported from C. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _swift_stdlib_getEnviron() } #elseif os(Linux) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return __environ } #endif
4c69ca1afcc3694e825fb4964992db34
27.251781
127
0.588868
false
false
false
false
LiulietLee/BilibiliCD
refs/heads/master
BCD/Supporting Files/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // BCD // // Created by Liuliet.Lee on 17/6/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit import CoreData import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window?.tintColor = UIColor.bilibiliPink let pageController = UIPageControl.appearance() if #available(iOS 13.0, *) { pageController.pageIndicatorTintColor = .secondaryLabel pageController.currentPageIndicatorTintColor = .label pageController.backgroundColor = .systemBackground } else { pageController.pageIndicatorTintColor = .lightGray pageController.currentPageIndicatorTintColor = .black pageController.backgroundColor = .white } UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) application.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print(userInfo) } func applicationDidBecomeActive(_ application: UIApplication) { DispatchQueue.global(qos: .background).async { HistoryManager().importFromCache() } } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. saveContext() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // custom code to handle push while app is in the foreground print("Handle push from foreground\(notification.request.content.userInfo)") let dict = notification.request.content.userInfo["aps"] as! NSDictionary let d = dict["alert"] as! [String : Any] let body = d["body"] as! String let title = d["title"] as! String print("Title:\(title) + body:\(body)") showAlertAppDelegate(title: title, message: body, buttonTitle: "ok") } func showAlertAppDelegate(title: String, message: String, buttonTitle: String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: buttonTitle, style: .default)) window?.rootViewController?.present(alert, animated: false) } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "BCD") container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } } return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch let error as NSError { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. fatalError("Unresolved error \(error), \(error.userInfo)") } } } }
d925a30eb7b84102d1ba09dfb6305233
42.623077
207
0.660025
false
false
false
false
anisimovsergey/lumino-ios
refs/heads/master
Lumino/ColorWheelView.swift
mit
1
// // ColorWheelView.swift // Lumino // // Created by Sergey Anisimov on 18/03/2017. // Copyright © 2017 Sergey Anisimov. All rights reserved. // import UIKit protocol ColorWheelDelegate: class { func HueChanged(_ hue: CGFloat, wheel: ColorWheelView) } class ColorWheelView: UIView, UIGestureRecognizerDelegate { private var colorHue: CGFloat = 0 private var circleCenter: CGPoint = CGPoint.init() private var circleRadius: CGFloat = 0 private var hueCircleLayer: HueCircleLayer! private var hueMarkerLayer: ColorSpotLayer! private var colorSpotLayer: ColorSpotLayer! private var panStarted: Bool = false private var hueTapGestureRecognizer: UITapGestureRecognizer! private var huePanGestureRecognizer: UIPanGestureRecognizer! weak var delegate: ColorWheelDelegate? var hue: CGFloat { get { return colorHue } set { colorHue = newValue setMarkerToHue() } } func setHueAnimated(_ hue: CGFloat) { colorHue = hue moveMarkerToHue() } var spotColor: CGColor { get { return colorSpotLayer.fillColor! } set { colorSpotLayer.fillColor = newValue } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { hueCircleLayer = HueCircleLayer() self.layer.addSublayer(hueCircleLayer) hueMarkerLayer = ColorSpotLayer() self.layer.addSublayer(hueMarkerLayer) colorSpotLayer = ColorSpotLayer() self.layer.addSublayer(colorSpotLayer) hueTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapHue)) self.addGestureRecognizer(hueTapGestureRecognizer) huePanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanHue)) self.addGestureRecognizer(huePanGestureRecognizer) } func isTapOnCircle(_ position: CGPoint) -> Bool { let distanceSquared: CGFloat = (circleCenter.x - position.x) * (circleCenter.x - position.x) + (circleCenter.y - position.y) * (circleCenter.y - position.y) let padRadius = hueMarkerLayer.bounds.width / 2 return (distanceSquared >= (circleRadius - padRadius) * (circleRadius - padRadius)) && (distanceSquared <= (circleRadius + padRadius) * (circleRadius + padRadius)) } func isTapOnMarker(_ position: CGPoint) -> Bool { let distanceSquared: CGFloat = (hueMarkerLayer.position.x - position.x) * (hueMarkerLayer.position.x - position.x) + (hueMarkerLayer.position.y - position.y) * (hueMarkerLayer.position.y - position.y) let padWidth = hueMarkerLayer.bounds.width return (distanceSquared <= padWidth * padWidth) } func setMarkerToHue() { CATransaction.begin() CATransaction.setDisableActions(true) hueMarkerLayer.position = self.getHueMarkerPosition() let color = UIColor(hue: colorHue, saturation: CGFloat(1), brightness: CGFloat(1), alpha: CGFloat(1)) hueMarkerLayer.fillColor = color.cgColor CATransaction.commit() } func moveMarkerToHue() { // Getting the previous position var position: CGPoint = hueMarkerLayer.position if hueMarkerLayer.presentation() != nil { position = (hueMarkerLayer.presentation()?.position)! } // Setting the new position hueMarkerLayer.position = self.getHueMarkerPosition() // Creating the animation path let path: CGMutablePath = CGMutablePath() let oldHue = getHueFrom(position: position) if abs(colorHue - oldHue) < 0.5 { path.addArc(center: circleCenter, radius: CGFloat(circleRadius), startAngle: -oldHue * 2.0 * .pi, endAngle: -colorHue * 2.0 * .pi, clockwise: colorHue > oldHue, transform: .identity) } else { path.addArc(center: circleCenter, radius: CGFloat(circleRadius), startAngle: -oldHue * 2.0 * .pi, endAngle: -colorHue * 2.0 * .pi, clockwise: colorHue < oldHue, transform: .identity) } let animation = CAKeyframeAnimation(keyPath: "position") animation.path = path hueMarkerLayer.removeAllAnimations() hueMarkerLayer.add(animation, forKey: "position") let color = UIColor(hue: colorHue, saturation: CGFloat(1), brightness: CGFloat(1), alpha: CGFloat(1)) hueMarkerLayer.fillColor = color.cgColor } func getHueFrom(position: CGPoint) -> CGFloat { let radians: CGFloat = atan2(circleCenter.y - position.y, position.x - circleCenter.x) var hue = radians / (2.0 * .pi) if hue < 0.0 { hue += 1.0 } return hue } func handlePanHue(_ gestureRecognizer: UIPanGestureRecognizer) { let position: CGPoint = gestureRecognizer.location(in: self) if gestureRecognizer.state == .began { panStarted = isTapOnMarker(position) } if (gestureRecognizer.state == .began || gestureRecognizer.state == .changed) && panStarted { self.hue = getHueFrom(position: position) delegate?.HueChanged(hue, wheel: self) } } func handleTapHue(_ gestureRecognizer: UITapGestureRecognizer) { let position: CGPoint = gestureRecognizer.location(in: self) if isTapOnCircle(position) { setHueAnimated(getHueFrom(position: position)) delegate?.HueChanged(hue, wheel: self) } } func getHueMarkerPosition() -> CGPoint { let radians: CGFloat = colorHue * 2.0 * .pi let x = cos(radians) * circleRadius + circleCenter.x let y = -sin(radians) * circleRadius + circleCenter.y return CGPoint(x: x, y: y) } override func layoutSubviews() { super.layoutSubviews() let markerSize = round(bounds.width / 7) let lineWidth = round(markerSize / 8) circleRadius = (bounds.width - markerSize) / 2.0 circleCenter = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2) hueCircleLayer.frame = self.bounds hueCircleLayer.radius = circleRadius hueCircleLayer.lineWidth = lineWidth hueMarkerLayer.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: markerSize, height: markerSize)) hueMarkerLayer.lineWidth = round(lineWidth / 2) hueMarkerLayer.position = self.getHueMarkerPosition() colorSpotLayer.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: circleRadius * 3/4, height: circleRadius * 3/4)) colorSpotLayer.lineWidth = round(lineWidth / 2) colorSpotLayer.position = CGPoint(x: bounds.width / 2 , y: bounds.height / 2) } }
a78d96af45d4a28dfe9c37a0ab09ae0b
33.910448
194
0.638449
false
false
false
false
VadimPavlov/SMVC
refs/heads/master
PerfectProject/Classes/Flow/LoginFlow.swift
mit
1
// // LoginFlow.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import UIKit class LoginFlow { let session: Session let navigationController: UINavigationController typealias LoginFlowCompletion = (User?) -> Void let completion: LoginFlowCompletion init?(session: Session, completion: @escaping LoginFlowCompletion) { let storyboard = UIStoryboard(name: "Login", bundle: nil) if let initial = storyboard.instantiateInitialViewController() as? UINavigationController { self.session = session self.navigationController = initial self.completion = completion } else { assertionFailure("LoginFlow: Initial view controller ins't UINavigationController") return nil } } } // MARK: - Show extension LoginFlow { func showSignInScreen() { // SignIn is root controller in current NavigationController and already displayed /* View */ guard let view = navigationController.viewControllers.first as? LoginView else { assertionFailure("view is not LoginView"); return } /* Controller */ let actions = LoginController.Actions(signIn: session.network.signin, signUp: session.network.signup) let controller = LoginController(actions: actions) { [unowned self] flow in switch flow { case .signup: self.showSignUpScreen() case .user(let user): self.navigationController.dismiss(animated: true, completion: nil) self.completion(user) } } controller.view = view view.events = ViewEvents.onDidLoad(controller.updateState) view.actions = LoginView.Actions( login: controller.signIn, cancelLogin: controller.cancelLogin ) } func showSignUpScreen() { /* View */ let view = LoginView() //... somehow from storyboard /* Controller */ let actions = LoginController.Actions(signIn: session.network.signin, signUp: session.network.signup) let controller = LoginController(actions: actions) { [unowned self] flow in switch flow { case .signup: self.showSignUpScreen() case .user(let user): self.navigationController.dismiss(animated: true, completion: nil) self.completion(user) } } view.events = ViewEvents.onDidLoad(controller.updateState) view.actions = LoginView.Actions( login: controller.signUp, cancelLogin: controller.cancelLogin ) } }
1ca7bfe6ecd73d1cd801e7a6cee8bba0
31.918605
109
0.605793
false
false
false
false
TOWNTHON/Antonym
refs/heads/master
iOS/Antonym/AppDelegate.swift
mit
1
// // AppDelegate.swift // Antonym // // Created by 広瀬緑 on 2016/10/29. // Copyright © 2016年 midori hirose. All rights reserved. // import UIKit import CoreData @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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Antonym") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
6326b05da316c3af5c9cb37bd91c72e1
48.311828
285
0.685565
false
false
false
false
madoffox/Stretching
refs/heads/master
Stretching/Stretching/TrainingView.swift
mit
1
// // ViewController.swift // Stretching // // Created by Admin on 16.12.16. // Copyright © 2016 Admin. All rights reserved. // import UIKit class TrainingController: UIViewController { @IBOutlet weak var numberOfCicle: UILabel! @IBOutlet weak var numberOfExercise: UILabel! @IBOutlet weak var restLabel: UILabel! @IBOutlet weak var exerciseName: UILabel! @IBOutlet weak var exerciseSeconds: UILabel! @IBOutlet weak var exercisePercents: UILabel! @IBOutlet weak var exerciseProgress: UIProgressView! @IBOutlet weak var exercisePicture: UIImageView! var trainingTitle = "" var startDate:NSDate = NSDate() override func viewDidLoad() { super.viewDidLoad() if(isMonday){ ifItIsMonday() print("it is monday") trainingTitle = "Today was Monday Training" } if(isWednesday){ ifItIsWednesday() print("it is wednesday") trainingTitle = "Today was Wednesday Training" } if(isFriday){ ifItIsFriday() print("it is friday") trainingTitle = "Today was Friday Training" } startDate = NSDate() if(isRandomOrder_constants){ dayTraining.shuffle() } numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)" exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)" exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture numberOfCicle.text = "\(cicleNumber_constants)"+"/"+"\(numberOfCicle_constants)" rest() } @IBAction func endTraining(_ sender: UIButton) { timerTrain.invalidate() addEvent(title: trainingTitle,startDate: startDate,endDate: NSDate()) returnValuesToDefault() print("end training") } @IBAction func previousExercise() { if(exerciseNumber_constants > 0){ timerTrain.invalidate() stopClockTikTak() exerciseNumber_constants -= 1 cicleNumber_constants = 1 print("previous exercise") numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)" exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)" exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture numberOfCicle.text = "1"+"/"+"\(numberOfCicle_constants)" } else { print("no previous exercise") } } @IBAction func nextExericse() { if(exerciseNumber_constants + 1 < UInt8(dayTraining.count)){ if(isRest) { stopClockTikTak() train() return } if(isTraining){ timerTrain.invalidate() stopClockTikTak() exerciseNumber_constants += 1 cicleNumber_constants = 1 print("next exercise") numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)" exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)" exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture numberOfCicle.text = "1"+"/"+"\(numberOfCicle_constants)" } } else { print("no next exercise") } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if(isTraining || isRest){ print("pause") if(timerTrain.isValid){ timerTrain.invalidate() self.view.alpha = 0.5 restLabel.text = "ПАУЗА!" } else{ timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) self.view.alpha = 1 if(isRest){ restLabel.text = "ОТДЫХ!" } if(isTraining){ restLabel.text = "РАБОТАЙ!" } } } } func rest(){ if(exerciseNumber_constants < UInt8(dayTraining.count)) { isRest = true isTraining = false restLabel.text = "ОТДЫХ!" numberOfExercise.text = "\(exerciseNumber_constants+1)"+"/"+"\(dayTraining.count)" exerciseName.text = "\(dayTraining[Int(exerciseNumber_constants)].name)" exercisePicture.image = dayTraining[Int(exerciseNumber_constants)].picture numberOfCicle.text = "\(cicleNumber_constants)"+"/"+"\(numberOfCicle_constants)" timerTrain.invalidate() timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) } } func train() { if(exerciseNumber_constants < UInt8(dayTraining.count)) { isRest = false isTraining = true restLabel.text = "РАБОТАЙ!" timerTrain.invalidate() timerTrain = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) } } func timerAction() { if(isRest){ if(UInt8(seconds.minutes * 60 + seconds.seconds) < restDuration ){ clockTikTak() } else{ stopClockTikTak() print("train") train() } } if(isTraining) { if(UInt8(seconds.minutes * 60 + seconds.seconds) < trainingDuration ){ clockTikTak() } else{ stopClockTikTak() print("rest") cicleNumber_constants += 1 if(cicleNumber_constants % (numberOfCicle_constants+1) == 0){ cicleNumber_constants = 1 exerciseNumber_constants += 1 } rest() } } } func clockTikTak() { seconds.miliseconds += 1 //print(seconds.miliseconds) if(seconds.miliseconds % 100 == 0){ seconds.seconds += 1 seconds.miliseconds = 0 b = true exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)" exercisePercents.text = "\(Int((Double(seconds.seconds) / Double(restDuration))*100))"+"%" exerciseProgress.setProgress(Float(Double(seconds.seconds) / Double(restDuration)), animated: true) } if(seconds.seconds % 60 == 0 && b){ seconds.seconds = 0 seconds.minutes += 1 } if(seconds.seconds < 10){ if(seconds.miliseconds < 10){ exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)" } else { exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":"+"\(seconds.miliseconds)" } } else{ if(seconds.miliseconds < 10){ exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds)" } else { exerciseSeconds.text = "0"+"\(seconds.minutes)"+":"+"\(seconds.seconds)"+":"+"\(seconds.miliseconds)" } } } func stopClockTikTak() { timerTrain.invalidate() b = false seconds.miliseconds = 1 seconds.seconds = 0 seconds.minutes = 0 isRest = false restLabel.text = "РАБОТАЙ!" //sleep(1) exercisePercents.text = "\(Int((Double(seconds.seconds) / Double(restDuration))*100))"+"%" exerciseProgress.setProgress(Float(Double(seconds.seconds) / Double(restDuration)), animated: true) exerciseSeconds.text = "0"+"\(seconds.minutes)"+":0"+"\(seconds.seconds)"+":0"+"\(seconds.miliseconds - 1)" if(exerciseNumber_constants+1 == UInt8(dayTraining.count) && cicleNumber_constants % (numberOfCicle_constants) == 0) { print("end of training") addEvent(title: trainingTitle,startDate: startDate,endDate: NSDate()) returnValuesToDefault() self.show(CongratulationsController(), sender: nil) } } func returnValuesToDefault(){ isMonday = false isWednesday = false isFriday = false numberOfCicle_constants = 5 isRandomOrder_constants = false restDuration = 120 trainingDuration = 120 exerciseNumber_constants = 0 cicleNumber_constants = 1 b = false seconds = (minutes: 0, seconds: 0, miliseconds: 1) isRest = false isTraining = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
6f9433622408f1ec340d4c8dfa8be0cd
28.102041
147
0.504508
false
false
false
false
ProjectDent/ARKit-CoreLocation
refs/heads/develop
ARKit+CoreLocation/NotSupportedViewController.swift
mit
1
// // NotSupportedViewController.swift // ARKit+CoreLocation // // Created by Vihan Bhargava on 9/2/17. // Copyright © 2017 Project Dent. All rights reserved. // import UIKit class NotSupportedViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white let label = UILabel() label.textAlignment = .center label.text = "iOS 11+ required" self.view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true } }
c0780178d8c369f0a51e508fdde8c0a5
25.357143
88
0.695122
false
false
false
false
willrichman/GithubToGo
refs/heads/master
GithubToGo/User.swift
mit
1
// // User.swift // GithubToGo // // Created by William Richman on 10/22/14. // Copyright (c) 2014 Will Richman. All rights reserved. // import Foundation import UIKit class User { var login : String? var avatarURL : String? var avatarImage : UIImage? var publicRepos : String? var privateRepos : String? init (login: String, avatarURL : String) { self.login = login self.avatarURL = avatarURL } class func parseJSONDataIntoUsers(rawJSONData : NSData) -> [User]? { /* Generic error for JSONObject error protocol */ var error : NSError? if let JSONDictionary = NSJSONSerialization.JSONObjectWithData(rawJSONData, options: nil, error: &error) as? NSDictionary { /* Empty array for users */ var users = [User]() if let searchResultsArray = JSONDictionary["items"] as? NSArray { for result in searchResultsArray { if let resultDictionary = result as? NSDictionary { let resultName = resultDictionary["login"] as String let resultURL = resultDictionary["avatar_url"] as String let newUser = User(login: resultName, avatarURL: resultURL) users.append(newUser) } } } return users } return nil } class func parseJSONDataIntoUser(rawJSONData : NSData) -> User? { var error : NSError? if let JSONDictionary = NSJSONSerialization.JSONObjectWithData(rawJSONData, options: nil, error: &error) as? NSDictionary { let resultName = JSONDictionary["login"] as String let resultURL = JSONDictionary["avatar_url"] as String let user = User(login: resultName, avatarURL: resultURL) let publicRepos = JSONDictionary["public_repos"] as? Int user.publicRepos = "\(publicRepos!)" if let privateDictionary = JSONDictionary["plan"] as? NSDictionary { let privateRepos = privateDictionary["private_repos"] as? Int user.privateRepos = "\(privateRepos!)" } else { user.privateRepos = "?" } return user } return nil } }
3832a98be5b7bfe2bee519c725096ec5
33.449275
131
0.568603
false
false
false
false
smac89/UVA_OJ
refs/heads/master
fun-projects/Classic Algorithms/Sieve.swift
mit
2
import Foundation #if os(Linux) import Glibc #endif /** Given a list of booleans all initialized to true, will sieve the list and set all the values to false which are not primes - Parameter primeNet: A reference to a list of booleans all initialized to true */ public func sieveOfEratosthenes(inout primeNet : [Bool]) { for i in 0..<primeNet.count { primeNet[i] = true } // explicitly set 1 to false primeNet[0] = false; primeNet[1] = false for p in 2...Int(sqrt(Double(primeNet.count)) + 1) { if primeNet[p] { for j in (p * p).stride(to: primeNet.count, by: p) { primeNet[j] = false } } } } let mcount = 10000001 var mseive = Array<Bool>(count: mcount, repeatedValue: true) let start = NSDate() sieveOfEratosthenes(&mseive) let end : Double = NSDate().timeIntervalSinceDate(start) var primes: Int = 0 for i in 1..<mcount { if mseive[i] { primes += 1 } } print ("There are \(primes) below \(mcount). This took \(end) seconds")
b3435c3c9c6ae345309c8f7719cdcfae
22.772727
80
0.604779
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
Signal/src/ViewControllers/CameraFirstNavigationController.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit @objc public protocol CameraFirstCaptureDelegate: AnyObject { func cameraFirstCaptureSendFlowDidComplete(_ cameraFirstCaptureSendFlow: CameraFirstCaptureSendFlow) func cameraFirstCaptureSendFlowDidCancel(_ cameraFirstCaptureSendFlow: CameraFirstCaptureSendFlow) } @objc public class CameraFirstCaptureSendFlow: NSObject { @objc public weak var delegate: CameraFirstCaptureDelegate? var approvedAttachments: [SignalAttachment]? var approvalMessageText: String? var selectedConversations: [ConversationItem] = [] // MARK: Dependencies var databaseStorage: SDSDatabaseStorage { return SSKEnvironment.shared.databaseStorage } var broadcastMediaMessageJobQueue: BroadcastMediaMessageJobQueue { return AppEnvironment.shared.broadcastMediaMessageJobQueue } } extension CameraFirstCaptureSendFlow: SendMediaNavDelegate { func sendMediaNavDidCancel(_ sendMediaNavigationController: SendMediaNavigationController) { delegate?.cameraFirstCaptureSendFlowDidCancel(self) } func sendMediaNav(_ sendMediaNavigationController: SendMediaNavigationController, didApproveAttachments attachments: [SignalAttachment], messageText: String?) { self.approvedAttachments = attachments self.approvalMessageText = messageText let pickerVC = ConversationPickerViewController() pickerVC.delegate = self sendMediaNavigationController.pushViewController(pickerVC, animated: true) } func sendMediaNavInitialMessageText(_ sendMediaNavigationController: SendMediaNavigationController) -> String? { return approvalMessageText } func sendMediaNav(_ sendMediaNavigationController: SendMediaNavigationController, didChangeMessageText newMessageText: String?) { self.approvalMessageText = newMessageText } var sendMediaNavApprovalButtonImageName: String { return "arrow-right-24" } var sendMediaNavCanSaveAttachments: Bool { return true } } extension CameraFirstCaptureSendFlow: ConversationPickerDelegate { var selectedConversationsForConversationPicker: [ConversationItem] { return selectedConversations } func conversationPicker(_ conversationPickerViewController: ConversationPickerViewController, didSelectConversation conversation: ConversationItem) { self.selectedConversations.append(conversation) } func conversationPicker(_ conversationPickerViewController: ConversationPickerViewController, didDeselectConversation conversation: ConversationItem) { self.selectedConversations = self.selectedConversations.filter { $0.messageRecipient != conversation.messageRecipient } } func conversationPickerDidCompleteSelection(_ conversationPickerViewController: ConversationPickerViewController) { guard let approvedAttachments = self.approvedAttachments else { owsFailDebug("approvedAttachments was unexpectedly nil") delegate?.cameraFirstCaptureSendFlowDidCancel(self) return } let conversations = selectedConversationsForConversationPicker DispatchQueue.global().async(.promise) { // Duplicate attachments per conversation let conversationAttachments: [(ConversationItem, [SignalAttachment])] = try conversations.map { conversation in return (conversation, try approvedAttachments.map { try $0.cloneAttachment() }) } // We only upload one set of attachments, and then copy the upload details into // each conversation before sending. let attachmentsToUpload: [OutgoingAttachmentInfo] = approvedAttachments.map { attachment in return OutgoingAttachmentInfo(dataSource: attachment.dataSource, contentType: attachment.mimeType, sourceFilename: attachment.filenameOrDefault, caption: attachment.captionText, albumMessageId: nil) } self.databaseStorage.write { transaction in var messages: [TSOutgoingMessage] = [] for (conversation, attachments) in conversationAttachments { let thread: TSThread switch conversation.messageRecipient { case .contact(let address): thread = TSContactThread.getOrCreateThread(withContactAddress: address, transaction: transaction) case .group(let groupThread): thread = groupThread } let message = try! ThreadUtil.createUnsentMessage(withText: self.approvalMessageText, mediaAttachments: attachments, in: thread, quotedReplyModel: nil, linkPreviewDraft: nil, transaction: transaction) messages.append(message) } // map of attachments we'll upload to their copies in each recipient thread var attachmentIdMap: [String: [String]] = [:] let correspondingAttachmentIds = transpose(messages.map { $0.attachmentIds }) for (index, attachmentInfo) in attachmentsToUpload.enumerated() { do { let attachmentToUpload = try attachmentInfo.asStreamConsumingDataSource(withIsVoiceMessage: false) attachmentToUpload.anyInsert(transaction: transaction) attachmentIdMap[attachmentToUpload.uniqueId] = correspondingAttachmentIds[index] } catch { owsFailDebug("error: \(error)") } } self.broadcastMediaMessageJobQueue.add(attachmentIdMap: attachmentIdMap, transaction: transaction) } }.done { _ in self.delegate?.cameraFirstCaptureSendFlowDidComplete(self) }.retainUntilComplete() } }
f7673e256036728f32c2ee51e6b64efa
43.496689
164
0.624498
false
false
false
false
segmentio/analytics-swift
refs/heads/main
Examples/other_plugins/CellularCarrier.swift
mit
1
// // CellularCarrier.swift // // // Created by Brandon Sneed on 4/12/22. // // NOTE: You can see this plugin in use in the SwiftUIKitExample application. // // This plugin is NOT SUPPORTED by Segment. It is here merely as an example, // and for your convenience should you find it useful. // MIT License // // Copyright (c) 2021 Segment // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) && !targetEnvironment(macCatalyst) import Foundation import Segment import CoreTelephony /** An example plugin to retrieve cellular information. This plugin will add all carrier information to the event's context.network object if cellular is currently in use. Example contents: { "home": "T-Mobile", "roaming": "AT&T", "secondary": "Verizon", } */ class CellularCarrier: Plugin { var type: PluginType = .enrichment weak var analytics: Analytics? func execute<T: RawEvent>(event: T?) -> T? { guard var workingEvent = event else { return event } if let isCellular: Bool = workingEvent.context?[keyPath: "network.cellular"], isCellular, let carriers = self.carriers { workingEvent.context?[keyPath: "network.carriers"] = carriers } return workingEvent } // done as a compute-once stored property; your use case may be different. var carriers: [String: String]? = { let info = CTTelephonyNetworkInfo() if let providers = info.serviceSubscriberCellularProviders { var results = [String: String]() for (key, value) in providers { if let carrier = value.carrierName, !carrier.isEmpty { results[key] = value.carrierName } } if !results.isEmpty { return results } } return nil }() } /** An example plugin to retrieve cellular information. This plugin will add primary ("home") carrier information to the event's context.network object if cellular is currently in use. This mimics the operation of the analytics-ios SDK. */ class PrimaryCellularCarrier: Plugin { var type: PluginType = .enrichment var analytics: Analytics? func execute<T: RawEvent>(event: T?) -> T? { guard var workingEvent = event else { return event } if let isCellular: Bool = workingEvent.context?[keyPath: "network"], isCellular, let carrier = self.carrier { workingEvent.context?[keyPath: "network.carriers"] = carrier } return workingEvent } // done as a compute-once stored property; your use case may be different. var carrier: String? = { let info = CTTelephonyNetworkInfo() if let providers = info.serviceSubscriberCellularProviders { let primary = providers["home"] if let carrier = primary?.carrierName, !carrier.isEmpty { return carrier } } return nil }() } #endif
21d33112f94012f35aed0605bec25e64
31.09375
108
0.65482
false
false
false
false
headione/criticalmaps-ios
refs/heads/release/4.0.0
CriticalMapsKit/Sources/ChatFeature/ChatInputView.swift
mit
1
import ComposableArchitecture import L10n import Styleguide import SwiftUI import UIKit public struct BasicInputView: View { private let placeholder: String let store: Store<ChatInputState, ChatInputAction> @ObservedObject var viewStore: ViewStore<ChatInputState, ChatInputAction> @State private var contentSizeThatFits: CGSize = .zero public init( store: Store<ChatInputState, ChatInputAction>, placeholder: String = "" ) { self.store = store self.viewStore = ViewStore(store) self.placeholder = placeholder self._contentSizeThatFits = State(initialValue: .zero) } private var messageEditorHeight: CGFloat { min( self.contentSizeThatFits.height, 0.25 * UIScreen.main.bounds.height ) } private var messageEditorView: some View { MultilineTextField( attributedText: viewStore.binding( get: \.internalAttributedMessage, send: { ChatInputAction.messageChanged($0.string) } ), placeholder: placeholder, isEditing: viewStore.binding( get: \.isEditing, send: ChatInputAction.isEditingChanged ), textAttributes: .chat ) .accessibilityLabel(Text(L10n.A11y.ChatInput.label)) .accessibilityValue(viewStore.message) .onPreferenceChange(ContentSizeThatFitsKey.self) { self.contentSizeThatFits = $0 } .frame(height: self.messageEditorHeight) } private var sendButton: some View { Button(action: { viewStore.send(.onCommit) }, label: { Circle().fill( withAnimation { viewStore.isSendButtonDisabled ? Color(.border) : .blue } ) .accessibleAnimation(.easeOut(duration: 0.13), value: viewStore.isSendButtonDisabled) .accessibilityLabel(Text(L10n.Chat.send)) .frame(width: 38, height: 38) .overlay( Group { if viewStore.state.isSending { ProgressView() } else { Image(systemName: "paperplane.fill") .resizable() .foregroundColor(.white) .offset(x: -1, y: 1) .padding(.grid(2)) } } ) }) .disabled(viewStore.isSendButtonDisabled) } public var body: some View { VStack { HStack(alignment: .bottom) { messageEditorView sendButton } .padding(.grid(1)) .background(Color(.backgroundPrimary)) .clipShape(RoundedRectangle(cornerRadius: 23)) .overlay( RoundedRectangle(cornerRadius: 23) .stroke(Color(.innerBorder), lineWidth: 1) ) } } } // MARK: Implementation Details public struct ContentSizeThatFitsKey: PreferenceKey { public static var defaultValue: CGSize = .zero public static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } internal struct TextAttributesKey: EnvironmentKey { static var defaultValue: TextAttributes = .init() } internal extension EnvironmentValues { var textAttributes: TextAttributes { get { self[TextAttributesKey.self] } set { self[TextAttributesKey.self] = newValue } } } internal struct TextAttributesModifier: ViewModifier { let textAttributes: TextAttributes func body(content: Content) -> some View { content.environment(\.textAttributes, self.textAttributes) } } internal extension View { func textAttributes(_ textAttributes: TextAttributes) -> some View { self.modifier(TextAttributesModifier(textAttributes: textAttributes)) } } // MARK: - MultilineText public struct MultilineTextField: View { @Binding private var attributedText: NSAttributedString @Binding private var isEditing: Bool @State private var contentSizeThatFits: CGSize = .zero private let placeholder: String private let textAttributes: TextAttributes private let onEditingChanged: ((Bool) -> Void)? private let onCommit: (() -> Void)? private var placeholderInset: EdgeInsets { .init(top: 8.0, leading: 8.0, bottom: 8.0, trailing: 8.0) } private var textContainerInset: UIEdgeInsets { .init(top: 8.0, left: 0.0, bottom: 8.0, right: 0.0) } private var lineFragmentPadding: CGFloat { 8.0 } public init ( attributedText: Binding<NSAttributedString>, placeholder: String = "", isEditing: Binding<Bool>, textAttributes: TextAttributes = .init(), onEditingChanged: ((Bool) -> Void)? = nil, onCommit: (() -> Void)? = nil ) { self._attributedText = attributedText self.placeholder = placeholder self._isEditing = isEditing self._contentSizeThatFits = State(initialValue: .zero) self.textAttributes = textAttributes self.onEditingChanged = onEditingChanged self.onCommit = onCommit } public var body: some View { AttributedText( attributedText: $attributedText, isEditing: $isEditing, textAttributes: textAttributes, onEditingChanged: onEditingChanged, onCommit: onCommit ) .onPreferenceChange(ContentSizeThatFitsKey.self) { self.contentSizeThatFits = $0 } .frame(idealHeight: self.contentSizeThatFits.height) .background(placeholderView, alignment: .topLeading) } @ViewBuilder private var placeholderView: some View { if attributedText.length == 0 { Text(placeholder).foregroundColor(.gray) .padding(placeholderInset) } } } // MARK: - AttributedText internal struct AttributedText: View { @Environment(\.textAttributes) var envTextAttributes: TextAttributes @Binding var attributedText: NSAttributedString @Binding var isEditing: Bool @State private var sizeThatFits: CGSize = .zero private let textAttributes: TextAttributes private let onLinkInteraction: (((URL, UITextItemInteraction) -> Bool))? private let onEditingChanged: ((Bool) -> Void)? private let onCommit: (() -> Void)? var body: some View { let textAttributes = self.textAttributes .overriding(self.envTextAttributes) .overriding(TextAttributes.default) return GeometryReader { geometry in return UITextViewWrapper( attributedText: self.$attributedText, isEditing: self.$isEditing, sizeThatFits: self.$sizeThatFits, maxSize: geometry.size, textAttributes: textAttributes, onLinkInteraction: self.onLinkInteraction, onEditingChanged: self.onEditingChanged, onCommit: self.onCommit ) .preference( key: ContentSizeThatFitsKey.self, value: self.sizeThatFits ) } } init( attributedText: Binding<NSAttributedString>, isEditing: Binding<Bool>, textAttributes: TextAttributes = .init(), onLinkInteraction: ((URL, UITextItemInteraction) -> Bool)? = nil, onEditingChanged: ((Bool) -> Void)? = nil, onCommit: (() -> Void)? = nil ) { self._attributedText = attributedText self._isEditing = isEditing self.textAttributes = textAttributes self.onLinkInteraction = onLinkInteraction self.onEditingChanged = onEditingChanged self.onCommit = onCommit } } public struct TextAttributes { var textContainerInset: UIEdgeInsets? var lineFragmentPadding: CGFloat? var returnKeyType: UIReturnKeyType? var textAlignment: NSTextAlignment? var linkTextAttributes: [NSAttributedString.Key: Any] var clearsOnInsertion: Bool? var contentType: UITextContentType? var autocorrectionType: UITextAutocorrectionType? var autocapitalizationType: UITextAutocapitalizationType? var lineLimit: Int? var lineBreakMode: NSLineBreakMode? var isSecure: Bool? var isEditable: Bool? var isSelectable: Bool? var isScrollingEnabled: Bool? public static var chat: Self { .init( textContainerInset: .init(top: 8.0, left: 0.0, bottom: 8.0, right: 0.0), lineFragmentPadding: 8.0, returnKeyType: .none, textAlignment: nil, linkTextAttributes: [:], clearsOnInsertion: false, contentType: .none, autocorrectionType: .no, autocapitalizationType: .some(.none), lineLimit: nil, lineBreakMode: .byWordWrapping, isSecure: false, isEditable: true, isSelectable: true, isScrollingEnabled: true ) } public static var `default`: Self { .init( textContainerInset: .init(top: 8.0, left: 0.0, bottom: 8.0, right: 0.0), lineFragmentPadding: 8.0, returnKeyType: .default, textAlignment: nil, linkTextAttributes: [:], clearsOnInsertion: false, contentType: nil, autocorrectionType: .default, autocapitalizationType: .some(.none), lineLimit: nil, lineBreakMode: .byWordWrapping, isSecure: false, isEditable: true, isSelectable: true, isScrollingEnabled: true ) } public init( textContainerInset: UIEdgeInsets? = nil, lineFragmentPadding: CGFloat? = nil, returnKeyType: UIReturnKeyType? = nil, textAlignment: NSTextAlignment? = nil, linkTextAttributes: [NSAttributedString.Key: Any] = [:], clearsOnInsertion: Bool? = nil, contentType: UITextContentType? = nil, autocorrectionType: UITextAutocorrectionType? = nil, autocapitalizationType: UITextAutocapitalizationType? = nil, lineLimit: Int? = nil, lineBreakMode: NSLineBreakMode? = nil, isSecure: Bool? = nil, isEditable: Bool? = nil, isSelectable: Bool? = nil, isScrollingEnabled: Bool? = nil ) { self.textContainerInset = textContainerInset self.lineFragmentPadding = lineFragmentPadding self.returnKeyType = returnKeyType self.textAlignment = textAlignment self.linkTextAttributes = linkTextAttributes self.clearsOnInsertion = clearsOnInsertion self.contentType = contentType self.autocorrectionType = autocorrectionType self.autocapitalizationType = autocapitalizationType self.lineLimit = lineLimit self.lineBreakMode = lineBreakMode self.isSecure = isSecure self.isEditable = isEditable self.isSelectable = isSelectable self.isScrollingEnabled = isScrollingEnabled } func overriding(_ fallback: Self) -> Self { let textContainerInset: UIEdgeInsets? = self.textContainerInset ?? fallback.textContainerInset let lineFragmentPadding: CGFloat? = self.lineFragmentPadding ?? fallback.lineFragmentPadding let returnKeyType: UIReturnKeyType? = self.returnKeyType ?? fallback.returnKeyType let textAlignment: NSTextAlignment? = self.textAlignment ?? fallback.textAlignment let linkTextAttributes: [NSAttributedString.Key: Any] = self.linkTextAttributes let clearsOnInsertion: Bool? = self.clearsOnInsertion ?? fallback.clearsOnInsertion let contentType: UITextContentType? = self.contentType ?? fallback.contentType let autocorrectionType: UITextAutocorrectionType? = self.autocorrectionType ?? fallback.autocorrectionType let autocapitalizationType: UITextAutocapitalizationType? = self.autocapitalizationType ?? fallback.autocapitalizationType let lineLimit: Int? = self.lineLimit ?? fallback.lineLimit let lineBreakMode: NSLineBreakMode? = self.lineBreakMode ?? fallback.lineBreakMode let isSecure: Bool? = self.isSecure ?? fallback.isSecure let isEditable: Bool? = self.isEditable ?? fallback.isEditable let isSelectable: Bool? = self.isSelectable ?? fallback.isSelectable let isScrollingEnabled: Bool? = self.isScrollingEnabled ?? fallback.isScrollingEnabled return .init( textContainerInset: textContainerInset, lineFragmentPadding: lineFragmentPadding, returnKeyType: returnKeyType, textAlignment: textAlignment, linkTextAttributes: linkTextAttributes, clearsOnInsertion: clearsOnInsertion, contentType: contentType, autocorrectionType: autocorrectionType, autocapitalizationType: autocapitalizationType, lineLimit: lineLimit, lineBreakMode: lineBreakMode, isSecure: isSecure, isEditable: isEditable, isSelectable: isSelectable, isScrollingEnabled: isScrollingEnabled ) } } internal struct UITextViewWrapper: UIViewRepresentable { typealias UIViewType = UITextView @Environment(\.textAttributes) var envTextAttributes: TextAttributes @Binding var attributedText: NSAttributedString @Binding var isEditing: Bool @Binding var sizeThatFits: CGSize private let maxSize: CGSize private let textAttributes: TextAttributes private let onLinkInteraction: (((URL, UITextItemInteraction) -> Bool))? private let onEditingChanged: ((Bool) -> Void)? private let onCommit: (() -> Void)? init( attributedText: Binding<NSAttributedString>, isEditing: Binding<Bool>, sizeThatFits: Binding<CGSize>, maxSize: CGSize, textAttributes: TextAttributes = .init(), onLinkInteraction: ((URL, UITextItemInteraction) -> Bool)? = nil, onEditingChanged: ((Bool) -> Void)? = nil, onCommit: (() -> Void)? = nil ) { self._attributedText = attributedText self._isEditing = isEditing self._sizeThatFits = sizeThatFits self.maxSize = maxSize self.textAttributes = textAttributes self.onLinkInteraction = onLinkInteraction self.onEditingChanged = onEditingChanged self.onCommit = onCommit } // swiftlint:disable:next cyclomatic_complexity func makeUIView(context: Context) -> UITextView { let view = UITextView() view.delegate = context.coordinator view.font = UIFont.preferredFont(forTextStyle: .body) view.textColor = UIColor.label view.backgroundColor = .clear let attrs = self.textAttributes if let textContainerInset = attrs.textContainerInset { view.textContainerInset = textContainerInset } if let lineFragmentPadding = attrs.lineFragmentPadding { view.textContainer.lineFragmentPadding = lineFragmentPadding } if let returnKeyType = attrs.returnKeyType { view.returnKeyType = returnKeyType } if let textAlignment = attrs.textAlignment { view.textAlignment = textAlignment } view.linkTextAttributes = attrs.linkTextAttributes view.linkTextAttributes = attrs.linkTextAttributes if let clearsOnInsertion = attrs.clearsOnInsertion { view.clearsOnInsertion = clearsOnInsertion } if let contentType = attrs.contentType { view.textContentType = contentType } if let autocorrectionType = attrs.autocorrectionType { view.autocorrectionType = autocorrectionType } if let autocapitalizationType = attrs.autocapitalizationType { view.autocapitalizationType = autocapitalizationType } if let isSecure = attrs.isSecure { view.isSecureTextEntry = isSecure } if let isEditable = attrs.isEditable { view.isEditable = isEditable } if let isSelectable = attrs.isSelectable { view.isSelectable = isSelectable } if let isScrollingEnabled = attrs.isScrollingEnabled { view.isScrollEnabled = isScrollingEnabled } if let lineLimit = attrs.lineLimit { view.textContainer.maximumNumberOfLines = lineLimit } if let lineBreakMode = attrs.lineBreakMode { view.textContainer.lineBreakMode = lineBreakMode } view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) return view } func updateUIView(_ uiView: UITextView, context: Context) { uiView.attributedText = attributedText if isEditing { uiView.becomeFirstResponder() } else { uiView.resignFirstResponder() } UITextViewWrapper.recalculateHeight( view: uiView, maxContentSize: self.maxSize, result: $sizeThatFits ) } func makeCoordinator() -> Coordinator { return Coordinator( attributedText: $attributedText, isEditing: $isEditing, sizeThatFits: $sizeThatFits, maxContentSize: { self.maxSize }, onLinkInteraction: onLinkInteraction, onEditingChanged: onEditingChanged, onCommit: onCommit ) } static func recalculateHeight( view: UIView, maxContentSize: CGSize, result: Binding<CGSize> ) { let sizeThatFits = view.sizeThatFits(maxContentSize) if result.wrappedValue != sizeThatFits { DispatchQueue.main.async { // Must be called asynchronously: result.wrappedValue = sizeThatFits } } } final class Coordinator: NSObject, UITextViewDelegate { @Binding var attributedText: NSAttributedString @Binding var isEditing: Bool @Binding var sizeThatFits: CGSize private let maxContentSize: () -> CGSize private var onLinkInteraction: (((URL, UITextItemInteraction) -> Bool))? private var onEditingChanged: ((Bool) -> Void)? private var onCommit: (() -> Void)? init( attributedText: Binding<NSAttributedString>, isEditing: Binding<Bool>, sizeThatFits: Binding<CGSize>, maxContentSize: @escaping () -> CGSize, onLinkInteraction: ((URL, UITextItemInteraction) -> Bool)?, onEditingChanged: ((Bool) -> Void)?, onCommit: (() -> Void)? ) { self._attributedText = attributedText self._isEditing = isEditing self._sizeThatFits = sizeThatFits self.maxContentSize = maxContentSize self.onLinkInteraction = onLinkInteraction self.onEditingChanged = onEditingChanged self.onCommit = onCommit } func textViewDidChange(_ uiView: UITextView) { attributedText = uiView.attributedText onEditingChanged?(true) UITextViewWrapper.recalculateHeight( view: uiView, maxContentSize: maxContentSize(), result: $sizeThatFits ) } func textViewDidBeginEditing(_ textView: UITextView) { DispatchQueue.main.async { guard !self.isEditing else { return } self.isEditing = true } onEditingChanged?(false) } func textViewDidEndEditing(_ textView: UITextView) { DispatchQueue.main.async { guard self.isEditing else { return } self.isEditing = false } onCommit?() } func textView( _ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction ) -> Bool { return onLinkInteraction?(url, interaction) ?? true } func textView( _ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String ) -> Bool { guard let onCommit = self.onCommit, text == "\n" else { return true } textView.resignFirstResponder() onCommit() return false } } } // swiftlint:disable:this file_length
f3aafa6a8dda1a5a412f54ae4bd95dc9
29.542071
126
0.684132
false
false
false
false
instacrate/tapcrate-api
refs/heads/master
Sources/App/Stripe/Models/StripeCupon.swift
mit
2
// // Coupon.swift // Stripe // // Created by Hakon Hanesand on 12/2/16. // // import Node import Foundation public enum Duration: String, NodeConvertible { case forever case once case repeating } public final class StripeCoupon: NodeConvertible { static let type = "coupon" public let id: String public let amount_off: Int? public let created: Date public let currency: String? public let duration: Duration public let duration_in_months: Int? public let livemode: Bool public let max_redemptions: Int public let percent_off: Int public let redeem_by: Date public let times_redeemed: Int public let valid: Bool public init(node: Node) throws { guard try node.extract("object") == StripeCoupon.type else { throw NodeError.unableToConvert(input: node, expectation: StripeCoupon.type, path: ["object"]) } id = try node.extract("id") amount_off = try? node.extract("amount_off") created = try node.extract("created") currency = try? node.extract("currency") duration = try node.extract("duration") duration_in_months = try? node.extract("duration_in_months") livemode = try node.extract("livemode") max_redemptions = try node.extract("max_redemptions") percent_off = try node.extract("percent_off") redeem_by = try node.extract("redeem_by") times_redeemed = try node.extract("times_redeemed") valid = try node.extract("valid") } public func makeNode(in context: Context?) throws -> Node { return try Node(node: [ "id" : .string(id), "created" : .number(.double(created.timeIntervalSince1970)), "duration" : try duration.makeNode(in: context), "livemode" : .bool(livemode), "max_redemptions" : .number(.int(max_redemptions)), "percent_off" : .number(.int(percent_off)), "redeem_by" : .number(.double(redeem_by.timeIntervalSince1970)), "times_redeemed" : .number(.int(times_redeemed)), "valid" : .bool(valid) ] as [String : Node]).add(objects: [ "amount_off" : amount_off, "currency" : currency, "duration_in_months" : duration_in_months ]) } }
2c799bc209462f8c34a85976dd382b9a
31.666667
106
0.606293
false
false
false
false
ustwo/videoplayback-ios
refs/heads/master
DemoVideoPlaybackKit/DemoVideoPlaybackKit/DemoViewController.swift
mit
1
// // ViewController.swift // DemoVideoPlaybackKit // // Created by Sonam on 4/25/17. // Copyright © 2017 ustwo. All rights reserved. // import UIKit import RxSwift import VideoPlaybackKit private enum DemoOption: String { case SingleVideoView, SingleViewViewAutoplay, CustomToolBar, FeedView, FeedAutoplayView } class DemoViewController: UIViewController { private let tableView = UITableView(frame: .zero) private let disposeBag = DisposeBag() private let demoList = Variable([DemoOption.SingleVideoView, DemoOption.SingleViewViewAutoplay, DemoOption.CustomToolBar, DemoOption.FeedView, DemoOption.FeedAutoplayView]) override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(view) } tableView.register(BasicTableViewCell.self, forCellReuseIdentifier: BasicTableViewCell.identifier) tableView.estimatedRowHeight = 300 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none setupDemoList() } private func setupDemoList() { demoList.asObservable().bind(to: tableView.rx.items(cellIdentifier: BasicTableViewCell.identifier)) { index, model, cell in guard let cell = cell as? BasicTableViewCell else { return } cell.titleText = model.rawValue }.addDisposableTo(disposeBag) tableView.rx.modelSelected(DemoOption.self).subscribe(onNext: { demoOption in switch demoOption { case .SingleVideoView: self.navigationController?.pushViewController(SingleVideoPlaybackViewController(), animated: true) case .SingleViewViewAutoplay: self.navigationController?.pushViewController(SingleVideoPlaybackViewController(shouldAutoPlay: true), animated: true) case .FeedView: self.navigationController?.pushViewController(FeedViewController(), animated: true) case .FeedAutoplayView: let feedVC = FeedViewController(true) self.navigationController?.pushViewController(feedVC, animated: true) case .CustomToolBar: let toolBarTheme = ToolBarTheme.custom(bottomBackgroundColor: UIColor.purple, sliderBackgroundColor: UIColor.white, sliderIndicatorColor: UIColor.lightGray, sliderCalloutColors: [.red, .orange, .green]) let singleVC = SingleVideoPlaybackViewController(shouldAutoPlay: false, customTheme: toolBarTheme) self.navigationController?.pushViewController(singleVC, animated: true) } }).addDisposableTo(disposeBag) } }
d5741569874a64933615c60ab179ac7d
38.083333
218
0.689055
false
false
false
false
CoderJackyHuang/ITClient-Swift
refs/heads/master
ITClient-Swift/Controller/Base/RootTabBarController.swift
mit
1
// // RootTabBarController.swift // ITClient-Swift // // Created by huangyibiao on 15/9/24. // Copyright © 2015年 huangyibiao. All rights reserved. // import Foundation import UIKit import HYBViewControllerCategory /// App Entrance /// /// Author: 黄仪标 /// Blog: http://www.hybblog.com/ /// Github: http://github.com/CoderJackyHuang/ /// Email: [email protected] /// Weibo: JackyHuang(标哥) class RootTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.viewControllers = [ nav("首页", image: "tab_home_icon", type: 0), nav("技术", image: "js", type: 1), nav("趣文", image: "qw", type: 2), nav("我的江湖", image: "user", type: 3) ] } private func nav(title: String, image: String, type: Int = 0) ->AppNavigationController { var controller: BaseController switch type { case 0: controller = HomeController() case 1: controller = TechnologyController() case 2: controller = InterestingController() default: controller = ProfileController() } let nav = AppNavigationController(rootViewController: controller) nav.hyb_setTabBarItemWithTitle(title, selectedImage: nil, unSelectedImage: image, imageMode: UIImageRenderingMode.AlwaysOriginal, selectedTextColor: UIColor.blueColor(), unSelectedTextColor: nil) return nav } }
ae4f74874d915d7d2acc688a1771b478
24.357143
91
0.658915
false
false
false
false
apatronl/Rain
refs/heads/master
Rain/PagesViewController.swift
mit
1
// // PagesViewController.swift // Rain // // Created by Alejandrina Patron on 5/26/16. // Copyright © 2016 Ale Patrón. All rights reserved. // import UIKit import CoreLocation class PagesViewController: UIViewController, CLLocationManagerDelegate { var pageMenu: CAPSPageMenu? var todayController: TodayViewController! var hourlyController: HourlyViewController! var dailyController: DailyViewController! let hud = MBProgressHUD() var location: CLLocation! var weather: WeatherData? let locationManager = CLLocationManager() @IBOutlet weak var cityName: UILabel! @IBOutlet weak var temperature: UILabel! @IBOutlet weak var emoji: UILabel! override func viewDidLoad() { // Set up views for page menu var controllerArray : [UIViewController] = [] // Today VC todayController = UIStoryboard(name: "MenuViewController", bundle: nil).instantiateViewController(withIdentifier: "TodayVC") as! TodayViewController todayController.title = "Today" controllerArray.append(todayController) // Hourly VC hourlyController = UIStoryboard(name: "MenuViewController", bundle: nil).instantiateViewController(withIdentifier: "HourlyVC") as! HourlyViewController hourlyController.title = "Hourly" controllerArray.append(hourlyController) // Daily VC dailyController = UIStoryboard(name: "MenuViewController", bundle: nil).instantiateViewController(withIdentifier: "DailyVC") as! DailyViewController dailyController.title = "Daily" controllerArray.append(dailyController) // let topMargin: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height+self.navigationController!.navigationBar.frame.size.height; // Status height is 20 now, check if it changes let topMargin: CGFloat = 20 + self.navigationController!.navigationBar.frame.size.height // Customize pages menu let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor.clear), .viewBackgroundColor(UIColor.clear), .selectionIndicatorColor(UIColor(red: 253.0/255.0, green: 184.0/255.0, blue:19.0/255.0, alpha: 1.0)), .bottomMenuHairlineColor(UIColor.clear), .menuItemFont(UIFont(name: "HelveticaNeue-Light", size: 13.0)!), .menuHeight(40.0), .menuItemWidth(self.view.frame.width / 3.5), .centerMenuItems(true) ] // Initialize page menu with controller array, frame, and optional parameters pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(origin: CGPoint(x: 0,y: topMargin), size: CGSize(width: self.view.frame.width, height: self.view.frame.height - topMargin)), pageMenuOptions: parameters) // Add page menu as subview of base view controller view self.addChildViewController(pageMenu!) self.view.addSubview(pageMenu!.view) pageMenu!.didMove(toParentViewController: self) // Set up activity indicator hud.labelText = "Loading..." hud.labelFont = UIFont(name: "HelveticaNeue-Light", size: 15.0)! hud.dimBackground = true hud.sendSubview(toBack: pageMenu!.view) self.view.addSubview(hud) // Get location locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.requestLocation() hud.show(true) } // MARK: - Location func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { self.location = location self.getForecast() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") // TODO: SHOW ALERT HERE hud.hide(true) } func reverseGeocoding(location: CLLocation) { CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in if let _ = error { self.hud.hide(true) self.weather?.city = "--" } else if (placemarks?.count)! > 0 { let pm = placemarks![0] if let locality = pm.locality { self.weather?.city = locality } } else { self.weather?.city = "--" } self.cityName.text = self.weather?.city }) } // MARK: - Forecast and UI updates func getForecast() { let latitude = String(location.coordinate.latitude) let longitude = String(location.coordinate.longitude) // let units = Settings.getUnits() DarkSkyService.weatherForCoordinates(latitude: latitude, longitude: longitude) { weatherData, error in if let _ = error { // TODO: SHOW ALERT HERE print("Error") } else { self.weather = weatherData self.reverseGeocoding(location: self.location) self.todayController.weather = weatherData?.today self.hourlyController.weather = weatherData?.hourly self.dailyController.weather = weatherData?.daily self.updateForecastUI() } self.hud.hide(true) } } func updateForecastUI() { // Update data common in all pages temperature.text = weather?.temperature emoji.text = weather?.emoji // Update "Today" page todayController.updateUI() } @IBAction func refreshButtonPressed(_ sender: UIBarButtonItem) { hud.show(true) locationManager.requestLocation() // TODO: make sure all 3 pages are updated } } // UGLY code // Alamofire.request(.GET, url + apiKey + "\(latitude),\(longitude)?units=" + units + "&exclude=minutely").validate().responseJSON { response in // switch response.result { // case .Success: // if let value = response.result.value { // let res = JSON(value) // let temperature = String(format: "%.0f", res["currently"]["temperature"].float!) + "º" + (units == "si" ? "C" : "F") // let emoji = (res["currently"]["icon"].string!).getEmoji() // self.forecast.temperature = temperature // self.forecast.emoji = emoji // // self.forecast.data = res // self.forecast.today.data = res // self.todayController.forecast = self.forecast.today // // self.forecast.hourly.data = res // self.hourlyController.forecast = self.forecast.hourly // // self.forecast.daily.data = res["daily"] // self.dailyController.forecast = self.forecast.daily // // } // self.hud.hide(true) // self.updateForecastUI() // if (self.hourlyController.isViewLoaded()) { // self.hourlyController.tableView.reloadData() // } // if (self.dailyController.isViewLoaded()) { // self.dailyController.tableView.reloadData() // self.dailyController.updateUI() // } // case .Failure(let error): // print(error) // self.hud.hide(true) // // Could not connect to the internet // print("No internet connection!!!") // } // }
3a4741d300e50d12b6c0848233366532
37.921182
233
0.589799
false
false
false
false
JGiola/swift
refs/heads/main
test/refactoring/ExtractRepeat/await.swift
apache-2.0
13
func myAsync() async -> Int { 0 } func myFoo() -> Int { 0 } func testExtract() async -> Int { let a = myFoo() let b = myFoo() let x = await myAsync() let y = await myAsync() return a + b + x + y } // rdar://72199992 // RUN: %empty-directory(%t.result) // RUN: %refactor -extract-repeat -source-filename %s -pos=5:11 -end-pos=5:18 >> %t.result/one.swift // RUN: diff -u %S/Outputs/await/one.swift.expected %t.result/one.swift // RUN: %refactor -extract-repeat -source-filename %s -pos=7:11 -end-pos=7:26 >> %t.result/two.swift // RUN: diff -u %S/Outputs/await/two.swift.expected %t.result/two.swift
01b44d18b854b7de131bc6f3099ea17a
34.882353
100
0.645902
false
true
false
false
wookay/AppConsole
refs/heads/master
Demo/Test/TestApp/TestApp/ViewController.swift
mit
1
// // ViewController.swift // TestApp // // Created by wookyoung on 4/3/16. // Copyright © 2016 factorcat. All rights reserved. // import UIKit class A { var s = "a string" var n = 5 var b = true var t = (5,6) func f() -> String { Log.info("a.f") return "b call" } func g(n: Int) -> Int { Log.info("a.g") return n+1 } init() { } } let a = A() class B: NSObject { var s = "b string" var n = 5 var b = true var t = (5,6) func f() -> String { Log.info("b.f") return "b call" } func g(n: Int) -> Int { Log.info("b.g") return n+1 } override init() { } } let b = B() class ViewController: UIViewController { @IBOutlet var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. label.text = AppConsole(initial: self).run { app in app.register("a", object: a) app.register("b", object: b) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
2e2b801f700e2d7dce507da4c1d1d9bb
16.178082
80
0.524342
false
false
false
false
tensorflow/swift-models
refs/heads/main
CycleGAN/Models/Layers.swift
apache-2.0
1
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import TensorFlow /// 2-D layer applying instance normalization over a mini-batch of inputs. /// /// Reference: [Instance Normalization](https://arxiv.org/abs/1607.08022) public struct InstanceNorm2D<Scalar: TensorFlowFloatingPoint>: Layer { /// Learnable parameter scale for affine transformation. public var scale: Tensor<Scalar> /// Learnable parameter offset for affine transformation. public var offset: Tensor<Scalar> /// Small value added in denominator for numerical stability. @noDerivative public var epsilon: Tensor<Scalar> /// Creates a instance normalization 2D Layer. /// /// - Parameters: /// - featureCount: Size of the channel axis in the expected input. /// - epsilon: Small scalar added for numerical stability. public init(featureCount: Int, epsilon: Tensor<Scalar> = Tensor(1e-5)) { self.epsilon = epsilon scale = Tensor<Scalar>(ones: [featureCount]) offset = Tensor<Scalar>(zeros: [featureCount]) } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. Expected input layout is BxHxWxC. /// - Returns: The output. @differentiable public func callAsFunction(_ input: Tensor<Scalar>) -> Tensor<Scalar> { // Calculate mean & variance along H,W axes. let mean = input.mean(alongAxes: [1, 2]) let variance = input.variance(alongAxes: [1, 2]) let norm = (input - mean) * rsqrt(variance + epsilon) return norm * scale + offset } } public struct ConvLayer: Layer { public typealias Input = Tensorf public typealias Output = Tensorf /// Padding layer. public var pad: ZeroPadding2D<Float> /// Convolution layer. public var conv2d: Conv2D<Float> /// Creates 2D convolution with padding layer. /// /// - Parameters: /// - inChannels: Number of input channels in convolution kernel. /// - outChannels: Number of output channels in convolution kernel. /// - kernelSize: Convolution kernel size (both width and height). /// - stride: Stride size (both width and height). public init(inChannels: Int, outChannels: Int, kernelSize: Int, stride: Int, padding: Int? = nil) { let _padding = padding ?? Int(kernelSize / 2) pad = ZeroPadding2D(padding: ((_padding, _padding), (_padding, _padding))) conv2d = Conv2D(filterShape: (kernelSize, kernelSize, inChannels, outChannels), strides: (stride, stride), filterInitializer: { Tensorf(randomNormal: $0, standardDeviation: Tensorf(0.02)) }) } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func callAsFunction(_ input: Input) -> Output { return input.sequenced(through: pad, conv2d) } } public struct ResNetBlock<NormalizationType: FeatureChannelInitializable>: Layer where NormalizationType.TangentVector.VectorSpaceScalar == Float, NormalizationType.Input == Tensorf, NormalizationType.Output == Tensorf { var conv1: Conv2D<Float> var norm1: NormalizationType var conv2: Conv2D<Float> var norm2: NormalizationType var dropOut: Dropout<Float> @noDerivative var useDropOut: Bool @noDerivative let paddingMode: Tensorf.PaddingMode public init(channels: Int, paddingMode: Tensorf.PaddingMode, normalization _: NormalizationType.Type, useDropOut: Bool = false, filterInit: (TensorShape) -> Tensorf, biasInit: (TensorShape) -> Tensorf) { conv1 = Conv2D(filterShape: (3, 3, channels, channels), filterInitializer: filterInit, biasInitializer: biasInit) norm1 = NormalizationType(featureCount: channels) conv2 = Conv2D(filterShape: (3, 3, channels, channels), filterInitializer: filterInit, biasInitializer: biasInit) norm2 = NormalizationType(featureCount: channels) dropOut = Dropout(probability: 0.5) self.useDropOut = useDropOut self.paddingMode = paddingMode } @differentiable public func callAsFunction(_ input: Tensorf) -> Tensorf { var retVal = input.padded(forSizes: [(0, 0), (1, 1), (1, 1), (0, 0)], mode: paddingMode) retVal = retVal.sequenced(through: conv1, norm1) retVal = relu(retVal) if useDropOut { retVal = dropOut(retVal) } retVal = retVal.padded(forSizes: [(0, 0), (1, 1), (1, 1), (0, 0)], mode: paddingMode) retVal = retVal.sequenced(through: conv2, norm2) return input + retVal } } extension Array: Module where Element: Layer, Element.Input == Element.Output { public typealias Input = Element.Input public typealias Output = Element.Output @differentiable public func callAsFunction(_ input: Input) -> Output { differentiableReduce(input) { $1($0) } } } extension Array: Layer where Element: Layer, Element.Input == Element.Output {}
3cb0f8277948853994bdd3ffc7d74995
38.436242
220
0.658271
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/CreateCustomCharts/SplineScatterLineChart.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // SplineScatterLineChart.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class SplineScatterLineChart: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min:SCIGeneric(0.1), max: SCIGeneric(0.1)) let yAxis = SCINumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.2), max: SCIGeneric(0.2)) let originalData = SCIXyDataSeries(xType: .float, yType: .float) let doubleSeries = DataManager.getSinewaveWithAmplitude(1.0, phase: 0.0, pointCount: 28, freq: 7) originalData.appendRangeX(doubleSeries!.xValues, y: doubleSeries!.yValues, count: doubleSeries!.size) let ellipsePointMarker = SCIEllipsePointMarker() ellipsePointMarker.width = 7; ellipsePointMarker.height = 7; ellipsePointMarker.strokeStyle = SCISolidPenStyle.init(colorCode: 0xFF006400, withThickness: 1.0) ellipsePointMarker.fillStyle = SCISolidBrushStyle.init(colorCode: 0xFFFFFFFF) let splineRenderSeries = SplineLineRenderableSeries() splineRenderSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xFF4282B4, withThickness: 1.0) splineRenderSeries.dataSeries = originalData splineRenderSeries.pointMarker = ellipsePointMarker splineRenderSeries.upSampleFactor = 10 let lineRenderSeries = SCIFastLineRenderableSeries() lineRenderSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xFF4282B4, withThickness: 1.0) lineRenderSeries.dataSeries = originalData lineRenderSeries.pointMarker = ellipsePointMarker let textAnnotation = SCITextAnnotation() textAnnotation.coordinateMode = .relative; textAnnotation.x1 = SCIGeneric(0.5); textAnnotation.y1 = SCIGeneric(0.01); textAnnotation.horizontalAnchorPoint = .center; textAnnotation.verticalAnchorPoint = .top; textAnnotation.style.textStyle.fontSize = 24; textAnnotation.text = "Custom Spline Chart"; textAnnotation.style.textColor = UIColor.white textAnnotation.style.backgroundColor = UIColor.clear SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(splineRenderSeries) self.surface.renderableSeries.add(lineRenderSeries) self.surface.annotations.add(textAnnotation) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()]) splineRenderSeries.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) lineRenderSeries.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } }
fae62f95b050dc03fa3117d4d7ce78a1
50.728571
158
0.685446
false
false
false
false
khizkhiz/swift
refs/heads/master
test/SILGen/enum.swift
apache-2.0
1
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | FileCheck %s enum Optional<Wrapped> { case none case some(Wrapped) } enum Boolish { case falsy case truthy } // CHECK-LABEL: sil hidden @_TFs13Boolish_casesFT_T_ func Boolish_cases() { // CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt _ = Boolish.falsy // CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt _ = Boolish.truthy } struct Int {} enum Optionable { case nought case mere(Int) } // CHECK-LABEL: sil hidden @_TFs16Optionable_casesFSiT_ func Optionable_cases(x: Int) { // CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4mereFMS_FSiS_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = Optionable.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int _ = Optionable.mere(x) } // CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4mereFMS_FSiS_ // CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4merefMS_FSiS_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4merefMS_FSiS_ // CHECK: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int // CHECK-NEXT: return [[RES]] : $Optionable // CHECK-NEXT: } protocol P {} struct S : P {} enum AddressOnly { case nought case mere(P) case phantom(S) } // CHECK-LABEL: sil hidden @_TFs17AddressOnly_casesFVs1ST_ func AddressOnly_cases(s: S) { // CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4mereFMS_FPs1P_S_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = AddressOnly.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: inject_enum_addr [[NOUGHT]] // CHECK-NEXT: destroy_addr [[NOUGHT]] // CHECK-NEXT: dealloc_stack [[NOUGHT]] _ = AddressOnly.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]] // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]] // CHECK-NEXT: store %0 to [[PAYLOAD_ADDR]] // CHECK-NEXT: inject_enum_addr [[MERE]] // CHECK-NEXT: destroy_addr [[MERE]] // CHECK-NEXT: dealloc_stack [[MERE]] _ = AddressOnly.mere(s) // Address-only enum vs loadable payload // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: store %0 to [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: destroy_addr [[PHANTOM]] // CHECK-NEXT: dealloc_stack [[PHANTOM]] _ = AddressOnly.phantom(s) // CHECK: return } // CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4mereFMS_FPs1P_S_ // CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4merefMS_FPs1P_S_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] : $@callee_owned (@in P) -> @out AddressOnly // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4merefMS_FPs1P_S_ // CHECK: [[RET_DATA:%.*]] = init_enum_data_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1 // CHECK-NEXT: copy_addr [take] %1 to [initialization] [[RET_DATA]] : $*P // CHECK-NEXT: inject_enum_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1 // CHECK: return // CHECK-NEXT: } enum PolyOptionable<T> { case nought case mere(T) } // CHECK-LABEL: sil hidden @_TFs20PolyOptionable_casesurFxT_ func PolyOptionable_cases<T>(t: T) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: inject_enum_addr [[NOUGHT]] // CHECK-NEXT: destroy_addr [[NOUGHT]] // CHECK-NEXT: dealloc_stack [[NOUGHT]] _ = PolyOptionable<T>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]] // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[MERE]] // CHECK-NEXT: destroy_addr [[MERE]] // CHECK-NEXT: dealloc_stack [[MERE]] _ = PolyOptionable<T>.mere(t) // CHECK-NEXT: destroy_addr %0 // CHECK: return } // The substituted type is loadable and trivial here // CHECK-LABEL: sil hidden @_TFs32PolyOptionable_specialized_casesFSiT_ func PolyOptionable_specialized_cases(t: Int) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt _ = PolyOptionable<Int>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0 _ = PolyOptionable<Int>.mere(t) // CHECK: return } // Regression test for a bug where temporary allocations created as a result of // tuple implosion were not deallocated in enum constructors. struct String { var ptr: Builtin.NativeObject } enum Foo { case A(P, String) } // CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AFMS_FTPs1P_SS_S_ // CHECK: [[FN:%.*]] = function_ref @_TFOs3Foo1AfMS_FTPs1P_SS_S_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AfMS_FTPs1P_SS_S_ // CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1 // CHECK-NEXT: copy_addr [take] %1 to [initialization] [[LEFT]] : $*P // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: inject_enum_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK: return // CHECK-NEXT: } func Foo_cases() { _ = Foo.A }
afa3d344c7ccf5d3ac7697c7644a428c
35.047368
115
0.628851
false
false
false
false
halmueller/ferries
refs/heads/master
Ferries/Ferries In Class/VesselsTableViewController.swift
apache-2.0
1
// // VesselsTableViewController.swift // Ferries In Class // // Created by Hal Mueller on 5/17/17. // Copyright © 2017 Hal Mueller. All rights reserved. // import UIKit import CoreData class VesselsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { var managedObjectContext: NSManagedObjectContext? = FerriesCoreDataStack.shared.persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let vessel = fetchedResultsController.object(at: indexPath) configureCell(cell, withVessel: vessel) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let context = fetchedResultsController.managedObjectContext context.delete(fetchedResultsController.object(at: indexPath)) do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } func configureCell(_ cell: UITableViewCell, withVessel vessel: Vessel) { cell.textLabel!.text = "\(vessel.name!) (\(vessel.vesselID!))" } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController<Vessel> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Vessel> = Vessel.fetchRequest() // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let nameSortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [nameSortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController<Vessel>? = nil // MARK: - NSFRC Delegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) // FIXME: do we want old indexPath, or newIndexPath? What can safely be force-unwrapped? case .update: if let cell = tableView.cellForRow(at: (indexPath)!) { configureCell(cell, withVessel: anObject as! Vessel) } case .move: // FIXME: check sequence of these two lines configureCell(tableView.cellForRow(at: indexPath!)!, withVessel: anObject as! Vessel) tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. tableView.reloadData() } */ }
bd74a6440a23b55e3189be465bc41ad3
42.404908
360
0.666855
false
false
false
false
wangchong321/tucao
refs/heads/master
测试项目/WCWeiBoText/Classes/Module/Main/BasicTableViewController.swift
mit
1
// // BasicTableViewController.swift // WCWeiBoText // // Created by 王充 on 15/5/11. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class BasicTableViewController: UITableViewController, VisitorViewDelegate { var visitorView : VisitorView? var userLogin = false override func loadView() { if userLogin == true{ super.loadView() return } visitorView = NSBundle.mainBundle().loadNibNamed("Visitor", owner: nil, options: nil).last as? VisitorView view = visitorView navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewregisterButtonClick") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewLoginButtonClick") visitorView?.delegate = self } func visitorViewLoginButtonClick() { println("登陆") } func visitorViewregisterButtonClick() { println("注册") } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } }
43b0bb06856e43ac63ef987c77b209c7
31.345455
162
0.670601
false
false
false
false
BrianBal/Themed
refs/heads/master
Example/Tests/StyleTests.swift
mit
1
// // StyleTests.swift // Themed // // Created by Brian Bal on 8/18/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest import UIKit @testable import Themed class StyleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // Style.init should set anme and theme property func test_base_init() { let style = Style("test") XCTAssertEqual("test", style.name) XCTAssertEqual("default", style.theme) } // Style.theme should be able to get and set a string value func test_base_theme() { let style = Style("test") style.theme = "A" XCTAssertEqual("A", style.theme) } // SimpleStyle.init should initialize styleBlock, name, theme func test_simple_init() { var test = 0 let block : ((UIView) -> Void) = { view in test += 1 } let style = SimpleStyle("simple_test", style: block) style.styleBlock(UIView()) XCTAssertEqual(1, test) XCTAssertEqual("simple_test", style.name) XCTAssertEqual("default", style.theme) } // SimpleStyle.apply should call the styleBlock with a passed view argument func test_simple_apply() { var test = 0 let block : ((UIView) -> Void) = { view in test += 1 } let style = SimpleStyle("simple_test", style: block) style.apply(UIView()) XCTAssertEqual(1, test) } }
c14999e002d884504abf0946a04c8552
26.348485
111
0.585042
false
true
false
false
Antuaaan/ECWeather
refs/heads/master
ECWeather/Pods/SwiftSky/Source/Speed.swift
mit
1
// // Speed.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Foundation /// Contains a value, unit and a label describing speed public struct Speed { /// `Float` representing speed private(set) public var value : Float = 0 /// `SpeedUnit` of the value public let unit : SpeedUnit /// Human-readable representation of the value and unit together public var label : String { return label(as: unit) } /** Same as `Speed.label`, but converted to a specific unit - parameter unit: `SpeedUnit` to convert label to - returns: String */ public func label(as unit : SpeedUnit) -> String { let converted = (self.unit == unit ? value : convert(value, from: self.unit, to: unit)) switch unit { case .milePerHour: return "\(converted.noDecimal) mph" case .kilometerPerHour: return "\(converted.noDecimal) kph" case .meterPerSecond: return "\(converted.oneDecimal) m/s" } } /** Same as `Speed.value`, but converted to a specific unit - parameter unit: `SpeedUnit` to convert value to - returns: Float */ public func value(as unit : SpeedUnit) -> Float { return convert(value, from: self.unit, to: unit) } private func convert(_ value : Float, from : SpeedUnit, to : SpeedUnit) -> Float { switch from { case .milePerHour: switch to { case .milePerHour: return value case .kilometerPerHour: return value * 1.609344 case .meterPerSecond: return value * 0.44704 } case .kilometerPerHour: switch to { case .kilometerPerHour: return value case .milePerHour: return value / 1.609344 case .meterPerSecond: return value / 3.6 } case .meterPerSecond: switch to { case .meterPerSecond: return value case .milePerHour: return value / 0.44704 case .kilometerPerHour: return value * 3.6 } } } init(_ value : Float, withUnit : SpeedUnit) { unit = SwiftSky.units.speed self.value = convert(value, from: withUnit, to: unit) } }
615cc6510e16d83330c891a03681451f
27.359551
95
0.543978
false
false
false
false