blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
625
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
47
| license_type
stringclasses 2
values | repo_name
stringlengths 5
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 643
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 80.4k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 16
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 85
values | src_encoding
stringclasses 7
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 4
6.44M
| extension
stringclasses 17
values | content
stringlengths 4
6.44M
| duplicates
sequencelengths 1
9.02k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9482713616be08a4310fed4e8928ad037189465c | aff0deac399490501d5c3dadd58b47158aae4661 | /Tests/WorkspaceTests/XCTestManifests.swift | 4f9985d2fa9ca789e445f60b025defaaf78dd906 | [
"Apache-2.0",
"Swift-exception"
] | permissive | orta/swift-package-manager | 1e05255388089d92827bb131bec1ac1306fc71ce | 02634fb38ec3201eaebb69126a51f3d10d5fd242 | refs/heads/master | 2021-01-20T02:42:56.838443 | 2017-08-24T11:05:09 | 2017-08-24T11:37:29 | 101,333,834 | 1 | 0 | null | 2017-08-24T20:10:04 | 2017-08-24T20:10:04 | null | UTF-8 | Swift | false | false | 654 | swift | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(InitTests.allTests),
testCase(PinsStoreTests.allTests),
testCase(ToolsVersionWriterTests.allTests),
testCase(WorkspaceTests.allTests),
testCase(WorkspaceTests2.allTests),
]
}
#endif
| [
-1
] |
5feb914eecc8821085d114779dfdc591733818db | 6979dadb29e2d173534d00a5e08d87840af8849e | /Tippy/UserSettings.swift | b2be6984d72c970aed2b729b1f9d0e912d903037 | [
"Apache-2.0"
] | permissive | fabienrenaud/codepath-demoapp-tippy | 14835ce48082f7969a4bc9c810e5c179c80d7b7f | faa5dafcc4297a75cfdefc0fa1c0b3a2c08e0b9f | refs/heads/master | 2021-01-13T09:17:51.116036 | 2016-09-23T06:40:23 | 2016-09-23T06:40:23 | 68,996,484 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 799 | swift | //
// UserSettings.swift
// Tippy
//
// Created by Fabien Renaud on 9/18/16.
// Copyright © 2016 Fabien Renaud. All rights reserved.
//
import Foundation
class UserSettings {
public static let instance = UserSettings()
var darkTheme: Bool
var defaultTip: Int
private init() {
let store = UserDefaults.standard
self.darkTheme = (store.object(forKey: "tippy.settings.darkTheme") ?? false) as! Bool
self.defaultTip = (store.object(forKey: "tippy.settings.defaultTip") ?? 20) as! Int
}
func save() {
let store = UserDefaults.standard
store.set(defaultTip, forKey: "tippy.settings.defaultTip")
store.set(darkTheme, forKey: "tippy.settings.darkTheme")
store.synchronize()
}
}
| [
-1
] |
ad3bc59046ef39e6aeeecebee45d7ff9481dcf81 | c8e8698417afcc61b27cd1e1fbb8a18002cdc519 | /ReciFoto/ComposeViewController.swift | f40d9ab8364db571cd3d3a59428c604a5208ba1d | [] | no_license | dmaulikr/ReciFoto | ab2bf8a00fb1acb8c85d2df9aebf70db7ea6e671 | 321beaba80108709d12a31a361aa4a9c14f8bc17 | refs/heads/master | 2021-01-15T22:18:42.020531 | 2017-05-27T22:39:34 | 2017-05-27T22:39:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,435 | swift | //
// ComposeViewController.swift
// NewsFeed
//
// Created by Alex Manzella on 28/07/16.
// Copyright © 2016 devlucky. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController, UITextViewDelegate {
var recipe_id = ""
let max_length = 180
private let textView: UITextView = {
let textView = UITextView()
textView.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
return textView
}()
private let titleLabel : UILabel = {
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textAlignment = .center
titleLabel.text = "180 left"
return titleLabel
}()
deinit {
NotificationCenter.default.removeObserver(self)
}
required init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
navigationItem.rightBarButtonItem?.isEnabled = false
view.addSubview(textView)
textView.delegate = self
textView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
self.navigationItem.titleView = titleLabel
[NSNotification.Name.UIKeyboardWillShow, NSNotification.Name.UIKeyboardWillChangeFrame, NSNotification.Name.UIKeyboardWillHide].forEach { (name) in
NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameDidChange(_:)), name: name, object: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
textView.resignFirstResponder()
}
// MARK: Actions
@objc private func keyboardFrameDidChange(_ notification: Notification) {
guard let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
textView.snp.updateConstraints { (make) in
make.bottom.equalTo(view).inset(frame.cgRectValue.height)
}
}
@objc private func cancel() {
dismiss(animated: true, completion: nil)
}
@objc private func done() {
NetworkManger.sharedInstance.addCommentAPI(parameters: [Constants.USER_ID_KEY : Me.user.id,
Constants.USER_SESSION_KEY : Me.session_id,
Constants.RECIPE_ID_KEY : recipe_id,
Constants.COMMENTS_KEY : textView.text,
Constants.IS_COMMENT_PRIVATE : "0"]) { (jsonResponse, status) in
if status == "1"{
}else {
let alertController = UIAlertController(title: "ReciFoto", message: jsonResponse["message"] as? String, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
dismiss(animated: true, completion: nil)
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
titleLabel.text = String(format: "%d left", max_length - textView.text.characters.count)
navigationItem.rightBarButtonItem?.isEnabled = textView.text.characters.count > 0
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if textView.text.characters.count < 180 {
return true
}else{
return false
}
}
}
| [
-1
] |
f9788b1a66daa0ffb19c79562d3992c8e7ffce46 | c6519f3b9814bce61264861766147b54f6388460 | /Ukazka/Networking/MockRequestProvider.swift | 126c42fa6ce71435e70c003489bc51c8d961b809 | [] | no_license | chlumik/UkazkaCampaigns | 5821b7eee0baed025a95bff0bc0f00ea65489aa9 | 627732973a15b9397497d9bf7967237b3bb2e507 | refs/heads/master | 2020-06-24T14:50:50.181823 | 2019-07-26T09:51:45 | 2019-07-26T09:51:45 | 198,991,563 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 912 | swift | //
// MockRequestProvider.swift
// Ukazka
//
// Created by Jiří Chlum on 24/07/2019.
// Copyright © 2019 Jiří Chlum. All rights reserved.
//
import Foundation
class MockRequestProvider: RequestProvider {
var settings: MockSettings
var responseDataProvider: RequestResponseDataProvider
init(settings: MockSettings, dataProvider: RequestResponseDataProvider) {
self.settings = settings
self.responseDataProvider = dataProvider
}
func request(endPoint: EndPoint, success: @escaping RequestSuccessCompletion, failure: @escaping RequestFailureCompletion) {
DispatchQueue.main.asyncAfter(deadline: .now() + self.settings.delay) { [weak self] in
if let data = self?.responseDataProvider.jsonData(for: endPoint) {
success(data, 200)
} else {
failure(.serverError, 500)
}
}
}
}
| [
-1
] |
7fe0005633104de4e6e754a51321a933b4329bfd | 50fef5cc9724c576ea19945550387444fdac5ff0 | /FileMTestApp/UI/Companion/MainScreenCompanion.swift | 9878a81d321af6b9cb9a97fd53833be60a94bf9f | [] | no_license | KanybekMomukeyev/FileMTestApp | f1d6ceb9b8fb863b0c7bebcc0ef98cd3ab250523 | 64df4b1e80b81b030f083f08ea23fad867257268 | refs/heads/master | 2020-12-30T12:54:52.293546 | 2017-05-15T17:23:27 | 2017-05-15T17:23:27 | 91,364,783 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,522 | swift | //
// MainScreenCompanion.swift
// FileMTestApp
//
// Created by kanybek on 5/15/17.
// Copyright © 2017 kanybek. All rights reserved.
//
import UIKit
let defaultFolderPath: String = "FileTestApp"
class MainScreenCompanion {
var someValue: UInt64
convenience init() {
self.init(someValue: 0)
}
init(someValue: UInt64) {
self.someValue = someValue
}
deinit {
print("MainScreenTVC deallocated")
}
func getFolders() -> [String] {
var arrayOfFolderPaths: [String] = []
if let arrayOfFolderPaths_ = FCFileManager.listDirectoriesInDirectory(atPath: defaultFolderPath) {
for folderPath in arrayOfFolderPaths_ {
if let folderPath_ = folderPath as? String {
arrayOfFolderPaths.append(folderPath_)
}
}
}
return arrayOfFolderPaths
}
func createFolder(folderName: String) -> Void {
FCFileManager.createDirectories(forPath:(defaultFolderPath + "/" + folderName))
}
func deleteFolder(folderPath: String) -> Void {
let folderName = self.nameForPath(path: folderPath)
FCFileManager.removeItem(atPath: (defaultFolderPath + "/" + folderName))
}
func nameForPath(path: String) -> String {
if let folderName_ = path.components(separatedBy: "/").last {
return folderName_
}
return ""
}
func createFile(folderName: String,
fileName: String,
fileContent: String) {
FCFileManager.createFile(atPath: (defaultFolderPath + "/" + folderName + "/" + fileName + ".txt"),
withContent: fileContent as NSObject)
}
func getFilesFor(folderName: String) -> [String] {
var arrayOfFilePath: [String] = []
if let arrayOfFilePath_ = FCFileManager.listFilesInDirectory(atPath: (defaultFolderPath + "/" + folderName)) {
for filePath in arrayOfFilePath_ {
if let filePath_ = filePath as? String {
arrayOfFilePath.append(filePath_)
}
}
}
return arrayOfFilePath
}
func readFileAt(folderName: String,
fileName: String) -> String {
if let fileContent_ = FCFileManager.readFile(atPath: (defaultFolderPath + "/" + folderName + "/" + fileName)) {
return fileContent_
}
return "Empty"
}
}
| [
-1
] |
553354d794fc8e3e3c4abadbbda6e66ceabdfd8f | cef6c3df5b45ee9ac7247e246b320876224b9bb0 | /FPGiOS/OptionsViewController.swift | e445c4beee1a2b64933d1302250d2270c0e918b0 | [] | no_license | xlfdll/FPGiOS | 40e870f505bc1bf23b5e2a393d9d9517d1c663b7 | 0e0777f283406f3c37831ddd88a520b3799de28d | refs/heads/master | 2023-01-30T12:37:54.136224 | 2020-12-13T03:35:06 | 2020-12-13T03:35:06 | 198,356,930 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 8,773 | swift | //
// OptionsViewController.swift
// FPGiOS
//
// Created by Xlfdll on 2019/07/25.
// Copyright © 2019 Xlfdll Workstation. All rights reserved.
//
import UIKit
class OptionsViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let passwordLength = UserDefaults.standard.integer(forKey: AppDataKeys.PasswordLengthKey)
PasswordLengthUIPickerView.delegate = self
PasswordLengthUIPickerView.dataSource = self
PasswordLengthUIPickerView.selectRow(passwordLength - 4, inComponent: 0, animated: true)
AutoCopyPasswordUISwitch.isOn = UserDefaults.standard.bool(forKey: AppDataKeys.AutoCopyPasswordKey)
SaveLastUserSaltUISwitch.isOn = UserDefaults.standard.bool(forKey: AppDataKeys.SaveLastUserSaltKey)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Edit Random Salt
if indexPath.row == 0 {
let alert = UIAlertController(title: NSLocalizedString("EditRandomSaltAlert.Title", comment: "Edit random salt"),
message: "",
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"),
style: UIAlertAction.Style.default,
handler: { (action) in
if alert.textFields?[0].text != nil && alert.textFields?[0].text?.isEmpty == false {
UserDefaults.standard.set(alert.textFields?[0].text, forKey: AppDataKeys.RandomSaltKey)
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel action"),
style: UIAlertAction.Style.cancel))
PasswordLengthDefaultAction = alert.actions[0]
alert.addTextField { (textField: UITextField) in
textField.text = String(UserDefaults.standard.string(forKey: AppDataKeys.RandomSaltKey)!)
textField.placeholder = NSLocalizedString("EditRandomSaltAlert.Placeholder", comment: "Random salt input placeholder")
textField.addTarget(self,
action: #selector(self.randomSaltValidate(textField:)),
for: UITextField.Event.editingChanged)
}
self.present(alert, animated: true)
}
// Generate New Random Salt
else if indexPath.row == 1 {
let alert = UIAlertController(title: NSLocalizedString("GenerateNewRandomSaltAlert.Title", comment: "Generate new random salt"),
message: NSLocalizedString("RandomSaltChangeAlert.Message", comment: "Random salt change warning"),
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "Default action"),
style: UIAlertAction.Style.default,
handler: { (action) in
UserDefaults.standard.set(PasswordHelper.generateSalt(length: PasswordHelper.RandomSaltLength),
forKey: AppDataKeys.RandomSaltKey)
let completeAlert = UIAlertController(title: NSLocalizedString("GenerateNewRandomSaltAlert.Title", comment: "Generate new random salt"),
message: NSLocalizedString("GenerateNewRandomSaltCompleteAlert.Message", comment: "Generate new random salt complete message"), preferredStyle: UIAlertController.Style.alert)
completeAlert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"),
style: UIAlertAction.Style.default))
self.present(completeAlert, animated: true)
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("No", comment: "Cancel action"),
style: UIAlertAction.Style.cancel))
self.present(alert, animated: true)
}
// Backup Random Salt
else if indexPath.row == 2 {
PasswordHelper.saveRandomSalt(UserDefaults.standard.string(forKey: AppDataKeys.RandomSaltKey)!)
var message = String(format: NSLocalizedString("BackupRandomSaltCompleteAlert.Message", comment: "Backup random salt complete message"), PasswordHelper.RandomSaltBackupDataFileName)
do {
let url = PasswordHelper.getRandomSaltFileURL()
if url == nil || !FileManager().fileExists(atPath: url!.path) {
message = NSLocalizedString("GenericError.Message", comment: "Generic error message")
}
}
let completeAlert = UIAlertController(title: NSLocalizedString("BackupRandomSaltAlert.Title", comment: "Backup random salt"),
message: message,
preferredStyle: UIAlertController.Style.alert)
completeAlert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"),
style: UIAlertAction.Style.default))
self.present(completeAlert, animated: true)
}
else if indexPath.row == 3 {
let alert = UIAlertController(title: NSLocalizedString("RestoreRandomSaltAlert.Title", comment: "Restore random salt"),
message: NSLocalizedString("RandomSaltChangeAlert.Message", comment: "Random salt change warning"),
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "Default action"),
style: UIAlertAction.Style.default,
handler: { (action) in
let randomSalt = PasswordHelper.loadRandomSalt()
var message = String(format: NSLocalizedString("RestoreRandomSaltCompleteAlert.Message", comment: "Restore random salt complete message"), PasswordHelper.RandomSaltBackupDataFileName)
if randomSalt != nil {
UserDefaults.standard.set(randomSalt, forKey: AppDataKeys.RandomSaltKey)
}
else {
message = String(format: NSLocalizedString("RestoreRandomSaltCompleteAlert.Error", comment: "Restore random salt error message"), PasswordHelper.RandomSaltBackupDataFileName)
}
let completeAlert = UIAlertController(title: NSLocalizedString("RestoreRandomSaltAlert.Title", comment: "Restore random salt"),
message: message,
preferredStyle: UIAlertController.Style.alert)
completeAlert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"),
style: UIAlertAction.Style.default))
self.present(completeAlert, animated: true)
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("No", comment: "Cancel action"),
style: UIAlertAction.Style.cancel))
self.present(alert, animated: true)
}
}
@objc func randomSaltValidate(textField: UITextField) {
PasswordLengthDefaultAction.isEnabled = (textField.text != nil && textField.text?.isEmpty == false)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 64 - 4 + 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(row + 4)
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let passwordLength = row + 4
UserDefaults.standard.set(passwordLength, forKey: AppDataKeys.PasswordLengthKey)
}
@IBAction func autoCopyPasswordValueChanged(_ sender: Any) {
UserDefaults.standard.set(AutoCopyPasswordUISwitch.isOn, forKey: AppDataKeys.AutoCopyPasswordKey)
}
@IBAction func saveLastUserSaltValueChanged(_ sender: Any) {
UserDefaults.standard.set(SaveLastUserSaltUISwitch.isOn, forKey: AppDataKeys.SaveLastUserSaltKey)
}
@IBOutlet weak var PasswordLengthUIPickerView: UIPickerView!
@IBOutlet weak var AutoCopyPasswordUISwitch: UISwitch!
@IBOutlet weak var SaveLastUserSaltUISwitch: UISwitch!
var PasswordLengthDefaultAction: UIAlertAction!
}
| [
-1
] |
7d09d5f1543578a3da3969d0f8fb6d12e4caa5f7 | 9390828bd76e91a34f2e3f73138af8d90e19a42d | /iOS/RootSplitViewController.swift | e84a8241f415a0d482ca19a17cca7c1eef0c4ca8 | [
"MIT"
] | permissive | kavon/NetNewsWire | aca7b95f6806ef43a0b3b87b6db5ea31531148e4 | ed64d47268aae9f499d6829c3f767aabae557632 | refs/heads/concur | 2023-01-27T15:43:26.623985 | 2020-12-09T01:06:52 | 2020-12-09T01:06:52 | 304,703,435 | 6 | 0 | MIT | 2020-10-29T23:22:21 | 2020-10-16T18:05:45 | Swift | UTF-8 | Swift | false | false | 3,328 | swift | //
// RootSplitViewController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 9/4/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import Account
class RootSplitViewController: UISplitViewController {
var coordinator: SceneCoordinator!
override var prefersStatusBarHidden: Bool {
return coordinator.prefersStatusBarHidden
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
override func viewDidAppear(_ animated: Bool) {
coordinator.resetFocus()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
self.coordinator.configurePanelMode(for: size)
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: Keyboard Shortcuts
@objc func scrollOrGoToNextUnread(_ sender: Any?) {
coordinator.scrollOrGoToNextUnread()
}
@objc func scrollUp(_ sender: Any?) {
coordinator.scrollUp()
}
@objc func goToPreviousUnread(_ sender: Any?) {
coordinator.selectPrevUnread()
}
@objc func nextUnread(_ sender: Any?) {
coordinator.selectNextUnread()
}
@objc func markRead(_ sender: Any?) {
coordinator.markAsReadForCurrentArticle()
}
@objc func markUnreadAndGoToNextUnread(_ sender: Any?) {
coordinator.markAsUnreadForCurrentArticle()
coordinator.selectNextUnread()
}
@objc func markAllAsReadAndGoToNextUnread(_ sender: Any?) {
coordinator.markAllAsReadInTimeline()
coordinator.selectNextUnread()
}
@objc func markAboveAsRead(_ sender: Any?) {
coordinator.markAboveAsRead()
}
@objc func markBelowAsRead(_ sender: Any?) {
coordinator.markBelowAsRead()
}
@objc func markUnread(_ sender: Any?) {
coordinator.markAsUnreadForCurrentArticle()
}
@objc func goToPreviousSubscription(_ sender: Any?) {
coordinator.selectPrevFeed()
}
@objc func goToNextSubscription(_ sender: Any?) {
coordinator.selectNextFeed()
}
@objc func openInBrowser(_ sender: Any?) {
coordinator.showBrowserForCurrentArticle()
}
@objc func openInAppBrowser(_ sender: Any?) {
coordinator.showInAppBrowser()
}
@objc func articleSearch(_ sender: Any?) {
coordinator.showSearch()
}
@objc func addNewFeed(_ sender: Any?) {
coordinator.showAddWebFeed()
}
@objc func addNewFolder(_ sender: Any?) {
coordinator.showAddFolder()
}
@objc func cleanUp(_ sender: Any?) {
coordinator.cleanUp(conditional: false)
}
@objc func toggleReadFeedsFilter(_ sender: Any?) {
coordinator.toggleReadFeedsFilter()
}
@objc func toggleReadArticlesFilter(_ sender: Any?) {
coordinator.toggleReadArticlesFilter()
}
@objc func refresh(_ sender: Any?) {
appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self))
}
@objc func goToToday(_ sender: Any?) {
coordinator.selectTodayFeed()
}
@objc func goToAllUnread(_ sender: Any?) {
coordinator.selectAllUnreadFeed()
}
@objc func goToStarred(_ sender: Any?) {
coordinator.selectStarredFeed()
}
@objc func goToSettings(_ sender: Any?) {
coordinator.showSettings()
}
@objc func toggleRead(_ sender: Any?) {
coordinator.toggleReadForCurrentArticle()
}
@objc func toggleStarred(_ sender: Any?) {
coordinator.toggleStarredForCurrentArticle()
}
@objc func toggleSidebar(_ sender: Any?) {
coordinator.toggleSidebar()
}
}
| [
-1
] |
b6b509a6c612fd281aca1c6e71899a8318987b9e | 83470d59ad4570d3f13b7fdb4c4c3027a7caa276 | /PhotoViewer/PhotoViewer/Utils/RemoteImageView.swift | 7ff6df4fbe49c2868bc83f5c76c07aadfdc223c1 | [] | no_license | D3migod/PhotoViewer | c01377ec2926f9de33eeff7bf4f9b98b67c4dc3d | 65bae50197dbc226fae7e679af338b6681432f36 | refs/heads/master | 2023-04-15T20:31:33.151591 | 2021-04-28T06:00:33 | 2021-04-28T06:33:04 | 362,349,008 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 554 | swift | //
// RemoteImageView.swift
// PhotoViewer
//
// Created by Bulat Galiev on 4/26/21.
//
import UIKit
final class RemoteImageView: UIImageView {
private var task: Cancelable?
var remoteImageSetter: RemoteImageSetter? {
didSet {
task?.cancel()
image = nil
let currentImageSetter = remoteImageSetter
task = remoteImageSetter?.requestImage { [weak self] image in
guard let self = self, self.remoteImageSetter === currentImageSetter else {
return
}
self.image = image
}
}
}
}
| [
-1
] |
b22e9c8910d92679eb22249bca04170989850a80 | 0c9fe6eec46123cdab838271f3edadac0fda288e | /src/Database/Workers/DBCategoryWorker.swift | ca9af05e4c8e4254af6a0aacc99ae8a7ec8d63ef | [] | no_license | pmieszal/shekly-ios | a69f99098d1d0fd24709c6308314410d31255940 | 7dff5c36964c247fec334dbfbc34b8fab6e7b4ee | refs/heads/master | 2021-07-24T15:15:43.555416 | 2020-04-25T13:02:42 | 2020-04-25T13:02:42 | 168,946,223 | 1 | 0 | null | 2019-10-15T14:47:12 | 2019-02-03T13:07:36 | Swift | UTF-8 | Swift | false | false | 1,229 | swift | import Domain
import RealmSwift
class DBCategoryWorker: DBGroup<DBCategoryModel> {
let walletWorker: DBWalletWorker
init(realm: Realm, walletWorker: DBWalletWorker) {
self.walletWorker = walletWorker
super.init(realm: realm)
}
func getCategories(forWallet wallet: WalletModel) -> [CategoryModel] {
guard let walletId = wallet.id else {
return []
}
return getCategories(forWalletId: walletId)
}
func save(category: CategoryModel) -> CategoryModel {
let dbEntry = DBCategoryModel(category)
let dbWallet = walletWorker.get(id: category.wallet?.id) ?? DBWalletModel(name: category.wallet?.name ?? "Unknown")
walletWorker.save(wallet: dbWallet)
execute { _ in
dbWallet.categories.append(dbEntry)
}
return CategoryModel(dbEntry)
}
}
extension DBCategoryWorker: CategoryRepository {
func getCategories(forWalletId walletId: String) -> [CategoryModel] {
let filter = NSPredicate(format: "ANY wallet.id = %@", walletId)
let categories = list(filter: filter)
return categories.map(CategoryModel.init)
}
}
| [
-1
] |
4cd21f78606fa22968116c3ed364fb98f6c481aa | 32fa67363a204167c7ebd5966b600606ad51660c | /AppTeatroIOS/AppTeatro/Controllers/ContentPageViewController.swift | 0a33a6742ab46194b55330bd99c17ab5d808bd4e | [] | no_license | lucasf282/DevAppTeatro | b38239ee971dff58b00f9142318c9692e6029b4e | 13f575227535222495f149fd002e6e776f024b42 | refs/heads/master | 2021-01-19T23:00:04.292414 | 2018-11-14T03:33:56 | 2018-11-14T03:33:56 | 88,906,487 | 0 | 4 | null | 2017-06-12T22:24:49 | 2017-04-20T20:12:34 | Objective-C | UTF-8 | Swift | false | false | 1,077 | swift | //
// ContentPageViewController.swift
// AppTeatro
//
// Created by Thiago Sousa on 07/05/17.
// Copyright © 2017 MyMac. All rights reserved.
//
import UIKit
class ContentPageViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
var imageFileName: String!
var pageIndex:Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myImageView.image = UIImage(named:imageFileName)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| [
279041,
279046,
281107,
300057,
296489,
281142,
300089,
238653,
286786,
129604,
228932,
228945,
203858,
280146,
212573,
309347,
309349,
309351,
309353,
286314,
296042,
277612,
311913,
164974,
284275,
277108,
284277,
284279,
292478,
284289,
284298,
278675,
349332,
284315,
284317,
282275,
284323,
313007,
284336,
276150,
280760,
296638,
277696,
280770,
280772,
280775,
284361,
230604,
298189,
302286,
230608,
317137,
290004,
284373,
290006,
189655,
302295,
298202,
278749,
280797,
298206,
363743,
290020,
301284,
277224,
280808,
199402,
280810,
289524,
120054,
226038,
280826,
276736,
280832,
312586,
278298,
329499,
287004,
281373,
281380,
233767,
283433,
278845,
279360,
296272,
289112,
188253,
292701,
311645,
227688,
277364,
207738,
290175,
183173,
233869,
304015,
226196,
284570,
284574,
284577,
289187,
289190,
289191,
305577,
291755,
289196,
370093,
279982,
286126,
297903,
305582,
282548,
293816,
127418,
293308,
278973,
291774,
286158,
280015,
301012,
280030,
279011,
289771,
282095,
302580,
236022,
288251,
287231
] |
3c428deea3c5ef9a9c35a153ff0ed39d98d9eafd | f8039d2110d65585de4b48ce4ed5276e8b69b4de | /Vector Field/GameViewController.swift | 03ebb93a946208f8d3ea6d0b963b99781ea1dc80 | [] | no_license | EvanBacon/SpriteKit-Vector-Field | 4fd2b65d2a0ed96272e20d3ca0617fe89667e0e4 | a0115a1e7fa7f229e80ac9ab287c245a5b2cd3b5 | refs/heads/master | 2020-07-31T00:30:48.861696 | 2016-09-15T21:02:12 | 2016-09-15T21:02:12 | 67,741,798 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,401 | swift | //
// GameViewController.swift
// Vector Field
//
// Created by Evan Bacon on 9/8/16.
// Copyright (c) 2016 Brix. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| [
316802,
182818,
282637,
277582,
234291,
280182,
282879
] |
83e48824442cbcf5312e434d474594042a7b58bf | 2ae1df8599ae9ac91651ab574e98500ba7583a5d | /Core/Domain/Entity/HackNews.swift | a04fb35df3d17bf3fbf9bf902a4b99fc68fdcd1d | [] | no_license | JurjDev/HackerNews-demo | 340fa9057d191f19e3d5d6f9f8177b56d7cadbeb | b39f1987d3b868778a6164f03f3004a7b0252e08 | refs/heads/main | 2023-04-05T09:01:38.525718 | 2021-04-19T03:15:56 | 2021-04-19T03:15:56 | 359,314,069 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 301 | swift | //
// HackNews.swift
// Core
//
// Created by JurjDev on 18/04/21.
//
import Foundation
public struct HackNews: Equatable, Hashable, Codable {
public let newsArticle: [NewsArticle]
internal enum CodingKeys: String, CodingKey {
case newsArticle = "hits"
}
}
| [
-1
] |
5918df4984d7e5c1994a6312219b7636b0fdc662 | cb8e71e493d27e3cff2b97f44e21a5ec4061adce | /virtualTourist/Model/PhotosResponse.swift | e5f7449b4ad4e60c8a8b5732399ac27d580ee481 | [] | no_license | a3wdh/virtualTourist | c9da1d014c4261ee1765f6df0cc22460f0e5af32 | 35b0f94b447f118c328d002d332345435dbed2d8 | refs/heads/master | 2022-12-02T13:08:33.915753 | 2020-08-21T06:18:26 | 2020-08-21T06:18:26 | 289,193,610 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 231 | swift | //
// photoResponse.swift
// virtualTourist
//
// Created by A Abdullah on 8/09/20.
// Copyright © 2020 Udacity. All rights reserved.
//
import Foundation
struct PhotosResponse: Codable{
let photos: PhotoResponse
}
| [
-1
] |
021ae851064563b70ae470af94693ce509165ef4 | 1038a7b1b0e824c5ce3bd6e8ef94c210159a4d58 | /WisataApp/WisataApp/SceneDelegate.swift | 89752cd4852cb8e9d17fc9600adb836b83a88d9e | [] | no_license | Thusal06/Hacktoberfest-2021 | 93c2362b4dbd74310d6be0f281869311bd106de0 | 3fd98a8dc4d223e2c0f3312c372acd1e8f8100b2 | refs/heads/main | 2023-08-29T12:28:04.487371 | 2021-10-28T15:41:03 | 2021-10-28T15:41:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,710 | swift | //
// SceneDelegate.swift
// WisataApp
//
// Created by KhalishTianto User on 06/04/21.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| [
393221,
393228,
393231,
393251,
352294,
344103,
393260,
163892,
393269,
213049,
385082,
376890,
16444,
393277,
254020,
376906,
327757,
254032,
286804,
368728,
180314,
254045,
368736,
376932,
286833,
368753,
286845,
286851,
262284,
360598,
286880,
286889,
377003,
377013,
164029,
327872,
377030,
377037,
180432,
368854,
377047,
377063,
205037,
393457,
393461,
336124,
418044,
336129,
385281,
262405,
180491,
262417,
368913,
262423,
377121,
262437,
254253,
336181,
262455,
262473,
344404,
418135,
262497,
418145,
262501,
213354,
262508,
262512,
213374,
385420,
393613,
262551,
262553,
385444,
262567,
385452,
262574,
393649,
385460,
262587,
262593,
336326,
360917,
369119,
328178,
328180,
328183,
328190,
254463,
328193,
164362,
328207,
410129,
393748,
262679,
377372,
188959,
385571,
377384,
33322,
352822,
270905,
197178,
418364,
369224,
385610,
270922,
352844,
385617,
352865,
262761,
352875,
344694,
352888,
377473,
336513,
385671,
213642,
148106,
352919,
344745,
271018,
361130,
385714,
434868,
164535,
336568,
164539,
328379,
328387,
344777,
418508,
385743,
385749,
139998,
189154,
369382,
418540,
361196,
418555,
344832,
344837,
344843,
328462,
361231,
394002,
418581,
418586,
434971,
369436,
418591,
369439,
262943,
418594,
336676,
418600,
336681,
418606,
328498,
369464,
361274,
328516,
328520,
361289,
328523,
213848,
361307,
197469,
254813,
361310,
361318,
344936,
361323,
361335,
369544,
361361,
222129,
345036,
386004,
345046,
386012,
386019,
386023,
435188,
418822,
328710,
328715,
377867,
361490,
386070,
336922,
345119,
345134,
361525,
386102,
361537,
377931,
197708,
345172,
189525,
156762,
402523,
361568,
148580,
345200,
361591,
386168,
410746,
361599,
214150,
345224,
386187,
337048,
345247,
361645,
337072,
337076,
345268,
402615,
361657,
337093,
402636,
165086,
66783,
328933,
222438,
386286,
328942,
386292,
206084,
115973,
345377,
345380,
353572,
345383,
263464,
337207,
378170,
369979,
386366,
337224,
337230,
337235,
353634,
197987,
337252,
402792,
345449,
99692,
271731,
378232,
337278,
271746,
181639,
181644,
361869,
181650,
230810,
263585,
181671,
181674,
181679,
337330,
181682,
181687,
370105,
181691,
181697,
361922,
337350,
271841,
329192,
116211,
402943,
337416,
329227,
419341,
419345,
329234,
419351,
419357,
345631,
370208,
419360,
394787,
419363,
370214,
419369,
419377,
419386,
206397,
214594,
419401,
353868,
419408,
214611,
419412,
403040,
345702,
222831,
370298,
353920,
403073,
403076,
345737,
198282,
403085,
345750,
419484,
345758,
419492,
345766,
419498,
419502,
370351,
419507,
337588,
419510,
419513,
337601,
403139,
337607,
419528,
419531,
272083,
419543,
394967,
419545,
345819,
419548,
181982,
419551,
345829,
419560,
419564,
337647,
370416,
141052,
337661,
337671,
362249,
362252,
395022,
362256,
321300,
116512,
345888,
362274,
378664,
354107,
345916,
354112,
247618,
329545,
354124,
345932,
370510,
337743,
354132,
247639,
370520,
337751,
313181,
354143,
345965,
354157,
345968,
345971,
345975,
182136,
403321,
354173,
247692,
337809,
247701,
329625,
436133,
362414,
337845,
190393,
346059,
247760,
346064,
346069,
419810,
354275,
329699,
190440,
247790,
354314,
436290,
378956,
395340,
436307,
100454,
329853,
329857,
329868,
411806,
346273,
362661,
379067,
387261,
346317,
411862,
411865,
411869,
411874,
379108,
411877,
387303,
395496,
338154,
387307,
346350,
387314,
436474,
321787,
379135,
411905,
411917,
43279,
379154,
395539,
387350,
387353,
338201,
182559,
395567,
248112,
264502,
362823,
436556,
190797,
321880,
362844,
379234,
182642,
354674,
420237,
379279,
354728,
338353,
338382,
272849,
338387,
248279,
256474,
182755,
338404,
330225,
248309,
199165,
199189,
420377,
191012,
330320,
199250,
346722,
174696,
248427,
191085,
346736,
338544,
191093,
346743,
330384,
346769,
150184,
363198,
223936,
355025,
273109,
355029,
264919,
183006,
338661,
338665,
264942,
330479,
363252,
338680,
207620,
191240,
338701,
338712,
363294,
199455,
396067,
346917,
396070,
215854,
355123,
355141,
355144,
338764,
355151,
330581,
387929,
330585,
355167,
265056,
355176,
355180,
355185,
330612,
330643,
412600,
207809,
379849,
347082,
396246,
330711,
248794,
248799,
437219,
338928,
257009,
265208,
330750,
265215,
199681,
158759,
396329,
347178,
404526,
396337,
396340,
339002,
388155,
339010,
347208,
412765,
339037,
257121,
322660,
265321,
248952,
420985,
330886,
248986,
44199,
380071,
339118,
249015,
339133,
322763,
388320,
363757,
388348,
339199,
175376,
175397,
208167,
273709,
372016,
437553,
347442,
199989,
44343,
175416,
396601,
208189,
437567,
175425,
437571,
126279,
437576,
437584,
331089,
437588,
331094,
396634,
175451,
437596,
429408,
175458,
208228,
175461,
175464,
249210,
175484,
175487,
249215,
175491,
249219,
249228,
249235,
175514,
175517,
396706,
175523,
355749,
396723,
388543,
380353,
339401,
380364,
339406,
372177,
208338,
249303,
413143,
339418,
339421,
249310,
249313,
339425,
339429,
339435,
249329,
69114,
372229,
339464,
249355,
208399,
175637,
405017,
134689,
339504,
413251,
265796,
265806,
224854,
224858,
257636,
224871,
372328,
257647,
372338,
339572,
224885,
224888,
224891,
224895,
372354,
421509,
126597,
339593,
224905,
159375,
11919,
126611,
224917,
126618,
208539,
224923,
224927,
224930,
224933,
257705,
224943,
257713,
224949,
257717,
257721,
224954,
257725,
224960,
257733,
224966,
224970,
257740,
339664,
224976,
257745,
257748,
224982,
257752,
224987,
257762,
224996,
225000,
339696,
225013,
257788,
225021,
257791,
225027,
257796,
257802,
257805,
225039,
257808,
225044,
167701,
372500,
257815,
225049,
257820,
225054,
184096,
257825,
225059,
339748,
257837,
413485,
225071,
225074,
257843,
372533,
225077,
257846,
225080,
397113,
225083,
397116,
257853,
225088,
225094,
225097,
323404,
257869,
257872,
225105,
339795,
397140,
225109,
225113,
257881,
257884,
257887,
225120,
413539,
257891,
225128,
257897,
339818,
225138,
339827,
257909,
372598,
225142,
257914,
257917,
225150,
257922,
380803,
225156,
339845,
257927,
225166,
397201,
225171,
380823,
225176,
225183,
184245,
372698,
372704,
372707,
356336,
372739,
266298,
217158,
421961,
200786,
356440,
217180,
430181,
356467,
266365,
192640,
266375,
381069,
225425,
250003,
225430,
250008,
356507,
225439,
225442,
438434,
225445,
225448,
356521,
438441,
225451,
225456,
430257,
225459,
225462,
225468,
389309,
225472,
372931,
225476,
389322,
225485,
225488,
225491,
225494,
266454,
225497,
225500,
225503,
225506,
356580,
217319,
225511,
225515,
225519,
381177,
397572,
389381,
381212,
258333,
356638,
356641,
356644,
356647,
389417,
356650,
356656,
332081,
307507,
356662,
397623,
332091,
225599,
332098,
201030,
348489,
151884,
430422,
348503,
250201,
332126,
332130,
250211,
340328,
250217,
348523,
332153,
356734,
250239,
389503,
438657,
332158,
389507,
348548,
356741,
332175,
160152,
373146,
340380,
373149,
373169,
266688,
201158,
127473,
217590,
340473,
266757,
340512,
381483,
356908,
356917,
348734,
356935,
348745,
381513,
389724,
332381,
373344,
381546,
119432,
340628,
184983,
373399,
340639,
332455,
389806,
381626,
373450,
357070,
357074,
332512,
332521,
340724,
332534,
155647,
348926,
389927,
152371,
348979,
348983,
340792,
398141,
127815,
357202,
389971,
136024,
357208,
389979,
357212,
430940,
357215,
439138,
201580,
201583,
349041,
340850,
201589,
430967,
324473,
398202,
119675,
324476,
340859,
324479,
324482,
373635,
324485,
324488,
381834,
324493,
324496,
324499,
430996,
324502,
324511,
422817,
373672,
324525,
111539,
324534,
324539,
324542,
398280,
349129,
340940,
340942,
209874,
431073,
398307,
340964,
209896,
201712,
209904,
381947,
201724,
431100,
431107,
349203,
250915,
357411,
250917,
357419,
209980,
209996,
431180,
341072,
349268,
250968,
210011,
373853,
341094,
210026,
210032,
349296,
210037,
349309,
152704,
349313,
160896,
210053,
210056,
259217,
373905,
210068,
251045,
210108,
333010,
210132,
333016,
210144,
218355,
218361,
275709,
275713,
242947,
275717,
349460,
333079,
251161,
349486,
349492,
251190,
415034,
251211,
357710,
210261,
365912,
259423,
374113,
365922,
374118,
333164,
234867,
390518,
357756,
136591,
374161,
349591,
333222,
259516,
415168,
54724,
415187,
415192,
415194,
415197,
415208,
366057,
366064,
423424,
415258,
415264,
366118,
382503,
415271,
349739,
144940,
415279,
415282,
349748,
415286,
210488,
415291,
415295,
349762,
333387,
333396,
374359,
366173,
333415,
423529,
423533,
333423,
210547,
415354,
333440,
267910,
333472,
333499,
333512,
210632,
259789,
358100,
366301,
153311,
333535,
366308,
366312,
431852,
399086,
366319,
210673,
366322,
399092,
366326,
268042,
210700,
366349,
210707,
399129,
210720,
366384,
358192,
210740,
366388,
358201,
399166,
325441,
366403,
325447,
341831,
341835,
341839,
341844,
415574,
341852,
350046,
399200,
399208,
358256,
268144,
341877,
399222,
325494,
243584,
325505,
333699,
399244,
333725,
382891,
382898,
333767,
350153,
358348,
333777,
399318,
358372,
350194,
333819,
350204,
350207,
350214,
219144,
268299,
350225,
186388,
350241,
374819,
350245,
350249,
350252,
178221,
350272,
243782,
350281,
374865,
342113,
342134,
374904,
268435,
333989,
350411,
350417,
350423,
350426,
334047,
350449,
375027,
358645,
350459,
350462,
350465,
350469,
325895,
268553,
194829,
350477,
268560,
350481,
432406,
350487,
325915,
350491,
325918,
350494,
325920,
350500,
194854,
350505,
391469,
350510,
358701,
358714,
358717,
383307,
334162,
358738,
383331,
383334,
391531,
383342,
268669,
194942,
391564,
383375,
366991,
268702,
416159,
342431,
375209,
326059,
375220,
334263,
358857,
195041,
334306,
104940,
375279,
162289,
416255,
350724,
350740,
334359,
342551,
342555,
334364,
416294,
350762,
252463,
334386,
358962,
358973,
334397,
252483,
219719,
399957,
334425,
326240,
375401,
268922,
334466,
334469,
162446,
326291,
342680,
342685,
260767,
342711,
260798,
260802,
350918,
342737,
391895,
154329,
416476,
113389,
342769,
203508,
375541,
342777,
391938,
391949,
326417,
375569,
375572,
375575,
375580,
162592,
326444,
383794,
326452,
326455,
375613,
244542,
326463,
326468,
326474,
326479,
326486,
342875,
326494,
326503,
375657,
433001,
326508,
400238,
326511,
211832,
392061,
359296,
351105,
252801,
260993,
400260,
211846,
342921,
236432,
342931,
400279,
392092,
400286,
252838,
359335,
252846,
400307,
351169,
359362,
170950,
187335,
359367,
359383,
359389,
383968,
359411,
261109,
261112,
244728,
383999,
261130,
326669,
261148,
359452,
211999,
261155,
261160,
359471,
375868,
343132,
384099,
384102,
326764,
367724,
384108,
326767,
187503,
343155,
384115,
212095,
351366,
384144,
351382,
351399,
367795,
367801,
351424,
244934,
367817,
326858,
244938,
253132,
343246,
351450,
343272,
351467,
351480,
351483,
351492,
343307,
261391,
359695,
253202,
261395,
253218,
171304,
384299,
376111,
326970,
384324,
343366,
212296,
212304,
367966,
343394,
343399,
367981,
343410,
155000,
327035,
253321,
155021,
384398,
245143,
343453,
155045,
40358,
245163,
114093,
343478,
359867,
384444,
146878,
327112,
384457,
327116,
327118,
359887,
359891,
343509,
368093,
155103,
343535,
343540,
368120,
343545,
409092,
253445,
359948,
359951,
245295,
359984,
343610,
400977,
400982,
343650,
245358,
138865,
155255,
155274,
368289,
425639,
425652,
155323,
425663,
155328,
155352,
212700,
155356,
155364,
245477,
155372,
212723,
245495,
409336,
155394,
155404,
245528,
155423,
360224,
155439,
204592,
155444,
155448,
384829,
384831,
360262,
155463,
155477,
376665,
155484,
261982,
425823,
376672,
155488,
155492,
327532,
261997,
376686,
262000,
262003,
425846,
262006,
327542,
262009,
147319,
262012,
155517,
155523,
155526,
360327,
376715,
155532,
262028,
262031,
262034,
262037,
262040,
262043,
155550,
253854,
262046,
262049,
262052,
155560,
155563,
155566,
393152,
311244,
212945,
393170,
155604,
155620,
253924,
155622,
253927,
327655,
360432,
204785,
393204,
360439,
253944,
393209,
393215
] |
a4ef1e0f00b68478b397e2964626d7e86ba9de21 | 23a54eb5ea872f461b5e1949ea19340ec52c003f | /src/Element/style/collection/utils/StyleCollectionParser.swift | 2d02bf86e4326ebfcc26de645d88f029947abe80 | [
"MIT"
] | permissive | Kode-Kitchen/Element | 1a8f1126216540622bc522d219b2cd97bcc90868 | 6019faceb93b6d2b039cd2a9d9fb19f6357464dd | refs/heads/master | 2021-01-23T01:12:08.370814 | 2017-03-22T13:59:03 | 2017-03-22T13:59:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,349 | swift | import Foundation
/*@testable import Utils*/
class StyleCollectionParser {
/**
* Returns an array of style names
*/
static func styleNames(_ styleCollection:IStyleCollection) -> [String]{
var styleNames:[String] = []
for i in 0..<styleCollection.styles.count{//TODO:use forEach instead
styleNames.append(styleCollection.styles[i].name)
}
return styleNames
}
/**
* Describes the stylecollection content
* Note can you use the ObjectDescriber in place of this class?
*/
static func describe(_ styleCollection:IStyleCollection) {
func printStyleProperties(_ style:IStyle) {
//Swift.print("printStyleProperties:")
Swift.print("<style.name>:"+style.name)
var propertyNames:Array = StyleParser.stylePropertyNames(style)
for e in 0..<style.styleProperties.count{//<--swift 3 for loop upgrade
let property:Any = style.getValueAt(e)
let name:String = propertyNames[e]
Swift.print("name:" + name + ", property: " + String(describing: property))
}
}
for i in 0..<styleCollection.styles.count{//<--swift 3 for loop upgrade
let style:IStyle = styleCollection.styles[i]
printStyleProperties(style)
}
}
}
| [
-1
] |
ad25951ddd98c536e56fe34a1de4e7d5952b2f08 | c9b22d20aab9b0015fcac0bab41eb5cd79e58392 | /SwiftUIFun/Animations/Unsplash/UnsplashListView.swift | 02fd30aec9bf1eaeffbad84727957806c2484fe6 | [] | no_license | connorb645/SwiftUIFun | 47e45f502adb24b623995fb0caef3c9d716105f5 | b7e4f1551cf6e4bdd71f19c17a4abb97b8545916 | refs/heads/main | 2023-06-27T06:02:37.414107 | 2021-07-14T15:28:15 | 2021-07-14T15:28:15 | 320,386,478 | 5 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,932 | swift | //
// UnsplashListView.swift
// SwiftUIFun
//
// Created by Connor Black on 18/12/2020.
//
import SwiftUI
struct UnsplashListView: View {
let imageNames: [String] = ["unsplash-1", "unsplash-2", "unsplash-3", "unsplash-4", "unsplash-5", "unsplash-6", "unsplash-7", "unsplash-8", "unsplash-9", "unsplash-10", "unsplash-11"]
@State var selectedImage: String?
@Namespace var unsplashNamespace
var body: some View {
ZStack {
ScrollView {
VStack(alignment: .center, spacing: 0) {
ForEach(imageNames, id: \.self) { imageName in
GeometryReader { geo in
VStack(alignment: .center) {
Button(action: {
withAnimation(Animation.spring()) {
self.selectedImage = imageName
}
}, label: {
Image(imageName)
.resizable()
.matchedGeometryEffect(id: imageName, in: unsplashNamespace)
.aspectRatio(contentMode: .fill)
.clipped()
.frame(width: geo.size.width - 40, height: 250)
.cornerRadius(20)
.rotation3DEffect(Angle(degrees: Double((geo.size.height - (geo.frame(in: .named("ParentScrollView")).minY)) / 20)), axis: (x: -1, y: 0, z: 0))
})
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}.frame(height: 250)
}
}
.padding(.vertical)
}
.edgesIgnoringSafeArea(.bottom)
.blur(radius: selectedImage == nil ? 0 : 20)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.coordinateSpace(name: "ParentScrollView")
if let image = selectedImage {
ZStack() {
VStack {
Spacer()
Image(image)
.resizable()
.cornerRadius(20)
.aspectRatio(contentMode: .fit)
.padding(.horizontal, 20)
.matchedGeometryEffect(id: image, in: unsplashNamespace)
Spacer()
}
}
.background(Color.offBlack.opacity(0.1))
.edgesIgnoringSafeArea(.bottom)
.onTapGesture {
withAnimation(Animation.spring()) {
selectedImage = nil
}
}
}
}
.navigationBarHidden(false)
.navigationBarTitle("Unsplash", displayMode: .inline)
}
}
struct UnsplashListView_Previews: PreviewProvider {
static var previews: some View {
UnsplashListView()
}
}
| [
-1
] |
d560932e7731c3240a9294c61f59fe1a698c8201 | b916e719c24a03973aff4f78105f4873c51fd6d0 | /CollectionView/AppDelegate.swift | a1906a7704a34871909ea2810e062846ef9e87ee | [] | no_license | ShawnMoore/SwiftUICollection | 897eab6bb996bccee0cb46ef4008c91a4125959f | f23fae02160398bd1f75303f307f45b60de1a173 | refs/heads/master | 2020-06-10T02:11:28.283592 | 2019-07-03T16:26:45 | 2019-07-03T16:26:45 | 193,552,938 | 7 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,623 | swift | //
// AppDelegate.swift
// CollectionView
//
// Created by Shawn Moore on 6/21/19.
// Copyright © 2019 Shawn Moore. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
354313,
268298,
393230,
333850,
346139,
405533,
393250,
344102,
393261,
350256,
393266,
163891,
376889,
385081,
393275,
217157,
243781,
421960,
376905,
378954,
327756,
350285,
286800,
374864,
338004,
180313,
342111,
180320,
368735,
376931,
430180,
100453,
329832,
286831,
342133,
374902,
286844,
286850,
381068,
250002,
250004,
225429,
329885,
225437,
286879,
135327,
225441,
346272,
225444,
362660,
438436,
286888,
438440,
100524,
333997,
258222,
225455,
430256,
225461,
225466,
379066,
225470,
256191,
327871,
381120,
350410,
260298,
225484,
346316,
377036,
180431,
350416,
225487,
225490,
225493,
350422,
377046,
411861,
350425,
211160,
268507,
225496,
334045,
411864,
411868,
225502,
411873,
356578,
379107,
377060,
411876,
225510,
346343,
338152,
327914,
350445,
225518,
372976,
393456,
375026,
346355,
393460,
381176,
350458,
321786,
336123,
350461,
411903,
350464,
325891,
350467,
262404,
389380,
180490,
350475,
350480,
262416,
379152,
350486,
338199,
262422,
387352,
350490,
325917,
350493,
356637,
356640,
350498,
338211,
262436,
356643,
350504,
356649,
350509,
248111,
332080,
356655,
340275,
336180,
356660,
262454,
332090,
332097,
362822,
262472,
348488,
332106,
190796,
334161,
213332,
321879,
250199,
383321,
250202,
332125,
418144,
250210,
383330,
213352,
348522,
246123,
391530,
348525,
262510,
348527,
354673,
321910,
332152,
334203,
213372,
194941,
250238,
385419,
391563,
420236,
379278,
340379,
385443,
354727,
393647,
338352,
334262,
262586,
262592,
334275,
326084,
358856,
330189,
338381,
338386,
360916,
369118,
334304,
338403,
334311,
375277,
328177,
334321,
328179,
328182,
340472,
199164,
328189,
324094,
328192,
330252,
328206,
324111,
410128,
186897,
342545,
199186,
340500,
324117,
334358,
393747,
342554,
334363,
254490,
330267,
188958,
332324,
354855,
377383,
350761,
381481,
324139,
356907,
252461,
324142,
334384,
358961,
356916,
324149,
352821,
334394,
324155,
188987,
348733,
324160,
252482,
219718,
356934,
334407,
369223,
381512,
385609,
10828,
324173,
324176,
199249,
352856,
174695,
262760,
248425,
191084,
346742,
377472,
334465,
148105,
162445,
326290,
340627,
184982,
342679,
98968,
342683,
260766,
332453,
150183,
361129,
332459,
332463,
381617,
385713,
164534,
332471,
336567,
248504,
328378,
244409,
342710,
223934,
334528,
328386,
332483,
350917,
332486,
352968,
352971,
418507,
332493,
385742,
273108,
264918,
416473,
361179,
183005,
189153,
338660,
264941,
342766,
375535,
203506,
363251,
332533,
342776,
348924,
344831,
207619,
338700,
326416,
336659,
418580,
418585,
434970,
369435,
199452,
418589,
418593,
336675,
328484,
346916,
389926,
215853,
418605,
355122,
326451,
340789,
326454,
348982,
355131,
244540,
326460,
375612,
326467,
328515,
355140,
127814,
244551,
328519,
326473,
328522,
336714,
338763,
326477,
336711,
355143,
355150,
330580,
326485,
416597,
426841,
326490,
430939,
254812,
355166,
361315,
326502,
355175,
361322,
201579,
326507,
355179,
201582,
326510,
211825,
330610,
201588,
211831,
324472,
398201,
119674,
324475,
340858,
328573,
324478,
351104,
324481,
373634,
377729,
324484,
324487,
324492,
236430,
324495,
330642,
430995,
324501,
324510,
324513,
252836,
201637,
359334,
211884,
324524,
340909,
222128,
324533,
5046,
412599,
324538,
324541,
207808,
351168,
326598,
398279,
379848,
340939,
340941,
345043,
359382,
248792,
386011,
340957,
431072,
386018,
340963,
398306,
386022,
209895,
359407,
257008,
183282,
435187,
349172,
244726,
330748,
383997,
328702,
431106,
330760,
328714,
330768,
361489,
209943,
336921,
261147,
359451,
336925,
345118,
250914,
158761,
209965,
345133,
209968,
345138,
209971,
209975,
339001,
209979,
388161,
209987,
347205,
209990,
248904,
330826,
341071,
189520,
345169,
248914,
349267,
250967,
156761,
210010,
339036,
257120,
384098,
341091,
384101,
210025,
210027,
367723,
210030,
345199,
210039,
410745,
210044,
152703,
160895,
349311,
210052,
384135,
210055,
330889,
384139,
210067,
351381,
384151,
210071,
337047,
248985,
339097,
210077,
345246,
214175,
210080,
384160,
384157,
210084,
251044,
210088,
210095,
337071,
210098,
337075,
244916,
367794,
249014,
210107,
384188,
351423,
210115,
332997,
326855,
384201,
244937,
343244,
330958,
384208,
333009,
146642,
210131,
386258,
330965,
333014,
210138,
384224,
359649,
343270,
351466,
386285,
384246,
351479,
251128,
275715,
275721,
343306,
261389,
359694,
261393,
384275,
333078,
251160,
384283,
245020,
384288,
345376,
345379,
245029,
208166,
410917,
351534,
372015,
376110,
349491,
199988,
251189,
345399,
378169,
415033,
120128,
437570,
212291,
126277,
337222,
343365,
437575,
251210,
357708,
212303,
331088,
337234,
331093,
365911,
396633,
259421,
367965,
343393,
175457,
208227,
251235,
374117,
343398,
175463,
345448,
333162,
367980,
343409,
234866,
378227,
175477,
154999,
333175,
249208,
327034,
175483,
343417,
249214,
249218,
181638,
245127,
249224,
353673,
181643,
249227,
384397,
136590,
245136,
181649,
249234,
112020,
181654,
245142,
245145,
343450,
175513,
245148,
245151,
357792,
245154,
245157,
181670,
245162,
380332,
181678,
337329,
396722,
181684,
359865,
181690,
384443,
146876,
361917,
181696,
327107,
372163,
384453,
216517,
181703,
337349,
216522,
327115,
327117,
359886,
372176,
208337,
366034,
343507,
415185,
337365,
339412,
413141,
339417,
249308,
271839,
249312,
333284,
366056,
339434,
329194,
343534,
116210,
343539,
210420,
337398,
368119,
343544,
368122,
329226,
419343,
380432,
419349,
345625,
419355,
370205,
419359,
394786,
419362,
366117,
144939,
339503,
359983,
419376,
265778,
210487,
206395,
214593,
349761,
415300,
396872,
419400,
333386,
353867,
419402,
265805,
343630,
419406,
419410,
333399,
366172,
333413,
394853,
372327,
423528,
327275,
423532,
245357,
222830,
138864,
210544,
224884,
224887,
224890,
224894,
224897,
216707,
339588,
403075,
421508,
155273,
159374,
11918,
339601,
224913,
224916,
345749,
224919,
224922,
345757,
245409,
345762,
224929,
419491,
224932,
345765,
425638,
224936,
257704,
419497,
419501,
224942,
370350,
257712,
419509,
337592,
257720,
419512,
155322,
257724,
425662,
337599,
155327,
257732,
333511,
419527,
419530,
339662,
419535,
272081,
358099,
245460,
419542,
155351,
419544,
181977,
155354,
212699,
419547,
419550,
224993,
257761,
245475,
155363,
366307,
224999,
419559,
337642,
245483,
419563,
337645,
366318,
339695,
210672,
431851,
366325,
141051,
225020,
337659,
339710,
225025,
337668,
210695,
339721,
210698,
366348,
395021,
210706,
321299,
372499,
116509,
184094,
345887,
155422,
225053,
225058,
378663,
225066,
413484,
225070,
358191,
225073,
366387,
372532,
399159,
155447,
358200,
225082,
225087,
325440,
247617,
366401,
341829,
325446,
354117,
155461,
46920,
323402,
341834,
370503,
370509,
341838,
354130,
341843,
415573,
337750,
376663,
358234,
155482,
313180,
261981,
354142,
155487,
425822,
155490,
155491,
261996,
261999,
358255,
262002,
327539,
341876,
358259,
345970,
425845,
345974,
333689,
262008,
403320,
155516,
354172,
325504,
155521,
333698,
339844,
155525,
155531,
247691,
262027,
262030,
333708,
337808,
247700,
262036,
329623,
262039,
225180,
333724,
155549,
436126,
262048,
118691,
436132,
327589,
155559,
337833,
382890,
155565,
362413,
184244,
337844,
372664,
350146,
358339,
346057,
333774,
247759,
346063,
393169,
372702,
329697,
358371,
155619,
155621,
327654,
253926,
354277,
247789,
350189,
393203,
380918,
360438,
393206,
393212
] |
64b77c4b0c2b264305062125fc2b15d860d6c56f | 129589ae5823724cc794d59e4cfe3b3ade67aa18 | /YoonitCamera/src/delegates/CameraEventListenerDelegate.swift | 9e064a85ae7efd381227d5d8b3e91cb805657fe9 | [
"MIT"
] | permissive | tuanle259/ios-yoonit-camera | 36adf88eecfd56502b6a72a6d0c999491863b06a | edc6d3ea88c00aa80e4ac46a3be3fdc82bd11255 | refs/heads/master | 2023-06-14T09:01:54.086193 | 2021-07-08T13:46:09 | 2021-07-08T13:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,216 | swift | //
// +-+-+-+-+-+-+
// |y|o|o|n|i|t|
// +-+-+-+-+-+-+
//
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Yoonit Camera lib for iOS applications |
// | Haroldo Teruya & Marcio Brufatto @ Cyberlabs AI 2020-2021 |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
import Foundation
@objc
public protocol CameraEventListenerDelegate {
func onImageCaptured(
_ type: String,
_ count: Int,
_ total: Int,
_ imagePath: String,
_ darkness: NSNumber?,
_ lightness: NSNumber?,
_ sharpness: NSNumber?
)
func onFaceDetected(
_ x: Int,
_ y: Int,
_ width: Int,
_ height: Int,
_ leftEyeOpenProbability: NSNumber?,
_ rightEyeOpenProbability: NSNumber?,
_ smilingProbability: NSNumber?,
_ headEulerAngleX: NSNumber?,
_ headEulerAngleY: NSNumber?,
_ headEulerAngleZ: NSNumber?
)
func onFaceUndetected()
func onEndCapture()
func onError(_ error: String)
func onMessage(_ message: String)
func onPermissionDenied()
func onQRCodeScanned(_ content: String)
}
| [
-1
] |
90548ef532497dbb4103576710d4313101fbc95d | 87f7e6cc56bc62e1a52a0b09401682bcd569a8af | /QuintypeMusicPlayer/MediaControll.swift | 90b145e64c0b772609204f8de8cb4dbff18632df | [] | no_license | quintype/musicplayer | db41fff727ed24f0c96f0ad9af491195ce9a14c5 | 561f4f5291fbf46eaf03f665fd7508ed5c891531 | refs/heads/master | 2021-01-01T16:15:01.842299 | 2017-07-20T08:14:29 | 2017-07-20T08:14:29 | 97,794,903 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,648 | swift | //
// MediaControll.swift
// MusicPlayer
//
// Created by Albin.git on 6/14/17.
// Copyright © 2017 Albin.git. All rights reserved.
//
import Foundation
import MediaPlayer
//MARK: - Control Center NowPlaying
extension Player{
public func configureCommandCenter() {
self.commandCenter.playCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let musicPlayer = self else { return .commandFailed }
musicPlayer.didClickOnPlay()
musicPlayer.updateNowPlayingInfoElapsedTime()
return .success
})
self.commandCenter.pauseCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let musicPlayer = self else { return .commandFailed }
if musicPlayer.player.isPlaying{
musicPlayer.didClickOnPlay()
musicPlayer.updateNowPlayingInfoElapsedTime()
}
return .success
})
self.commandCenter.nextTrackCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let musicPlayer = self else { return .commandFailed }
musicPlayer.didClickOnNext()
musicPlayer.updateNowPlayingInfoElapsedTime()
return .success
})
self.commandCenter.previousTrackCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let musicPlayer = self else { return .commandFailed }
musicPlayer.didClickOnPrevious()
musicPlayer.updateNowPlayingInfoElapsedTime()
return .success
})
self.commandCenter.changePlaybackPositionCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if let unwrappedEvent = event as? MPChangePlaybackPositionCommandEvent{
print(unwrappedEvent.positionTime)
let position = unwrappedEvent.positionTime
let playerItemDuration = self.currentPlayerItemDuration
let valued = (position * (1)/playerItemDuration.seconds)
self.deinitTimeObserver()
self.initTimeObserver()
self.scrub(value: Float(valued), minValue: 0, maxValue: 1, isSeeking: { (isSeeking) in
print(isSeeking)
})
}
return .success
}
self.commandCenter.seekForwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
return .success
}
}
public func updateNowPlayingInfoForCurrentPlaybackItem(){
guard (self.player) != nil else {
self.configureNowPlayingInfo(nil)
return
}
guard let datasource = self.dataSource else {self.removeStatusObservers(); return}
let unwrappedUrl = datasource.musicPlayerDidAskForArtWorksImageUrl(manager: self,size: .medium)
let titleAndAuthor = datasource.musicPlayerDidAskForTrackTitleAndAuthor(manager: self)
let nowPlayingInfo = [MPMediaItemPropertyTitle:titleAndAuthor.0,
MPMediaItemPropertyArtist:titleAndAuthor.1,
MPMediaItemPropertyPlaybackDuration:"\(self.currentPlayerItemDuration.seconds)",
MPNowPlayingInfoPropertyPlaybackRate:NSNumber(value: 1.0 as Float)] as [String : Any]
self.downloadImage(url: unwrappedUrl, completion: { (image) -> (Void) in
guard var nowPlayingInfo = self.nowPlayingInfo else { return }
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: CGSize(width: 100, height: 100), requestHandler: { (size) -> UIImage in
return image
})
self.configureNowPlayingInfo(nowPlayingInfo)
})
self.configureNowPlayingInfo(nowPlayingInfo as [String : AnyObject]?)
self.updateNowPlayingInfoElapsedTime()
}
public func downloadImage(url:URL?, completion:@escaping ((UIImage) -> (Void))){
if let unwrappedUrl = url{
URLSession.shared.dataTask(with: unwrappedUrl) { (data, response, error) in
DispatchQueue.main.async {
if let unwrappedData = data{
completion(UIImage(data: unwrappedData) ?? UIImage())
}
}
}.resume()
}
}
public func configureNowPlayingInfo(_ nowPlayingInfo: [String: AnyObject]?) {
self.nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
self.nowPlayingInfo = nowPlayingInfo
}
public func updateNowPlayingInfoElapsedTime() {
guard var nowPlayingInfo = self.nowPlayingInfo else { return }
print("Player Current Time:\(self.player.currentTime().seconds)")
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NSNumber(value: self.player.currentTime().seconds as Double);
self.configureNowPlayingInfo(nowPlayingInfo)
}
public func resetNowPlayingInfoCenter(){
self.nowPlayingInfo = nil
self.nowPlayingInfoCenter.nowPlayingInfo = nil
}
public func updatePlayerUI(){
//set the duration
let playerDuration = self.currentPlayerItemDuration
self.multicastDelegate.invoke { (delegate) in
delegate.setPlayeritemDuration(duration: playerDuration.seconds)
}
//set artwork Image
guard let datasource = self.dataSource else {self.removeStatusObservers(); return}
let unwrappedUrl = datasource.musicPlayerDidAskForArtWorksImageUrl(manager: self,size: .medium)
let trackname = datasource.musicPlayerDidAskForTrackTitleAndAuthor(manager: self)
self.multicastDelegate.invoke(invokation: { (delegate:MusicPlayerDelegate) in
delegate.didsetArtWorkWithUrl(url: unwrappedUrl)
delegate.didsetName(title: trackname.0,AutorName: trackname.1)
})
}
open func getQueuedTracks() -> [Tracks]?{
guard let unwrappedDataSource = dataSource else{return nil}
return unwrappedDataSource.musicPlayerDidAskForQueue()
}
open func getCurrentSongIndex() -> Int?{
guard let unwrappedDataSource = dataSource else{return nil }
return unwrappedDataSource.musicPlayerDidAskForCurrentSongIndex()
}
}
| [
-1
] |
e37672938e3e7f54b231ce75bc5b03c871dcde60 | ffae875ba30bbbdac217f232a6ec08dfc3e97435 | /ApolloAI/DoctorProfileViewController.swift | 3ebad257735551ecae9a6650261ed288c3b1eb97 | [] | no_license | MangoHacks-2019/ParasiteAI-IOS | ee912423e24534d2387f3104917bac6dba137cf9 | 712573929666075b9ae81b786fe8b360cd14de78 | refs/heads/master | 2022-05-30T21:28:57.615961 | 2019-02-05T17:07:16 | 2019-02-05T17:07:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 5,194 | swift | //
// DoctorProfileViewController.swift
// ApolloAI
//
// Created by Luis F. Perrone on 2/2/19.
// Copyright © 2019 Luis Perrone. All rights reserved.
//
import UIKit
import EightBase
class DoctorProfileViewController: UIViewController {
@IBOutlet weak var doctorNameLabel: UILabel!
@IBOutlet weak var doctorImageView: UIImageView!
@IBOutlet weak var doctorImageBGView: UIView!
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var malayriaDetectorButton: UIButton!
@IBOutlet weak var firstPatient: UIButton!
@IBOutlet weak var secondPatient: UIButton!
@IBOutlet weak var thirdPatient: UIButton!
@IBOutlet weak var fourthPatient: UIButton!
@IBOutlet weak var fifthPatient: UIButton!
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.style
}
var style:UIStatusBarStyle = .lightContent
@IBAction func buttonAction(_ sender: Any) {
switch ((sender as! UIButton).tag) {
case 0:
let viewController = UIStoryboard.viewControllerMain(identifier: "CameraViewController") as! ViewController
self.present(viewController, animated: true, completion: nil)
break
case 1:
break
case 2:
mostRecentQuery(first: 5)
EightBase.Apollo?.clearCache()
viewDidLayoutSubviews()
print("Im HERE!! :D")
break
default:
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
prepareLayout()
setNeedsStatusBarAppearanceUpdate()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
mostRecentQuery(first: 5)
EightBase.Apollo?.clearCache()
}
func prepareLayout() {
cardView.layer.cornerRadius = 8.0
cardView.layer.masksToBounds = false
cardView.layer.shadowColor = UIColor.black.cgColor
cardView.layer.shadowRadius = 6
cardView.layer.shadowOpacity = 0.30
cardView.layer.shadowOffset = CGSize(width: -4, height: 8)
doctorImageBGView.layer.cornerRadius = 60
doctorImageBGView.layer.masksToBounds = false
doctorImageBGView.layer.shadowColor = UIColor.black.cgColor
doctorImageBGView.layer.shadowRadius = 6
doctorImageBGView.layer.shadowOpacity = 0.30
doctorImageBGView.layer.shadowOffset = CGSize(width: -4, height: 8)
doctorImageView.layer.cornerRadius = 57.5
doctorImageView.layer.masksToBounds = true
malayriaDetectorButton.layer.cornerRadius = 6.0
malayriaDetectorButton.layer.masksToBounds = false
malayriaDetectorButton.layer.shadowColor = UIColor.black.cgColor
malayriaDetectorButton.layer.shadowRadius = 6
malayriaDetectorButton.layer.shadowOpacity = 0.30
malayriaDetectorButton.layer.shadowOffset = CGSize(width: -4, height: 8)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension DoctorProfileViewController {
func mostRecentQuery(first: Int) {
// activityIndicator.startAnimating()
// 1
let patientsListQuery = PatientsListQuery(first: first, orderBy: [PatientOrderBy.createdAtDesc])
// 2
EightBase.Apollo?.fetch(query: patientsListQuery) { (result, error) in
if let error = error {
print(error.localizedDescription)
return
}
// 3
let res1: String! = result?.data?.patientsList.items[0].pname!
let res2: String! = result?.data?.patientsList.items[0].result!
self.firstPatient.setTitle( res1 + ": " + res2, for: .normal)
let res3: String! = result?.data?.patientsList.items[1].pname!
let res4: String! = result?.data?.patientsList.items[1].result!
self.secondPatient.setTitle( res3 + ": " + res4, for: .normal)
let res5: String! = result?.data?.patientsList.items[2].pname!
let res6: String! = result?.data?.patientsList.items[2].result!
self.thirdPatient.setTitle( res5 + ": " + res6, for: .normal)
let res7: String! = result?.data?.patientsList.items[3].pname!
let res8: String! = result?.data?.patientsList.items[3].result!
self.fourthPatient.setTitle( res7 + ": " + res8, for: .normal)
let res9: String! = result?.data?.patientsList.items[4].pname!
let res10: String! = result?.data?.patientsList.items[4].result!
self.fifthPatient.setTitle( res9 + ": " + res10, for: .normal)
print(result)
}
}
}
| [
-1
] |
734f85e64aad79ec2b0fdc209fdb390c6eba567c | 4a21056c56ee379a11f28d441d5c7102892b7bfc | /MyMovies/View Controllers/MovieSearchTableViewController.swift | ca229c1da2ca846e808ca44c7a579f8198771ca3 | [] | no_license | hedgemanNate/ios-sprint-challenge-my-movies | 3934b8b107e3c295de5703deda7af3bcdffb4df8 | c4d73586bbd398ffb1f9ab8595d23f5488a62642 | refs/heads/master | 2020-07-10T19:31:28.744167 | 2019-08-27T20:56:09 | 2019-08-27T20:56:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,678 | swift | //
// MovieSearchTableViewController.swift
// MyMovies
//
// Created by Spencer Curtis on 8/17/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
class MovieSearchTableViewController: UITableViewController, UISearchBarDelegate, SearchMovieTableViewCellDelegate {
//Properties
var movieController = MovieController()
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
func addMovieToCoreData(for cell: SearchMovieTableViewCell) {
guard let title = cell.titleLabel.text else { return }
self.movieController.createMovie(withTitle: title)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let searchTerm = searchBar.text else { return }
movieController.searchForMovie(with: searchTerm) { (error) in
guard error == nil else { return }
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movieController.searchedMovies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as? SearchMovieTableViewCell else {return UITableViewCell() }
cell.titleLabel.text = movieController.searchedMovies[indexPath.row].title
cell.delegate = self
return cell
}
}
| [
-1
] |
019d8e5df843dee1c5e2aeeb65fbca6203fa6040 | 4e2d24bbce04c9125d780f677be17c0a1883327d | /Math Equations/Modules/Settings/View/SettingsController.swift | 681ef2117977b72eeb3920fdecee895569378d43 | [] | no_license | MhMudSalAh/IOS-Math-Equations | 3a99fdfa3d5d396249d8c791ca7ee1d4cb4e2c7f | 96060aa02c57ad7471f1b549ebe40c2372eac8ad | refs/heads/master | 2023-07-18T01:50:04.076276 | 2021-09-02T17:23:37 | 2021-09-02T17:23:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,489 | swift | //
// SettingsController.swift
// Math Equations
//
// Created by MhMuD SalAh on 01/09/2021.
//
import UIKit
class SettingsController: BaseController {
@IBOutlet weak var tableView: UITableView!
var presenter: SettingsPresenterInterface!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
navigationItem.title = localizedText("settings")
initTableView()
}
}
extension SettingsController: SettingsView {
func showLanguageAlert() {
let alert = UIAlertController(title: localizedText("change_language_message"), message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: localizedText("english"), style: .default) { action in
self.presenter.switchToEnglishApp()
})
alert.addAction(UIAlertAction(title: localizedText("arabic"), style: .default) { action in
self.presenter.switchToArabicApp()
})
alert.addAction(UIAlertAction(title: localizedText("cancel"), style: .cancel, handler: nil))
if let popover = alert.popoverPresentationController {
popover.sourceView = self.view
popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popover.permittedArrowDirections = []
}
self.present(alert, animated: true, completion: nil)
}
}
| [
-1
] |
4a09f43427a55b99f79031ce2876432d4812b992 | e6f2c642ace73ca1fc5ccb96b816d75e4eebdb4e | /AcceptanceTests/Fixtures/XcodeServerSynchronisation/ShouldCreateABotWhenOutOfSyncWithXcodeServer.swift | fccf46990caf1e63a07886423fa273692ff35468 | [] | no_license | seanhenry/xcsautobuild | c1fed8e2461fa3577e0e4691a4af77007fa0e247 | 6f883edf9a730dfdb9e65acc95f321a2419fcec3 | refs/heads/master | 2020-04-12T06:19:48.419203 | 2016-12-15T20:46:26 | 2016-12-15T20:46:26 | 63,723,341 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 1,076 | swift |
import Foundation
@objc(ShouldCreateABotWhenOutOfSyncWithXcodeServer)
class ShouldCreateABotWhenOutOfSyncWithXcodeServer: XcodeServerSynchronisation {
// MARK: - Output
var botCreated: String!
var branchBotID: String!
// MARK: - Test
override func setUp() {
super.setUp()
botCreated = nil
branchBotID = nil
setUpGit(branches: branch)
}
override func test() {
super.test()
botCreated = fitnesseString(from: mockedNetwork.duplicateBotCount == 1)
branchBotID = botDataStore.load(fromBranchName: "develop")?.id
}
override func setUpMockedNetwork() {
super.setUpMockedNetwork()
mockedNetwork.expectDuplicateBot(id: testTemplateBotID)
mockedNetwork.stubGetBot(withID: validBotID, name: "develop")
mockedNetwork.stubGetBotError(withID: invalidBotID, statusCode: 404)
mockedNetwork.stubGetBot(withID: newBotID, name: "develop")
mockedNetwork.stubPatchBot(withID: newBotID)
mockedNetwork.stubbedDuplicatedBotID = newBotID
}
}
| [
-1
] |
0cd13d1953eb1c71519e8171cf6e0cf7c31e79e1 | 5490a291d6bffee7c7975e6089e529ef948001a9 | /Cart/Products/Model/InMemoryProducts.swift | fe27194f1bfdfa2b50a8d70210fb474bc3727518 | [
"MIT"
] | permissive | ip3r/Cart | 4b5a5e51c4708e37db08bb95e04c63e47cc804a7 | b523003c90bd718bd62c7a943d29835318040238 | refs/heads/master | 2020-06-01T10:38:06.702236 | 2017-06-12T17:53:11 | 2017-06-12T17:53:11 | 94,071,484 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 705 | swift | //
// InMemoryProducts.swift
// Cart
//
// Created by Jens Meder on 12.06.17.
// Copyright © 2017 Jens Meder. All rights reserved.
//
import Foundation
internal final class InMemoryProducts: Products {
private let products: Memory<[UUID:Memory<[String:String]>]>
private let product: (UUID) -> (Product)
// MARK: Init
internal required init(products: Memory<[UUID:Memory<[String:String]>]>, product: @escaping (UUID) -> (Product)) {
self.products = products
self.product = product
}
// MARK: Products
var count: Int {
return products.value.count
}
subscript(index: Int) -> Product {
let uuid = Array(products.value.keys)[index]
return product(uuid)
}
}
| [
-1
] |
0425c836a02e01e3393d893c9c0c8c1e18b60903 | 704c2fb2bf9fec8dd1c099f4a68bed4bb9b68fd5 | /XMLY_Learn_Swift/Module/Play/PlayDetail/Controller/XMLYPlayDetailProgramViewController.swift | fa9210722923e208fb94b042dbdf41248d436248 | [
"MIT"
] | permissive | JingyuZhao/XMLY_Learn_Swift | 4c6e076ffb2a327bedc16ae374d2378606793d33 | 4a849b132b5414e919808da3be74582417b235fe | refs/heads/master | 2020-09-14T10:41:12.854621 | 2019-11-21T06:41:07 | 2019-11-21T06:41:07 | 223,105,791 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,591 | swift | //
// XMLYPlayDetailProgramViewController.swift
// XMLY_Learn_Swift
//
// Created by zhaojingyu on 2019/11/12.
// Copyright © 2019 XMLY. All rights reserved.
//
import UIKit
import LTScrollView
class XMLYPlayDetailProgramViewController: XMLYBaseViewController,LTTableViewProtocal {
private var playDetailTracks:XMLYPlayDetailTracksModel?
private let XMLYPlayDetailProgramCellID : String = "XMLYPlayDetailProgramCellID"
private lazy var tableView : UITableView = {
let tableView = tableViewConfig(CGRect.init(x: 0, y: 0, width: XMLYScreenWidth, height: XMLYScreenHeight), self, self, nil)
tableView.register(XMLYPLayDetailProgramCell.self, forCellReuseIdentifier: XMLYPlayDetailProgramCellID)
tableView.separatorStyle = .none
tableView.rowHeight = 80
return tableView
}()
var playDetailTracksModel:XMLYPlayDetailTracksModel?{
didSet{
guard let model = playDetailTracksModel else {return}
self.playDetailTracks = model
// self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func configUI() {
self.view.addSubview(self.tableView)
glt_scrollView = tableView
}
}
extension XMLYPlayDetailProgramViewController : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.playDetailTracks?.list?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: XMLYPlayDetailProgramCellID, for: indexPath) as! XMLYPLayDetailProgramCell
cell.indexPath = indexPath
cell.playDetailTracksList = self.playDetailTracks?.list?[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let albumId = self.playDetailTracks?.list?[indexPath.row].albumId ?? 0
let trackUid = self.playDetailTracks?.list?[indexPath.row].trackId ?? 0
let uid = self.playDetailTracks?.list?[indexPath.row].uid ?? 0
let vc = XMLYNavigationController.init(rootViewController: XMLYPlayDetailPlayerViewController(albumId:albumId, trackUid:trackUid, uid:uid))
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
}
}
| [
-1
] |
fba99b64116476bfb4b3498af944bc57d8edb588 | 6e32f2bfe6811f0c00fe7ff3ff4ba38796b662d7 | /anniu/anniu/ViewController.swift | f614ca03827e79bb7de21b864be2711d173c1c3e | [] | no_license | 20161104574/aaaaaa | 9501ee1f5d371feb60db02864f47aad52c74d5c8 | 5413a7be835d7ad3502373ad40c7b68acff09adf | refs/heads/master | 2020-03-29T21:22:15.900348 | 2018-10-10T02:21:09 | 2018-10-10T02:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 355 | swift | //
// ViewController.swift
// anniu
//
// Created by 20161104574 on 2018/9/21.
// Copyright © 2018年 20161104574. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| [
327555,
334467,
350725,
323334,
240520,
333177,
316810,
249229,
189326,
319888,
342547,
329235,
316949,
314774,
291223,
317972,
409238,
316825,
314780,
342300,
316317,
135840,
324769,
135842,
172578,
326435,
396707,
190120,
340649,
172586,
242346,
337068,
336557,
241071,
322735,
243505,
172722,
244411,
314048,
339520,
266816,
354113,
219715,
313029,
319815,
326600,
323016,
182474,
353869,
437582,
346065,
323575,
146645,
328926,
313182,
359390,
412766,
353635,
250212,
315492,
56044,
215408,
343541,
319990,
435189,
327033,
415355,
314748,
334205,
351486
] |
2a38647f2cec3ed29e1538776dba6b0849d297aa | e5dbaad57d3cb1fc0cf92fdfb96b4189f709af53 | /test/ReddiftColorTest.swift | 7afa32d134d127f7ad5d14b7f8e900033ed844a4 | [
"MIT"
] | permissive | ccrama/reddift | 2373f35804aaa5b3f209aad327d339d026af6125 | bb77a789b94731d0291f1a673f343cbcab13e02c | refs/heads/master | 2021-07-13T08:16:33.907303 | 2021-03-27T23:24:48 | 2021-03-27T23:24:48 | 77,404,008 | 7 | 8 | MIT | 2021-03-27T23:24:48 | 2016-12-26T19:54:00 | Swift | UTF-8 | Swift | false | false | 680 | swift | //
// ReddiftColorTest.swift
// reddift
//
// Created by sonson on 2017/01/05.
// Copyright © 2017年 sonson. All rights reserved.
//
import XCTest
class ReddiftColorTest: XCTestCase {
func testReddiftColor() {
let hexString = "#FFFF00"
let color = ReddiftColor.color(with: hexString)
XCTAssert(color.hexString() == hexString)
}
func testReddiftClassMethodColor() {
XCTAssert(ReddiftColor.red.hexString() == "#FF0000")
XCTAssert(ReddiftColor.green.hexString() == "#00FF00")
XCTAssert(ReddiftColor.blue.hexString() == "#0000FF")
XCTAssert(ReddiftColor.yellow.hexString() == "#FFFF00")
}
}
| [
-1
] |
5fc479b2e419ccea3d01644dec25a44a0446346c | d832aa4ed390de1a5d4c046f077476988777b088 | /MKCacheStorage/Cache/MKCSCacheHandler.swift | 6d195b754a95981d95a85a75da7beaf25f74b6fb | [
"Apache-2.0"
] | permissive | Mo0812/MKCacheStorage | 3edc7fec0344e9fef33d5b090f5210bf07b40430 | 2d5b632a55d147b51f92bf2379f890ecf1707fe1 | refs/heads/master | 2021-05-13T19:05:43.914243 | 2018-03-16T22:44:57 | 2018-03-16T22:44:57 | 116,884,390 | 1 | 2 | Apache-2.0 | 2018-03-16T22:44:58 | 2018-01-09T23:52:43 | Swift | UTF-8 | Swift | false | false | 2,033 | swift | //
// MKCSCacheHandler.swift
// MKCacheStorage
//
// Created by Moritz Kanzler on 23.01.18.
// Copyright © 2018 Moritz Kanzler. All rights reserved.
//
import Foundation
class MKCSCacheHandler {
var storageItems = [String: Any]()
var cacheLimit = 50
var cacheLFU = [String: Int]()
init(cacheLimit: Int = 50) {
self.cacheLimit = cacheLimit
}
private func isCacheFree() -> Bool {
return self.storageItems.count <= self.cacheLimit
}
private func insertCacheEntry(for identifier: String) {
let lfuIndex = 1
if self.cacheLFU[identifier] == nil {
self.cacheLFU[identifier] = lfuIndex
}
}
private func removeCacheEntry() throws {
let sortedArr = Array(self.cacheLFU.values).sorted(by: <)
guard let lfu = sortedArr.first else { throw MKCacheStorageError.cacheEmpty }
let filteredEntries = self.cacheLFU.filter {
$0.value == lfu
}
guard let removedKey = filteredEntries.first?.key else { throw MKCacheStorageError.cacheError }
self.storageItems[removedKey] = nil
self.cacheLFU[removedKey] = nil
}
public func getCacheResult<T: Codable>(identifier: String) -> T? {
let retVal = self.storageItems[identifier] as? T
/*if let oldLFU = self.cacheLFU[identifier] {
self.cacheLFU[identifier] = oldLFU + 1
} else {
self.cacheLFU[identifier] = 1
}*/
return retVal
}
public func cache<T: Codable>(object: T, under identifier: String) {
/*if !self.isCacheFree() {
do {
try self.removeCacheEntry()
} catch {
print(error.localizedDescription)
}
}*/
self.storageItems[identifier] = object
//self.insertCacheEntry(for: identifier)
}
public func clearCache() {
self.storageItems = [String: Any]()
self.cacheLFU = [String: Int]()
}
}
| [
-1
] |
f0cbade06bf72035b2c12728c0b0185e964f2185 | 07390e6e4443334d228e6e9b5b5bb7b154b1f304 | /CRHelper/CRHelper/Classes/View/Tournaments/Player Details/View/Achievements/SCPlayerAchievementCell.swift | 1aba17a58cf980721430e84927524707789ca826 | [
"Apache-2.0"
] | permissive | rayray199085/CRHelper | f28525457bdd2bcdd5b2657991fc1813f273acd2 | 13360aeb7fd93714f65552a9ad288efbcfec3e85 | refs/heads/master | 2020-06-14T10:15:21.363766 | 2019-07-09T04:55:34 | 2019-07-09T04:55:34 | 194,978,797 | 2 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 877 | swift | //
// SCPlayerAchievementCell.swift
// CRHelper
//
// Created by Stephen Cao on 5/7/19.
// Copyright © 2019 Stephencao Cao. All rights reserved.
//
import UIKit
class SCPlayerAchievementCell: UITableViewCell {
var achievement: SCPlayerAchievement?{
didSet{
nameLabel.text = achievement?.name
infoLabel.text = achievement?.info
for v in starStackView.subviews{
v.isHidden = true
}
var startCount = achievement?.stars ?? 0
startCount = startCount > 3 ? 3 : startCount
for index in 0..<startCount{
let v = starStackView.subviews[index]
v.isHidden = false
}
}
}
@IBOutlet weak var starStackView: UIStackView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var infoLabel: UILabel!
}
| [
-1
] |
ad7a90d56f9fbae1246ac30db93af7b7813bd1f7 | 4a1ad6b1ca3a26d2e1fd0ee1d29fa4bd83cbc41e | /Modules/UICommonComponents/SmallUtilityValueButtons.swift | c508cd694882395af99cebf13d9522f4425fa417 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | TanyEm/mymonero-app-ios | c34951d46642099de2076f22e982797b88b09a18 | d37b9f59ff2cbe06d9de86aaa0c7f4ae74344e19 | refs/heads/master | 2020-04-15T03:12:40.656451 | 2019-03-03T16:24:16 | 2019-03-03T16:24:16 | 164,340,157 | 0 | 0 | NOASSERTION | 2019-01-06T19:51:00 | 2019-01-06T19:50:59 | null | UTF-8 | Swift | false | false | 7,267 | swift | //
// SmallUtilityValueButtons.swift
// MyMonero
//
// Created by Paul Shapiro on 6/26/17.
// Copyright (c) 2014-2018, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
import MobileCoreServices
import PKHUD
extension UICommonComponents
{
class SmallUtilityValueButton: UIButton
{
//
// Constants - Static/class
static let usabilityPadding_h: CGFloat = 16
class func w() -> CGFloat { return self.visual_w() + usabilityPadding_h*2 }
static let h: CGFloat = 30 // for usability
class func visual_w() -> CGFloat { return 33 }
//
// Properties
//
// Lifecycle - Init
required init()
{
super.init(frame: .zero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()
{
self.setTitle(NSLocalizedString("COPY", comment: ""), for: .normal)
self.titleLabel!.font = UIFont.smallBoldSansSerif
self.contentHorizontalAlignment = .right // so that SHARE btns right-align with COPY btns
self.setTitleColor(.utilityOrConstructiveLinkColor, for: .normal)
self.setTitleColor(.disabledAndSemiVisibleLinkColor, for: .disabled)
self.addTarget(self, action: #selector(did_touchUpInside), for: .touchUpInside)
//
let frame = CGRect(x: 0, y: 0, width: type(of: self).w(), height: type(of: self).h)
self.frame = frame
}
//
// Delegation
@objc func did_touchUpInside()
{
}
}
class SmallUtilityCopyValueButton: SmallUtilityValueButton
{
//
// Constants - Overrides
override class func visual_w() -> CGFloat { return 33 }
//
// Properties
private var pasteboardItem_value_text: String?
private var pasteboardItem_value_html: String?
//
// Lifecycle - Init - Overrides
override func setup()
{
super.setup()
//
self.setTitle(NSLocalizedString("COPY", comment: ""), for: .normal)
self._updateInteractivityByValues() // initial
}
//
// Imperatives
func set(text: String?)
{
self.pasteboardItem_value_text = text
self._updateInteractivityByValues()
}
func set(html: String?)
{
self.pasteboardItem_value_html = html
self._updateInteractivityByValues()
}
func _updateInteractivityByValues()
{
let aValueExists = (self.pasteboardItem_value_html != nil && self.pasteboardItem_value_html != "") || (self.pasteboardItem_value_text != nil && self.pasteboardItem_value_text != "")
self.isEnabled = aValueExists
}
private func doCopy()
{
guard self.pasteboardItem_value_text != nil || self.pasteboardItem_value_text != nil else {
assert(false)
return
}
var pasteboardItems: [[String: Any]] = []
if let value = self.pasteboardItem_value_text {
pasteboardItems.append([ (kUTTypePlainText as String): value ])
}
if let value = self.pasteboardItem_value_html {
pasteboardItems.append([ (kUTTypeHTML as String): value ])
}
assert(pasteboardItems.count != 0) // not that it would be, with the above assert
let tomorrow = Date().addingTimeInterval(60 * 60 * 24)
UIPasteboard.general.setItems(
pasteboardItems,
options:
[
.localOnly : true,
.expirationDate: tomorrow
]
)
//
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(.success)
//
HUD.flash(.label(NSLocalizedString("Copied", comment: "")), delay: 0.05) // would like to be able to modify fade-out duration of HUD
}
//
// Delegation - Overrides
override func did_touchUpInside()
{
self.doCopy()
}
}
class SmallUtilityShareValueButton: SmallUtilityValueButton
{
//
// Constants - Overrides
override class func visual_w() -> CGFloat { return 33 }
//
// Properties
private var value_text: String?
private var value_url: URL?
private var value_image: UIImage?
//
// Lifecycle - Init - Overrides
override func setup()
{
super.setup()
//
self.setTitle(NSLocalizedString("SHARE", comment: ""), for: .normal)
self._updateInteractivityByValues() // initial
}
//
// Imperatives
func setButtonValue(text: String?)
{
self.value_text = text
self._updateInteractivityByValues()
}
func setButtonValue(url: URL?)
{
self.value_url = url
self._updateInteractivityByValues()
}
func setButtonValue(image: UIImage?)
{
self.value_image = image
self._updateInteractivityByValues()
}
func _updateInteractivityByValues()
{
let aValueExists = self.value_url != nil || (self.value_text != nil && self.value_text != "") || self.value_image != nil
self.isEnabled = aValueExists
}
private func openShareActionSheet()
{
var items: [Any] = []
if let value = self.value_text {
items.append(value)
}
if let value = self.value_url {
items.append(value)
}
if let value = self.value_image {
items.append(value)
}
let controller = UIActivityViewController(
activityItems: items,
applicationActivities: nil
)
controller.modalPresentationStyle = .popover // to prevent iPad crash
let presentInViewController = WindowController.presentModalsInViewController! // TODO: is this ok? or is it preferable to yield items and controller to present / ask for or be initialized with presentInViewController?
if let popoverPresentationController = controller.popoverPresentationController { // iPad support
popoverPresentationController.sourceView = self
var sourceRect: CGRect = .zero
sourceRect.origin.y += frame.size.height/2 // vertical middle instead of top edge
popoverPresentationController.sourceRect = sourceRect
}
presentInViewController.present(controller, animated: true, completion: nil)
}
//
// Delegation - Overrides
override func did_touchUpInside()
{
self.openShareActionSheet()
}
}
}
| [
-1
] |
0f0a280d493e57260b21b8cec945e3c426e8f28d | d70cf603879044aac8216caebde3e9455b3a683e | /todo-list/todo-list/Controller/ToDoListViewController.swift | 269a5be04b60741d9e3065d0a205268af8302a00 | [] | no_license | Sonjh1306/todo-list | c1a93e4ef608e2debc7a04d8a17b95cb3df91617 | 79eb1c3f3787c7470f79b53f2ab6e8003cb1abd8 | refs/heads/main | 2023-04-07T05:58:48.898466 | 2021-04-11T03:48:08 | 2021-04-11T03:48:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 460 | swift | //
// ViewController.swift
// todo-list
//
// Created by sonjuhyeong on 2021/04/06.
//
import UIKit
class ToDoListViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func sideMenuButtonTouched(_ sender: Any) {
let sideMenuVC = SideMenuViewController(nibName: "SideMenuViewController", bundle: .none)
self.present(sideMenuVC, animated: true, completion: nil)
}
}
| [
-1
] |
eceb213e3045dcb97fee5b6cc262bbaab6405e64 | 64faa4976b71a1e335cb6028b63c011fe35fea1e | /AppDelegate.swift | 0b19f82b8bfc56ab584adf9ccec00117dedcb2e5 | [] | no_license | SalehAlameeri310/Mosaedee | 342d577c63e33f11a69224496c4db81f1b347f02 | 54cbf766b10af76a4c52e410d6d8af7aba92a275 | refs/heads/master | 2022-11-19T13:13:33.070666 | 2020-07-19T20:18:15 | 2020-07-19T20:18:15 | 280,943,490 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,424 | swift | //
// AppDelegate.swift
// Mosaedee
//
// Created by Saleh Alameeri on 7/17/20.
// Copyright © 2020 Saleh Alameeri. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
393230,
393250,
344102,
393261,
393266,
163891,
213048,
376889,
385081,
393275,
376905,
327756,
254030,
286800,
368727,
180313,
368735,
180320,
376931,
368752,
262283,
377012,
327871,
180416,
377036,
180431,
377046,
377060,
327914,
205036,
393456,
393460,
336123,
418043,
336128,
385280,
262404,
180490,
368911,
262422,
377117,
262436,
336180,
262454,
262472,
344403,
213332,
65880,
262496,
262499,
246123,
262507,
262510,
213372,
385419,
393612,
262550,
262552,
385440,
385443,
385451,
262573,
393647,
385458,
262586,
344511,
360916,
369118,
328177,
328179,
328182,
328189,
328192,
164361,
328206,
410128,
393747,
254490,
385570,
33316,
377383,
197159,
352821,
188987,
418363,
369223,
385609,
385616,
352856,
352864,
369253,
262760,
352874,
254587,
377472,
336512,
148105,
377484,
352918,
98968,
344744,
361129,
385713,
434867,
164534,
336567,
328378,
164538,
328386,
352968,
344776,
418507,
385742,
385748,
361179,
189153,
369381,
361195,
344831,
344835,
336643,
344841,
361230,
336659,
418580,
418585,
434970,
369435,
418589,
262942,
418593,
336675,
328484,
418598,
418605,
336696,
361273,
328515,
336708,
328519,
336711,
361288,
328522,
336714,
426841,
197468,
361309,
361315,
361322,
328573,
377729,
369542,
361360,
222128,
345035,
345043,
386003,
386011,
386018,
386022,
435187,
328702,
328714,
361489,
386069,
336921,
386073,
336925,
345118,
377887,
345138,
386101,
361536,
197707,
345169,
156761,
361567,
148578,
345199,
386167,
361593,
410745,
361598,
214149,
345222,
386186,
337047,
345246,
214175,
337071,
337075,
386258,
328924,
66782,
222437,
328941,
386285,
386291,
345376,
345379,
410917,
337205,
345399,
378169,
369978,
337222,
337229,
337234,
263508,
402791,
345448,
378227,
181638,
353673,
181643,
181654,
230809,
181670,
181673,
337329,
181681,
181684,
181690,
361917,
181696,
337349,
181703,
337365,
271839,
329191,
361960,
329194,
116210,
337398,
337415,
329226,
419343,
419349,
345625,
419355,
370205,
419359,
419362,
394786,
370213,
419368,
419376,
206395,
214593,
419400,
419402,
353867,
419406,
214610,
419410,
345701,
394853,
222830,
370297,
403070,
403075,
345736,
198280,
345749,
345762,
419491,
345765,
419497,
419501,
370350,
419506,
419509,
337592,
419512,
419517,
337599,
419527,
419530,
419535,
272081,
419542,
394966,
419544,
181977,
345818,
419547,
419550,
419559,
337642,
419563,
337645,
370415,
141051,
337659,
337668,
362247,
395021,
362255,
321299,
395029,
116509,
345887,
378663,
345905,
354106,
354111,
247617,
354117,
329544,
345930,
370509,
354130,
247637,
337750,
313180,
345964,
345967,
345970,
345974,
403320,
354172,
247691,
337808,
247700,
329623,
436132,
337833,
337844,
346057,
247759,
346063,
329697,
354277,
190439,
247789,
354313,
346139,
436289,
378954,
395339,
338004,
100453,
329832,
329855,
329867,
329885,
346272,
100524,
387249,
379066,
387260,
256191,
346316,
411864,
411868,
411873,
379107,
411876,
387301,
346343,
338152,
387306,
387312,
346355,
436473,
321786,
379134,
411903,
395538,
387349,
338199,
387352,
182558,
338211,
248111,
362822,
436555,
190796,
321879,
379233,
354673,
321910,
248186,
420236,
379278,
354727,
338352,
330189,
338381,
338386,
338403,
338409,
248308,
199164,
330252,
420376,
330267,
354855,
10828,
199249,
174695,
248425,
191084,
338543,
191092,
346742,
330383,
354974,
150183,
248504,
223934,
355024,
273108,
355028,
264918,
183005,
256734,
436962,
338660,
338664,
264941,
207619,
338700,
256786,
199452,
363293,
396066,
346916,
396069,
215853,
355122,
355131,
355140,
355143,
338763,
355150,
330580,
355166,
265055,
355175,
387944,
355179,
330610,
330642,
355218,
412599,
207808,
379848,
396245,
330710,
248792,
248798,
347105,
257008,
183282,
265207,
330748,
265214,
330760,
330768,
248862,
396328,
158761,
199728,
330800,
396339,
339001,
388154,
388161,
347205,
248904,
330826,
248914,
339036,
412764,
257120,
265320,
248951,
420984,
330889,
248985,
339097,
44197,
380070,
339112,
249014,
330965,
265436,
388319,
388347,
175375,
159005,
175396,
208166,
273708,
347441,
372018,
199988,
175415,
396600,
437566,
175423,
437570,
437575,
437583,
331088,
437587,
331093,
396633,
175450,
437595,
175457,
208227,
175460,
175463,
437620,
175477,
249208,
175483,
249214,
175486,
175489,
249218,
249227,
249234,
175513,
175516,
396705,
175522,
355748,
380332,
396722,
388542,
372163,
216517,
380360,
216522,
339404,
372176,
208337,
339412,
413141,
339417,
249308,
339424,
339428,
339434,
249328,
69113,
372228,
339461,
208398,
380432,
175635,
339503,
265778,
265795,
396872,
265805,
224853,
224857,
224870,
257646,
372337,
224884,
224887,
224890,
224894,
224897,
372353,
216707,
339588,
126596,
224904,
159374,
11918,
339601,
126610,
224913,
224916,
224919,
126616,
224922,
224926,
224929,
224932,
257704,
224936,
224942,
257712,
224947,
257716,
257720,
257724,
224959,
257732,
224965,
224969,
339662,
224975,
257747,
224981,
224986,
224993,
257761,
257764,
224999,
339695,
225012,
257787,
225020,
339710,
257790,
225025,
257794,
339721,
257801,
257804,
225038,
257807,
372499,
225043,
225048,
257819,
225053,
225058,
339747,
339749,
257833,
225066,
413484,
257836,
225070,
225073,
372532,
397112,
225082,
397115,
225087,
323402,
257868,
225103,
257871,
397139,
225108,
225112,
257883,
257886,
225119,
339814,
225127,
257896,
274280,
257901,
225137,
257908,
225141,
257912,
225148,
257916,
257920,
225155,
339844,
225165,
397200,
225170,
380822,
225175,
225180,
118691,
184244,
372664,
372702,
372706,
356335,
380918,
405533,
430129,
217157,
421960,
356439,
421990,
266350,
266362,
381068,
225423,
250002,
250004,
225429,
356506,
225437,
135327,
192673,
438433,
225441,
225444,
438436,
225447,
438440,
225450,
258222,
225455,
430256,
225458,
225461,
225466,
225470,
381120,
372929,
225475,
389320,
225484,
225487,
225490,
225493,
266453,
225496,
225499,
225502,
225505,
356578,
225510,
225514,
225518,
372976,
381176,
389380,
356637,
356640,
356643,
356646,
356649,
356655,
332080,
340275,
356660,
397622,
332090,
332097,
201028,
348488,
332106,
332117,
348502,
250199,
250202,
332125,
250210,
348525,
332152,
250238,
389502,
356740,
332172,
373145,
340379,
389550,
324030,
266687,
340451,
127471,
340472,
324094,
266754,
324099,
324102,
324111,
340500,
324117,
324131,
332324,
381481,
324139,
356907,
324142,
356916,
324149,
324155,
348733,
324160,
324164,
348743,
381512,
324170,
324173,
324176,
389723,
332380,
381545,
340627,
184982,
373398,
258721,
332453,
332459,
389805,
332463,
381617,
332471,
332483,
332486,
373449,
332493,
357069,
357073,
332511,
332520,
340718,
332533,
348924,
373510,
389926,
152370,
340789,
348982,
398139,
127814,
389978,
430939,
357211,
357214,
201579,
201582,
349040,
340849,
201588,
381813,
430965,
324472,
398201,
119674,
324475,
340858,
340861,
324478,
430972,
324481,
373634,
398211,
324484,
324487,
381833,
324492,
324495,
324498,
430995,
324501,
324510,
422816,
324513,
201637,
398245,
324524,
340909,
324533,
5046,
324538,
324541,
398279,
340939,
340941,
209873,
340957,
431072,
398306,
340963,
209895,
201711,
349172,
381946,
349180,
439294,
431106,
209943,
250914,
357410,
185380,
357418,
209965,
209968,
209971,
209975,
209979,
209987,
209990,
341071,
349267,
250967,
210010,
341091,
210025,
210027,
210030,
210036,
210039,
341113,
210044,
349308,
152703,
160895,
349311,
210052,
210055,
210067,
210071,
210077,
210080,
210084,
251044,
185511,
210088,
210095,
210098,
210115,
332997,
210127,
333009,
210131,
333014,
210138,
210143,
218354,
251128,
218360,
275706,
275712,
275715,
275721,
349459,
333078,
251160,
349484,
349491,
251189,
415033,
251210,
357708,
210260,
259421,
365921,
333154,
251235,
333162,
234866,
390516,
333175,
357755,
136590,
112020,
349590,
357792,
259515,
415166,
415185,
366034,
415191,
415193,
415196,
415199,
423392,
333284,
366056,
366061,
210420,
415224,
423423,
415257,
415263,
366117,
415270,
144939,
415278,
415281,
415285,
210487,
415290,
415293,
349761,
415300,
333386,
333399,
366172,
333413,
423528,
423532,
210544,
415353,
333439,
415361,
267909,
333498,
333511,
210631,
358099,
153302,
333534,
431851,
366318,
210672,
366321,
210695,
268041,
210698,
366348,
210706,
399128,
333594,
210719,
358191,
366387,
399159,
358200,
325440,
366401,
341829,
325446,
46920,
341834,
341838,
341843,
415573,
358234,
341851,
350045,
399199,
259938,
399206,
268143,
399215,
358255,
358259,
341876,
333689,
243579,
325504,
333698,
333708,
333724,
382890,
350146,
358339,
333774,
358371,
350189,
350193,
350202,
333818,
350206,
350213,
268298,
350224,
350231,
333850,
350237,
350244,
350248,
178218,
350251,
350256,
350271,
243781,
350285,
374864,
342111,
342133,
374902,
432271,
333997,
334011,
260289,
350410,
260298,
350416,
350422,
211160,
350425,
268507,
334045,
350445,
375026,
358644,
350458,
350461,
350464,
325891,
350467,
350475,
375053,
268559,
350480,
432405,
350486,
350490,
325914,
325917,
350493,
350498,
350504,
391468,
350509,
358700,
358704,
358713,
358716,
383306,
334161,
383321,
383330,
383333,
391530,
383341,
334203,
268668,
194941,
391563,
366990,
268701,
342430,
416157,
375208,
326058,
375216,
334262,
334275,
326084,
358856,
195039,
334304,
334311,
375277,
334321,
350723,
186897,
342545,
334358,
342550,
342554,
334363,
350761,
252461,
334384,
383536,
334394,
252482,
219718,
334407,
334420,
350822,
375400,
334465,
334468,
162445,
326290,
342679,
342683,
260766,
342710,
244409,
260797,
334528,
260801,
350917,
391894,
154328,
416473,
64230,
342766,
375535,
203506,
342776,
391937,
391948,
326416,
375568,
375571,
375574,
162591,
326441,
326451,
326454,
244540,
326460,
375612,
326467,
244551,
326473,
326477,
326485,
326490,
326502,
433000,
375656,
326507,
326510,
211825,
211831,
351097,
392060,
359295,
351104,
342915,
400259,
236430,
342930,
252822,
392091,
400285,
252836,
211884,
400306,
351168,
359361,
326598,
359366,
359382,
359388,
383967,
359407,
261108,
244726,
261111,
383997,
261129,
261147,
359451,
261153,
261159,
359470,
359476,
343131,
384098,
384101,
367723,
384107,
187502,
343154,
384114,
212094,
351364,
384135,
384139,
384143,
351381,
384151,
384160,
384168,
367794,
244916,
384181,
367800,
384188,
384191,
351423,
326855,
244937,
384201,
253130,
343244,
384208,
146642,
384224,
359649,
343270,
351466,
384246,
351479,
343306,
359694,
384275,
384283,
245020,
384288,
245029,
171302,
376110,
245040,
425276,
212291,
384323,
343365,
212303,
367965,
343393,
343398,
367980,
343409,
154999,
253303,
343417,
327034,
245127,
384397,
245136,
245142,
245145,
343450,
245148,
245151,
245154,
245157,
245162,
327084,
359865,
384443,
146876,
327107,
384453,
327110,
327115,
327117,
359886,
359890,
343507,
343534,
343539,
368119,
343544,
409091,
359947,
359955,
359983,
343630,
327275,
245357,
138864,
155254,
155273,
368288,
245409,
425638,
155322,
425662,
155327,
245460,
155351,
155354,
212699,
245475,
155363,
245483,
155371,
409335,
155393,
155403,
245525,
155422,
360223,
155438,
155442,
155447,
360261,
155461,
376663,
155482,
261981,
425822,
376671,
155487,
155490,
155491,
327531,
261996,
376685,
261999,
262002,
327539,
147317,
262005,
425845,
262008,
262011,
155516,
155521,
155525,
360326,
376714,
155531,
262027,
262030,
262033,
262036,
262039,
262042,
155549,
262045,
262048,
262051,
327589,
155559,
155562,
155565,
393150,
393169,
384977,
155611,
155619,
253923,
155621,
327654,
253926,
393203,
393206,
253943,
360438,
393212,
155646
] |
61a34c1d142f244a6ef839e584826a70814f0f75 | 9ce64392a878ee1229014b4e82c668102950df6f | /Snapet/AppDelegate.swift | f1cf369fcc088ead88ebfbb43dbb42897b21ad62 | [] | no_license | Dyanngg/Snapet | 9a0c643fe47c76fdb3a6a343675ecfc282af420d | 5d4ccc11a53b277606285c0e2b55b1c4e1bd10a4 | refs/heads/master | 2020-05-29T19:03:14.037113 | 2017-06-11T09:47:54 | 2017-06-11T09:47:54 | 82,604,431 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,583 | swift | //
// AppDelegate.swift
// Snapet
//
// Created by Yang Ding on 2/19/17.
// Copyright © 2017 Yang Ding. 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: "Snapet")
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)")
}
}
}
}
| [
294405,
243717,
163848,
313353,
320008,
320014,
313360,
288275,
322580,
289300,
290326,
329747,
139803,
103964,
322080,
306721,
296483,
322083,
229411,
306726,
309287,
308266,
292907,
217132,
322092,
40495,
316465,
288306,
322102,
324663,
164408,
308281,
322109,
286783,
315457,
313409,
313413,
320582,
349765,
309832,
288329,
242250,
215117,
196177,
241746,
344661,
231000,
212571,
300124,
287323,
309342,
325220,
306790,
290409,
310378,
296043,
311914,
322666,
334446,
307310,
292466,
314995,
307315,
314487,
291450,
314491,
288383,
318599,
312970,
239252,
311444,
294038,
311449,
323739,
300194,
298662,
233638,
233644,
286896,
295600,
300208,
286389,
294070,
125111,
234677,
309439,
235200,
284352,
296641,
242371,
302787,
284360,
321228,
319181,
298709,
284374,
189654,
182486,
320730,
241371,
311516,
357083,
179420,
322272,
317665,
298210,
165091,
311525,
288489,
290025,
229098,
307436,
304365,
323310,
125167,
313073,
286455,
306424,
322299,
319228,
302332,
319231,
184576,
309505,
241410,
311043,
366339,
309509,
318728,
254217,
125194,
234763,
321806,
125201,
296218,
313116,
237858,
326434,
295716,
313125,
300836,
289577,
125226,
133421,
317233,
241971,
316726,
318264,
201530,
313660,
159549,
287038,
292159,
218943,
182079,
288578,
301893,
234828,
292172,
300882,
321364,
243032,
201051,
230748,
258397,
294238,
298844,
291169,
199020,
293741,
266606,
319342,
292212,
313205,
244598,
316788,
124796,
196988,
305022,
317821,
243072,
314241,
313215,
303999,
242050,
325509,
293767,
316300,
306576,
322448,
308114,
319900,
298910,
313250,
308132,
316327,
306605,
316334,
324015,
324017,
200625,
300979,
316339,
322998,
296888,
316345,
67000,
300987,
319932,
310718,
292288,
317888,
323520,
312772,
214980,
298950,
306632,
310733,
289744,
310740,
235994,
286174,
315359,
240098,
323555,
236008,
319465,
248299,
311789,
326640,
188913,
203761,
320498,
314357,
288246,
309243,
300540,
310782
] |
32a7a50d8db2f5dfe5eecaee91321f5678b12e7b | 3e24148eeae6d7a16ba04cfd00ab0d40ab29b780 | /faeBeta/faeBetaTests/faeBetaTests.swift | f6d64960d547c4085f8a748224b7192ae180a271 | [] | no_license | mingjiej/Fae-CB1-Frontend | a4c845f4efbe75772722607ad17154a4274aaf50 | 425160d5ecb8e22199b04650e6d04b342fb08559 | refs/heads/master | 2020-12-07T15:34:17.392773 | 2016-05-12T03:44:38 | 2016-05-12T03:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 966 | swift | //
// faeBetaTests.swift
// faeBetaTests
//
// Created by blesssecret on 5/11/16.
// Copyright © 2016 fae. All rights reserved.
//
import XCTest
@testable import faeBeta
class faeBetaTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| [
98333,
278558,
16419,
229413,
204840,
278570,
344107,
253999,
229424,
237620,
229430,
319542,
180280,
213052,
352326,
311372,
311374,
196691,
278615,
237663,
131178,
278634,
319598,
352368,
204916,
131191,
237689,
131198,
278655,
319629,
311438,
278677,
278685,
311458,
278691,
49316,
278699,
32941,
278704,
278708,
131256,
180408,
295098,
254170,
311519,
286958,
327929,
278797,
180493,
254226,
319763,
278816,
237857,
98610,
278842,
287041,
319813,
311621,
139589,
319821,
254286,
344401,
155990,
106847,
246127,
246136,
139640,
246137,
311681,
311691,
246178,
311727,
377264,
319930,
278970,
311738,
336317,
311745,
278978,
188871,
278989,
278993,
278999,
328152,
369116,
287198,
279008,
279013,
279018,
311786,
319981,
319987,
279029,
279032,
279039,
287241,
279050,
303631,
279057,
303636,
279062,
279065,
180771,
377386,
352829,
115270,
377418,
287318,
295519,
66150,
344680,
279146,
295536,
287346,
287352,
279164,
189057,
311941,
279177,
369289,
344715,
311949,
287374,
352917,
230040,
271000,
295576,
303771,
221852,
205471,
279206,
295590,
279210,
287404,
295599,
205487,
303793,
164533,
230072,
287417,
303803,
287422,
66242,
287433,
287439,
279252,
287452,
295652,
279269,
246503,
312047,
279280,
312052,
230134,
221948,
279294,
205568,
295682,
312079,
295697,
336671,
344865,
279336,
295724,
312108,
353069,
164656,
328499,
353078,
230199,
353079,
336702,
279362,
295746,
353094,
353095,
353109,
230234,
279392,
295776,
303972,
246641,
246648,
279417,
361337,
254850,
287622,
58253,
295824,
189348,
279464,
353195,
140204,
353197,
230332,
353215,
353216,
213960,
279498,
50143,
123881,
304110,
320494,
287731,
295927,
304122,
320507,
328700,
312314,
328706,
320516,
230410,
320527,
238610,
418837,
140310,
197657,
336929,
189474,
345132,
238639,
238651,
214086,
238664,
296019,
353367,
156764,
156765,
304222,
230499,
279660,
312434,
353397,
279672,
337017,
279685,
222343,
296086,
238743,
296092,
238765,
279728,
238769,
230588,
279747,
353479,
353481,
353482,
189652,
189653,
279765,
148696,
296153,
279774,
304351,
304356,
279792,
353523,
320770,
279814,
312587,
328971,
320796,
115998,
304421,
279854,
345396,
116026,
222524,
279875,
304456,
230729,
312648,
222541,
238927,
296273,
222559,
230756,
230765,
296303,
279920,
312689,
296307,
116084,
181625,
378244,
304524,
296335,
279974,
279984,
173491,
304564,
279989,
280004,
361927,
296392,
280010,
370123,
148940,
280013,
312782,
222675,
353750,
239068,
280032,
280041,
361963,
329197,
329200,
321009,
280055,
288249,
230913,
230921,
304656,
329232,
230959,
312880,
288309,
288318,
280130,
124485,
288326,
288327,
280147,
239198,
157281,
312940,
222832,
247416,
288378,
337535,
312965,
288392,
239250,
345752,
255649,
206504,
321199,
337591,
321207,
296632,
280251,
280257,
321219,
280267,
9936,
313041,
9937,
280278,
280280,
18138,
321247,
321249,
280300,
239341,
313081,
124669,
288512,
288516,
280327,
280329,
321295,
321302,
116505,
321310,
313120,
247590,
280366,
280372,
321337,
280380,
280390,
280392,
345929,
18262,
280410,
370522,
345951,
362337,
345955,
296806,
288619,
288620,
280430,
296814,
362352,
313203,
124798,
182144,
305026,
67463,
329622,
337815,
124824,
214937,
214938,
239514,
354212,
313254,
124852,
288697,
214977,
280514,
280519,
214984,
247757,
231375,
280541,
337895,
247785,
296941,
329712,
362480,
223218,
313339,
313357,
182296,
239650,
329765,
354343,
354345,
223274,
124975,
346162,
124984,
288828,
288833,
288834,
313416,
354385,
280661,
329814,
338007,
354393,
280675,
280677,
43110,
313447,
321637,
329829,
288879,
280694,
223350,
288889,
215164,
313469,
215166,
280712,
215178,
346271,
239793,
125109,
182456,
280762,
223419,
379071,
280768,
338119,
280778,
321745,
280795,
280802,
338150,
346346,
125169,
338164,
125183,
125188,
313608,
125193,
321800,
125198,
125203,
338197,
125208,
305440,
125217,
125235,
280887,
125240,
321860,
182597,
280902,
182598,
289110,
379225,
272729,
354655,
321894,
280939,
313713,
354676,
362881,
248194,
395659,
395661,
240016,
108944,
190871,
141728,
289189,
108972,
281037,
281040,
289232,
330218,
281072,
109042,
289304,
182817,
338490,
322120,
281166,
281171,
354911,
436832,
191082,
313966,
281199,
330379,
330387,
330388,
314009,
289434,
338613,
166582,
289462,
314040,
109241,
158394,
248517,
363211,
289502,
363230,
338662,
346858,
289518,
199414,
35583,
363263,
191235,
322313,
322316,
322319,
166676,
207640,
281377,
289598,
281408,
420677,
281427,
281433,
322395,
109409,
330609,
174963,
207732,
109428,
158593,
240518,
109447,
289690,
289698,
289703,
240552,
289722,
289727,
363458,
19399,
183248,
338899,
248797,
207838,
314342,
52200,
289774,
183279,
314355,
240630,
314362,
134150,
330763,
322582,
281626,
175132,
248872,
322612,
314448,
339030,
281697,
314467,
281700,
322663,
281706,
207979,
363644,
150657,
248961,
339102,
249002,
306346,
208058,
339130,
290000,
298208,
298212,
290022,
330984,
298221,
298228,
216315,
208124,
388349,
363771,
322824,
126237,
339234,
298291,
306494,
216386,
224586,
372043,
331090,
314709,
314710,
134491,
314720,
281957,
306542,
314739,
249204,
249205,
290169,
306559,
224640,
306560,
314758,
298374,
314760,
142729,
388487,
314766,
306579,
224661,
282007,
290207,
314783,
314789,
282022,
314791,
282024,
241066,
314798,
380357,
339398,
306631,
306639,
191981,
282096,
306673,
306677,
191990,
290301,
282114,
306692,
306693,
323080,
323087,
282129,
323089,
282136,
282141,
282146,
306723,
290358,
282183,
224847,
118353,
290390,
306776,
44635,
282213,
323178,
224883,
314998,
175741,
282245,
282246,
224901,
290443,
323217,
282259,
282271,
282273,
257699,
323236,
282276,
298661,
290471,
282280,
298667,
61101,
323263,
282303,
323264,
306890,
241361,
282327,
298712,
298720,
282339,
12010,
282348,
282355,
282358,
282369,
175873,
323331,
323332,
216839,
323346,
282391,
249626,
282400,
241441,
339745,
315171,
257830,
282409,
282417,
200498,
282427,
315202,
282434,
307011,
282438,
413521,
282480,
241528,
315264,
339841,
241540,
282504,
315273,
315274,
184208,
282518,
282519,
298909,
118685,
200627,
151497,
298980,
282612,
290811,
282633,
241692,
102437,
315434,
233517,
282672,
241716,
315465,
315476,
307289,
200794,
315487,
45153,
307299,
315497,
315498,
299121,
233589,
233590,
241808,
323729,
233636,
299174,
233642,
299187,
184505,
299198,
258239,
299203,
282831,
356576,
176362,
184570,
184575,
299293,
282909,
233762,
217380,
282919,
151847,
332083,
332085,
332089,
315706,
282939,
241986,
332101,
323916,
348492,
250192,
323920,
282960,
348500,
168281,
332123,
323935,
332127,
242029,
242033,
291192,
315773,
291198,
225670,
332167,
242058,
291224,
283038,
242078,
61857,
315810,
315811,
381347,
61859,
340398,
61873,
299441,
61880,
283064,
291265,
127427,
283075,
291267,
127428,
324039,
176601,
242139,
160225,
242148,
127465,
291311,
233978,
291333,
340490,
283153,
291358,
283182,
283184,
234036,
315960,
70209,
348742,
70215,
348749,
332378,
111208,
291454,
348806,
184973,
316049,
111253,
316053,
111258,
111259,
299699,
299700,
225995,
242386,
299746,
299759,
234234,
299770,
299776,
291592,
291604,
283419,
291612,
234277,
283430,
152365,
242485,
234294,
160575,
299849,
283467,
201549,
201551,
349026,
275303,
201577,
177001,
308076,
242541,
209783,
209785,
177019,
308092,
316298,
308107,
308112,
209817,
324506,
324507,
127902,
324517,
283558,
316333,
316343,
349121,
316364,
340955,
340961,
234472,
234473,
324586,
340974,
316405,
201720,
234500,
324625,
234514,
308243,
316437,
201755,
300068,
357414,
300084,
324666,
308287,
21569,
300111,
341073,
234587,
250981,
300135,
300136,
316520,
316526,
357486,
144496,
234609,
300146,
300150,
300151,
160891,
341115,
300158,
234625,
349316,
349318,
234638,
169104,
177296,
308372,
185493,
283802,
119962,
300188,
300187,
234663,
300201,
300202,
283840,
259268,
283847,
62665,
283852,
283853,
357595,
333022,
234733,
292091,
316669,
234755,
242954,
292107,
251153,
177428,
333090,
300343,
333117,
193859,
300359,
177484,
251213,
234831,
120148,
283991,
357719,
316765,
292195,
333160,
284014,
243056,
111993,
112017,
112018,
234898,
357786,
333220,
316842,
210358,
284089,
292283,
415171,
292292,
300487,
300489,
284107,
366037,
210390,
210391,
210393,
144867,
103909,
316902,
54765,
251378,
308723,
300536,
300542,
210433,
366083,
292356,
316946,
308756,
398869,
308764,
349726,
349741,
169518,
194110,
235070,
349763,
292423,
218696,
292425,
243274,
128587,
333388,
333393,
300630,
128599,
235095,
333408,
374372,
317032,
54893,
333430,
366203,
235135,
300714,
218819,
333509,
333517,
333520,
333521,
333523,
153319,
284401,
300794,
325371,
194303,
194304,
300811,
284429,
284431,
243472,
161554,
366360,
284442,
325404,
325410,
341796,
284459,
300848,
317232,
325439,
325445,
153415,
341836,
325457,
317269,
284507,
300894,
284512,
284514,
276327,
292712,
325484,
292720,
325492,
194429,
325503,
333701,
243591,
243597,
325518,
292771,
300963,
333735,
284587,
292782,
317360,
243637,
284619,
301008,
153554,
219101,
292836,
292837,
317415,
325619,
333817,
292858,
145435,
317467,
292902,
227370,
325674,
309295,
358456,
309345,
227428,
194666,
333940,
284788,
292988,
292992,
194691,
227460,
333955,
235662,
325776,
317587,
284825,
284826,
333991,
333992,
284842,
227513,
301251,
227524,
309444,
227548,
194782,
301279,
243962,
309503,
194820,
375051,
325905,
325912,
309529,
227616,
211235,
211238,
260418,
325968,
6481,
366929,
366930,
6489,
334171,
391520,
416104,
285040,
317820,
211326,
227725,
227726,
178582,
293274,
285084,
317852,
285090,
375207,
293303,
293310,
317901,
326100,
285150,
358882,
342498,
195045,
309744,
301571,
342536,
342553,
375333,
293419,
244269,
236081,
23092,
309830,
301638,
55881,
309846,
244310,
244327,
301689,
244347,
227990,
342682,
285361,
318130,
342706,
342713,
285373,
154316,
334547,
318173,
285415,
342762,
293612,
129773,
154359,
228088,
162561,
285444,
326414,
285458,
285466,
326429,
293664,
326433,
318250,
318252,
285487,
301871,
285497,
293693,
318278,
293711,
301918,
293730,
351077,
342887,
400239,
310131,
228215,
269178,
359298,
113542,
416646,
228233,
228234,
236428,
56208,
293781,
318364,
310182,
236461,
293806,
130016,
64485,
203757,
277492,
318461,
293893,
146448,
326685,
252980,
359478,
302139,
359495,
277597,
113760,
302177,
285798,
228458,
318572,
15471,
187506,
285814,
285820,
187521,
285828,
302213,
285830,
302216,
228491,
228493,
285838,
162961,
326804,
187544,
285851,
302240,
343203,
253099,
367799,
64700,
228540,
228542,
302274,
343234,
367810,
244940,
228563,
310497,
228588,
253167,
302325,
228600,
228609,
245019,
130338,
130343,
351537,
171317,
318775,
286013,
286018,
113987,
294218,
318805,
294243,
163175,
327025,
327031,
179587,
294275,
368011,
318864,
318875,
310692,
286129,
228795,
302529,
302531,
163268,
302540,
310732,
64975,
310736,
327121,
228827,
286172,
310757,
187878,
245223,
343542,
343543,
286202,
228861,
286205,
228867,
253452,
146964,
302623,
187938,
245287,
245292,
286254,
56902,
228943,
286288,
196187,
343647,
286306,
310889,
204397,
138863,
294529,
229001,
310923,
188048,
302739,
229020,
302754,
245412,
229029,
40613,
40614,
40615,
286391,
319162,
327358,
286399,
302797,
212685,
212688,
245457,
302802,
286423,
278233,
278234,
294622,
278240,
229088,
212716,
212717,
229113,
286459,
278272,
319233,
311042,
278291,
278293,
294678,
286494,
294700,
360252,
319292,
188251,
245599,
237408,
302946,
188292,
253829,
327557,
294807,
294814,
311199,
319392,
294823,
294843,
294850,
163781,
344013,
212946,
294886,
253929,
327661,
278512,
311281,
311282
] |
03be2f88b4b28675a1e5ba664b7e6028dc5467c5 | bdc369d824fd932437948b25267cd9f9746d8b0c | /Guia Investimento/Code/Others/OthersDataView.swift | 9ce95604debbd702829669c69a56df64d826ce2d | [] | no_license | thiagoprochnow/Guia-Investimento-iOS | 97aabc73801345c1a694c70e7670ec8d95da6d1a | 866c397f00ecb9824cf749e9bb463399f9025e1e | refs/heads/master | 2021-10-28T13:08:16.980443 | 2018-12-02T22:46:35 | 2018-12-02T22:46:35 | 135,068,354 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 12,263 | swift | //
// OthersData.swift
// Guia Investimento
//
// Created by Felipe on 01/06/18.
// Copyright © 2018 Thiago. All rights reserved.
//
import Foundation
import UIKit
class OthersDataView: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet var othersTable: UITableView!
@IBOutlet var fab: UIImageView!
@IBOutlet var emptyListView: UILabel!
var othersDatas: Array<OthersData> = []
var selectedSymbol: String = ""
var current: String = ""
var sold: String = ""
var bought: String = ""
var gain: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Background Color
self.view.backgroundColor = UIColor(red: 237/255, green: 237/255, blue: 237/255, alpha: 1)
// Table View
self.othersTable.dataSource = self
self.othersTable.delegate = self
self.othersTable.separatorStyle = .none
let xib = UINib(nibName: "OthersDataCell", bundle: nil)
self.othersTable.register(xib, forCellReuseIdentifier: "cell")
// Load fab (Floating action button)
// Set images for each icon
let fabImg = UIImage(named: "fab")
fab.image = fabImg
// Add action to open buy form when tapped
fab.isUserInteractionEnabled = true
let tapBuyOthers = UITapGestureRecognizer(target: self, action: #selector(OthersDataView.buyOthers))
fab.addGestureRecognizer(tapBuyOthers)
}
override func viewWillAppear(_ animated: Bool) {
// Load all Active Others Datas to show on this list
let dataDB = OthersDataDB()
othersDatas = dataDB.getData()
var selectedSymbol: String = ""
var current: String = ""
var sold: String = ""
var bought: String = ""
var gain: String = ""
if (othersDatas.isEmpty){
self.othersTable.isHidden = true
self.emptyListView.isHidden = false
} else {
self.othersTable.isHidden = false
self.emptyListView.isHidden = true
}
dataDB.close()
// Reload data every time OthersDataView is shown
self.othersTable.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (othersDatas.isEmpty){
return 0
} else {
// +1 to leave a empty field for Floating Button to scroll
return othersDatas.count + 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let linha = indexPath.row
let cell = self.othersTable.dequeueReusableCell(withIdentifier: "cell") as! OthersDataCell
// Do not show highlight when selected
cell.selectionStyle = .none
if(linha < (othersDatas.count)){
// Load each Others Data information on cell
let locale = Locale(identifier: "pt_BR")
let data = othersDatas[linha]
let totalGain = data.totalGain
let othersAppreciation = data.variation
let currentTotal = data.currentTotal
let totalIncome = data.liquidIncome
let buyTotal = data.buyTotal
let sellTotal = data.sellTotal
let variationPercent = "(" + String(format: "%.2f", locale: locale, arguments: [othersAppreciation/buyTotal * 100]) + "%)"
let netIncomePercent = "(" + String(format: "%.2f", locale: locale, arguments: [totalIncome/buyTotal * 100]) + "%)"
let totalGainPercent = "(" + String(format: "%.2f", locale: locale, arguments: [totalGain/buyTotal * 100]) + "%)"
let currentPercent = String(format: "%.2f", locale: locale, arguments: [data.currentPercent]) + "%"
cell.symbolLabel.text = data.symbol
cell.currentLabel.text = Utils.doubleToRealCurrency(value: currentTotal)
cell.boughtLabel.text = Utils.doubleToRealCurrency(value: buyTotal)
cell.soldLabel.text = Utils.doubleToRealCurrency(value: sellTotal)
cell.currentPercent.text = currentPercent
cell.variationLabel.text = Utils.doubleToRealCurrency(value: othersAppreciation)
cell.variationPercent.text = variationPercent
if(data.variation >= 0){
cell.variationLabel.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
cell.variationPercent.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
} else {
cell.variationLabel.textColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
cell.variationPercent.textColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
}
cell.incomeLabel.text = Utils.doubleToRealCurrency(value: totalIncome)
cell.incomeLabel.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
cell.incomePercent.text = netIncomePercent
cell.incomePercent.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
cell.gainLabel.text = Utils.doubleToRealCurrency(value: totalGain)
cell.gainPercent.text = totalGainPercent
if(data.totalGain >= 0){
cell.gainLabel.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
cell.gainPercent.textColor = UIColor(red: 139/255, green: 195/255, blue: 74/255, alpha: 1)
} else {
cell.gainLabel.textColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
cell.gainPercent.textColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
}
if(data.updateStatus == Constants.UpdateStatus.NOT_UPDATED){
cell.errorIconView.isHidden = false
} else {
cell.errorIconView.isHidden = true
let locale = Locale(identifier: "pt_BR")
}
return cell
} else {
cell.isHidden = true
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// When a others is selected in the table view, it will show menu asking for action
// View details, Buy, Sell, Delete
let linha = indexPath.row
let data = othersDatas[linha]
selectedSymbol = data.symbol
current = String(data.currentTotal)
sold = String(data.sellTotal)
bought = String(data.buyTotal)
gain = String(data.totalGain)
let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
if(linha < (othersDatas.count)){
let detailAction = UIAlertAction(title: NSLocalizedString("Mais Detalhes", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.othersDetails()
})
let buyAction = UIAlertAction(title: NSLocalizedString("Comprar", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.buyOthers()
})
let sellAction = UIAlertAction(title: NSLocalizedString("Vender", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.sellOthers()
})
let editAction = UIAlertAction(title: NSLocalizedString("Editar Total Atual", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.editOthers(others: data)
})
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancelar", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.selectedSymbol = ""
self.current = ""
self.sold = ""
self.bought = ""
self.gain = ""
})
let deleteAction = UIAlertAction(title: NSLocalizedString("Deletar", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
let deleteAlertController = UIAlertController(title: "Deletar investimento da sua carteira?", message: "Se vendeu esse investimento, escolha Vender no menu de opções. Deletar irá remover todos os dados sobre ele.", preferredStyle: .alert)
let okAction = UIAlertAction(title: NSLocalizedString("Deletar", comment: ""), style: .default, handler: {(action: UIAlertAction) -> Void in
self.deleteData(self.selectedSymbol)
self.othersTable.reloadData()
self.selectedSymbol = ""
self.current = ""
self.sold = ""
self.bought = ""
self.gain = ""
})
deleteAlertController.addAction(cancelAction)
deleteAlertController.addAction(okAction)
self.present(deleteAlertController, animated: false, completion: nil)
})
alertController.addAction(detailAction)
alertController.addAction(buyAction)
alertController.addAction(sellAction)
alertController.addAction(editAction)
alertController.addAction(deleteAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: false, completion: nil)
}
}
// Open form to buy others
@IBAction func buyOthers(){
let buyOthersForm = BuyOthersForm()
if(selectedSymbol != ""){
buyOthersForm.symbol = selectedSymbol
}
self.navigationController?.pushViewController(buyOthersForm, animated: true)
}
// Open form to sell others
@IBAction func sellOthers(){
let sellOthersForm = SellOthersForm()
if(selectedSymbol != ""){
sellOthersForm.symbol = selectedSymbol
}
self.navigationController?.pushViewController(sellOthersForm, animated: true)
}
func editOthers(others:OthersData){
let editOthersForm = OthersEditPriceForm()
editOthersForm.prealodedData = others
self.navigationController?.pushViewController(editOthersForm, animated: true)
}
// Delete others data, all its transactions and incomes
func deleteData(_ symbol: String){
let dataDB = OthersDataDB()
let transactionDB = OthersTransactionDB()
dataDB.deleteBySymbol(symbol)
transactionDB.deleteBySymbol(symbol)
othersDatas = dataDB.getData()
Utils.updateOthersPortfolio()
dataDB.close()
transactionDB.close()
}
// Open others details view
@IBAction func othersDetails(){
let othersDetails = OthersDetailsView()
let othersIncomes = OthersIncomesView()
let tabController = TabController()
othersDetails.tabBarItem.title = ""
othersDetails.tabBarItem.image = Utils.makeThumbnailFromText(text: "Operações")
othersIncomes.tabBarItem.title = ""
othersIncomes.tabBarItem.image = Utils.makeThumbnailFromText(text: "Rendimentos")
if(selectedSymbol != ""){
othersDetails.symbol = selectedSymbol
othersDetails.current = current
othersDetails.sold = sold
othersDetails.bought = bought
othersDetails.gain = gain
othersIncomes.symbol = selectedSymbol
tabController.title = selectedSymbol
}
// Create custom Back Button
let backButton = UIBarButtonItem(title: "Voltar", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let font = UIFont.init(name: "Arial", size: 14)
backButton.setTitleTextAttributes([NSAttributedStringKey.font: font], for: .normal)
tabController.navigationItem.backBarButtonItem = backButton
tabController.navigationItem.backBarButtonItem?.tintColor = UIColor.white
tabController.viewControllers = [othersDetails, othersIncomes]
self.navigationController?.pushViewController(tabController, animated: true)
}
}
| [
-1
] |
2573f005921ef60cad75078ab67509a1e40e78fb | 894608d577f6e3af13ebafc0c2e7e4e6c1251f99 | /ComTec-Kitchen/server/HttpConnection.swift | c9362b2c8cf3ccddaa85878ee4ef09dc8f1a4468 | [
"BSD-3-Clause"
] | permissive | Clashsoft/ComTec-Kitchen-iOS | dfec27f85cab380e1ae0150b2719c46f8ce1c38f | c2ac8f0a631a40a83b828e8faba0785a70b341a5 | refs/heads/master | 2020-04-24T20:09:21.679815 | 2019-03-26T11:42:14 | 2019-03-26T11:42:14 | 172,234,952 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,769 | swift | //
// Created by Adrian Kunz on 2019-02-23.
// Copyright (c) 2019 Clashsoft. All rights reserved.
//
import Foundation
typealias Headers = [String: String]
typealias CompletionHandler = (Data?, Error?) -> Void
let ignoreResult: CompletionHandler = { (data, error) in }
class HttpConnection {
static func get(url: URL, headers: Headers, completion: @escaping CompletionHandler) {
request(url: url, method: "GET", headers: headers, body: nil, completion: completion)
}
static func post(url: URL, headers: Headers, body: Data, completion: @escaping CompletionHandler) {
request(url: url, method: "POST", headers: headers, body: body, completion: completion)
}
static func put(url: URL, headers: Headers, body: Data, completion: @escaping CompletionHandler) {
request(url: url, method: "PUT", headers: headers, body: body, completion: completion)
}
static func delete(url: URL, headers: Headers, completion: @escaping CompletionHandler) {
request(url: url, method: "DELETE", headers: headers, body: nil, completion: completion)
}
private static func request(url: URL, method: String, headers: Headers, body: Data?, completion: @escaping CompletionHandler) {
let request = URLRequest(url: url, method: method, headers: headers, body: body)
URLSession.shared.dataTask(with: request) { (data, response, error) in
completion(data, error)
}.resume()
}
}
extension URLRequest {
init(url: URL, method: String, headers: Headers, body: Data?) {
self.init(url: url)
self.httpMethod = method
for (key, value) in headers {
self.addValue(value, forHTTPHeaderField: key)
}
if let body = body {
self.httpBody = body
}
}
}
extension URL {
static func /(lhs: URL, rhs: String) -> URL {
return lhs.appendingPathComponent(rhs)
}
}
| [
-1
] |
ff883db1b04dfaa4d994114057a69a245e37bc04 | 54b82ef58cd50728f0ce3efe2e57bb9f9fb2f38c | /Teki/ViewController.swift | 0b9e8eb9f6e2b105d9da94ec9a50d13bf03ff1f8 | [] | no_license | haouazied/Teki | aacca9a30d68d65eba66f7ebeb089edf3b47a8fe | 6c441ab135a1d8163bbcc24aca8512f1e30d83d0 | refs/heads/master | 2020-04-18T02:23:20.035918 | 2019-01-23T14:06:45 | 2019-01-23T14:06:45 | 167,160,289 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,152 | swift | //
// ViewController.swift
// Teki
//
// Created by MacBook on 1/23/19.
// Copyright © 2019 Haoua Zied. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var celebrities = ["le Steve Jobs", "le Zinedine Zidane", "la Madonna", "le Karl Lagarfeld", "la Scarlett Johansson"]
var activities = ["du dancefloor", "du barbecue", "de la surprise ratée", "des blagues lourdes", "de la raclette party"]
@IBOutlet weak var quoteLabel: UILabel!
@IBAction func changeQuote() {
let randomIndex1 = Int(arc4random_uniform(UInt32(celebrities.count)))
let celebrity = celebrities[randomIndex1]
// On séléctionne un élément aléatoire parmi les activités
let randomIndex2 = Int(arc4random_uniform(UInt32(activities.count)))
let activity = activities[randomIndex2]
let quote = "Tu es " + celebrity + " " + activity + " !"
quoteLabel.text = quote
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| [
-1
] |
90c15f4d1bc956bf3300f6ae8913edf23c401a86 | 48aa2d6be171f5576fd8e1b9c40aa8687ec3bc4f | /Test_task/SubNavBarView.swift | 71f06b4640d2a137d6d695df1af13488a502483f | [] | no_license | ToniAngers/Test_task | 5931ecdd315ea19a5433e8c8116270f4f717fce1 | 9913652499c4422811cea87dd3ab3181e21fdddf | refs/heads/master | 2021-01-23T10:20:41.634266 | 2017-06-02T22:42:10 | 2017-06-02T22:42:10 | 93,052,513 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,654 | swift | //
// SubNavBarView.swift
// Test_task
//
// Created by Anton Voropaev on 01.06.17.
// Copyright © 2017 Anton Voropaev. All rights reserved.
//
import UIKit
import SnapKit
protocol PageButtonProtocol {
func subNavBarView(_ subNavBar: SubNavBarView, didSelectButton: NSInteger)
}
class SubNavBarView: UIView {
var delegate: PageButtonProtocol?
//Buttons
private var leftButton: UIButton!
private var centerButton: UIButton!
private var rightButton: UIButton!
private var selectedButton = UIButton()
private var indicatorPositionX: Constraint?
private var lastContentOffset: CGFloat = 0
var indicator:UIView!
init() {
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
self.backgroundColor = UIColor.white
configureView()
configureLayout()
}
func configureView() {
creatingAnIndicator()
leftButton = UIButton()
leftButton.setTitle("Net cash flow", for: .normal)
leftButton.setTitleColor(UIColor.black, for: .normal)
leftButton.titleLabel!.font = FONT_LIGHT_16
leftButton.tag = 0
leftButton.addTarget(self, action: #selector(titleButtonPressed(sender:)), for: .touchUpInside)
centerButton = UIButton()
centerButton.setTitle("Incoming", for: .normal)
centerButton.setTitleColor(UIColor.black, for: .normal)
centerButton.titleLabel?.textAlignment = .center
centerButton.titleLabel!.font = FONT_LIGHT_16
centerButton.tag = 1
centerButton.addTarget(self, action: #selector(titleButtonPressed(sender:)), for: .touchUpInside)
rightButton = UIButton()
rightButton.setTitle("Outgoing", for: .normal)
rightButton.setTitleColor(UIColor.black, for: .normal)
rightButton.titleLabel!.font = FONT_LIGHT_16
rightButton.tag = 2
rightButton.addTarget(self, action: #selector(titleButtonPressed(sender:)), for: .touchUpInside)
self.addSubview(leftButton)
self.addSubview(centerButton)
self.addSubview(rightButton)
}
func configureLayout() {
indicator.snp.makeConstraints { (make) in
indicatorPositionX = make.centerX.equalTo(leftButton.snp.centerX).constraint
make.width.equalTo(35)
make.height.equalTo(2)
make.bottom.equalTo(self)
}
leftButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(centerButton.snp.width)
}
centerButton.snp.makeConstraints { (make) in
make.top.equalTo(self)
// make.centerX.equalTo(self)
make.left.equalTo(leftButton.snp.right).offset(5)
make.right.equalTo(rightButton.snp.left)
make.bottom.equalTo(self)
make.width.equalTo(leftButton.snp.width)
}
rightButton.snp.makeConstraints { (make) in
make.right.equalTo(self).offset(10)
make.top.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(centerButton.snp.width)
}
}
//MARK: Actions
func titleButtonPressed(sender: UIButton) {
moveIndicatorTo(button:sender)
self.delegate?.subNavBarView(self, didSelectButton: sender.tag)
}
func moveIndicatorTo(button: UIButton) {
let newPoint = button.center.x
UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {
self.indicator.center.x = newPoint
}, completion:{ finished in
})
}
//MARK: help func
func creatingAnIndicator() {
indicator = UIView()
indicator.layer.cornerRadius = 1
indicator.layer.masksToBounds = true
indicator.backgroundColor = UIColor.black
self.addSubview(indicator)
}
func highlightItem(at index: NSInteger) {
for v in self.subviews {
if v.isKind(of: UIButton.self) {
let button = v as! UIButton
button.titleLabel?.font = FONT_LIGHT_16
if button.tag == index {
button.titleLabel?.font = FONT_BOLD_16
}
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| [
-1
] |
63c50053aa6e8cb6b6039572b2fc2fbdb8d03f68 | 345f411ff57a4737e540434b25b7aaa9a5fb1616 | /TestLab/Controllers/List and Tables/CrudAdvancedViewController.swift | bcb575aa20869b9c7b665cb73761eb2bdbfe3508 | [] | no_license | randop/TestLab | 006955dc4cd0aa502482cb8ba5081c82d8bccc25 | c023c226fc8cac75c419b52fcbddea61a0644098 | refs/heads/master | 2021-05-04T13:15:29.540161 | 2019-08-08T15:03:50 | 2019-08-08T15:03:50 | 120,309,894 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,632 | swift | //
// CrudAdvancedViewController.swift
// TestLab
//
// Created by Randolph on 8/4/19.
// Copyright © 2019 Randolph. All rights reserved.
//
import UIKit
class CrudAdvancedViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
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 to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| [
-1
] |
96aa4802164e1336294363edb0d3b495ebad8f4c | 29d945df6460d5179efb0a538553174b14ee9623 | /GridTapper/ViewController.swift | 0b5f0bf8ba6870254b4a56dd986fcc727eec3974 | [] | no_license | pthomas1/GridTapper | 0dbac6a45249106c8b54f82dfbb9428510db6998 | ed1b4bf04affcd5d327f8851e72ca9b00fa3ab5d | refs/heads/master | 2020-12-30T17:51:00.058395 | 2017-04-28T02:55:21 | 2017-04-28T02:55:21 | 89,661,077 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,392 | swift | //
// ViewController.swift
// GridTapper
//
// Created by Peter Thomas on 4/26/17.
// Copyright © 2017 Peter Thomas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var gameState:GameState = GameState()
var displaylink:CADisplayLink!
@IBOutlet weak var gridView: GridCellView!
var touchReceivingView:TouchReceivingView { return view as! TouchReceivingView }
override func viewDidLoad() {
super.viewDidLoad()
touchReceivingView.delegate = self
gameState.delegate = self
if displaylink == nil {
displaylink = CADisplayLink(target: self, selector: #selector(stepDisplayLinkTimer(_:)))
displaylink.add(to: .current, forMode: .defaultRunLoopMode)
}
var childViews = [GridCellView]()
gameState.visitAllCells { (child, index) in
let childView = GridCellView.createGridCellView(child, atIndex:index)
childViews.append(childView)
}
gridView.addChildViews(childViews)
childViews.enumerated().forEach {
$0.element.splitFrame(forIndex: $0.offset)
}
gridView.shadowOpacity = 0.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
gameState.isPaused = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
gameState.isPaused = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func stepDisplayLinkTimer(_ displayLink:CADisplayLink) {
gameState.tick(deltaTimeInterval: 1.0/60.0)
}
}
extension ViewController: TouchReceivingViewDelegate {
func touchBegan(touch:UITouch) {
var nearestTouchedCell:GridCell?
var nearestTouchedDistance = CGFloat.infinity
gameState.visitAllCells { (child, index) in
guard child.isHighlighted else { return }
guard let childView = child.cellView, child.childCells == nil else { return }
let touchLocation = touch.location(in: childView)
if childView.bounds.contains(touchLocation) {
nearestTouchedCell = child
nearestTouchedDistance = 0
} else {
let center = CGPoint(x:childView.bounds.origin.x + childView.bounds.size.width / 2,
y:childView.bounds.origin.y + childView.bounds.size.height / 2)
let delta = CGPoint(x:center.x - touchLocation.x,
y:center.y - touchLocation.y)
let distance = sqrt(delta.x * delta.x + delta.y * delta.y)
if distance < 35 {
if nearestTouchedCell == nil || distance < nearestTouchedDistance {
nearestTouchedCell = child
nearestTouchedDistance = distance
}
}
}
}
guard let touchedCell = nearestTouchedCell else { return }
if nearestTouchedDistance > 0 {
logger.debug("nearestTouchedDistance: \(nearestTouchedDistance)")
}
gameState.cellWasTouched(touchedCell)
}
}
extension ViewController: GameStateDelegateProtocol {
func gameState(_ gameState:GameState, didSplitCell cell:GridCell) {
guard let cellView = cell.cellView else { return }
cellView.split(into: cell.childCells)
}
func gameState(_ gameState:GameState, willMergeCell cell:GridCell, isMergeRoot:Bool) {
guard let cellView = cell.cellView else { return }
cellView.merge()
}
func gameState(_ gameState:GameState, didHighlightCell cell:GridCell) {
guard let cellView = cell.cellView else { return }
UIView.animate(withDuration: 0.2) {
cellView.highlightType = cell.highlightType
}
}
func gameState(_ gameState:GameState, didDehighlightCell cell:GridCell) {
guard let cellView = cell.cellView else { return }
UIView.animate(withDuration: 0.2) {
cellView.highlightType = nil
}
}
}
| [
-1
] |
adb56bdc64f789a4e06f5b7f4e29646aaf13186c | a0f014377b977338dbc619de9f19c4b33dbd088a | /Stepic/MatchingReply.swift | 76dbed725983ec4d365280a6eb0b4e4d4ee3e50e | [
"MIT"
] | permissive | smarus/stepik-ios | d4e4153952cd7f272b596e043b6ee3e660b7e142 | 73d2de58eb5d8d5f18b29c990423aafe2da461d6 | refs/heads/master | 2020-06-24T14:59:08.281433 | 2019-07-12T14:13:33 | 2019-07-12T14:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 494 | swift | //
// MatchingReply.swift
// Stepic
//
// Created by Alexander Karpov on 16.01.17.
// Copyright © 2017 Alex Karpov. All rights reserved.
//
import UIKit
import SwiftyJSON
class MatchingReply: Reply {
var ordering: [Int]
init(ordering: [Int]) {
self.ordering = ordering
}
required init(json: JSON) {
ordering = json["ordering"].arrayValue.map({return $0.intValue})
}
var dictValue: [String : Any] {
return ["ordering": ordering]
}
}
| [
-1
] |
63eb7a3d0d835e4ab8d01b7afdb280eea3166e83 | ea609e3b931966644b79d2047a4b997d6bf60998 | /LucidTests/Core/CoreManagerContractTests.swift | 4f973e3b71aca344479ecabd515255340a07a989 | [
"MIT"
] | permissive | ekmixon/Lucid | c6e20b10dc85e2a13ca366458eb8fa62f903c0b6 | e06fa8d5fc02e6892146aa8e894c87c02821be2e | refs/heads/main | 2023-05-31T10:04:34.833277 | 2021-06-24T15:14:15 | 2021-06-24T15:14:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 50,999 | swift | //
// CoreManagerContractTests.swift
// LucidTests
//
// Created by Stephane Magne on 6/4/20.
// Copyright © 2020 Scribd. All rights reserved.
//
import Combine
import XCTest
@testable import Lucid
@testable import LucidTestKit
final class CoreManagerContractTests: XCTestCase {
private var remoteStoreSpy: StoreSpy<EntitySpy>!
private var memoryStoreSpy: StoreSpy<EntitySpy>!
private var manager: CoreManaging<EntitySpy, AnyEntitySpy>!
private var cancellables: Set<AnyCancellable>!
override func setUp() {
super.setUp()
LucidConfiguration.logger = LoggerMock(shouldCauseFailures: false)
remoteStoreSpy = StoreSpy()
remoteStoreSpy.levelStub = .remote
memoryStoreSpy = StoreSpy()
memoryStoreSpy.levelStub = .memory
cancellables = Set()
}
override func tearDown() {
defer { super.tearDown() }
remoteStoreSpy = nil
memoryStoreSpy = nil
manager = nil
cancellables = nil
}
private enum StackType {
case local
case remoteAndLocal
}
private func buildManager(for stackType: StackType) {
switch stackType {
case .local:
manager = CoreManager(stores: [memoryStoreSpy.storing]).managing()
case .remoteAndLocal:
manager = CoreManager(stores: [remoteStoreSpy.storing, memoryStoreSpy.storing]).managing()
}
}
// MARK: - Base EntityContext Tests
// MARK: GET
func test_core_manager_get_should_return_complete_results_when_no_contract_is_provided() {
buildManager(for: .local)
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
let onceExpectation = self.expectation(description: "once")
manager
.get(byID: EntitySpyIdentifier(value: .remote(1, nil)))
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_return_complete_results_when_entity_meets_contract_requirements() {
buildManager(for: .local)
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .requested(1))
))
let onceExpectation = self.expectation(description: "once")
let contract = IdentifierContract(successfulIdentifiers: [
EntitySpyIdentifier(value: .remote(1, nil))
])
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.get(byID: EntitySpyIdentifier(value: .remote(1, nil)), in: context)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_filter_results_when_enity_does_not_meet_contract_requirements() {
buildManager(for: .local)
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
let onceExpectation = self.expectation(description: "once")
let contract = IdentifierContract(successfulIdentifiers: [])
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.get(byID: EntitySpyIdentifier(value: .remote(1, nil)), in: context)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
// MARK: - SEARCH
func test_core_manager_search_should_return_complete_results_when_no_contract_is_provided() {
buildManager(for: .local)
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(2))
]))
let onceExpectation = self.expectation(description: "once")
manager
.search(withQuery: .all)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_should_return_complete_results_when_all_entities_meet_contract_requirements() {
buildManager(for: .local)
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(1)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(2))
]))
let onceExpectation = self.expectation(description: "once")
let contract = IdentifierContract(successfulIdentifiers: [
EntitySpyIdentifier(value: .remote(1, nil)),
EntitySpyIdentifier(value: .remote(2, nil))
])
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.search(withQuery: .all, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_should_return_filtered_results_when_partial_entities_meet_contract_requirements() {
buildManager(for: .local)
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(2))
]))
let onceExpectation = self.expectation(description: "once")
let contract = IdentifierContract(successfulIdentifiers: [
EntitySpyIdentifier(value: .remote(2, nil))
])
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.search(withQuery: .all, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
// MARK: - CONTINUOUS
func test_continuous_obvserver_should_get_filtered_results_matching_entities_that_meet_contract_requirements() {
buildManager(for: .remoteAndLocal)
memoryStoreSpy.searchResultStub = .success(.entities([]))
var continuousCount = 0
let continuousSetupExpectation = self.expectation(description: "continuous")
let continuousCompletedExpectation = self.expectation(description: "continuous")
let continuousContract = IdentifierContract(successfulIdentifiers: [
EntitySpyIdentifier(value: .remote(2, nil))
])
let continuousContext = ReadContext<EntitySpy>(dataSource: .local, contract: continuousContract)
manager
.search(withQuery: .all, in: continuousContext)
.continuous
.sink { result in
continuousCount += 1
if continuousCount == 1 {
XCTAssertEqual(result.count, 0)
continuousSetupExpectation.fulfill()
} else if continuousCount == 2 {
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
continuousCompletedExpectation.fulfill()
} else {
XCTFail("Received more responses than expected")
}
}
.store(in: &cancellables)
wait(for: [continuousSetupExpectation], timeout: 1)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(2))
]))
memoryStoreSpy.searchResultStub = .success(.entities([]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(2))
])
let onceExpectation = self.expectation(description: "once")
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true)
)
manager
.search(withQuery: .all, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
wait(for: [continuousCompletedExpectation, onceExpectation], timeout: 1)
}
// MARK: - ReadContext.DataSource Tests
// MARK: GET
func test_core_manager_get_should_return_empty_results_when_no_entities_in_local_store_meet_contract_requirements() {
buildManager(for: .remoteAndLocal)
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.get(
byID: EntitySpyIdentifier(value: .remote(1, nil)),
in: context
)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_return_results_from_remote_when_no_entities_in_local_store_meet_contract_requirements_for_local_or_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
))
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localOr(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
manager
.get(
byID: EntitySpyIdentifier(value: .remote(1, nil)),
in: context
)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.lazy.value(), 9)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_return_results_from_remote_when_no_entities_meet_contract_requirements_in_local_store_for_local_then_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
))
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localThen(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
manager
.get(
byID: EntitySpyIdentifier(value: .remote(1, nil)),
in: context
)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.lazy.value(), 9)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_return_local_result_when_no_entities_meet_contract_requirements_in_remote_store_for_remote_or_local_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
memoryStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: true,
trustRemoteFiltering: true
),
contract: contract
)
manager
.get(
byID: EntitySpyIdentifier(value: .remote(1, nil)),
in: context
)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.lazy.value(), 9)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_get_should_return_empty_results_when_no_entities_meet_contract_requirements_in_remote_store_for_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.getResultStub = .success(.entity(
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested)
))
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .doNotPersist,
orLocal: false,
trustRemoteFiltering: true
),
contract: contract
)
manager
.get(
byID: EntitySpyIdentifier(value: .remote(1, nil)),
in: context
)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
// MARK: SEARCH by IDs
func test_core_manager_search_by_ids_should_trust_partial_results_in_local_store_for_local_data_source() {
buildManager(for: .remoteAndLocal)
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_ids_should_return_remote_results_when_at_least_one_entity_doesnt_meet_contract_requirements_in_local_store_for_local_or_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localOr(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_ids_should_return_remote_results_when_at_least_one_entity_doesnt_meet_contract_requirements_in_local_store_for_local_then_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localThen(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_ids_should_trust_partial_results_in_remote_store_for_remote_or_local_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: true,
trustRemoteFiltering: true
),
contract: contract
)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_ids_should_trust_remote_results_when_applying_contract_for_remote_or_local_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .unrequested)
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: true,
trustRemoteFiltering: true
),
contract: contract
)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_ids_should_trust_remote_results_when_applying_contract_for_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .unrequested)
]))
memoryStoreSpy.searchResultStub = .success(.entities([
]))
memoryStoreSpy.setResultStub = .success([
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
),
contract: contract
)
manager
.get(
byIDs: [EntitySpyIdentifier(value: .remote(1, nil)), EntitySpyIdentifier(value: .remote(2, nil))],
in: context
)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
// MARK: SEARCH by Query
func test_core_manager_search_by_query_should_trust_local_store_for_local_data_source() {
buildManager(for: .remoteAndLocal)
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
]))
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(dataSource: .local, contract: contract)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_trust_partial_results_in_local_store_for_local_or_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localOr(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_fetch_results_in_remote_store_when_local_store_returns_nil_for_local_or_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .unrequested)
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), title: "test", lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), title: "test", lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localOr(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_trust_partial_results_in_local_store_for_local_then_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localThen(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_fetch_results_in_remote_store_when_local_store_returns_nil_for_local_then_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .unrequested)
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: .localThen(
._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
)
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 2)
XCTAssertEqual(result.array.first?.identifier, EntitySpyIdentifier(value: .remote(1, nil)))
XCTAssertEqual(result.array.last?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_trust_partial_results_in_remote_store_for_remote_or_local_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: true,
trustRemoteFiltering: true
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertEqual(result.count, 1)
XCTAssertEqual(result.first?.identifier, EntitySpyIdentifier(value: .remote(2, nil)))
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_trust_remote_results_when_applying_contract_for_remote_or_local_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .unrequested)
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: true,
trustRemoteFiltering: true
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
func test_core_manager_search_by_query_should_trust_remote_results_when_applying_contract_for_remote_data_source() {
buildManager(for: .remoteAndLocal)
remoteStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .unrequested),
EntitySpy(idValue: .remote(2, nil), lazy: .unrequested)
]))
memoryStoreSpy.searchResultStub = .success(.entities([
EntitySpy(idValue: .remote(1, nil), lazy: .requested(9)),
EntitySpy(idValue: .remote(2, nil), lazy: .requested(5))
]))
memoryStoreSpy.setResultStub = .success([
])
let onceExpectation = self.expectation(description: "once")
let contract = LazyPropertyContract()
let context = ReadContext<EntitySpy>(
dataSource: ._remote(
endpoint: .request(APIRequestConfig(method: .get, path: .path("fake_entity/42")), resultPayload: .empty),
persistenceStrategy: .persist(.retainExtraLocalData),
orLocal: false,
trustRemoteFiltering: true
),
contract: contract
)
let query = Query<EntitySpy>(filter: .title == .string("test"))
manager
.search(withQuery: query, in: context)
.once
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
XCTFail("Unexpected error: \(error)")
case .finished:
return
}
onceExpectation.fulfill()
}, receiveValue: { result in
XCTAssertTrue(result.isEmpty)
onceExpectation.fulfill()
})
.store(in: &cancellables)
waitForExpectations(timeout: 1, handler: nil)
}
}
// MARK: - Contract Helpers
private struct IdentifierContract: EntityContract {
let successfulIdentifiers: [EntitySpyIdentifier]
init(successfulIdentifiers: [EntitySpyIdentifier]) {
self.successfulIdentifiers = successfulIdentifiers
}
public func shouldValidate<E>(_ entityType: E.Type) -> Bool where E: Entity {
return true
}
func isEntityValid<E>(_ entity: E, for query: Query<E>) -> Bool where E: Entity {
switch entity {
case let entity as EntitySpy:
return successfulIdentifiers.contains(entity.identifier)
default:
return true
}
}
}
private struct LazyPropertyContract: EntityContract {
public func shouldValidate<E>(_ entityType: E.Type) -> Bool where E: Entity {
return true
}
func isEntityValid<E>(_ entity: E, for query: Query<E>) -> Bool where E: Entity {
switch entity {
case let entity as EntitySpy:
switch entity.lazy {
case .requested: return true
case .unrequested: return false
}
default:
return true
}
}
}
| [
-1
] |
eeda720d66a5b9e585085fa0452a72b21f5e4c0a | 21a2f72185597d832ec149f2733c89a5916b0636 | /phoenix-ios/phoenix-ios/views/onboarding/RestoreWalletView.swift | cd37cef52801d6e4da9732cfa93ab69a4935149a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ImTheBadWolf/phoenix | 30dddc502d26cc1bc6e60f269707048bdc5fc3e6 | 9b20cfdfde8dfd89376bd599410a90a897fac0c0 | refs/heads/master | 2023-08-22T11:38:12.878424 | 2021-10-20T14:56:45 | 2021-10-20T14:56:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 19,218 | swift | import SwiftUI
import PhoenixShared
import os.log
#if DEBUG && false
fileprivate var log = Logger(
subsystem: Bundle.main.bundleIdentifier!,
category: "RestoreWalletView"
)
#else
fileprivate var log = Logger(OSLog.disabled)
#endif
struct RestoreWalletView: MVIView {
@StateObject var mvi = MVIState({ $0.restoreWallet() })
@Environment(\.controllerFactory) var factoryEnv
var factory: ControllerFactory { return factoryEnv }
@State var acceptedWarning = false
@State var mnemonics = [String]()
@State var autocomplete = [String]()
@ViewBuilder
var view: some View {
ZStack {
// Animation Note:
// We have 2 options:
//
// 1. Put the background here, in this layer.
// Which means when the WarningView dimisses (slides down vertically),
// then only the content (text & buttons) are moving.
// And the background stays in place.
//
// 2. Put the background in each layer below (WarningView & RestoreView).
// Which would mean when the WarningView dismisses (slides down vertically),
// then you see the background dismiss with it.
// Only to be replaced with the exact same background.
//
// In testing, I think #1 looks cleaner.
//
Color.primaryBackground
.edgesIgnoringSafeArea(.all)
if AppDelegate.showTestnetBackground {
Image("testnet_bg")
.resizable(resizingMode: .tile)
.edgesIgnoringSafeArea([.horizontal, .bottom]) // not underneath status bar
}
main
}
.navigationBarTitle(
NSLocalizedString("Restore my wallet", comment: "Navigation bar title"),
displayMode: .inline
)
.onChange(of: mvi.model, perform: { model in
onModelChange(model: model)
})
}
@ViewBuilder
var main: some View {
if !acceptedWarning {
WarningView(acceptedWarning: $acceptedWarning)
.zIndex(1)
.transition(.move(edge: .bottom))
} else {
RestoreView(
mvi: mvi,
mnemonics: $mnemonics,
autocomplete: $autocomplete
)
.zIndex(0)
}
}
func onModelChange(model: RestoreWallet.Model) -> Void {
log.trace("onModelChange()")
if let model = model as? RestoreWallet.ModelValidMnemonics {
finishAndRestoreWallet(model: model)
}
}
func finishAndRestoreWallet(model: RestoreWallet.ModelValidMnemonics) -> Void {
log.trace("finishAndRestoreWallet()")
AppSecurity.shared.addKeychainEntry(mnemonics: mnemonics) { (error: Error?) in
if error == nil {
AppDelegate.get().loadWallet(seed: model.seed)
}
}
}
}
struct WarningView: View {
@Binding var acceptedWarning: Bool
@State var iUnderstand: Bool = false
var body: some View {
VStack {
Text(
"""
Do not import a seed that was NOT created by this application.
Also, make sure that you don't have another Phoenix wallet running with the same seed.
"""
)
.padding(.top, 30)
HStack {
Spacer()
Text("I understand.")
.font(.headline)
.padding(.trailing, 10)
Toggle("", isOn: $iUnderstand).labelsHidden()
Spacer()
}
.padding([.top, .bottom], 16)
Button {
withAnimation {
acceptedWarning = true
}
} label: {
HStack {
Text("Next")
Image(systemName: "checkmark")
.imageScale(.medium)
}
.padding([.top, .bottom], 8)
.padding([.leading, .trailing], 16)
}
.disabled(!iUnderstand)
.buttonStyle(
ScaleButtonStyle(
backgroundFill: Color.primaryBackground,
borderStroke: Color.appAccent,
disabledBorderStroke: Color(UIColor.separator)
)
)
Spacer()
} // </VStack>
.padding([.leading, .trailing])
}
}
struct RestoreView: View {
@ObservedObject var mvi: MVIState<RestoreWallet.Model, RestoreWallet.Intent>
@Binding var mnemonics: [String]
@Binding var autocomplete: [String]
@State var wordInput: String = ""
@State var isProcessingPaste = false
@Namespace var topID
@Namespace var inputID
let keyboardWillShow = NotificationCenter.default.publisher(for:
UIApplication.keyboardWillShowNotification
)
let keyboardDidHide = NotificationCenter.default.publisher(for:
UIApplication.keyboardDidHideNotification
)
let maxAutocompleteCount = 12
var body: some View {
ScrollViewReader { scrollViewProxy in
ScrollView {
ZStack {
// This interfers with tapping on buttons.
// It only seems to affect the device (not the simulator)
//
// A better solution is to use keyboardDismissMode, as below.
//
// Color(UIColor.clear)
// .frame(maxWidth: .infinity, maxHeight: .infinity)
// .contentShape(Rectangle())
// .onTapGesture {
// // dismiss keyboard if visible
// let keyWindow = UIApplication.shared.connectedScenes
// .filter({ $0.activationState == .foregroundActive })
// .map({ $0 as? UIWindowScene })
// .compactMap({ $0 })
// .first?.windows
// .filter({ $0.isKeyWindow }).first
// keyWindow?.endEditing(true)
// }
main(scrollViewProxy)
}
}
}
.onAppear {
UIScrollView.appearance().keyboardDismissMode = .interactive
}
}
@ViewBuilder
func main(_ scrollViewProxy: ScrollViewProxy) -> some View {
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
HStack(alignment: VerticalAlignment.center, spacing: 0) {
Spacer()
Text("Your wallet's seed is a list of 12 english words.")
.id(topID)
Spacer()
}
.padding([.leading, .trailing], 16)
HStack(alignment: VerticalAlignment.center, spacing: 0) {
TextField("Enter keywords from your seed", text: $wordInput)
.onChange(of: wordInput) { _ in
onInput()
}
.autocapitalization(.none)
.disableAutocorrection(true)
.disabled(mnemonics.count == 12)
.padding(.trailing, 4)
// Clear button (appears when TextField's text is non-empty)
Button {
wordInput = ""
} label: {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.secondary)
}
.isHidden(wordInput == "")
}
.padding([.top, .bottom], 8)
.padding(.leading, 16)
.padding(.trailing, 8)
.background(Color.primaryBackground)
.cornerRadius(100)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color(UIColor.separator), lineWidth: 1.5)
)
.padding(.top)
.id(inputID)
// Autocomplete suggestions for mnemonics
ScrollView(.horizontal) {
LazyHStack {
if autocomplete.count < maxAutocompleteCount {
ForEach(autocomplete, id: \.self) { word in
Button {
selectMnemonic(word)
} label: {
Text(word)
.underline()
.foregroundColor(Color.primary)
}
}
}
}
}
.frame(height: 32)
Divider().padding(.bottom)
mnemonicsList()
if mvi.model is RestoreWallet.ModelInvalidMnemonics {
Text(
"""
This seed is invalid and cannot be imported.
Please try again
"""
)
.padding([.top, .bottom])
.foregroundColor(Color.red)
}
HStack { // Center button using: HStack {[space, button, space]}
Spacer()
Button {
onImportButtonTapped()
} label: {
HStack {
Text("Import")
Image(systemName: "checkmark.circle")
.imageScale(.medium)
}
.padding([.top, .bottom], 8)
.padding([.leading, .trailing], 16)
}
.disabled(mnemonics.count != 12)
.buttonStyle(
ScaleButtonStyle(
backgroundFill: Color.primaryBackground,
borderStroke: Color.appAccent,
disabledBorderStroke: Color(UIColor.separator)
)
)
Spacer()
}
.padding(.top)
} // </VStack>
.padding(.top, 30)
.padding([.leading, .trailing], 20)
.padding(.bottom) // buffer space at bottom of scrollView
.onChange(of: mvi.model, perform: { model in
onModelChange(model: model)
})
.onChange(of: autocomplete) { _ in
onAutocompleteListChanged()
}
.onReceive(keyboardWillShow) { notification in
// Maybe add this for smaller phones like iPhone 8:
// withAnimation {
// scrollViewProxy.scrollTo(inputID, anchor: .top)
// }
}
.onReceive(keyboardDidHide) { _ in
// withAnimation {
// scrollViewProxy.scrollTo(topID, anchor: .top)
// }
}
}
@ViewBuilder
func mnemonicsList() -> some View {
// Design:
//
// #1 hammer (x) #7 bacon (x)
// #2 fat (x) #8 animal (x)
// ...
//
// Architecture:
//
// There are 3 ways to layout the design:
//
// 1) VStack of HStack's
//
// So each row is its own HStack.
// And VStack puts all the rows together.
//
// VStack {
// ForEach {
// HStack {
// {} #1
// {} hammer (x)
// {} #7
// {} bacon (x)
// }
// }
// }
//
// The problem with this design is that items aren't aligned vertically.
// For example, it will end up looking like this:
//
// #9 bacon
// #10 animal
//
// What we want is for "bacon" & "animal" to be aligned vertically.
// But we can't get that with this design unless we:
// - hardcode the width of the number-row (difficult to do with adaptive text sizes)
// - use tricks to calculate the proper width based on current font size (possible option)
//
// 2) HStack of VStack's
//
// So each column is its own VStack.
// And HStack puts all the columns together.
//
// HStack {
// VStack { ForEach{} } // column: #1
// VStack { ForEach{} } // column: hammer (x)
// VStack { ForEach{} } // column: #7
// VStack { ForEach{} } // column: bacon (x)
// }
//
// This fixes the vertical alignment problem with the previous design.
// But we have to be very careful to ensure that each VStack is the same height.
// This works if:
// - we use the same font size for all text
// - the button size is <= the font size
//
// 3) Use a LazyVGrid and design the columns manually
//
// let columns: [GridItem] = [
// GridItem(.flexible(?), spacing: 2),
// GridItem(.flexible(?), spacing: 8),
// GridItem(.flexible(?), spacing: 2),
// GridItem(.flexible(?), spacing: 0)
// ]
//
// The problem is that GridItem isn't very flexible.
// What we want to say is:
// - make columns [0, 2] the minimum possible size
// - make columns [1, 3] the remainder
//
// But that's not an option. We have to define the min & max width.
// So we're back to the exact same problem we had with design #1.
//
// Thus, we're going with design #2 for now.
let row_bottomSpacing: CGFloat = 6
HStack(alignment: VerticalAlignment.center, spacing: 0) {
// #1
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
ForEach(0..<6, id: \.self) { idx in
HStack(alignment: VerticalAlignment.center, spacing: 0) {
Text(verbatim: "#\(idx + 1) ")
.font(Font.headline.weight(.regular))
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.padding(.bottom, row_bottomSpacing)
}
}
.padding(.trailing, 2)
// hammer (x)
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
ForEach(0..<6, id: \.self) { idx in
HStack(alignment: VerticalAlignment.center, spacing: 0) {
Text(mnemonic(idx))
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
Button {
mnemonics.removeSubrange(idx..<mnemonics.count)
} label: {
Image(systemName: "xmark")
.font(Font.caption.weight(.thin))
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.isHidden(mnemonics.count <= idx)
}
.padding(.bottom, row_bottomSpacing)
}
}
.padding(.trailing, 8)
// #7
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
ForEach(6..<12, id: \.self) { idx in
HStack(alignment: VerticalAlignment.center, spacing: 0) {
Text(verbatim: "#\(idx + 1) ")
.font(Font.headline.weight(.regular))
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.padding(.bottom, row_bottomSpacing)
}
}
.padding(.trailing, 2)
// bacon (x)
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
ForEach(6..<12, id: \.self) { idx in
HStack(alignment: VerticalAlignment.center, spacing: 0) {
Text(mnemonic(idx ))
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
Button {
mnemonics.removeSubrange(idx..<mnemonics.count)
} label: {
Image(systemName: "xmark")
.font(Font.caption.weight(.thin))
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.isHidden(mnemonics.count <= idx)
}
.padding(.bottom, row_bottomSpacing)
}
}
}
}
func mnemonic(_ idx: Int) -> String {
return (mnemonics.count > idx) ? mnemonics[idx] : " "
}
func onModelChange(model: RestoreWallet.Model) -> Void {
log.trace("[RestoreView] onModelChange()")
if let model = model as? RestoreWallet.ModelFilteredWordlist {
log.debug("ModelFilteredWordlist.words = \(model.words)")
if autocomplete == model.words {
// Careful:
// autocomplete = model.words
// ^ this won't do anything. Will not call: onAutocompleteListChanged()
//
// So we need to do it manually.
// For more info, see issue #109
//
onAutocompleteListChanged()
} else {
autocomplete = model.words
}
}
}
func onInput() -> Void {
log.trace("[RestoreView] onInput(): \"\(wordInput)\"")
// When the user hits space, we auto-accept the first mnemonic in the autocomplete list
if maybeSelectMnemonic(isAutocompleteTrigger: false) {
return
} else {
updateAutocompleteList()
}
}
func updateAutocompleteList() {
log.trace("[RestoreView] updateAutocompleteList()")
// Some keyboards will inject the entire word plus a space.
//
// For example, if using a sliding keyboard (e.g. SwiftKey),
// then after sliding from key to key, and lifting your finger,
// the entire word will be injected plus a space: "bacon "
//
// We should also consider the possibility that the user pasted in their seed.
let tokens = wordInput.trimmingCharacters(in: .whitespaces).split(separator: " ")
if let firstToken = tokens.first {
log.debug("[RestoreView] Requesting autocomplete for: '\(firstToken)'")
mvi.intent(RestoreWallet.IntentFilterWordList(
predicate: String(firstToken),
uuid: UUID().uuidString
))
} else {
log.debug("[RestoreView] Clearing autocomplete list")
mvi.intent(RestoreWallet.IntentFilterWordList(
predicate: "",
uuid: UUID().uuidString
))
}
}
func onAutocompleteListChanged() {
log.trace("[RestoreView] onAutocompleteListChanged()")
// Example flow that gets us here:
//
// - user is using fancy keyboard (e.g. SwiftKey)
// - user slides on keyboard to type word
// - the completed work is injected, plus a space: "Bacon "
// - onInput("Bacon ") is called, but autocomplete list is empty
// - we ask the business library for an updated autocomplete list
// - the library responds with: ["bacon"]
// - this function is called
maybeSelectMnemonic(isAutocompleteTrigger: true)
}
@discardableResult
func maybeSelectMnemonic(isAutocompleteTrigger: Bool) -> Bool {
log.trace("[RestoreView] maybeSelectMnemonic(isAutocompleteTrigger = \(isAutocompleteTrigger))")
if isAutocompleteTrigger && autocomplete.count >= 1 {
// Example:
// The user pasted in their seed, so the input has multiple tokens: "bacon fat animal ...",
// We want to automatically select each mnemonic in the list (if it's an exact match).
let tokens = wordInput.trimmingCharacters(in: .whitespaces).split(separator: " ")
if let firstToken = tokens.first {
let mnemonic = autocomplete[0]
if firstToken.caseInsensitiveCompare(mnemonic) == .orderedSame {
if !isProcessingPaste && tokens.count > 1 {
// Paste processsing triggered:
// - there are multiple tokens in the wordList
// - the first token is an exact match
// - let's process each token until we reach the end or a non-match
isProcessingPaste = true
log.debug("[RestoreView] isProcessingPaste = true")
}
if isProcessingPaste {
selectMnemonic(mnemonic)
return true
}
}
}
}
if isAutocompleteTrigger && isProcessingPaste {
isProcessingPaste = false
log.debug("[RestoreView] isProcessingPaste = false")
}
if wordInput.hasSuffix(" "),
let acceptedWord = autocomplete.first,
autocomplete.count < maxAutocompleteCount // only if autocomplete list is visible
{
// Example:
// The input is "Bacon ", and the autocomplete list is ["bacon"],
// so we should automatically select the mnemonic.
//
// This needs to happen if:
//
// - the user hits space when typing, so we want to automatically accept
// the first entry in the autocomplete list
//
// - the user is using a fancy keyboard (e.g. SwiftKey),
// and the input was injected at one time as a word plus space: "Bacon "
selectMnemonic(acceptedWord)
return true
}
return false
}
func selectMnemonic(_ word: String) -> Void {
log.trace("[RestoreView] selectMnemonic()")
if (mnemonics.count < 12) {
mnemonics.append(word)
}
if let token = wordInput.trimmingCharacters(in: .whitespaces).split(separator: " ").first,
let range = wordInput.range(of: token)
{
var input = wordInput
input.removeSubrange(wordInput.startIndex ..< range.upperBound)
input = input.trimmingCharacters(in: .whitespaces)
log.debug("[RestoreView] Remaining wordInput: \"\(input)\"")
wordInput = input
} else {
log.debug("[RestoreView] Remaining wordInput: \"\"")
wordInput = ""
}
}
func onImportButtonTapped() -> Void {
log.trace("[RestoreView] onImportButtonTapped()")
mvi.intent(RestoreWallet.IntentValidate(mnemonics: self.mnemonics))
}
}
class RestoreWalletView_Previews: PreviewProvider {
static let filteredWordList1 = [
"abc", "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access"
]
static let filteredWordList2 = [
"abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account"
]
static let filteredWordList3 = [
"abc", "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid"
]
static var previews: some View {
RestoreWalletView().mock(
RestoreWallet.ModelReady()
)
.previewDevice("iPhone 11")
RestoreWalletView().mock(
RestoreWallet.ModelInvalidMnemonics()
)
.previewDevice("iPhone 11")
RestoreWalletView().mock(
RestoreWallet.ModelFilteredWordlist(uuid: "", predicate: "ab", words: filteredWordList1)
)
.previewDevice("iPhone 11")
RestoreWalletView().mock(
RestoreWallet.ModelFilteredWordlist(uuid: "", predicate: "ab", words: filteredWordList2)
)
.previewDevice("iPhone 11")
RestoreWalletView().mock(
RestoreWallet.ModelFilteredWordlist(uuid: "", predicate: "ab", words: filteredWordList3)
)
.previewDevice("iPhone 11")
}
}
| [
-1
] |
516922fbbe27bada880bc40a20ce308dba8cac69 | 2fdf3a40110b5b83a97e6a3e4148005d8185b832 | /BrewStyle/Controllers/TermListingController (MobileCI's conflicted copy 2017-04-26).swift | 06ab6d70894933cf04c042978f8d23ed14bfb4bb | [] | no_license | gregkdunn/BrewStyle | 7ef62019b4c1046650a2eeb1a26c5c6242bbe02d | 527599af9e83c9846aa75afc042cf3b9ce6fc1d1 | refs/heads/master | 2020-03-19T08:30:05.665123 | 2018-06-05T17:15:16 | 2018-06-05T17:15:16 | 136,209,249 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 7,417 | swift | //
// TermListingController.swift
// BrewStyle
//
// Created by Greg Dunn on 10/29/15.
// Copyright © 2015 Greg K Dunn. All rights reserved.
//
import UIKit
enum TermCellIdentifiers : String {
case header = "overview"
case term = "TermListingCell"
}
enum TermCollectionViewSections : Int {
case Terms
}
class TermListingController: GKDFilterableViewController {
let titleString = "Glossary"
let descString = "Some terminology used in the style guidelines may be unfamiliar to some readers. Rather than include a complete dictionary, we have highlighted a few terms that either may not be well understood, or that imply specific meanings within the guidelines. Sometimes ingredient names are used as a shorthand for the character they provide to beer. When judges use these terms, they don’t necessarily imply that those specific ingredients have been used, just that the perceived characteristics match those commonly provided by the mentioned ingredients."
private let sizingTermsCell = TermListingCell()
lazy var data : Array<TermViewModel> = []
override func viewDidLoad() {
super.viewDidLoad()
createSettingsButton()
configueBackButton()
createCollectionView()
//createFilterMenu()
reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"reloadData", name:Constants.Notification.DefaultsVersion, object:nil)
}
// MARK: Data
func reloadData () {
dataDisplayed = 0
self.data.removeAll()
collectionView.reloadData()
ContentStore.sharedInstance.fetchTermsWithCompletionBlock {
(result: [TermViewModel]) in
self.data = self.sortByCategory(result)
if result.count > 0 {
self.loadMoreData()
self.empty.disable()
} else {
self.empty.noData()
}
}
}
func sortByCategory (result: [TermViewModel]) -> [TermViewModel]{
var appearance : [TermViewModel] = []
var quality : [TermViewModel] = []
var yeast : [TermViewModel] = []
var malt : [TermViewModel] = []
var hop : [TermViewModel] = []
for termVM in result {
if let cat = termVM.category() {
switch cat {
case .Appearance :
appearance.append(termVM)
case .Quality :
quality.append(termVM)
case .Yeast :
yeast.append(termVM)
case .Malt :
malt.append(termVM)
case .Hop :
hop.append(termVM)
}
}
}
var sorted : [TermViewModel] = []
sorted.appendContentsOf(appearance)
sorted.appendContentsOf(quality)
sorted.appendContentsOf(yeast)
sorted.appendContentsOf(malt)
sorted.appendContentsOf(hop)
return sorted
}
// MARK: Collection View
override func createCollectionView () {
super.createCollectionView()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(TermListingCell.self, forCellWithReuseIdentifier: CategoryCellIdentifiers.category.rawValue)
collectionView.registerClass(CategoryDetailView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: SubCategoryCellIdentifiers.PageHeader.rawValue)
empty.configWithIcon(UIImage(named:"pint_beer_white_2"),title:"loading", description: "terms")
}
}
extension TermListingController : UICollectionViewDataSource {
// MARK - Header
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CategoryDetailView.sizeForText(descString, width: collectionView.bounds.width)
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let header : CategoryDetailView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: SubCategoryCellIdentifiers.PageHeader.rawValue, forIndexPath: indexPath) as! CategoryDetailView
header.titleLabel.text = titleString
header.descLabel.text = descString
header.resetGradientFrame()
return header as UICollectionReusableView
}
//MARK - Cells
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataDisplayed
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CategoryCellIdentifiers.category.rawValue, forIndexPath: indexPath) as UICollectionViewCell
configCell(cell, indexPath: indexPath)
return cell
}
func configCell(cell: UICollectionViewCell, indexPath: NSIndexPath) {
if let termListingCell = cell as? TermListingCell,
let termVM : TermViewModel = data[indexPath.row] {
termListingCell.cellWidth = collectionView.bounds.width - 2
termListingCell.configWithTermViewModel(termVM)
}
}
}
extension TermListingController : UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let _ : TermViewModel = data[indexPath.row] else {
return
}
//show subcategories with term
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension TermListingController : UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.row > dataDisplayed {
loadMoreData()
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if let termVM : TermViewModel = data[indexPath.row] {
sizingTermsCell.prepareForReuse()
sizingTermsCell.cellWidth = collectionView.bounds.width - 2
sizingTermsCell.configWithTermViewModel(termVM)
return sizingTermsCell.intrinsicContentSize()
}
return CGSize(width: collectionView.bounds.width - 2, height: 55)
}
}
// Infinite Scrolling
extension TermListingController : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height * 0.6
if offsetY > contentHeight - scrollView.frame.size.height {
loadMoreData()
}
}
func loadMoreData () {
guard dataLoading == false && dataAllLoaded == false else {
return
}
updateInsertDataCount()
insertData()
}
func insertData () {
dataLoading = true
var insertIndexPaths : [NSIndexPath] = []
let start = dataDisplayed
let total = start + insertCount
for (var i = start; i < total; i++) {
insertIndexPaths.append(NSIndexPath(forItem: i, inSection: 0))
}
guard insertIndexPaths.count > 0 else {
dataLoading = false
dataAllLoaded = true
return
}
dataDisplayed = dataDisplayed + insertCount
collectionView.insertItemsAtIndexPaths(insertIndexPaths)
dataLoading = false
empty.disable()
}
func updateInsertDataCount () -> Int {
guard dataLoading == false else {
return dataDisplayed
}
let newCount = (data.count > dataIncrement + dataDisplayed) ? dataIncrement + dataDisplayed : data.count
insertCount = newCount - dataDisplayed
return newCount
}
}
| [
-1
] |
4bdaaf64d0c8a69bb16364a1f30005b5fe8a7c94 | e40e24da345877685a4ccd83a514d2387b395fa9 | /IChat/Extensions/GradientView.swift | 455d04870b013cfa5b5842bff6256902e0640537 | [] | no_license | kristi405/IChat | ed6744d423e85ef1c51c8a8bb901512b3d5687f5 | 5699082b542c34259fd31f38aea2c1ba233e03f2 | refs/heads/master | 2022-12-31T00:24:58.582967 | 2020-10-19T05:11:41 | 2020-10-19T05:11:41 | 305,411,568 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,677 | swift | //
// GradientView.swift
// IChat
//
// Created by kris on 21/09/2020.
// Copyright © 2020 kris. All rights reserved.
//
import UIKit
class GradientView: UIView {
private let gradientLayer = CAGradientLayer()
enum Point {
case leading
case topLeading
case bottomLeading
case top
case center
case bottom
case trailing
case topTrailing
case bottomTrailing
var point: CGPoint {
switch self {
case .leading:
return CGPoint(x: 0, y: 0)
case .topLeading:
return CGPoint(x: 0, y: 0.5)
case .bottomLeading:
return CGPoint(x: 0, y: 1)
case .top:
return CGPoint(x: 0.5, y: 0)
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .bottom:
return CGPoint(x: 0.5, y: 1)
case .trailing:
return CGPoint(x: 1, y: 0)
case .topTrailing:
return CGPoint(x: 1, y: 0.5)
case .bottomTrailing:
return CGPoint(x: 1, y: 1)
}
}
}
init(from: Point, to: Point, startColor: UIColor?, endColor: UIColor?) {
self.init()
setupGradient(from: from, to: to, startColor: startColor, endColor: endColor)
}
@IBInspectable private var startColor: UIColor? {
didSet {
setupGradientColors(startColor: startColor, endColor: endColor)
}
}
@IBInspectable private var endColor: UIColor? {
didSet {
setupGradientColors(startColor: startColor, endColor: endColor)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
private func setupGradient(from: Point, to: Point, startColor: UIColor?, endColor: UIColor?) {
self.layer.addSublayer(gradientLayer)
setupGradientColors(startColor: startColor, endColor: endColor)
gradientLayer.startPoint = from.point
gradientLayer.endPoint = to.point
}
private func setupGradientColors(startColor: UIColor?, endColor: UIColor?) {
if let startColor = startColor, let endColor = endColor {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupGradient(from: .leading, to: .trailing, startColor: startColor, endColor: endColor)
}
}
| [
342407
] |
6ab5e4bb0608d35557be051a6c4e718d616bb4f1 | 747486f93441eee8cbdb4ee165e53419747c2506 | /iOS/AppDelegate.swift | 50713a85b5880f4961cf333e8136df269c8347bd | [] | no_license | ctdewaters/Music-Memories | cd831f3784fa145aff64b3dff6e72da97bfd3b1d | 71a9d26f7723b9fed466b52258691b44237214ae | refs/heads/master | 2021-03-27T10:32:44.591925 | 2019-10-10T20:41:44 | 2019-10-10T20:41:44 | 120,354,327 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 22,652 | swift | //
// AppDelegate.swift
// Music Memories
//
// Created by Collin DeWaters on 7/6/17.
// Copyright © 2017 Collin DeWaters. All rights reserved.
//
import UIKit
import CoreData
import StoreKit
import MemoriesKit
import IQKeyboardManagerSwift
import UserNotifications
import AuthenticationServices
import GSTouchesShowingWindow_Swift
import CoreData
///Application open settings, for playing or creating a memory.
var applicationOpenSettings: ApplicationOpenSettings?
///Reference to "Main.storyboard".
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
///Reference to "Onboarding.storyboard".
let onboardingStoryboard = UIStoryboard(name: "Onboarding", bundle: nil)
///Reference to "MemoryCreation.storyboard".
let memoryCreationStoryboard = UIStoryboard(name: "MemoryCreation", bundle: nil)
///Reference to "EditMemory.storyboard".
let editMemoryStoryboard = UIStoryboard(name: "EditMemory", bundle: nil)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
//MARK: - Properties.
///The retrieved notification settings.
public static var notificationSettings: UNNotificationSettings?
///The application window.
var customWindow: GSTouchesShowingWindow?
var window: UIWindow? /*{
get {
customWindow = customWindow ?? GSTouchesShowingWindow(frame: UIScreen.main.bounds)
return customWindow
}
set {}
}*/
///The id of the last dynamic memory registered for a notification.
public static var lastDynamicNotificationID: String? {
set {
UserDefaults.standard.set(newValue, forKey: "lastDynamicNotificationID")
}
get {
return UserDefaults.standard.string(forKey: "lastDynamicNotificationID")
}
}
static let didBecomeActiveNotification = Notification.Name("didBecomeActive")
override var canBecomeFirstResponder: Bool {
return true
}
//MARK: - UIApplicationDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
//Set the current user notification center delegate to the app delegate.
UNUserNotificationCenter.current().delegate = self
//Setup IQKeyboardManager.
IQKeyboardManager.shared.enable = true
//Start sending playback notifications.
MKMusicPlaybackHandler.mediaPlayerController.beginGeneratingPlaybackNotifications()
//UI appearances.
self.setAppearances()
//Check if onboarding has been completed.
//self.checkForOnboardingCompletion()
self.verifyAuthentication()
//Choose which settings VC to set in the tab bar.
self.setupSettingsViewController()
//Turn on retaining managed objects in Core Data.
MKCoreData.shared.managedObjectContext.retainsRegisteredObjects = true
NotificationCenter.default.addObserver(self, selector: #selector(self.didRecieveSettingsRefresh(withNotification:)), name: MKCloudManager.serverSettingsDidRefreshNotification, object: nil)
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.
CDMiniPlayerController.shared.updateShuffleAndRepeatModeUI()
//Set badge number to zero.
UIApplication.shared.applicationIconBadgeNumber = 0
if MKAuth.isAuthenticated && Settings.shared.onboardingComplete {
//Sync memories
MKCloudManager.syncServerMemories(updateDynamicMemory: true)
//Retrieve the current user's settings from their account.
MKCloudManager.retrieveUserSettings { (settingsData) in
self.handleSettingsRefreshResponse(settingsData)
}
}
//Check if onboarding is complete, if so, check if the tokens are valid.
if Settings.shared.onboardingComplete {
DispatchQueue.global().async {
//Check tokens.
MKAuth.testTokens { (valid) in
//Check if the response is valid.
if valid {
MKAuth.requestCloudServiceCapabilities {
//Send retrieved notifications.
NotificationCenter.default.post(name: MKAuth.developerTokenWasRetrievedNotification, object: nil, userInfo: nil)
NotificationCenter.default.post(name: MKAuth.musicUserTokenWasRetrievedNotification, object: nil, userInfo: nil)
}
}
else {
//Reload tokens.
MKAuth.resetTokens()
if MKAuth.musicUserTokenRetrievalAttempts < 1 {
MKAuth.retrieveMusicUserToken()
}
}
}
DispatchQueue.main.async {
MKCoreData.shared.save(context: MKCoreData.shared.managedObjectContext)
}
//Request cloud service capabilities.
MKAuth.requestCloudServiceCapabilities {
//Disable dynamic memories if user is not an Apple Music subscriber.
if !MKAuth.isAppleMusicSubscriber {
DispatchQueue.main.async {
Settings.shared.dynamicMemoriesEnabled = false
}
}
}
}
}
NotificationCenter.default.post(name: AppDelegate.didBecomeActiveNotification, object: nil)
}
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.
}
//MARK: - UserNotifications
///Registers the application to recieve notifications.
class func registerForNotifications(withCompletion completion: @escaping (Bool) -> Void) {
let center = UNUserNotificationCenter.current()
//Request permission to send notifications.
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
//Run completion block.
completion(granted)
}
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
//Send the token to the Music Memories server.
MKCloudManager.register(deviceToken: token)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
print(userInfo)
MKCloudManager.handle(apnsUserInfo: userInfo)
}
///Retrieves the UserNotification settings.
class func retrieveNotificationSettings(withCompletion completion: @escaping (UNNotificationSettings?) -> Void) {
let center = UNUserNotificationCenter.current()
//Get the notification settings.
center.getNotificationSettings { (settings) in
//Set the settings property.
AppDelegate.notificationSettings = settings
//Run the completion block with no settings if the application is not authorized to schedule notifications.
guard settings.authorizationStatus == .authorized else {
completion(nil)
return
}
//User authorized notifications.
completion(settings)
}
}
///Schedules a local notification, given content, an identifier, and a date to send it.
class func schedule(localNotificationWithContent content: UNNotificationContent, withIdentifier identifier: String, andSendDate sendDate: Date) {
//Check if the notification settings show the user authorized.
if AppDelegate.notificationSettings?.authorizationStatus == .authorized {
//Create and add the request.
let timeInterval = sendDate.timeIntervalSinceNow
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if error != nil {
print(error?.localizedDescription ?? "Notification Scheduling Error Occurred")
}
}
}
}
///Cancels a scheduled notification request, with a given identifier.
class func cancel(notificationRequestWithIdentifier identifier: String) {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
}
//MARK: - UNUserNotificationCenterDelegate.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//Increment badge.
UIApplication.shared.applicationIconBadgeNumber += 1
completionHandler([.alert, .sound])
}
//MARK: - Setup Functions
/// Sets the global appearances for bars and other UI elements.
func setAppearances() {
UITabBar.appearance().tintColor = .theme
UITabBar.appearance().unselectedItemTintColor = .secondaryText
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "SFProRounded-Medium", size: 12) ?? UIFont.systemFont(ofSize: 12)], for: .normal)
UINavigationBar.appearance().tintColor = .theme
let largeTitlePointSize: CGFloat = 34
let titlePointSize: CGFloat = 18
UINavigationBar.appearance().largeTitleTextAttributes =
[NSAttributedString.Key.foregroundColor : UIColor.navigationForeground, NSAttributedString.Key.font: UIFont(name: "SFProRounded-Bold", size: largeTitlePointSize) ??
UIFont.systemFont(ofSize: largeTitlePointSize)]
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.text, NSAttributedString.Key.font: UIFont(name: "SFProRounded-Semibold", size: titlePointSize) ??
UIFont.systemFont(ofSize: titlePointSize)]
UISwitch.appearance().onTintColor = .theme
}
/// Checks if the onboarding process has been completed, and sets the onboarding root view controller as the root view controller if not.
func checkForOnboardingCompletion() {
if !Settings.shared.onboardingComplete {
Settings.shared.dynamicMemoriesEnabled = false
//Go to the onboarding storyboard.
self.window?.rootViewController = onboardingStoryboard.instantiateInitialViewController()
}
}
/// Verifies the user has been authenticated, and if not, sets the onboarding process as the root view controller.
func verifyAuthentication() {
if !Settings.shared.onboardingComplete {
Settings.shared.dynamicMemoriesEnabled = false
//Go to the onboarding storyboard.
self.window?.rootViewController = onboardingStoryboard.instantiateInitialViewController()
return
}
if !MKAuth.isAuthenticated && didSkipAuth == false {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.window?.rootViewController?.present(onboardingStoryboard.instantiateInitialViewController()!, animated: true, completion: nil)
}
return
}
if #available(iOS 13, *) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
appleIDProvider.getCredentialState(forUserID: MKAuth.userID ?? "") { (credentialState, error) in
switch credentialState {
case .authorized :
//User has successfully signed in previously, check rest of onboarding has completed.
DispatchQueue.main.async {
self.checkForOnboardingCompletion()
}
break
case .revoked, .notFound :
//User is not signed in, sign out locally, delete the account associated memories, and show the onboarding process with the login view controller.
if didSkipAuth { return }
MKAuth.signOut()
//Retreive all memories in a private queue MOC.
let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
moc.parent = MKCoreData.shared.managedObjectContext
let memories = MKCoreData.shared.fetchAllMemories(inContext: moc)
//Delete them in the background.
moc.perform {
for memory in memories {
moc.delete(memory)
}
MKCoreData.shared.save(context: moc)
}
DispatchQueue.main.async {
self.window?.rootViewController?.present(onboardingStoryboard.instantiateInitialViewController()!, animated: true, completion: nil)
}
break
default :
break
}
}
}
else {
//iOS 12, check if onboarding has been completed.
self.checkForOnboardingCompletion()
}
}
/// Chooses the correct settings view controller, given the current iOS version.
func setupSettingsViewController() {
if let tabBarVC = window?.rootViewController as? UITabBarController {
if #available(iOS 13.0, *) {
//iOS 13, use default SwiftUI powered view controller (already set in Main.Storyboard).
}
else {
//On iOS 12 or earlier, fall back on the legacy view controller class.
if var vcs = tabBarVC.viewControllers {
vcs.removeLast()
vcs.append(mainStoryboard.instantiateViewController(withIdentifier: "settingsLegacyNavVC"))
tabBarVC.setViewControllers(vcs, animated: true)
}
}
}
}
//MARK: - Server Settings Refreshing
@objc func didRecieveSettingsRefresh(withNotification notification: Notification) {
guard let userInfo = notification.userInfo as? [String : Any], let settings = userInfo["settings"] as? MKCloudSettings else { return }
self.handleSettingsRefreshResponse(settings)
}
/// Handles a settings request response from the MM server.
/// - Parameter settings: The settings tuple retrieved from the server.
private func handleSettingsRefreshResponse(_ settings: MKCloudSettings?) {
guard let settings = settings, let dynamicMemories = settings.dynamicMemories, let duration = settings.duration, let addToLibrary = settings.addToLibrary else {
//Settings not set on server, send local settings.
MKCloudManager.updateUserSettings(dynamicMemories: Settings.shared.dynamicMemoriesEnabled, duration: Settings.shared.dynamicMemoriesUpdatePeriod.serverID, addToLibrary: Settings.shared.addDynamicMemoriesToLibrary)
return
}
//Set the local settings properties.
Settings.shared.dynamicMemoriesEnabled = dynamicMemories
if let dmUpdatePeriod = Settings.DynamicMemoriesUpdatePeriod.fromServerID(duration) {
Settings.shared.dynamicMemoriesUpdatePeriod = dmUpdatePeriod
}
Settings.shared.addDynamicMemoriesToLibrary = addToLibrary
}
//MARK: - Key Commands
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "N", modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Create Memory"),
UIKeyCommand(input: "F", modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Search Albums"),
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Increase Volume"),
UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Decrease Volume"),
UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Next Track"),
UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: .command, action: #selector(self.didRecieveKeyCommand(_:)), discoverabilityTitle: "Previous Track")
]
}
@objc private func didRecieveKeyCommand(_ keyCommand: UIKeyCommand) {
if keyCommand.input == "N" {
self.handleCreateMemoryResponse()
return
}
if keyCommand.input == "F" {
LibraryViewController.shared?.searchController?.searchBar.becomeFirstResponder()
return
}
if keyCommand.input == UIKeyCommand.inputUpArrow {
if let view = LibraryViewController.shared?.volumeView.subviews.first as? UISlider {
view.value += 0.0625
}
return
}
if keyCommand.input == UIKeyCommand.inputDownArrow {
if let view = LibraryViewController.shared?.volumeView.subviews.first as? UISlider {
view.value -= 0.0625
}
return
}
if keyCommand.input == UIKeyCommand.inputRightArrow {
MKMusicPlaybackHandler.mediaPlayerController.skipToNextItem()
return
}
if keyCommand.input == UIKeyCommand.inputLeftArrow {
if MKMusicPlaybackHandler.mediaPlayerController.currentPlaybackTime > 3 {
MKMusicPlaybackHandler.mediaPlayerController.skipToBeginning()
return
}
MKMusicPlaybackHandler.mediaPlayerController.skipToPreviousItem()
return
}
}
//MARK: - Shortcut items
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
print(shortcutItem.type)
if shortcutItem.type == "com.CollinDeWaters.MusicMemories.composeMemory" && Settings.shared.onboardingComplete {
//Set the open settings to open the memory compose view.
self.handleCreateMemoryResponse()
}
}
//MARK: - Open Response Handling
private func handleCreateMemoryResponse() {
DispatchQueue.main.async {
if memoriesViewController != nil {
memoriesViewController?.tabBarController?.selectedIndex = 0
//Open the memory creation view.
memoriesViewController?.createMemory(self)
}
else {
LibraryViewController.shared?.tabBarController?.selectedIndex = 0
//Set the application open settings to true.
applicationOpenSettings = ApplicationOpenSettings()
applicationOpenSettings?.openCreateView = true
}
}
}
}
///`ApplicationOpenSettings`: provides codes received when the application is opening on what action to take.
class ApplicationOpenSettings {
//Codes
///When this code is recieved on open, the global applicationOpenSettings object will be initialized with open create view set to true.
static let createCode = 100
///When this code is recieved, we should look for a delete id in the message received from Apple Watch.
static let deleteCode = 200
///Open create view setting.
var openCreateView = false
init() {}
}
var didSkipAuth: Bool {
set {
UserDefaults.standard.set(newValue, forKey: "didSkipAuthentication")
}
get {
return UserDefaults.standard.bool(forKey: "didSkipAuthentication")
}
}
| [
-1
] |
feca68f6264f2f649f14816ead224a372e43fc04 | 3b8430d8bf5419bfa806c48faa602ba2dd33b7c6 | /KonkolFinalApp/ViewController.swift | bb00a903d6c3199e71729228904d6f179e8af4a9 | [] | no_license | chukon/KonkolFinalApp | bc60270fe361fc0d644db23a7e13288b1fca3eea | 19b4de0a89de49669ef058e4f26548968e86af72 | refs/heads/main | 2023-06-16T07:38:24.668782 | 2021-07-10T15:49:55 | 2021-07-10T15:49:55 | 384,734,853 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 287 | swift | //
// ViewController.swift
// KonkolFinalApp
//
// Created by RVCTechBusTeacher on 7/10/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| [
266816,
187937,
265797,
352295,
354729,
11920,
370352,
199251,
344695,
370521,
357209,
340988,
420381
] |
d267fc618c5326f9512334a97991540a52acf4aa | ca69236e10e173f9440356ee1016e2ed94551e58 | /Reading List/Reading List/BookDetailViewController.swift | 1e46d56f117bbd3b3b3ab36bb3be79d73d414e67 | [] | no_license | vshaweddy/ios-reading-list | 57ddb15eecea35cb01b8d6588a31f12501c6cde2 | ab473e78d86086646ca61c38539adb88b13b3434 | refs/heads/master | 2020-07-03T04:02:47.336419 | 2019-08-12T20:05:27 | 2019-08-12T20:05:27 | 201,776,959 | 0 | 0 | null | 2019-08-11T14:43:19 | 2019-08-11T14:43:19 | null | UTF-8 | Swift | false | false | 1,624 | swift | //
// BookDetailViewController.swift
// Reading List
//
// Created by Vici Shaweddy on 8/11/19.
// Copyright © 2019 Lambda School. All rights reserved.
//
import UIKit
class BookDetailViewController: UIViewController {
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var reasonTextView: UITextView!
var bookController: BookController?
var book: Book?
override func viewDidLoad() {
super.viewDidLoad()
updateViews()
}
func updateViews() {
self.titleTextField.text = book?.name
self.reasonTextView.text = book?.reasonToRead
if book?.name.isEmpty == true {
titleTextField.text = "Add a new book"
}
}
@IBAction func savePressed(_ sender: Any) {
guard let title = titleTextField.text,
!title.isEmpty,
let reason = reasonTextView.text,
!reason.isEmpty else { return }
if let book = book {
bookController?.editBook(book: book, newName: title, newReason: reason)
} else {
bookController?.createBook(named: title, reasoned: reason, readStatus: false)
}
navigationController?.popViewController(animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| [
-1
] |
b19dee489c908d90a25d4a7c3d0e6de6044381d1 | febbd861ccd5bd2723d492de99b6569001cd3d46 | /HazeDemo/Services/Api/Api.swift | 02ccf4b626e026b6fb5f6ba2baa5de4107553c67 | [] | no_license | alienxp03/HazeDemo | ef699454aa010099d3ad9a94d4d23d8519d28fa3 | 41b0e7e8e35ed492279bb532c1d1e08b40af7b60 | refs/heads/master | 2021-01-10T14:30:30.358769 | 2016-01-18T16:49:53 | 2016-01-18T16:49:53 | 49,889,635 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 477 | swift | //
// Api.swift
// HazeDemo
//
// Created by Muhammad Azuan Zira Zairein on 16/01/2016.
// Copyright © 2016 Azuan. All rights reserved.
//
import UIKit
protocol Api {
var baseApiUrl: String { get }
}
extension Api {
var baseApiUrl: String {
return "https://raw.githubusercontent.com/HazeWatchApp/apims_data/gh-pages/index_v2.json"
}
func request(endpoint endpoint: String) -> String {
return "\(baseApiUrl)/api/\(endpoint)"
}
}
| [
-1
] |
e2cd2745973131115a797cc9c43e9cfcc38ff34e | 46986be727802d006b3358573554484cb75a1b2f | /VirojFernando-COBSCComp171P-023/controllers/LoginViewController.swift | 5b5d0102201d44283f089136ca9051e1016007a7 | [
"MIT"
] | permissive | Trish-V/NIBM-Connect | 2676838a8ff84036192b68ff5b8ba6a7b9d23dea | ab4d0dd9da9cf4605755d68daca2586c58cceda0 | refs/heads/master | 2020-05-27T17:13:57.264823 | 2019-05-31T12:47:02 | 2019-05-31T12:47:02 | 188,716,450 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,899 | swift | //
// LoginViewController.swift
// VirojFernando-COBSCComp171P-023
//
// Created by Viroj Fernando on 5/25/19.
// Copyright © 2019 Heaven'sCode. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class LoginViewController: UIViewController {
@IBOutlet weak var logInButton: UIButton!
@IBOutlet weak var createAccountView: UIVisualEffectView!
@IBOutlet weak var blurBackground: UIVisualEffectView!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var resetPassword: UIVisualEffectView!
override func viewDidLoad() {
super.viewDidLoad()
self.logInButton.layer.cornerRadius = self.logInButton.frame.height / 4
self.blurBackground.alpha = 0
self.createAccountView.alpha = 0
self.resetPassword.alpha = 0
self.blurBackground.layer.cornerRadius = self.blurBackground.frame.height / 10
self.createAccountView.layer.cornerRadius = self.createAccountView.frame.height / 8
self.resetPassword.layer.cornerRadius = self.resetPassword.frame.height / 8
self.animateControls()
}
@IBAction func logInClicked(_ sender: Any) {
Auth.auth().signIn(withEmail: self.username.text!, password: self.password.text! ) { [weak self] user, error in
guard self != nil else { return }
if (error != nil){
let alertController = UIAlertController(title: "Problem!",
message: "Pleas check your credentials and try again",
preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
self?.present(alertController, animated: true, completion: nil)
return
}
self!.performSegue(withIdentifier: "loginSegue", sender: nil)
}
}
func animateControls ( ) {
UIView.animate(withDuration: 0.2, delay: 1, options: .curveLinear, animations: {
self.blurBackground.alpha = 1
self.resetPassword.alpha = 1
self.createAccountView.alpha = 1
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| [
-1
] |
dfaebbeb39f7e1d066e46305c92882cfb56ec7a4 | c7f269172bacdd544bc2c562e8c4bbab7654be66 | /SCTiledImage/SCTiledImage/TiledImageDataSourceRotationDecorator.swift | 302ea878df7a2e14e777fae35c3c1aadb65a9d61 | [
"MIT"
] | permissive | aproplan/SCTiledImage | 56226f0e7f7b04ac3283f2ed0cd4b5ffbf58537e | cf0e3de139e00ace65a30a78801e76862dd597dc | refs/heads/master | 2020-03-27T02:59:44.669209 | 2019-10-21T09:00:11 | 2019-10-21T09:00:11 | 145,832,080 | 0 | 0 | null | 2018-08-23T09:32:50 | 2018-08-23T09:32:49 | null | UTF-8 | Swift | false | false | 2,632 | swift | //
// TiledImageDataSourceRotationAdapter.swift
// SCTiledImage
//
// Created by Maxime POUWELS on 18/07/2017.
//
import UIKit
class TiledImageDataSourceRotationDecorator: SCTiledImageViewDataSource {
private let tiledImageDataSource: SCTiledImageViewDataSource
var rotation: SCTiledImageRotation
weak var delegate: SCTiledImageViewDataSourceDelegate? {
didSet {
tiledImageDataSource.delegate = self
}
}
var imageSize: CGSize {
return tiledImageDataSource.imageSize
}
var tileSize: CGSize {
return tiledImageDataSource.tileSize
}
var zoomLevels: Int {
return tiledImageDataSource.zoomLevels
}
init(tiledImageDataSource: SCTiledImageViewDataSource) {
self.tiledImageDataSource = tiledImageDataSource
self.rotation = tiledImageDataSource.rotation
}
func requestTiles(_ tiles: [SCTile]) {
tiledImageDataSource.requestTiles(tiles)
}
func requestBackgroundImage(completionHandler: @escaping (UIImage?) -> ()) {
tiledImageDataSource.requestBackgroundImage() { [weak self] image in
guard let`self` = self, let image = image else {
completionHandler(nil)
return
}
let rotatedImage: UIImage = {
if self.rotation == .none {
return image
}
let angle = self.rotation.angleInRadians
return image.rotated(angleInRadians: CGFloat(angle)) ?? image
}()
completionHandler(rotatedImage)
}
}
func getCachedImage(for tile: SCTile) -> UIImage? {
if rotation == .none {
return tiledImageDataSource.getCachedImage(for: tile)
}
let angle = CGFloat(rotation.angleInRadians)
return tiledImageDataSource.getCachedImage(for: tile)?.rotated(angleInRadians: angle)
}
}
extension TiledImageDataSourceRotationDecorator: SCTiledImageViewDataSourceDelegate {
func didRetrieve(tilesWithImage: [(SCTile, UIImage)]) {
if rotation == .none {
delegate?.didRetrieve(tilesWithImage: tilesWithImage)
} else {
let angle = CGFloat(rotation.angleInRadians)
let rotatedTilesWithImage: [(SCTile, UIImage)] = tilesWithImage.map { (tile, image) in
let rotatedImage = image.rotated(angleInRadians: angle) ?? image
return (tile, rotatedImage)
}
delegate?.didRetrieve(tilesWithImage: rotatedTilesWithImage)
}
}
}
| [
-1
] |
6133b36190ecdc0359950bb9d24b976f93ec444e | 4fc7810bb32b62bb0b629ac66a74ff7c30ca087d | /Square Frame/ViewController.swift | 226e941760b93da7491064e221e61c6563fccc17 | [] | no_license | Astha725/EditPhotoWithSquareFrame | ef92bc164bbcfdb603054f189fbcfa06fe11d9ef | 2aa8f35ef36fd90cf018a8895022cf520af5f9fc | refs/heads/main | 2023-04-28T15:18:11.954260 | 2021-05-25T19:15:02 | 2021-05-25T19:15:02 | 370,802,174 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 199 | swift |
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| [
262528,
275714,
398203,
436489,
317194,
384145,
409238,
308374,
316825,
370299,
155424,
187937,
345378,
167459,
391456,
356652,
384300,
273710,
370352,
381618,
383797,
167350,
319291,
294845,
266816,
359368,
421962,
437582,
265807,
199251,
257750,
359390,
165087,
425824,
399201,
437220,
155493,
155623,
318568,
350187,
339566,
56046,
381179,
349297,
361595
] |
af1d4956fdf8a92ef245aa08688e90f98471dbf8 | a90d2dc21c36a149fbc9e618160c7e04cd253664 | /HTTPTests/Internal/HTTPTaskTests.swift | 39c242adbda57b618f8d9463634818a902defb08 | [] | no_license | ttionn/HTTP | 72818c76a274292a7a6ccd8f813a019e51431c68 | 72f01664bfb491ca1a77ab8c4ee76de83c72829d | refs/heads/master | 2020-03-27T05:08:01.897441 | 2018-09-28T01:06:56 | 2018-09-28T01:06:56 | 145,996,150 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,737 | swift | //
// HTTPTaskTests.swift
// HTTPTests
//
// Created by TTSY on 2018/9/7.
// Copyright © 2018 TTSY. All rights reserved.
//
import XCTest
@testable import HTTP
class HTTPTaskTests: XCTestCase {
var sut: HTTPTask!
let request = URLRequest(url: URL(string: "www.fake.com")!)
let session = URLSession.shared
let fakeBase = "www.fake.com"
let fakePath = "/fake/path"
override func setUp() {
sut = HTTPDataTask(request: request, session: session, completion: { _ in })
}
func testDataTask() {
let dataTask = sut as! HTTPDataTask
XCTAssert(dataTask.sessionTask is URLSessionDataTask)
}
func testDataTaskForDownload() {
sut = HTTPDataTask(request: request, session: session, taskType: .download, completion: { _ in })
XCTAssert((sut as! HTTPDataTask).sessionTask is URLSessionDownloadTask)
}
func testDataTaskForUpload() {
let content = MultiPartContent(name: "", fileName: "", type: .png, data: Data())
sut = HTTPDataTask(request: request, session: session, taskType: .upload(content), completion: { _ in })
XCTAssert((sut as! HTTPDataTask).sessionTask is URLSessionDataTask)
}
func testFileTaskForDownload() {
let progress: ProgressClosure = { _, _, _ in }
let completed: CompletedClosure = { _, _ in }
sut = HTTPFileTask(request: request, session: session, taskType: .download, progress: progress, completed: completed)
XCTAssertEqual((sut as! HTTPFileTask).taskType, .download)
XCTAssertNotNil((sut as! HTTPFileTask).progress)
XCTAssertNotNil((sut as! HTTPFileTask).completed)
XCTAssert((sut as! HTTPFileTask).sessionTask is URLSessionDownloadTask)
}
func testFileTaskForUpload() {
let content = MultiPartContent(name: "", fileName: "", type: .png, data: Data())
let fileRequest = HTTPFileRequest(base: fakeBase, path: fakePath, method: .post, params: nil, headers: nil, sessionConfig: .standard, taskType: .upload(content), completed: nil)
let request = fileRequest.urlRequest!
let progress: ProgressClosure = { _, _, _ in }
let completed: CompletedClosure = { _, _ in }
sut = HTTPFileTask(request: request, session: session, taskType: .upload(content), progress: progress, completed: completed)
XCTAssertEqual((sut as! HTTPFileTask).taskType, .upload(content))
XCTAssertNotNil((sut as! HTTPFileTask).progress)
XCTAssertNotNil((sut as! HTTPFileTask).completed)
XCTAssert((sut as! HTTPFileTask).sessionTask is URLSessionUploadTask)
}
func testTaskType() {
let content = MultiPartContent(name: "file", fileName: "swift.jpg", type: .jpg, data: Data())
let data: TaskType = .data
let download: TaskType = .download
let upload: TaskType = .upload(content)
XCTAssertEqual(data, TaskType.data)
XCTAssertEqual(download, TaskType.download)
XCTAssertEqual(upload, TaskType.upload(content))
}
func testTaskState() {
let sessionTask = (sut as! HTTPDataTask).sessionTask
let taskState = TaskState(sessionTask)
XCTAssertEqual(taskState, .suspended)
let running = TaskState.running
XCTAssertEqual(running, TaskState.running)
let suspended = TaskState.suspended
XCTAssertEqual(suspended, TaskState.suspended)
let canceling = TaskState.canceling
XCTAssertEqual(canceling, TaskState.canceling)
let completed = TaskState.completed
XCTAssertEqual(completed, TaskState.completed)
}
}
| [
-1
] |
db8244a7e6abf4091f44a904a1297ca52c2bc9e2 | 6687de2d280edf8af6e6448894c48a6f324d07a4 | /ClassX/WebFlow/MyWebViewController.swift | 463e2a910e97c00cd2edb6e1d5ab2cbc44101ac3 | [] | no_license | pengxueting/ClassX | 2844dd32c9d2005d67d6540b8096b25bcb86022a | 3ab642cd7085e5c72b340d32932398116471ea0c | refs/heads/master | 2020-06-18T16:28:15.952770 | 2019-07-11T12:11:27 | 2019-07-11T12:11:27 | 196,364,272 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 690 | swift | //
// MyWebViewController.swift
// ClassX
//
// Created by stu-38 on 2019/7/11.
// Copyright © 2019 stu-38. All rights reserved.
//
import UIKit
class MyWebViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| [
374273,
240520,
330762,
328459,
162447,
317972,
358293,
340502,
361496,
318109,
342301,
324512,
349478,
215852,
337836,
318129,
185524,
185525,
190391,
219715,
323268,
313029,
320583,
322759,
315467,
337231,
312273,
146645,
196693,
172513,
333798,
347111,
327656,
317931,
324465,
321399,
56058,
340988,
313341
] |
709db81c355df8795a4326a912b9d27a7ee2ac36 | aaa5febef633b14ef730196b768eaab5cc2d05a7 | /LockItPasswordData/V2/V3/Controllers/LChangePhoneNumberController.swift | 0582c56b3a15bd93f4140af1f9b994ddfd97c755 | [] | no_license | JorgeZapata27/LockIt-iOS | 97b5b2cc1d416ceda8d2dbab916a1a4c567b7ce9 | 6b2633d6e8f67fccc4ceb253a7ca140b1cfc3195 | refs/heads/master | 2022-04-08T11:50:57.342089 | 2020-04-02T17:15:05 | 2020-04-02T17:15:05 | 232,160,668 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 5,060 | swift | //
// LChangePhoneNumberController.swift
// LockItPasswordData
//
// Created by JJ Zapata on 1/12/20.
// Copyright © 2020 JJ Zapata. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class LChangePhoneNumberController : UIViewController, UITextFieldDelegate {
let accountNameTF : UITextField = {
let tf = UITextField()
tf.placeholder = "Phone Number"
tf.textColor = .label
tf.backgroundColor = .systemBackground
tf.keyboardType = .decimalPad
tf.tintColor = .yellow
tf.clearButtonMode = UITextField.ViewMode.always
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let loginButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Change", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.addTarget(self, action: #selector(change), for: .touchUpInside)
button.tintColor = .systemYellow
button.setTitleColor(.systemYellow, for: .normal)
button.layer.cornerRadius = 5
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
accountNameTF.delegate = self
// Functions To Throw
confugreUI()
Firebase()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var fullString = textField.text ?? ""
fullString.append(string)
if range.length == 1 {
textField.text = format(phoneNumber: fullString, shouldRemoveLastDigit: true)
} else {
textField.text = format(phoneNumber: fullString)
}
return false
}
func format(phoneNumber: String, shouldRemoveLastDigit: Bool = false) -> String {
guard !phoneNumber.isEmpty else { return "" }
guard let regex = try? NSRegularExpression(pattern: "[\\s-\\(\\)]", options: .caseInsensitive) else { return "" }
let r = NSString(string: phoneNumber).range(of: phoneNumber)
var number = regex.stringByReplacingMatches(in: phoneNumber, options: .init(rawValue: 0), range: r, withTemplate: "")
if number.count > 10 {
let tenthDigitIndex = number.index(number.startIndex, offsetBy: 10)
number = String(number[number.startIndex..<tenthDigitIndex])
}
if shouldRemoveLastDigit {
let end = number.index(number.startIndex, offsetBy: number.count-1)
number = String(number[number.startIndex..<end])
}
if number.count < 7 {
let end = number.index(number.startIndex, offsetBy: number.count)
let range = number.startIndex..<end
number = number.replacingOccurrences(of: "(\\d{3})(\\d+)", with: "($1) $2", options: .regularExpression, range: range)
} else {
let end = number.index(number.startIndex, offsetBy: number.count)
let range = number.startIndex..<end
number = number.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1) $2-$3", options: .regularExpression, range: range)
}
return number
}
func confugreUI() {
view.backgroundColor = UIColor.systemBackground
view.addSubview(accountNameTF)
accountNameTF.topAnchor.constraint(equalTo: view.topAnchor, constant: 200).isActive = true
accountNameTF.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
accountNameTF.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 30).isActive = true
accountNameTF.heightAnchor.constraint(equalToConstant: 63).isActive = true
view.addSubview(loginButton)
loginButton.anchor(top: accountNameTF.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 10, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 120, height: 30)
}
// Hides keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
// Return key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return (true)
}
@objc func change() {
if accountNameTF.text != "" {
let uid = Auth.auth().currentUser!.uid
Database.database().reference().child("Users").child(uid).child("phoneNumber").setValue(accountNameTF.text!)
let alertController = UIAlertController(title: "Success", message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Okay", style: .cancel, handler: { (alert) in
self.navigationController?.popViewController(animated: true)
}))
self.present(alertController, animated: true, completion: nil)
}
}
func Firebase() {
let uid = Auth.auth().currentUser!.uid
print(uid)
Database.database().reference().child("Users").child(uid).child("phoneNumber").observe(.value, with: { (data) in
let name : String = (data.value as? String)!
self.accountNameTF.text = name
debugPrint(name)
})
}
}
| [
-1
] |
f87270626f133dbe4f90d387c1ca61c40f11e901 | cdaf6760d3aa3d2284c862cac5362ac520fe0141 | /firekit/firekit/classes/models/Resource.swift | fab08d6e32e6c0f67f4db349884e138188088a0a | [
"Apache-2.0"
] | permissive | ryanbaldwin/FireKit | d3a3ddc746538d6d4c9e8cf6159d5b8e10a7b316 | bcda24766a4ee9a59dbb84f3323e3032428d1f9c | refs/heads/master | 2022-12-10T04:43:42.706382 | 2020-09-10T17:44:23 | 2020-09-10T17:44:23 | 80,225,256 | 14 | 8 | null | 2017-11-09T23:47:40 | 2017-01-27T16:38:48 | Swift | UTF-8 | Swift | false | false | 3,172 | swift | //
// Resource.swift
// SwiftFHIR
//
// Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Resource) on 2017-11-13.
// 2017, SMART Health IT.
//
// Updated for Realm support by Ryan Baldwin on 2017-11-13
// Copyright @ 2017 Bunnyhug. All rights fall under Apache 2
import Foundation
import Realm
import RealmSwift
/**
* Base Resource.
*
* This is the base resource type for everything.
*/
open class Resource: FHIRAbstractResource {
override open class var resourceType: String {
get { return "Resource" }
}
@objc public dynamic var id: String?
@objc public dynamic var pk = UUID().uuidString
override open static func primaryKey() -> String? { return "pk" }
@objc public dynamic var implicitRules: String?
@objc public dynamic var language: String?
@objc public dynamic var meta: Meta?
public func upsert(meta: Meta?) {
upsert(prop: &self.meta, val: meta)
}
// MARK: Codable
private enum CodingKeys: String, CodingKey {
case id = "id"
case implicitRules = "implicitRules"
case language = "language"
case meta = "meta"
}
public required init() {
super.init()
}
public required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
public required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(String.self, forKey: .id)
self.implicitRules = try container.decodeIfPresent(String.self, forKey: .implicitRules)
self.language = try container.decodeIfPresent(String.self, forKey: .language)
self.meta = try container.decodeIfPresent(Meta.self, forKey: .meta)
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.id, forKey: .id)
try container.encodeIfPresent(self.implicitRules, forKey: .implicitRules)
try container.encodeIfPresent(self.language, forKey: .language)
try container.encodeIfPresent(self.meta, forKey: .meta)
}
public override func copy(with zone: NSZone? = nil) -> Any {
do {
let data = try JSONEncoder().encode(self)
let clone = try JSONDecoder().decode(Resource.self, from: data)
return clone
} catch let error {
print("Failed to copy Resource. Will return empty instance: \(error))")
}
return Resource.init()
}
public override func populate(from other: Any) {
guard let o = other as? Resource else {
print("Tried to populate \(Swift.type(of: self)) with values from \(Swift.type(of: other)). Skipping.")
return
}
super.populate(from: o)
id = o.id
implicitRules = o.implicitRules
language = o.language
FireKit.populate(&self.meta, from: o.meta)
}
}
| [
-1
] |
34d29bed8971521e5bb05b2300206fbc2bded272 | 91e27ee2a86032c61951f49678af9baaf04edc4b | /Sources/Soto/Services/GuardDuty/GuardDuty_api.swift | 0a708190eb3080267544108b4eb01d5e737b0c1e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ADGrant/aws-sdk-swift | 6cec9cffe8d1784abd873c8b4bd593e650ee3738 | 2a0f0d51cbb4a4ffd74dbf49c559e6263d43681c | refs/heads/master | 2023-01-24T03:38:55.258413 | 2023-01-04T17:04:03 | 2023-01-04T17:04:03 | 133,521,608 | 0 | 0 | null | 2018-05-15T13:38:09 | 2018-05-15T13:38:09 | null | UTF-8 | Swift | false | false | 71,641 | swift | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2022 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
@_exported import SotoCore
/// Service object for interacting with AWS GuardDuty service.
///
/// Amazon GuardDuty is a continuous security monitoring service that analyzes and processes the following data sources: VPC flow logs, Amazon Web Services CloudTrail management event logs, CloudTrail S3 data event logs, EKS audit logs, DNS logs, and Amazon EBS volume data. It uses threat intelligence feeds, such as lists of malicious IPs and domains, and machine learning to identify unexpected, potentially unauthorized, and malicious activity within your Amazon Web Services environment. This can include issues like escalations of privileges, uses of exposed credentials, or communication with malicious IPs, domains, or presence of malware on your Amazon EC2 instances and container workloads. For example, GuardDuty can detect compromised EC2 instances and container workloads serving malware, or mining bitcoin. GuardDuty also monitors Amazon Web Services account access behavior for signs of compromise, such as unauthorized infrastructure deployments like EC2 instances deployed in a Region that has never been used, or unusual API calls like a password policy change to reduce password strength. GuardDuty informs you about the status of your Amazon Web Services environment by producing security findings that you can view in the GuardDuty console or through Amazon EventBridge. For more information, see the Amazon GuardDuty User Guide .
public struct GuardDuty: AWSService {
// MARK: Member variables
/// Client used for communication with AWS
public let client: AWSClient
/// Service configuration
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the GuardDuty client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "guardduty",
serviceProtocol: .restjson,
apiVersion: "2017-11-28",
endpoint: endpoint,
variantEndpoints: [
[.fips]: .init(endpoints: [
"us-east-1": "guardduty-fips.us-east-1.amazonaws.com",
"us-east-2": "guardduty-fips.us-east-2.amazonaws.com",
"us-gov-east-1": "guardduty.us-gov-east-1.amazonaws.com",
"us-gov-west-1": "guardduty.us-gov-west-1.amazonaws.com",
"us-west-1": "guardduty-fips.us-west-1.amazonaws.com",
"us-west-2": "guardduty-fips.us-west-2.amazonaws.com"
])
],
errorType: GuardDutyErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Accepts the invitation to be a member account and get monitored by a GuardDuty administrator account that sent the invitation.
public func acceptAdministratorInvitation(_ input: AcceptAdministratorInvitationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AcceptAdministratorInvitationResponse> {
return self.client.execute(operation: "AcceptAdministratorInvitation", path: "/detector/{DetectorId}/administrator", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Accepts the invitation to be monitored by a GuardDuty administrator account.
@available(*, deprecated, message: "This operation is deprecated, use AcceptAdministratorInvitation instead")
public func acceptInvitation(_ input: AcceptInvitationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AcceptInvitationResponse> {
return self.client.execute(operation: "AcceptInvitation", path: "/detector/{DetectorId}/master", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Archives GuardDuty findings that are specified by the list of finding IDs. Only the administrator account can archive findings. Member accounts don't have permission to archive findings from their accounts.
public func archiveFindings(_ input: ArchiveFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ArchiveFindingsResponse> {
return self.client.execute(operation: "ArchiveFindings", path: "/detector/{DetectorId}/findings/archive", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a single Amazon GuardDuty detector. A detector is a resource that represents the GuardDuty service. To start using GuardDuty, you must create a detector in each Region where you enable the service. You can have only one detector per account per Region. All data sources are enabled in a new detector by default.
public func createDetector(_ input: CreateDetectorRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDetectorResponse> {
return self.client.execute(operation: "CreateDetector", path: "/detector", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a filter using the specified finding criteria.
public func createFilter(_ input: CreateFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateFilterResponse> {
return self.client.execute(operation: "CreateFilter", path: "/detector/{DetectorId}/filter", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new IPSet, which is called a trusted IP list in the console user interface. An IPSet is a list of IP addresses that are trusted for secure communication with Amazon Web Services infrastructure and applications. GuardDuty doesn't generate findings for IP addresses that are included in IPSets. Only users from the administrator account can use this operation.
public func createIPSet(_ input: CreateIPSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateIPSetResponse> {
return self.client.execute(operation: "CreateIPSet", path: "/detector/{DetectorId}/ipset", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates member accounts of the current Amazon Web Services account by specifying a list of Amazon Web Services account IDs. This step is a prerequisite for managing the associated member accounts either by invitation or through an organization. When using Create Members as an organizations delegated administrator this action will enable GuardDuty in the added member accounts, with the exception of the organization delegated administrator account, which must enable GuardDuty prior to being added as a member. If you are adding accounts by invitation use this action after GuardDuty has been enabled in potential member accounts and before using Invite Members .
public func createMembers(_ input: CreateMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateMembersResponse> {
return self.client.execute(operation: "CreateMembers", path: "/detector/{DetectorId}/member", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a publishing destination to export findings to. The resource to export findings to must exist before you use this operation.
public func createPublishingDestination(_ input: CreatePublishingDestinationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePublishingDestinationResponse> {
return self.client.execute(operation: "CreatePublishingDestination", path: "/detector/{DetectorId}/publishingDestination", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Generates example findings of types specified by the list of finding types. If 'NULL' is specified for findingTypes, the API generates example findings of all supported finding types.
public func createSampleFindings(_ input: CreateSampleFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateSampleFindingsResponse> {
return self.client.execute(operation: "CreateSampleFindings", path: "/detector/{DetectorId}/findings/create", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new ThreatIntelSet. ThreatIntelSets consist of known malicious IP addresses. GuardDuty generates findings based on ThreatIntelSets. Only users of the administrator account can use this operation.
public func createThreatIntelSet(_ input: CreateThreatIntelSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateThreatIntelSetResponse> {
return self.client.execute(operation: "CreateThreatIntelSet", path: "/detector/{DetectorId}/threatintelset", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Declines invitations sent to the current member account by Amazon Web Services accounts specified by their account IDs.
public func declineInvitations(_ input: DeclineInvitationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeclineInvitationsResponse> {
return self.client.execute(operation: "DeclineInvitations", path: "/invitation/decline", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes an Amazon GuardDuty detector that is specified by the detector ID.
public func deleteDetector(_ input: DeleteDetectorRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteDetectorResponse> {
return self.client.execute(operation: "DeleteDetector", path: "/detector/{DetectorId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the filter specified by the filter name.
public func deleteFilter(_ input: DeleteFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteFilterResponse> {
return self.client.execute(operation: "DeleteFilter", path: "/detector/{DetectorId}/filter/{FilterName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the IPSet specified by the ipSetId. IPSets are called trusted IP lists in the console user interface.
public func deleteIPSet(_ input: DeleteIPSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteIPSetResponse> {
return self.client.execute(operation: "DeleteIPSet", path: "/detector/{DetectorId}/ipset/{IpSetId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes invitations sent to the current member account by Amazon Web Services accounts specified by their account IDs.
public func deleteInvitations(_ input: DeleteInvitationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteInvitationsResponse> {
return self.client.execute(operation: "DeleteInvitations", path: "/invitation/delete", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes GuardDuty member accounts (to the current GuardDuty administrator account) specified by the account IDs.
public func deleteMembers(_ input: DeleteMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteMembersResponse> {
return self.client.execute(operation: "DeleteMembers", path: "/detector/{DetectorId}/member/delete", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the publishing definition with the specified destinationId.
public func deletePublishingDestination(_ input: DeletePublishingDestinationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePublishingDestinationResponse> {
return self.client.execute(operation: "DeletePublishingDestination", path: "/detector/{DetectorId}/publishingDestination/{DestinationId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the ThreatIntelSet specified by the ThreatIntelSet ID.
public func deleteThreatIntelSet(_ input: DeleteThreatIntelSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteThreatIntelSetResponse> {
return self.client.execute(operation: "DeleteThreatIntelSet", path: "/detector/{DetectorId}/threatintelset/{ThreatIntelSetId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of malware scans. Each member account can view the malware scans for their own accounts. An administrator can view the malware scans for all the member accounts.
public func describeMalwareScans(_ input: DescribeMalwareScansRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeMalwareScansResponse> {
return self.client.execute(operation: "DescribeMalwareScans", path: "/detector/{DetectorId}/malware-scans", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about the account selected as the delegated administrator for GuardDuty.
public func describeOrganizationConfiguration(_ input: DescribeOrganizationConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeOrganizationConfigurationResponse> {
return self.client.execute(operation: "DescribeOrganizationConfiguration", path: "/detector/{DetectorId}/admin", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about the publishing destination specified by the provided destinationId.
public func describePublishingDestination(_ input: DescribePublishingDestinationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePublishingDestinationResponse> {
return self.client.execute(operation: "DescribePublishingDestination", path: "/detector/{DetectorId}/publishingDestination/{DestinationId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disables an Amazon Web Services account within the Organization as the GuardDuty delegated administrator.
public func disableOrganizationAdminAccount(_ input: DisableOrganizationAdminAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisableOrganizationAdminAccountResponse> {
return self.client.execute(operation: "DisableOrganizationAdminAccount", path: "/admin/disable", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disassociates the current GuardDuty member account from its administrator account.
public func disassociateFromAdministratorAccount(_ input: DisassociateFromAdministratorAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociateFromAdministratorAccountResponse> {
return self.client.execute(operation: "DisassociateFromAdministratorAccount", path: "/detector/{DetectorId}/administrator/disassociate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disassociates the current GuardDuty member account from its administrator account.
@available(*, deprecated, message: "This operation is deprecated, use DisassociateFromAdministratorAccount instead")
public func disassociateFromMasterAccount(_ input: DisassociateFromMasterAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociateFromMasterAccountResponse> {
return self.client.execute(operation: "DisassociateFromMasterAccount", path: "/detector/{DetectorId}/master/disassociate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disassociates GuardDuty member accounts (to the current administrator account) specified by the account IDs.
public func disassociateMembers(_ input: DisassociateMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociateMembersResponse> {
return self.client.execute(operation: "DisassociateMembers", path: "/detector/{DetectorId}/member/disassociate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Enables an Amazon Web Services account within the organization as the GuardDuty delegated administrator.
public func enableOrganizationAdminAccount(_ input: EnableOrganizationAdminAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<EnableOrganizationAdminAccountResponse> {
return self.client.execute(operation: "EnableOrganizationAdminAccount", path: "/admin/enable", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Provides the details for the GuardDuty administrator account associated with the current GuardDuty member account.
public func getAdministratorAccount(_ input: GetAdministratorAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetAdministratorAccountResponse> {
return self.client.execute(operation: "GetAdministratorAccount", path: "/detector/{DetectorId}/administrator", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves an Amazon GuardDuty detector specified by the detectorId.
public func getDetector(_ input: GetDetectorRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetDetectorResponse> {
return self.client.execute(operation: "GetDetector", path: "/detector/{DetectorId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the details of the filter specified by the filter name.
public func getFilter(_ input: GetFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetFilterResponse> {
return self.client.execute(operation: "GetFilter", path: "/detector/{DetectorId}/filter/{FilterName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes Amazon GuardDuty findings specified by finding IDs.
public func getFindings(_ input: GetFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetFindingsResponse> {
return self.client.execute(operation: "GetFindings", path: "/detector/{DetectorId}/findings/get", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists Amazon GuardDuty findings statistics for the specified detector ID.
public func getFindingsStatistics(_ input: GetFindingsStatisticsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetFindingsStatisticsResponse> {
return self.client.execute(operation: "GetFindingsStatistics", path: "/detector/{DetectorId}/findings/statistics", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves the IPSet specified by the ipSetId.
public func getIPSet(_ input: GetIPSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetIPSetResponse> {
return self.client.execute(operation: "GetIPSet", path: "/detector/{DetectorId}/ipset/{IpSetId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the count of all GuardDuty membership invitations that were sent to the current member account except the currently accepted invitation.
public func getInvitationsCount(_ input: GetInvitationsCountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetInvitationsCountResponse> {
return self.client.execute(operation: "GetInvitationsCount", path: "/invitation/count", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the details of the malware scan settings.
public func getMalwareScanSettings(_ input: GetMalwareScanSettingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMalwareScanSettingsResponse> {
return self.client.execute(operation: "GetMalwareScanSettings", path: "/detector/{DetectorId}/malware-scan-settings", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Provides the details for the GuardDuty administrator account associated with the current GuardDuty member account.
@available(*, deprecated, message: "This operation is deprecated, use GetAdministratorAccount instead")
public func getMasterAccount(_ input: GetMasterAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMasterAccountResponse> {
return self.client.execute(operation: "GetMasterAccount", path: "/detector/{DetectorId}/master", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes which data sources are enabled for the member account's detector.
public func getMemberDetectors(_ input: GetMemberDetectorsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMemberDetectorsResponse> {
return self.client.execute(operation: "GetMemberDetectors", path: "/detector/{DetectorId}/member/detector/get", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves GuardDuty member accounts (of the current GuardDuty administrator account) specified by the account IDs.
public func getMembers(_ input: GetMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetMembersResponse> {
return self.client.execute(operation: "GetMembers", path: "/detector/{DetectorId}/member/get", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Provides the number of days left for each data source used in the free trial period.
public func getRemainingFreeTrialDays(_ input: GetRemainingFreeTrialDaysRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetRemainingFreeTrialDaysResponse> {
return self.client.execute(operation: "GetRemainingFreeTrialDays", path: "/detector/{DetectorId}/freeTrial/daysRemaining", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves the ThreatIntelSet that is specified by the ThreatIntelSet ID.
public func getThreatIntelSet(_ input: GetThreatIntelSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetThreatIntelSetResponse> {
return self.client.execute(operation: "GetThreatIntelSet", path: "/detector/{DetectorId}/threatintelset/{ThreatIntelSetId}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists Amazon GuardDuty usage statistics over the last 30 days for the specified detector ID. For newly enabled detectors or data sources, the cost returned will include only the usage so far under 30 days. This may differ from the cost metrics in the console, which project usage over 30 days to provide a monthly cost estimate. For more information, see Understanding How Usage Costs are Calculated.
public func getUsageStatistics(_ input: GetUsageStatisticsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetUsageStatisticsResponse> {
return self.client.execute(operation: "GetUsageStatistics", path: "/detector/{DetectorId}/usage/statistics", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Invites other Amazon Web Services accounts (created as members of the current Amazon Web Services account by CreateMembers) to enable GuardDuty, and allow the current Amazon Web Services account to view and manage these accounts' findings on their behalf as the GuardDuty administrator account.
public func inviteMembers(_ input: InviteMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<InviteMembersResponse> {
return self.client.execute(operation: "InviteMembers", path: "/detector/{DetectorId}/member/invite", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists detectorIds of all the existing Amazon GuardDuty detector resources.
public func listDetectors(_ input: ListDetectorsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDetectorsResponse> {
return self.client.execute(operation: "ListDetectors", path: "/detector", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a paginated list of the current filters.
public func listFilters(_ input: ListFiltersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListFiltersResponse> {
return self.client.execute(operation: "ListFilters", path: "/detector/{DetectorId}/filter", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists Amazon GuardDuty findings for the specified detector ID.
public func listFindings(_ input: ListFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListFindingsResponse> {
return self.client.execute(operation: "ListFindings", path: "/detector/{DetectorId}/findings", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the IPSets of the GuardDuty service specified by the detector ID. If you use this operation from a member account, the IPSets returned are the IPSets from the associated administrator account.
public func listIPSets(_ input: ListIPSetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListIPSetsResponse> {
return self.client.execute(operation: "ListIPSets", path: "/detector/{DetectorId}/ipset", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all GuardDuty membership invitations that were sent to the current Amazon Web Services account.
public func listInvitations(_ input: ListInvitationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListInvitationsResponse> {
return self.client.execute(operation: "ListInvitations", path: "/invitation", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists details about all member accounts for the current GuardDuty administrator account.
public func listMembers(_ input: ListMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListMembersResponse> {
return self.client.execute(operation: "ListMembers", path: "/detector/{DetectorId}/member", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the accounts configured as GuardDuty delegated administrators.
public func listOrganizationAdminAccounts(_ input: ListOrganizationAdminAccountsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListOrganizationAdminAccountsResponse> {
return self.client.execute(operation: "ListOrganizationAdminAccounts", path: "/admin", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of publishing destinations associated with the specified detectorId.
public func listPublishingDestinations(_ input: ListPublishingDestinationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPublishingDestinationsResponse> {
return self.client.execute(operation: "ListPublishingDestinations", path: "/detector/{DetectorId}/publishingDestination", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists tags for a resource. Tagging is currently supported for detectors, finding filters, IP sets, and threat intel sets, with a limit of 50 tags per resource. When invoked, this operation returns all assigned tags for a given resource.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> {
return self.client.execute(operation: "ListTagsForResource", path: "/tags/{ResourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the ThreatIntelSets of the GuardDuty service specified by the detector ID. If you use this operation from a member account, the ThreatIntelSets associated with the administrator account are returned.
public func listThreatIntelSets(_ input: ListThreatIntelSetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListThreatIntelSetsResponse> {
return self.client.execute(operation: "ListThreatIntelSets", path: "/detector/{DetectorId}/threatintelset", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Turns on GuardDuty monitoring of the specified member accounts. Use this operation to restart monitoring of accounts that you stopped monitoring with the StopMonitoringMembers operation.
public func startMonitoringMembers(_ input: StartMonitoringMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartMonitoringMembersResponse> {
return self.client.execute(operation: "StartMonitoringMembers", path: "/detector/{DetectorId}/member/start", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Stops GuardDuty monitoring for the specified member accounts. Use the StartMonitoringMembers operation to restart monitoring for those accounts.
public func stopMonitoringMembers(_ input: StopMonitoringMembersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StopMonitoringMembersResponse> {
return self.client.execute(operation: "StopMonitoringMembers", path: "/detector/{DetectorId}/member/stop", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds tags to a resource.
public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> {
return self.client.execute(operation: "TagResource", path: "/tags/{ResourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Unarchives GuardDuty findings specified by the findingIds.
public func unarchiveFindings(_ input: UnarchiveFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UnarchiveFindingsResponse> {
return self.client.execute(operation: "UnarchiveFindings", path: "/detector/{DetectorId}/findings/unarchive", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes tags from a resource.
public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> {
return self.client.execute(operation: "UntagResource", path: "/tags/{ResourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the Amazon GuardDuty detector specified by the detectorId.
public func updateDetector(_ input: UpdateDetectorRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateDetectorResponse> {
return self.client.execute(operation: "UpdateDetector", path: "/detector/{DetectorId}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the filter specified by the filter name.
public func updateFilter(_ input: UpdateFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateFilterResponse> {
return self.client.execute(operation: "UpdateFilter", path: "/detector/{DetectorId}/filter/{FilterName}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Marks the specified GuardDuty findings as useful or not useful.
public func updateFindingsFeedback(_ input: UpdateFindingsFeedbackRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateFindingsFeedbackResponse> {
return self.client.execute(operation: "UpdateFindingsFeedback", path: "/detector/{DetectorId}/findings/feedback", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the IPSet specified by the IPSet ID.
public func updateIPSet(_ input: UpdateIPSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateIPSetResponse> {
return self.client.execute(operation: "UpdateIPSet", path: "/detector/{DetectorId}/ipset/{IpSetId}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the malware scan settings.
public func updateMalwareScanSettings(_ input: UpdateMalwareScanSettingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateMalwareScanSettingsResponse> {
return self.client.execute(operation: "UpdateMalwareScanSettings", path: "/detector/{DetectorId}/malware-scan-settings", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Contains information on member accounts to be updated.
public func updateMemberDetectors(_ input: UpdateMemberDetectorsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateMemberDetectorsResponse> {
return self.client.execute(operation: "UpdateMemberDetectors", path: "/detector/{DetectorId}/member/detector/update", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the delegated administrator account with the values provided.
public func updateOrganizationConfiguration(_ input: UpdateOrganizationConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateOrganizationConfigurationResponse> {
return self.client.execute(operation: "UpdateOrganizationConfiguration", path: "/detector/{DetectorId}/admin", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates information about the publishing destination specified by the destinationId.
public func updatePublishingDestination(_ input: UpdatePublishingDestinationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdatePublishingDestinationResponse> {
return self.client.execute(operation: "UpdatePublishingDestination", path: "/detector/{DetectorId}/publishingDestination/{DestinationId}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the ThreatIntelSet specified by the ThreatIntelSet ID.
public func updateThreatIntelSet(_ input: UpdateThreatIntelSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateThreatIntelSetResponse> {
return self.client.execute(operation: "UpdateThreatIntelSet", path: "/detector/{DetectorId}/threatintelset/{ThreatIntelSetId}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension GuardDuty {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: GuardDuty, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
// MARK: Paginators
extension GuardDuty {
/// Returns a list of malware scans. Each member account can view the malware scans for their own accounts. An administrator can view the malware scans for all the member accounts.
///
/// 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 describeMalwareScansPaginator<Result>(
_ input: DescribeMalwareScansRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeMalwareScansResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.describeMalwareScans,
inputKey: \DescribeMalwareScansRequest.nextToken,
outputKey: \DescribeMalwareScansResponse.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 describeMalwareScansPaginator(
_ input: DescribeMalwareScansRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeMalwareScansResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.describeMalwareScans,
inputKey: \DescribeMalwareScansRequest.nextToken,
outputKey: \DescribeMalwareScansResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists Amazon GuardDuty usage statistics over the last 30 days for the specified detector ID. For newly enabled detectors or data sources, the cost returned will include only the usage so far under 30 days. This may differ from the cost metrics in the console, which project usage over 30 days to provide a monthly cost estimate. For more information, see Understanding How Usage Costs are Calculated.
///
/// 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 getUsageStatisticsPaginator<Result>(
_ input: GetUsageStatisticsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetUsageStatisticsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.getUsageStatistics,
inputKey: \GetUsageStatisticsRequest.nextToken,
outputKey: \GetUsageStatisticsResponse.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 getUsageStatisticsPaginator(
_ input: GetUsageStatisticsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetUsageStatisticsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.getUsageStatistics,
inputKey: \GetUsageStatisticsRequest.nextToken,
outputKey: \GetUsageStatisticsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists detectorIds of all the existing Amazon GuardDuty detector resources.
///
/// 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 listDetectorsPaginator<Result>(
_ input: ListDetectorsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDetectorsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listDetectors,
inputKey: \ListDetectorsRequest.nextToken,
outputKey: \ListDetectorsResponse.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 listDetectorsPaginator(
_ input: ListDetectorsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDetectorsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listDetectors,
inputKey: \ListDetectorsRequest.nextToken,
outputKey: \ListDetectorsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a paginated list of the current filters.
///
/// 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 listFiltersPaginator<Result>(
_ input: ListFiltersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListFiltersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listFilters,
inputKey: \ListFiltersRequest.nextToken,
outputKey: \ListFiltersResponse.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 listFiltersPaginator(
_ input: ListFiltersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListFiltersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listFilters,
inputKey: \ListFiltersRequest.nextToken,
outputKey: \ListFiltersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists Amazon GuardDuty findings for the specified detector ID.
///
/// 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 listFindingsPaginator<Result>(
_ input: ListFindingsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListFindingsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listFindings,
inputKey: \ListFindingsRequest.nextToken,
outputKey: \ListFindingsResponse.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 listFindingsPaginator(
_ input: ListFindingsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListFindingsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listFindings,
inputKey: \ListFindingsRequest.nextToken,
outputKey: \ListFindingsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the IPSets of the GuardDuty service specified by the detector ID. If you use this operation from a member account, the IPSets returned are the IPSets from the associated administrator account.
///
/// 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 listIPSetsPaginator<Result>(
_ input: ListIPSetsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListIPSetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listIPSets,
inputKey: \ListIPSetsRequest.nextToken,
outputKey: \ListIPSetsResponse.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 listIPSetsPaginator(
_ input: ListIPSetsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListIPSetsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listIPSets,
inputKey: \ListIPSetsRequest.nextToken,
outputKey: \ListIPSetsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists all GuardDuty membership invitations that were sent to the current Amazon Web Services account.
///
/// 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 listInvitationsPaginator<Result>(
_ input: ListInvitationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListInvitationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listInvitations,
inputKey: \ListInvitationsRequest.nextToken,
outputKey: \ListInvitationsResponse.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 listInvitationsPaginator(
_ input: ListInvitationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListInvitationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listInvitations,
inputKey: \ListInvitationsRequest.nextToken,
outputKey: \ListInvitationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists details about all member accounts for the current GuardDuty administrator account.
///
/// 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 listMembersPaginator<Result>(
_ input: ListMembersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMembersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listMembers,
inputKey: \ListMembersRequest.nextToken,
outputKey: \ListMembersResponse.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 listMembersPaginator(
_ input: ListMembersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMembersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listMembers,
inputKey: \ListMembersRequest.nextToken,
outputKey: \ListMembersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the accounts configured as GuardDuty delegated administrators.
///
/// 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 listOrganizationAdminAccountsPaginator<Result>(
_ input: ListOrganizationAdminAccountsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListOrganizationAdminAccountsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listOrganizationAdminAccounts,
inputKey: \ListOrganizationAdminAccountsRequest.nextToken,
outputKey: \ListOrganizationAdminAccountsResponse.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 listOrganizationAdminAccountsPaginator(
_ input: ListOrganizationAdminAccountsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListOrganizationAdminAccountsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listOrganizationAdminAccounts,
inputKey: \ListOrganizationAdminAccountsRequest.nextToken,
outputKey: \ListOrganizationAdminAccountsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of publishing destinations associated with the specified detectorId.
///
/// 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 listPublishingDestinationsPaginator<Result>(
_ input: ListPublishingDestinationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListPublishingDestinationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listPublishingDestinations,
inputKey: \ListPublishingDestinationsRequest.nextToken,
outputKey: \ListPublishingDestinationsResponse.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 listPublishingDestinationsPaginator(
_ input: ListPublishingDestinationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListPublishingDestinationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listPublishingDestinations,
inputKey: \ListPublishingDestinationsRequest.nextToken,
outputKey: \ListPublishingDestinationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the ThreatIntelSets of the GuardDuty service specified by the detector ID. If you use this operation from a member account, the ThreatIntelSets associated with the administrator account are returned.
///
/// 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 listThreatIntelSetsPaginator<Result>(
_ input: ListThreatIntelSetsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListThreatIntelSetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return self.client.paginate(
input: input,
initialValue: initialValue,
command: self.listThreatIntelSets,
inputKey: \ListThreatIntelSetsRequest.nextToken,
outputKey: \ListThreatIntelSetsResponse.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 listThreatIntelSetsPaginator(
_ input: ListThreatIntelSetsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListThreatIntelSetsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return self.client.paginate(
input: input,
command: self.listThreatIntelSets,
inputKey: \ListThreatIntelSetsRequest.nextToken,
outputKey: \ListThreatIntelSetsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension GuardDuty.DescribeMalwareScansRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.DescribeMalwareScansRequest {
return .init(
detectorId: self.detectorId,
filterCriteria: self.filterCriteria,
maxResults: self.maxResults,
nextToken: token,
sortCriteria: self.sortCriteria
)
}
}
extension GuardDuty.GetUsageStatisticsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.GetUsageStatisticsRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token,
unit: self.unit,
usageCriteria: self.usageCriteria,
usageStatisticType: self.usageStatisticType
)
}
}
extension GuardDuty.ListDetectorsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListDetectorsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListFiltersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListFiltersRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListFindingsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListFindingsRequest {
return .init(
detectorId: self.detectorId,
findingCriteria: self.findingCriteria,
maxResults: self.maxResults,
nextToken: token,
sortCriteria: self.sortCriteria
)
}
}
extension GuardDuty.ListIPSetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListIPSetsRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListInvitationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListInvitationsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListMembersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListMembersRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token,
onlyAssociated: self.onlyAssociated
)
}
}
extension GuardDuty.ListOrganizationAdminAccountsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListOrganizationAdminAccountsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListPublishingDestinationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListPublishingDestinationsRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GuardDuty.ListThreatIntelSetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GuardDuty.ListThreatIntelSetsRequest {
return .init(
detectorId: self.detectorId,
maxResults: self.maxResults,
nextToken: token
)
}
}
| [
-1
] |
2e9a267a6bd9c891f22de430ce6e6c240d9f4b60 | 81aecd9fa7a198359586d0f0757dcd0d518654be | /Sources/LLVM/Instruction.swift | a4e1666e06e98d0c0651efbcef7c2315ba962f3f | [
"MIT"
] | permissive | Maskmale/LLVMSwift | 4679385fc4b9090d0011f81803b828d314439dd7 | 78d734e576770e573441de6219550263fc4f703b | refs/heads/master | 2020-05-02T12:38:03.214686 | 2019-03-22T16:15:47 | 2019-03-22T16:15:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,218 | swift | #if SWIFT_PACKAGE
import cllvm
#endif
/// An `Instruction` represents an instruction residing in a basic block.
public struct Instruction: IRValue {
internal let llvm: LLVMValueRef
/// Creates an `Intruction` from an `LLVMValueRef` object.
public init(llvm: LLVMValueRef) {
self.llvm = llvm
}
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return llvm
}
/// Retrieves the opcode associated with this `Instruction`.
public var opCode: OpCode {
return OpCode(rawValue: LLVMGetInstructionOpcode(llvm))
}
/// Obtain the instruction that occurs before this one, if it exists.
public func previous() -> Instruction? {
guard let val = LLVMGetPreviousInstruction(llvm) else { return nil }
return Instruction(llvm: val)
}
/// Obtain the instruction that occurs after this one, if it exists.
public func next() -> Instruction? {
guard let val = LLVMGetNextInstruction(llvm) else { return nil }
return Instruction(llvm: val)
}
/// Retrieves the parent basic block that contains this instruction, if it
/// exists.
public var parentBlock: BasicBlock? {
guard let parent = LLVMGetInstructionParent(self.llvm) else { return nil }
return BasicBlock(llvm: parent)
}
/// Retrieves the first use of this instruction.
public var firstUse: Use? {
guard let use = LLVMGetFirstUse(llvm) else { return nil }
return Use(llvm: use)
}
/// Retrieves the sequence of instructions that use the value from this
/// instruction.
public var uses: AnySequence<Use> {
var current = firstUse
return AnySequence<Use> {
return AnyIterator<Use> {
defer { current = current?.next() }
return current
}
}
}
/// Removes this instruction from a basic block but keeps it alive.
///
/// - note: To ensure correct removal of the instruction, you must invalidate
/// any references to its result values, if any.
public func removeFromParent() {
LLVMInstructionRemoveFromParent(llvm)
}
/// Create a copy of 'this' instruction that is identical in all ways except
/// the following:
///
/// - The instruction has no parent
/// - The instruction has no name
public func clone() -> Instruction {
return Instruction(llvm: LLVMInstructionClone(self.llvm))
}
}
/// A `TerminatorInstruction` represents an instruction that terminates a
/// basic block.
public struct TerminatorInstruction {
internal let llvm: LLVMValueRef
/// Creates a `TerminatorInstruction` from an `LLVMValueRef` object.
public init(llvm: LLVMValueRef) {
self.llvm = llvm
}
/// Retrieves the number of successors of this terminator instruction.
public var successorCount: Int {
return Int(LLVMGetNumSuccessors(llvm))
}
/// Returns the successor block at the specified index, if it exists.
public func getSuccessor(at idx: Int) -> BasicBlock? {
guard let succ = LLVMGetSuccessor(llvm, UInt32(idx)) else { return nil }
return BasicBlock(llvm: succ)
}
/// Updates the successor block at the specified index.
public func setSuccessor(at idx: Int, to bb: BasicBlock) {
LLVMSetSuccessor(llvm, UInt32(idx), bb.asLLVM())
}
}
| [
-1
] |
c2551809c7c6e35a333472b370f439b24a3eb690 | 73f60ad52d413d0c3edde3747a91c33cff5d8919 | /quizzie/Extensions/Array.swift | 25495664abe1fcdf03b20fb418fa7b0d9c11991b | [] | no_license | ensarbaba/Quizzie | 393fbdabb5003adb42f55b406b84944addf3c4b8 | a95337b60c2b4352a870305a8f673811f6719ad2 | refs/heads/master | 2022-10-21T20:16:10.566286 | 2020-06-10T11:24:29 | 2020-06-10T11:24:29 | 260,304,073 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 385 | swift | //
// Array.swift
// quizzie
//
// Created by Ensar Baba on 1.05.2020.
// Copyright © 2020 Ensar Baba. All rights reserved.
//
import Foundation
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
| [
421070,
265616,
100370,
266483,
173141,
68826
] |
c8f0493481c2ed032798ae3ac52ef0e44c6db80a | 358eb615ecb691c087577e7d55c000dbb8e588c9 | /Viper/Modules/Details/View/DetailsViewController.swift | e41e1ee9089902478becaed53e94e8bdcc27b4fd | [] | no_license | vuonghominh/ios-viper | ffb42a8fc89e00d046b65cbd020a45e8cc4b2dfe | 80bb9cc677279ed918251b55733617922cab7493 | refs/heads/master | 2020-03-24T03:28:49.447046 | 2018-07-26T09:35:31 | 2018-07-26T09:35:31 | 142,420,823 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,087 | swift | //
// DetailsViewController.swift
// Viper
//
// Created by Leon Ho on 7/26/18.
// Copyright © 2018 Leo. All rights reserved.
//
import UIKit
import Kingfisher
class DetailsViewController : UIViewController {
var presenter: DetailsPresentation!
@IBOutlet weak var articleImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
}
fileprivate func setupView() {
navigationController!.title = Localization.Details.navigationBarTitle
}
}
extension DetailsViewController: DetailsView {
func showDetails(forArticle article: Article) {
authorsLabel.text = article.authors
titleLabel.text = article.title
articleImageView.kf.setImage(
with: URL(string: article.imageUrl),
placeholder: UIImage(named: Constants.imagePlaceholder),
options: nil,
progressBlock: nil,
completionHandler: nil
)
}
}
| [
-1
] |
e321f6f65a33b9dc81cd567f5ba526eb0531276b | 79f04435bc9d5067aba926295abb959279cf4b89 | /Example/iOS Example/iOS Example/Layouts/CommonFlowLayout.swift | 652191ed4f64f1ebc361759d9e4e9fcdcfcc6535 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | carabina/ItemsDataSource | b990aa41de46ecac52376cb938190b4ed986dbc9 | 67dc811a029a8c553664f665115e8f4a087c1796 | refs/heads/master | 2020-03-10T09:41:14.359235 | 2018-04-12T08:19:39 | 2018-04-12T08:19:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,666 | swift | //
// CommonFlowLayout.swift
// iOS Example
//
// Created by Sasha Prokhorenko on 19.12.17.
// Copyright © 2017 Sasha Prokhorenko. All rights reserved.
//
import UIKit
final class CommonFlowLayout: UICollectionViewFlowLayout {
// MRK: - Properties
let columns: CGFloat
let itemHeight: CGFloat
let inset: CGFloat
let spacing: CGFloat
let lineSpacing: CGFloat
let withHeader: Bool
// MARK: - Init
init(columns: CGFloat, itemHeight: CGFloat, inset: CGFloat, spacing: CGFloat, lineSpacing: CGFloat, withHeader: Bool = false) {
self.columns = columns
self.itemHeight = itemHeight
self.inset = inset
self.spacing = spacing
self.lineSpacing = lineSpacing
self.withHeader = withHeader
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout Lifecycle
override func prepare() {
super.prepare()
setupLayout()
}
func itemWidth() -> CGFloat {
return ((collectionView!.frame.width / columns) - (inset + spacing))
}
override var itemSize: CGSize {
set {
self.itemSize = CGSize(width: itemWidth(), height: itemHeight)
}
get {
return CGSize(width: itemWidth(), height: itemHeight)
}
}
func setupLayout() {
minimumInteritemSpacing = spacing
minimumLineSpacing = lineSpacing
if withHeader == true {
headerReferenceSize = CGSize(width: itemWidth(), height: 80)
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return collectionView!.contentOffset
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| [
-1
] |
e81d7aa9a17076478f14ccbd3a7eaed814d8f1bc | 70fdca6bf55c45bb2df7ccdd55c435aaffc041b5 | /Matrix Calculator (XR and XS Version)/Matrix Calculator/CalculationResults.swift | aae8667bbb7408033a9266bb0deb6210e22c60eb | [] | no_license | shuheng-cao/MatrixCalculator | 2ccc143595a89fd9d1f136bbe15f22fd103133c0 | 440fa743ec7ff6dbca4fb27947210dd8fc812dc2 | refs/heads/master | 2020-03-23T07:36:41.185665 | 2018-09-27T22:00:15 | 2018-09-27T22:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 18,056 | swift | //
// CalculationResults.swift
// Matrix!
//
// Created by shuster on 2018/8/10.
// Copyright © 2018 曹书恒. All rights reserved.
//
import Foundation
import UIKit
import Accelerate
enum myOperations {
case inverse
case power
case determinate
case diagonal
case RREF
case eigenvalue
case transpose
case addition
case substraction
case multiplication
}
class myCalculationResult {
// For inverse operation only
var invertible = false
// For power operation only
var degreeOfPower = 0
// For eigenvalues only
var eigenvectors: [[Double]] = []
// For diagonalizable only
var diagonalizable: Bool = false
// For landscape mode only
var secondMatrix: [[Double]] = []
// General Case:
var operationType: myOperations
var inputMatrix: [[Double]]
var outputMatrix: [[Double]]
init(_ input: [[Double]],_ operation: myOperations,_ power: Int = 0,_ secondInput: [[Double]] = []) {
operationType = operation
degreeOfPower = power
inputMatrix = input
secondMatrix = secondInput
switch operation {
case .RREF:
outputMatrix = calRREF(myMatrix: input)
case .inverse:
if (calDeterminant(myMatrix: input) != 0) {
invertible = true
}
outputMatrix = calInverse(input)
case .power:
outputMatrix = calPower(myMatrix: input, toPower: power)
case .determinate:
outputMatrix = [[calDeterminant(myMatrix: input)]]
case .diagonal:
let tmp = calDiagonal(myMatrix: input)
outputMatrix = [tmp.1]
eigenvectors = tmp.0
diagonalizable = tmp.2
case .eigenvalue:
outputMatrix = [calEigenvalue(myMatrix: input)]
case .transpose:
outputMatrix = calTranspose(myMatrix: input)
case .addition:
outputMatrix = calAddition(leftMatrix: inputMatrix, rightMatrix: secondMatrix)
case .substraction:
outputMatrix = calSubstrraction(leftMatrix: inputMatrix, rightMatrix: secondMatrix)
case .multiplication:
outputMatrix = calMultiplication(leftMatrix: inputMatrix, rightMatrix: secondMatrix)
}
}
}
// MARK: Determinant
func calDeterminant(myMatrix: [[Double]]) -> Double {
if (myMatrix.count == 2) {
return myMatrix[0][0] * myMatrix[1][1] - myMatrix[0][1] * myMatrix[1][0]
} else {
var answer: Double = 0
for i in 0..<myMatrix.count {
if (i % 2 == 0) {
answer += myMatrix[i][0] * calDeterminant(myMatrix: deleteRowAndColumn(myMatrix: myMatrix, x: i, y: 0))
} else {
answer -= myMatrix[i][0] * calDeterminant(myMatrix: deleteRowAndColumn(myMatrix: myMatrix, x: i, y: 0))
}
}
return answer
}
}
// helper for calDeterminant
func deleteRowAndColumn(myMatrix: [[Double]], x: Int, y: Int) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in 0..<myMatrix.count {
var tmp: [Double] = []
for j in 0..<myMatrix[0].count {
if (i != x && j != y) {
tmp.append(myMatrix[i][j])
}
}
if (tmp != []) {
newMatrix.append(tmp)
}
}
// print(newMatrix)
return newMatrix
}
// MARK: RREF
func calRREF(myMatrix: [[Double]]) -> [[Double]] {
//
// count += 1
// print("round \(count): \(myMatrix)")
if (myMatrix.count == 1) {
// Base Case I
var tmp: [Double] = []
var pivot: Double = 1
for i in myMatrix[0] {
// To avoid rounding error
if (avoidRoundingError(x: i, precise: 5) != 0) {
pivot = i
break
}
}
for i in myMatrix[0] {
tmp.append(i / pivot)
}
return [tmp]
} else if (myMatrix[0].count == 1) {
// Base Case II
var allZero = true
for i in myMatrix {
// To avoid rounding error
if (avoidRoundingError(x: i[0], precise: 5) != 0) {
allZero = false
}
}
var tmp: [[Double]] = []
if (allZero) {
tmp.append([0])
} else {
tmp.append([1])
}
for _ in 1..<myMatrix.count {
tmp.append([0])
}
return tmp
} else {
// Recursive Case
// Firstly, we need to keep everything in order
var newMatrix: [[Double]] = []
for i in myMatrix {
if (newMatrix == []) {
newMatrix.append(i)
} else {
// Make sure the smallest non-zero is at first line
if ((abs(i[0]) < abs(newMatrix[0][0]) && avoidRoundingError(x: i[0], precise: 5) != 0)
|| avoidRoundingError(x: newMatrix[0][0], precise: 5) == 0) {
newMatrix.insert(i, at: 0)
} else {
newMatrix.append(i)
}
}
}
// Secondly, make the first column a RREF
// If the top left corner is non-zero
if (avoidRoundingError(x: newMatrix[0][0], precise: 5) != 0) {
// make sure entry (0, 0) is 1
for i in 1..<newMatrix[0].count {
newMatrix[0][i] = ( newMatrix[0][i] / newMatrix[0][0] )
}
newMatrix[0][0] = 1
for j in 1..<newMatrix.count {
newMatrix[j] = makeTheFisrtZero(newMatrix[0], rowToBeMutate: newMatrix[j], p: 0)
}
// the remaining should be in RREF form
let theRemaining: [[Double]] = calRREF(myMatrix: ingnoreTheFirstColAndRow(aMatrix: newMatrix))
newMatrix = [newMatrix[0]]
// Adding zeros to the first col
for i in theRemaining {
var tmp: [Double] = i
tmp.insert(0, at: 0)
newMatrix.append(tmp)
}
// count += 1
// print("round \(count): \(newMatrix)")
// TODO: erase the non-zero number in first line
for i in 1..<newMatrix.count {
let indexOfLeadingOne = leadingOne(aRow: newMatrix[i])
if (indexOfLeadingOne == -1) {
continue
} else {
let newFirstRow = makeTheFisrtZero(newMatrix[i], rowToBeMutate: newMatrix[0], p: indexOfLeadingOne)
newMatrix[0] = newFirstRow
}
}
} else {
// when the first col are all zeros
let theRemaining: [[Double]] = calRREF(myMatrix: ignoreTheFirstCol(aMatrix: newMatrix))
newMatrix = []
newMatrix = addingZerosAsFirstCol(aMatrix: theRemaining)
}
// count += 1
// print("round \(count): \(newMatrix)")
// At last, orgonize it in the correct order
for i in 0..<newMatrix.count {
if (allZero(aRow: newMatrix[i])) {
newMatrix.append(newMatrix[i])
newMatrix.remove(at: i)
}
}
return newMatrix
}
}
// helper for RREF
// Require: the first item must be 1 at index p
func addingZerosAsFirstCol(aMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in aMatrix {
var tmp = i
tmp.insert(0, at: 0)
newMatrix.append(tmp)
}
return newMatrix
}
func makeTheFisrtZero(_ rowWithLeadingOne: [Double], rowToBeMutate: [Double], p: Int) -> [Double] {
var newRow: [Double] = []
for i in 0..<p {
newRow.append(rowToBeMutate[i])
}
for i in p..<rowWithLeadingOne.count {
newRow.append(rowToBeMutate[i] - rowWithLeadingOne[i] * rowToBeMutate[p])
}
return newRow
}
func ingnoreTheFirstColAndRow(aMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
var firstTIme = true
for i in aMatrix {
if (firstTIme) {
firstTIme = false
continue
}
var tmp: [Double] = []
for j in 1..<i.count {
tmp.append(i[j])
}
newMatrix.append(tmp)
}
return newMatrix
}
func ignoreTheFirstCol(aMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in aMatrix {
var tmp: [Double] = []
for j in 1..<i.count {
tmp.append(i[j])
}
newMatrix.append(tmp)
}
return newMatrix
}
func leadingOne(aRow: [Double]) -> Int {
for i in 0..<aRow.count {
if ( avoidRoundingError(x: aRow[i], precise: 5) == 100000 ) {
return i
}
// For debugging only
assert( avoidRoundingError(x: aRow[i], precise: 5) == 0 )
}
return -1
}
// To avoid rounding error, we multiply the double by 10...0 times
func avoidRoundingError(x: Double, precise: Int) -> Int {
var tmp = x
// Off by one
for _ in 0...precise {
tmp = tmp * 10
}
var intTmp = Int(tmp)
if (intTmp % 10 >= 5) {
intTmp += 1
}
return ( intTmp / 10 )
}
func allZero(aRow: [Double]) -> Bool {
for i in aRow {
if (avoidRoundingError(x: i, precise: 5) != 0) {
return false
}
}
return true
}
// MARK: Rank
func calRank(myMatrix: [[Double]]) -> Int {
var count = 0
let rrefForm = calRREF(myMatrix: myMatrix)
for i in rrefForm {
if (leadingOne(aRow: i) != -1) {
count += 1
}
}
return count
}
// MARK: Transpose
func calTranspose(myMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in 0..<myMatrix[0].count {
var tmp: [Double] = []
for j in 0..<myMatrix.count {
tmp.append(myMatrix[j][i])
}
newMatrix.append(tmp)
}
return newMatrix
}
// MARK: Inverse
//func calInverse(myMatrix: [[Double]]) -> [[Double]] {
//
// var newMatrix: [[Double]] = []
//
// var addingIdentity: [[Double]] = []
// for i in 0..<myMatrix.count {
// var tmp: [Double] = myMatrix[i]
// for j in 0..<myMatrix[0].count {
// if (j == i) {
// tmp.append(1)
// } else {
// tmp.append(0)
// }
// }
// addingIdentity.append(tmp)
// }
//
// let rrefForm = calRREF(myMatrix: addingIdentity)
//
// for i in 0..<addingIdentity.count {
// var tmp: [Double] = []
// for j in myMatrix[0].count..<addingIdentity[0].count {
// tmp.append(rrefForm[i][j])
// }
// newMatrix.append(tmp)
// }
//
// return newMatrix
//}
func calInverse(_ A: [[Double]]) -> [[Double]] {
// precondition(A.rows == A.cols, "Matrix dimensions must agree")
var M = __CLPK_integer(A.count)
var N = M
var LDA = N
var pivot = [__CLPK_integer](repeating: 0, count: Int(N))
var wkOpt = __CLPK_doublereal(0.0)
var lWork = __CLPK_integer(-1)
var error: __CLPK_integer = 0
var flattenedMatrix = flattenMatrix(myMatrix: A)
dgetrf_(&M, &N, &flattenedMatrix, &LDA, &pivot, &error)
// precondition(error == 0, "Matrix is non invertible")
/* Query and allocate the optimal workspace */
dgetri_(&N, &flattenedMatrix, &LDA, &pivot, &wkOpt, &lWork, &error)
lWork = __CLPK_integer(wkOpt)
// var work = Vector(repeating: 0.0, count: Int(lWork))
/* Compute inversed matrix */
dgetri_(&N, &flattenedMatrix, &LDA, &pivot, &wkOpt, &lWork, &error)
// precondition(error == 0, "Matrix is non invertible")
var newMatrix: [[Double]] = []
for i in 0..<A.count {
var tmp: [Double] = []
for j in 0..<A.count {
tmp.append(flattenedMatrix[i * A.count + j])
}
newMatrix.append(tmp)
}
return newMatrix
}
// MARK: Multiplication
func calMultiplication(leftMatrix: [[Double]], rightMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for row in 0..<leftMatrix.count {
var tmpRow: [Double] = []
for col in 0..<rightMatrix[0].count {
var sum: Double = 0
for k in 0..<leftMatrix[0].count {
sum += leftMatrix[row][k] * rightMatrix[k][col]
}
tmpRow.append(sum)
}
newMatrix.append(tmpRow)
}
return newMatrix
}
// MARK: Power
func calPower(myMatrix: [[Double]], toPower: Int) -> [[Double]] {
var newMatrix: [[Double]] = myMatrix
for _ in 1..<toPower {
newMatrix = calMultiplication(leftMatrix: newMatrix, rightMatrix: myMatrix)
}
return newMatrix
}
// MARK: Diagonalization
func calDiagonal(myMatrix: [[Double]]) -> ([[Double]], [Double], Bool) {
var matrix:[__CLPK_doublereal] = flattenMatrix(myMatrix: myMatrix)
var N = __CLPK_integer(sqrt(Double(matrix.count)))
//var pivots = [__CLPK_integer](repeating: 0, count: Int(N))
var LDA = N
var wkOpt = __CLPK_doublereal(0.0)
var lWork = __CLPK_integer(-1)
var jobvl: Int8 = 86 // 'V'
var jobvr: Int8 = 86 // 'V'
var error = __CLPK_integer(0)
// Real parts of eigenvalues
var wr = [Double](repeating: 0, count: Int(N))
// Imaginary parts of eigenvalues
var wi = [Double](repeating: 0, count: Int(N))
// Left eigenvectors
var vl = [__CLPK_doublereal](repeating: 0, count: Int(N*N))
// Right eigenvectors
var vr = [__CLPK_doublereal](repeating: 0, count: Int(N*N))
var ldvl = N
var ldvr = N
/* Query and allocate the optimal workspace */
var workspaceQuery: Double = 0.0
dgeev_(&jobvl, &jobvr, &N, &matrix, &LDA, &wr, &wi, &vl, &ldvl, &vr, &ldvr, &workspaceQuery, &lWork, &error)
// size workspace per the results of the query:
var workspace = [Double](repeating: 0.0, count: Int(workspaceQuery))
lWork = __CLPK_integer(workspaceQuery)
/* Compute eigen vectors */
dgeev_(&jobvl, &jobvr, &N, &matrix, &LDA, &wr, &wi, &vl, &ldvl, &vr, &ldvr, &workspace, &lWork, &error)
var newMatrix: [[Double]] = myMatrix
for i in 0..<myMatrix.count {
for j in 0..<myMatrix[0].count {
newMatrix[j][i] = vl[i * myMatrix.count + j]
}
}
// To check whether the eigenvals are correct
var count = 0
var diagonalizable = true
var acc: [Int] = []
for i in 0..<wr.count {
let tmp = calSubstrraction(leftMatrix: myMatrix, rightMatrix: scalarIdentityMatrix(dimension: myMatrix.count, scaler: wr[i]))
let rank = calRank(myMatrix: tmp)
if (rank == myMatrix.count) {
acc.append(i)
diagonalizable = false
} else {
count += myMatrix.count - rank
}
}
for i in (0..<acc.count).reversed() {
wr.remove(at: acc[i])
}
if (count != myMatrix.count) {
diagonalizable = false
}
// To avoid repeat
var arrayOfEigenvals: [Double] = []
for i in wr {
var tmp = Double(round(i * 1000) / 1000)
if (!includedIn(tmp, arrayOfEigenvals)) {
arrayOfEigenvals.append(tmp)
}
}
// Special Case for matrix that already diagonalized
var alreadyDiagonal: Bool = true
for i in 0..<myMatrix.count {
for j in 0..<myMatrix[0].count {
if (i != j && avoidRoundingError(x: myMatrix[i][j], precise: 5) != 0) {
alreadyDiagonal = false
}
}
}
if alreadyDiagonal {
newMatrix.removeAll()
newMatrix = scalarIdentityMatrix(dimension: myMatrix.count, scaler: 1)
arrayOfEigenvals.removeAll()
for i in 0..<myMatrix.count {
if (!includedIn(myMatrix[i][i], arrayOfEigenvals)) {
arrayOfEigenvals.append(myMatrix[i][i])
}
}
diagonalizable = true
}
return (newMatrix, arrayOfEigenvals, diagonalizable);
}
// helper for egienvals
func includedIn(_ x: Double,_ arrayOfDouble: [Double]) -> Bool {
for i in arrayOfDouble {
if (x == i) { return true }
}
return false
}
func flattenMatrix(myMatrix: [[Double]]) -> [__CLPK_doublereal] {
var tmp:[__CLPK_doublereal] = []
for i in myMatrix {
for j in i {
tmp.append(__CLPK_doublereal(j))
}
}
return tmp
}
func scalarIdentityMatrix(dimension: Int, scaler: Double) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in 0..<dimension {
var tmp: [Double] = []
for j in 0..<dimension {
if (i == j) {
tmp.append(scaler)
} else {
tmp.append(0)
}
}
newMatrix.append(tmp)
}
return newMatrix
}
// MARK: Eigenvalues
func calEigenvalue(myMatrix: [[Double]]) -> [Double] {
return calDiagonal(myMatrix: myMatrix).1
}
// MARK: Addition and Substraction
func calAddition(leftMatrix:[[Double]], rightMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in 0..<leftMatrix.count {
var tmp: [Double] = []
for j in 0..<leftMatrix[0].count {
tmp.append(leftMatrix[i][j] + rightMatrix[i][j])
}
newMatrix.append(tmp)
}
return newMatrix
}
func calSubstrraction(leftMatrix:[[Double]], rightMatrix: [[Double]]) -> [[Double]] {
var newMatrix: [[Double]] = []
for i in 0..<leftMatrix.count {
var tmp: [Double] = []
for j in 0..<leftMatrix[0].count {
tmp.append(leftMatrix[i][j] - rightMatrix[i][j])
}
newMatrix.append(tmp)
}
return newMatrix
}
| [
-1
] |
0d4567c3d95ec77d7ab20266181c3b049a3abd00 | aa9271386967d99caa11b6e12cee588f725fa19c | /Auction/ViewControllers/Settings/SettingsCurrency/SettingsCurrencyPresenter.swift | 58747388d917a3865d36e8931e68ce897b77d789 | [] | no_license | Profiteam/Auction.iOS | 57cbaf36f25bc21692c31e0def016f16af2ed224 | 125776c71090cb267edca9dc98ebfdf493b09731 | refs/heads/master | 2020-07-14T22:39:42.759347 | 2020-01-18T13:35:56 | 2020-01-18T13:35:56 | 205,417,645 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 966 | swift | //
// SettingsCurrencyPresenter.swift
// Auction
//
// Created by Q on 25/10/2018.
// Copyright © 2018 Oxbee. All rights reserved.
//
import UIKit
class SettingsCurrencyPresenter: SettingsCurrencyPresenterProtocol, SettingsCurrencyInteractorOutputProtocol {
weak private var view: SettingsCurrencyViewProtocol?
var interactor: SettingsCurrencyInteractorInputProtocol?
private let router: SettingsCurrencyWireframeProtocol
init(interface: SettingsCurrencyViewProtocol, interactor: SettingsCurrencyInteractorInputProtocol?, router: SettingsCurrencyWireframeProtocol) {
self.view = interface
self.interactor = interactor
self.router = router
}
func receiveCurrency(data: Data) {
self.view?.setCurrency(data: data)
}
func currencyDidChange() {
self.view?.currencySelected()
}
func receiveCurrencyRate(data: Data) {
self.view?.setCurrencyRate(data: data)
}
}
| [
-1
] |
ded3d2de631ed5a82e165fbffce066b5cc0ab87f | 5bfba18dd2e0915739fa4ec78ba9dec1acae7f00 | /AssetClient/PasswordChangeViewController.swift | 6fce1b06b078f0b2d36099f848018dc7e2ed9e22 | [] | no_license | jgoodliffe/AssetMac-New | 10e303e244a3433e6e91c7d77a5d2e2f49150cdf | 29dca5b11d6f50f866a8537b3e6a0eb3606483f9 | refs/heads/master | 2022-04-12T10:22:07.412434 | 2020-04-05T16:26:24 | 2020-04-05T16:26:24 | 238,450,755 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 10,597 | swift | //
// PasswordChangeViewController.swift
// Production Manager Pro
//
// Created by Jamie Goodliffe on 18/02/2020.
// Copyright © 2020 Jamie Goodliffe. All rights reserved.
//
import Cocoa
import AppKit
import Alamofire
import SwiftyJSON
extension Notification.Name {
static let changedUserPassword = Notification.Name("changedUserPassword")
static let hideDashboard = Notification.Name("hideDashboard")
static let showDashboard = Notification.Name("showDashboard")
}
class PasswordChangeViewController: NSViewController {
@IBOutlet weak var btnChangePassword: NSButtonCell!
@IBOutlet weak var btnDismiss: NSButton!
@IBOutlet weak var txtCurrentPass: NSSecureTextField!
@IBOutlet weak var txtNewPass: NSSecureTextField!
@IBOutlet weak var txtVerifyPass: NSSecureTextField!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
@IBOutlet weak var labelStatus: NSTextField!
var changingPassword = false
//Token Stores + App Delegate Declaration
let appDelegate = NSApp.delegate as? AppDelegate
let coreDataFuncs = CoreDataFuncs()
var authenticationInfo:[String] = []
//Alamofire Information
let port: String = ":8080"
var manager = Alamofire.Session.default
let configuration = URLSessionConfiguration.default
lazy var changePasswordInProgress: [IndexPath: Operation] = [:]
lazy var changePasswordQueue: OperationQueue = {
var changePasswordQueue = OperationQueue()
changePasswordQueue.name = "Change Password queue"
changePasswordQueue.maxConcurrentOperationCount = 1
return changePasswordQueue
}()
override func viewDidLoad() {
super.viewDidLoad()
progressIndicator.isHidden = true
authenticationInfo = coreDataFuncs.retrieveTokenAndHost()
NotificationCenter.default.post(Notification(name: .hideDashboard))
}
@IBAction func btnDismissClicked(_ sender: Any) {
changingPassword = false
changePasswordQueue.cancelAllOperations()
NotificationCenter.default.post(Notification(name: .showDashboard))
self.dismiss(self)
}
@IBAction func btnChangePasswordClicked(_ sender: Any) {
let answer = dialogConfirm(question: "This action will log you out!", text: "Changing your password is an irreversible action that will require you to log in again.")
if(answer){
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
changePassword()
} else{
NotificationCenter.default.post(Notification(name: .showDashboard))
dismiss(self)
}
}
func validateFields()->Bool{
let currentPassword = txtCurrentPass.stringValue
let newPassword = txtNewPass.stringValue
let verifyPassword = txtVerifyPass.stringValue
//Check if anything has actually been entered
if(currentPassword==""||newPassword==""||verifyPassword==""){
labelStatus.textColor = NSColor.red
labelStatus.stringValue = "You have not filled in all fields.\nPlease check your entry and try again."
return false
}
//Check if new password meets length requirements
if(newPassword.count<8 || newPassword.count>80){
labelStatus.textColor = NSColor.red
labelStatus.stringValue = "Your new password is too short.\nPlease check your entry and try again."
return false
}
//Check if password contains numbers and letters
let textRange = newPassword.rangeOfCharacter(from: CharacterSet.letters)
let decimalRange = newPassword.rangeOfCharacter(from: CharacterSet.decimalDigits)
if(decimalRange==nil || textRange==nil){
labelStatus.textColor = NSColor.red
labelStatus.stringValue = "Your new password must contain both letters and numbers.\nPlease check your entry and try again."
return false
}
//Check if password contains forbidden characters
if(newPassword.contains("/") || newPassword.contains("\"")){
labelStatus.textColor = NSColor.red
labelStatus.stringValue = "Your password may not contain slashes.\nPlease check your entry and try again."
return false
}
//Check if new password and verify password are the same.
let isEqual = (newPassword == verifyPassword)
if(!isEqual){
labelStatus.textColor = NSColor.red
labelStatus.stringValue = "Your new password doesn't match the verified password.\nPlease check your entry and try again."
return false
}
return true
}
func dialogConfirm(question: String, text: String) -> Bool {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .informational
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert.runModal() == .alertFirstButtonReturn
}
@IBAction func enterKeypressed(_ sender: Any) {
let answer = dialogConfirm(question: "This action will log you out!", text: "Changing your password is an irreversible action that will require you to log in again.")
if(answer){
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
changePassword()
} else{
dismiss(self)
}
}
func changePassword(){
if changingPassword{
changingPassword = false
btnChangePassword.title = "Change Password"
labelStatus.stringValue = "Enter your existing password, followed by your desired password."
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
labelStatus.textColor = NSColor.systemGray
changePasswordQueue.cancelAllOperations()
}
changingPassword = true
labelStatus.textColor = NSColor.systemGray
labelStatus.stringValue = "Changing password..."
btnChangePassword.title = "Abort"
if(validateFields()){
configuration.timeoutIntervalForRequest = 5
configuration.timeoutIntervalForResource = 5
self.manager = Alamofire.Session(configuration:configuration)
let currentPassEncoded = ((txtCurrentPass.stringValue).data(using: .utf8))?.base64EncodedString() ?? "" //Encode to UTF-8 -> Unwrap Optional
let newPassEncoded = ((txtNewPass.stringValue).data(using: .utf8))?.base64EncodedString() ?? "" //Encode to UTF-8 -> Unwrap Optional
let headers:HTTPHeaders = [
"token": authenticationInfo.first ?? "",
"currentPassword": currentPassEncoded,
"newPassword": newPassEncoded
]
let requestURL = authenticationInfo[1] + port + "/utilities/changePassword"
if changePasswordQueue.operationCount<1{
changePasswordQueue.addOperation {
self.manager.request(requestURL, method: .post, headers: headers).responseJSON{ response in
switch response.result{
case.success(let jsonResponse):
if let JSON = jsonResponse as? [String:Any]{
let status = JSON["response-code"] as! Int
if(status==200){
DispatchQueue.main.async {
self.btnChangePassword.title = "Change Password"
self.progressIndicator.stopAnimation(self)
self.progressIndicator.isHidden = true
self.labelStatus.textColor = NSColor.green
self.labelStatus.stringValue = "Successfully changed password."
//Close window after a second pause.
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.dismiss(self)
//Notify Dashboard Window(s) to close...
NotificationCenter.default.post(Notification(name: .changedUserPassword))
self.performSegue(withIdentifier: "backToLogin", sender: nil)
}
}
} else{
let errorMessage:String = "Error Changing Password.\n Error Code: "+String(status)+" "+String(JSON["error-type"] as! String)
DispatchQueue.main.async {
self.labelStatus.textColor = NSColor.red
self.labelStatus.stringValue = errorMessage
self.btnChangePassword.title = "Change Password"
self.progressIndicator.stopAnimation(self)
self.progressIndicator.isHidden = true
}
}
}
case .failure(let error):
let errorString = String(describing: error.localizedDescription)
DispatchQueue.main.async {
self.labelStatus.textColor = NSColor.red
self.labelStatus.stringValue = "There was an error changing the password: \n" + errorString
self.btnChangePassword.title = "Change Password"
self.progressIndicator.stopAnimation(self)
self.progressIndicator.isHidden = true
}
}
}
}
}
} else{
btnChangePassword.title = "Change Password"
changingPassword = false
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
}
}
}
| [
-1
] |
ad1407d0beaa6c821501d5e40516e6c1f18407eb | be1ac0438369be7014260574f5779a39f8501794 | /NestedCollectionViewController/ParentViewController.swift | d50fc8290143bf7c3a0120959fbfa3219d46bd2f | [
"MIT"
] | permissive | shtnkgm/NestedCollectionViewController | 29e4f6fcdcdb8f568ae82e37fd1c48e0bc557321 | e9141e83129f79a103e151c89526872527e88794 | refs/heads/master | 2021-09-24T10:45:19.022734 | 2017-11-22T21:19:39 | 2017-11-22T21:19:39 | 111,473,621 | 0 | 0 | MIT | 2018-10-08T14:30:38 | 2017-11-20T23:21:27 | Swift | UTF-8 | Swift | false | false | 2,490 | swift | //
// ParentViewController.swift
// NestedCollectionViewController
//
// Created by Shota Nakagami on 2017/11/20.
// Copyright © 2017年 Shota Nakagami. All rights reserved.
//
import UIKit
final class ParentViewController: LifecycleLoggingViewController {
@IBOutlet private weak var collectionView: UICollectionView!
private let margin: CGFloat = 10
private var reuseIdentifier: String {
return String(describing: ParentCell.self)
}
private var collectionViewFlowLayout: UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = margin
layout.minimumInteritemSpacing = margin
layout.itemSize = CGSize(width: view.bounds.width - margin * 2, height: 100)
layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
layout.scrollDirection = .vertical
layout.invalidateLayout()
return layout
}
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
private func setupCollectionView() {
let nib = UINib(nibName: reuseIdentifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.collectionViewLayout = collectionViewFlowLayout
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.contentInset = .zero
}
}
extension ParentViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
guard let parentCell = cell as? ParentCell else { return cell }
parentCell.configure(parentViewController: self, index: indexPath.row)
return parentCell
}
}
extension ParentViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(className + ":" + #function + "(\(indexPath.row))")
}
}
| [
-1
] |
0f4ab69271e69cdfceca8234271c5b7a07d21cad | aaa31603f3ec36172261a7558fd018af1ff4cf70 | /Pelis/Pages/Menu/MenuTransitioningManager.swift | bf65946e24e906b7472baa1d3914ddc5bda5525e | [] | no_license | BlaShadow/TestApi | 9d879b7b25e1e2164195a24c69f6e5325f75ca5b | 4297b3c155c002e5668eda05794e05948fca3083 | refs/heads/master | 2020-07-20T12:25:50.822411 | 2019-09-05T19:24:23 | 2019-09-05T19:24:23 | 206,639,841 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,190 | swift | //
// MenuTransitioningManager.swift
// Pelis
//
// Created by Blashadow on 9/5/19.
// Copyright © 2019 Blashadow. All rights reserved.
//
import UIKit
class MenuTransitioningManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
static let snapshotDistance: CGFloat = 200
static let snapshotScale: CGFloat = 0.7
var duration = 0.7
var isPresenting = false
var snapshot: UIView?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: .from)
let toView = transitionContext.view(forKey: .to)
let container = transitionContext.containerView
let xValue = container.frame.width - MenuTransitioningManager.snapshotDistance
var moveRight = CGAffineTransform(translationX: xValue, y: 0)
let moveLeft = CGAffineTransform(translationX: 0, y: 0)
if isPresenting {
let destinationController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
toView?.transform = moveLeft
snapshot = fromView?.snapshotView(afterScreenUpdates: true)
snapshot?.layer.cornerRadius = 20
snapshot?.clipsToBounds = true
if let destinationController = destinationController as? MenuViewController {
let selector = #selector(destinationController.closeMenu)
let tapGesture = UITapGestureRecognizer(target: destinationController, action: selector)
snapshot?.addGestureRecognizer(tapGesture)
}
if let toView = toView, let snapshot = snapshot {
container.addSubview(toView)
container.addSubview(snapshot)
toView.addSubview(snapshot)
}
}
UIView.animate(withDuration: duration,
delay: 0.0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: 0.3,
options: .curveEaseIn,
animations: {
if self.isPresenting {
let scale = MenuTransitioningManager.snapshotScale
moveRight = moveRight.scaledBy(x: scale, y: scale)
fromView?.transform = moveRight
self.snapshot?.transform = moveRight
self.snapshot?.layer.cornerRadius = 20
toView?.transform = CGAffineTransform.identity
} else {
self.snapshot?.transform = CGAffineTransform.identity
self.snapshot?.layer.cornerRadius = 0
toView?.transform = CGAffineTransform.identity
fromView?.transform = CGAffineTransform.identity
}
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
}
| [
-1
] |
09ae7de50d4d8b3439a8ec84e53a11ffb1c4a58e | aadeae4b55845dbdc2bac32a5cf746fd636d4418 | /Crema/SpotDetailViewController.swift | 1d2fc8c5a59b386bcafe975cd226f305b6c4736a | [] | no_license | KantaroFujimori/Crema | b7dbeb476d34dd9a05269398c0299f794376e605 | 78b3703cbf69afcf11967076a86e0be11c103698 | refs/heads/master | 2021-01-19T19:12:21.837337 | 2017-05-04T09:40:11 | 2017-05-04T09:40:11 | 88,405,854 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,864 | swift | //
// SpotDetailViewController.swift
// Crema
//
// Created by 藤森侃太郎 on 2017/04/13.
// Copyright © 2017年 藤森侃太郎. All rights reserved.
//
import UIKit
import SDWebImage
import Bond
class SpotDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomDelegate {
@IBOutlet weak var spotDetailTableView: UITableView!
@IBOutlet weak var customNavigationView: CustomNavigationView!
var contribution: Contribution?
var navigationVC: UINavigationController?
override func viewDidLoad() {
super.viewDidLoad()
self.spotDetailTableView.register(UINib(nibName: "SpotDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "SpotDetailTableViewCell")
self.spotDetailTableView.register(UINib(nibName: "FeedTableViewCell", bundle: nil), forCellReuseIdentifier: "FeedTableViewCell")
self.spotDetailTableView.delegate = self
self.spotDetailTableView.dataSource = self
self.customNavigationView.customDelegate = self
self.spotDetailTableView.estimatedRowHeight = 400
self.spotDetailTableView.rowHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tappedBackBtn(){
self.dismiss(animated: true, completion: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section == 0){
return 1
}else{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//spot情報
if (indexPath.section == 0){
let cell = tableView.dequeueReusableCell(withIdentifier: "SpotDetailTableViewCell", for: indexPath) as! SpotDetailTableViewCell
cell.spotNameLabel.text = self.contribution?.spotInstaName
let imageURL = URL(string: (self.contribution?.standardImage)!)
cell.spotTopImage.sd_setImage(with: imageURL)
//MARK: set temporary info
let jenreConverter = JenreConverter()
let jenre = jenreConverter.convert(types: (self.contribution?.types)!)
cell.jenreImage.image = UIImage(named: jenre)
cell.priceLabel.text = "〜999"
cell.likeNumberLabel.text = "34"
cell.favoriteNumberLabel.text = "20"
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
cell.profileNameLabel.text = self.contribution?.userName
let imageURL = URL(string: (self.contribution?.standardImage)!)
cell.contributionImage.sd_setImage(with: imageURL)
cell.captionLabel.text = self.contribution?.caption
cell.captionLabel.numberOfLines = 0
cell.captionLabel.sizeToFit()
cell.captionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.profileImage.layer.borderColor = UIColor.gray.cgColor
cell.profileImage.layer.borderWidth = 1
cell.profileImage.layer.cornerRadius = 20
cell.profileImage.layer.masksToBounds = true
let profileImageUrl = URL(string: (self.contribution?.userProfileUrl)!)
cell.profileImage.sd_setImage(with: profileImageUrl)
cell.selectionStyle = UITableViewCellSelectionStyle.blue
return cell
}
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if(indexPath.section == 0){
return nil
}else{
return indexPath
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let feedDetailVC: FeedDetailViewController = self.storyboard!.instantiateViewController(withIdentifier: "FeedDetailViewController") as! FeedDetailViewController
feedDetailVC.contribution = self.contribution
self.navigationController?.pushViewController(feedDetailVC, animated: true)
//present(navigationVC, animated: true, completion: nil)
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
}
| [
-1
] |
59c25dfa50ad005e2e2408c55744d273ec6b33ab | e6e7a3fe7673b7a72491b2e401e1cd348b2043eb | /simple-polyline/SimplePolyline/ViewController.swift | 090f62b3e5df5b8c7b066ac20b814f8bf90f4351 | [
"MIT"
] | permissive | jcfausto/google-maps-ios-study | bf7960e04bc27ed8c4ebf5a4e80ec9ecda16a3be | 68d3cfd4be017f7adf405fe3e355605929cadc2b | refs/heads/master | 2021-01-10T08:54:45.622846 | 2016-02-22T23:22:50 | 2016-02-22T23:22:50 | 52,311,378 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,362 | swift | //
// ViewController.swift
// SimplePolyline
//
// Created by Julio Cesar Fausto on 22/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import UIKit
import GoogleMaps
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if appDelegate.gmsOk {
let camera = GMSCameraPosition.cameraWithLatitude(0, longitude:-165, zoom:2)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)
let path = GMSMutablePath()
path.addLatitude(-33.866, longitude: 151.195) //Sydney
path.addLatitude(-18.142, longitude: 178.431) //Fiji
path.addLatitude(21.291, longitude: -157.821) //Hawaii
path.addLatitude(37.423, longitude: -122.091) //Mountain View
let polyline = GMSPolyline(path: path)
polyline.strokeColor = UIColor.blueColor()
polyline.strokeWidth = 5.0
polyline.map = mapView
self.view = mapView
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
-1
] |
2e14958272c54e5ef3d4bc79bec41c9846d4597e | 8f4085fb701e783ba06a64423a1f3490955c92f2 | /HW-InstaDiaries/InstaDiary/AppDelegate.swift | 0b9057f1548f7bc6e199ab8d992776e44356c065 | [] | no_license | jinqili0310/CIM613-MobileAppDev | 2ec197739cce4451b04f0b5e1ee5c92b30c948e4 | 72d9cf87d7f6ad0a25af0e76da88e67987153271 | refs/heads/master | 2023-01-28T11:28:43.374412 | 2023-01-13T20:25:38 | 2023-01-13T20:25:38 | 266,045,523 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,411 | swift | //
// AppDelegate.swift
// InstaDiary
//
// Created by Jinqi Li on 1/22/20.
// Copyright © 2020 Jinqi Li. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
393230,
393250,
344102,
393261,
393266,
213048,
385081,
376889,
393275,
376905,
327756,
254030,
286800,
368727,
180313,
368735,
180320,
376931,
286831,
368752,
286844,
262283,
286879,
286888,
377012,
327871,
180416,
377036,
180431,
377046,
377060,
327914,
205036,
393456,
393460,
336123,
418043,
336128,
385280,
262404,
180490,
368911,
262416,
262422,
377117,
262436,
336180,
262454,
262472,
344403,
213332,
65880,
262496,
418144,
262499,
213352,
262507,
246123,
262510,
213372,
385419,
393612,
262550,
262552,
385440,
385443,
385451,
262573,
393647,
385458,
262586,
344511,
262592,
360916,
369118,
328177,
328179,
328182,
328189,
328192,
164361,
410128,
393747,
254490,
188958,
385570,
33316,
197159,
377383,
352821,
188987,
418363,
369223,
385609,
385616,
352864,
369253,
262760,
352874,
352887,
254587,
377472,
148105,
377484,
352918,
98968,
344744,
361129,
336555,
385713,
434867,
164534,
336567,
164538,
328378,
328386,
352968,
344776,
418507,
385742,
385748,
361179,
189153,
369381,
361195,
418553,
344831,
336643,
344835,
344841,
361230,
336659,
418580,
418585,
434970,
369435,
418589,
262942,
418593,
336675,
328484,
418598,
418605,
336696,
361273,
328515,
336708,
328519,
336711,
361288,
328522,
336714,
426841,
197468,
254812,
361309,
361315,
361322,
328573,
377729,
369542,
361360,
222128,
345035,
345043,
386003,
386011,
386018,
386022,
435187,
328714,
361489,
386069,
336921,
386073,
336925,
345118,
377887,
345133,
345138,
386101,
361536,
197707,
189520,
345169,
156761,
361567,
148578,
345199,
386167,
361593,
410745,
361598,
214149,
345222,
386186,
337047,
345246,
214175,
337071,
337075,
386258,
328924,
66782,
222437,
386285,
328941,
386291,
345376,
353570,
345379,
410917,
345382,
345399,
378169,
369978,
337222,
337229,
337234,
263508,
402791,
345448,
271730,
378227,
271745,
181638,
353673,
181643,
181654,
230809,
181670,
181673,
181678,
337329,
181681,
181684,
181690,
361917,
181696,
337349,
181703,
337365,
271839,
329191,
361960,
329194,
116210,
337398,
337415,
329226,
419339,
419343,
419349,
345625,
419355,
370205,
419359,
419362,
394786,
370213,
419368,
419376,
206395,
214593,
419400,
419402,
353867,
419406,
419410,
345701,
394853,
222830,
370297,
403070,
403075,
345736,
198280,
345749,
345757,
345762,
419491,
345765,
419497,
419501,
370350,
419506,
419509,
337592,
419512,
419517,
337599,
419527,
419530,
419535,
272081,
394966,
419542,
419544,
181977,
345818,
419547,
419550,
419559,
337642,
419563,
337645,
370415,
337659,
141051,
337668,
362247,
395021,
362255,
116509,
345887,
378663,
345905,
354106,
354111,
247617,
354117,
370503,
329544,
345930,
370509,
354130,
247637,
337750,
370519,
313180,
354142,
345964,
345967,
345970,
345974,
403320,
354172,
247691,
337808,
247700,
329623,
436126,
436132,
337833,
362413,
337844,
346057,
346063,
247759,
329697,
354277,
190439,
247789,
354313,
346139,
436289,
378954,
395339,
338004,
329832,
329855,
329885,
411805,
346272,
100524,
387249,
379066,
387260,
256191,
395466,
346316,
411861,
411864,
411868,
411873,
379107,
411876,
387301,
346343,
338152,
387306,
387312,
346355,
436473,
321786,
379134,
411903,
411916,
379152,
395538,
387349,
338199,
387352,
182558,
338211,
395566,
248111,
362822,
436555,
190796,
379233,
354673,
248186,
420236,
379278,
354727,
338352,
330189,
338381,
338386,
338403,
338409,
248308,
199164,
330252,
199186,
420376,
330267,
354855,
10828,
199249,
346721,
174695,
248425,
191084,
338543,
191092,
346742,
330383,
354974,
150183,
174774,
248504,
174777,
223934,
355024,
273108,
355028,
264918,
183005,
256734,
436962,
338660,
338664,
264941,
207619,
264964,
338700,
256786,
199452,
363293,
396066,
346916,
396069,
215853,
355122,
355131,
355140,
355143,
338763,
355150,
330580,
355166,
265055,
265058,
355175,
387944,
355179,
330610,
330642,
355218,
412599,
207808,
379848,
396245,
330710,
248792,
248798,
347105,
257008,
183282,
265207,
330748,
265214,
330760,
330768,
248862,
396328,
158761,
396336,
199728,
330800,
396339,
339001,
388154,
388161,
347205,
248904,
330826,
248914,
339036,
412764,
257120,
265320,
248951,
420984,
330889,
347287,
339097,
248985,
44197,
380070,
339112,
249014,
330958,
330965,
265432,
265436,
388319,
388347,
175375,
159005,
175396,
208166,
273708,
372015,
347441,
372018,
199988,
175415,
396600,
437566,
175423,
437570,
437575,
437583,
331088,
437587,
331093,
396633,
175450,
437595,
175457,
208227,
175460,
175463,
265580,
437620,
175477,
249208,
175483,
175486,
249214,
175489,
249218,
249224,
249227,
249234,
175513,
175516,
396705,
175522,
355748,
380332,
396722,
388542,
372163,
216517,
380360,
216522,
339404,
372176,
208337,
339412,
413141,
339417,
249308,
339420,
249312,
339424,
339428,
339434,
249328,
69113,
372228,
208398,
380432,
175635,
339503,
265778,
265795,
396872,
265805,
224853,
224857,
257633,
224870,
372327,
257646,
372337,
224884,
224887,
224890,
224894,
224897,
372353,
216707,
126596,
421508,
224904,
224909,
11918,
159374,
224913,
126610,
224916,
224919,
126616,
208538,
224922,
224926,
224929,
224932,
224936,
257704,
224942,
257712,
224947,
257716,
257720,
224953,
257724,
224959,
257732,
224965,
224969,
339662,
224975,
257747,
224981,
224986,
224993,
257761,
257764,
224999,
339695,
225012,
257787,
225020,
339710,
257790,
225025,
257794,
339721,
257801,
257804,
225038,
257807,
372499,
167700,
225043,
225048,
257819,
225053,
184094,
225058,
339747,
339749,
257833,
225066,
257836,
413484,
225070,
225073,
372532,
257845,
225079,
397112,
225082,
397115,
225087,
225092,
225096,
323402,
257868,
257871,
225103,
397139,
225108,
225112,
257883,
257886,
225119,
257890,
339814,
225127,
257896,
274280,
257901,
225137,
339826,
257908,
225141,
257912,
225148,
257916,
257920,
225155,
339844,
225165,
397200,
225170,
380822,
225175,
225180,
118691,
184244,
372664,
372702,
372706,
356335,
380918,
405533,
430129,
266294,
421960,
356439,
421990,
266350,
356466,
266362,
381068,
225423,
250002,
250004,
225429,
356506,
225437,
135327,
225441,
438433,
225444,
438436,
225447,
438440,
225450,
258222,
225455,
430256,
225458,
225461,
225466,
389307,
225470,
381120,
372929,
430274,
225475,
389320,
225484,
225487,
225490,
266453,
225493,
225496,
225499,
225502,
225505,
356578,
225510,
217318,
225514,
225518,
372976,
381176,
397571,
389380,
356637,
356640,
356643,
356646,
266536,
356649,
356655,
332080,
340275,
356660,
397622,
332090,
225597,
332097,
201028,
348488,
332106,
332117,
348502,
250199,
250202,
332125,
250210,
348522,
348525,
348527,
332152,
250238,
389502,
332161,
356740,
332172,
373145,
340379,
389550,
324030,
266687,
160234,
127471,
340472,
324094,
266754,
324099,
324102,
324111,
340500,
324117,
324131,
332324,
381481,
324139,
356907,
324142,
356916,
324149,
324155,
348733,
324164,
356934,
348743,
381512,
324170,
324173,
324176,
389723,
332380,
373343,
381545,
340627,
184982,
373398,
258721,
332453,
332459,
389805,
332463,
381617,
332471,
332483,
332486,
373449,
357069,
332493,
357073,
332511,
332520,
340718,
332533,
348924,
373510,
389926,
152370,
348978,
340789,
348982,
398139,
127814,
357201,
357206,
389978,
357211,
430939,
357214,
201579,
201582,
349040,
340849,
201588,
430965,
381813,
324472,
398201,
119674,
324475,
430972,
340861,
324478,
340858,
324481,
373634,
398211,
324484,
324487,
381833,
324492,
324495,
324498,
430995,
324501,
324510,
422816,
324513,
398245,
201637,
324524,
340909,
324533,
324538,
324541,
398279,
340939,
340941,
209873,
340957,
431072,
398306,
340963,
209895,
201711,
349172,
381946,
349180,
439294,
431106,
209943,
250914,
357410,
185380,
357418,
209965,
209968,
209971,
209975,
209979,
209987,
209990,
341071,
349267,
250967,
210010,
341091,
210025,
210027,
210030,
210036,
210039,
210044,
349308,
160895,
152703,
349311,
210052,
210055,
349319,
210067,
210071,
210077,
210080,
210084,
251044,
185511,
210088,
210095,
210098,
210107,
210115,
332997,
210127,
333009,
210131,
333014,
210138,
210143,
218354,
218360,
251128,
275706,
275712,
275715,
275721,
349459,
333078,
251160,
349484,
349491,
251189,
415033,
251210,
357708,
210260,
259421,
365921,
333154,
251235,
374117,
333162,
234866,
390516,
333175,
357755,
251271,
136590,
112020,
349590,
357792,
259515,
415166,
415185,
366034,
366038,
415191,
415193,
415196,
415199,
423392,
333284,
415207,
366056,
366061,
210420,
415224,
423423,
415257,
415263,
366117,
415270,
144939,
415278,
415281,
415285,
210487,
415290,
415293,
349761,
415300,
333386,
333399,
366172,
333413,
423528,
423532,
210544,
415353,
333439,
415361,
267909,
333498,
210631,
333511,
358099,
153302,
333534,
366307,
366311,
431851,
366318,
210672,
366321,
210695,
268041,
210698,
366348,
210706,
399128,
333594,
210719,
358191,
366387,
399159,
358200,
325440,
366401,
341829,
325446,
46920,
341834,
341838,
341843,
415573,
358234,
341851,
350045,
399199,
259938,
399206,
358255,
399215,
268143,
358259,
341876,
333689,
243579,
325504,
333698,
333708,
333724,
382890,
350146,
333774,
358371,
350189,
350193,
333818,
350202,
350206,
350213,
268298,
350224,
350231,
333850,
350237,
350240,
350244,
350248,
178218,
350251,
350256,
350259,
350271,
243781,
350285,
374864,
342111,
342133,
374902,
432271,
333997,
334011,
260289,
260298,
350410,
350416,
350422,
211160,
350425,
268507,
334045,
350445,
375026,
358644,
350458,
350461,
350464,
350467,
325891,
350475,
375053,
268559,
350480,
432405,
350486,
325914,
350490,
325917,
350493,
350498,
350504,
358700,
350509,
391468,
358704,
358713,
358716,
383306,
334161,
383321,
383330,
383333,
391530,
383341,
334203,
268668,
194941,
391563,
366990,
416157,
342430,
268701,
375208,
326058,
375216,
334262,
334275,
326084,
358856,
195039,
334304,
334311,
375277,
334321,
350723,
186897,
342545,
334358,
342550,
342554,
334363,
350761,
252461,
383536,
358961,
334384,
334394,
252482,
219718,
334407,
334420,
350822,
375400,
334465,
334468,
162445,
326290,
342679,
342683,
260766,
342710,
244409,
260797,
260801,
350917,
154317,
391894,
154328,
416473,
64230,
113388,
342766,
375535,
203506,
342776,
391937,
391948,
326416,
375568,
375571,
375574,
162591,
326441,
326451,
326454,
244540,
326460,
375612,
260924,
326467,
244551,
326473,
326477,
326485,
416597,
342874,
326490,
326502,
375656,
433000,
326507,
326510,
211825,
211831,
351097,
392060,
359295,
351104,
342915,
400259,
236430,
342930,
252822,
392091,
400285,
252836,
359334,
211884,
400306,
351168,
359361,
359366,
326598,
359382,
359388,
383967,
343015,
359407,
261108,
244726,
261111,
383997,
261129,
261147,
359451,
211998,
261153,
261159,
359470,
359476,
343131,
384098,
384101,
367723,
384107,
187502,
384114,
343154,
212094,
351364,
384135,
384139,
384143,
351381,
384160,
384168,
367794,
384181,
367800,
351423,
384191,
326855,
244937,
253130,
343244,
146642,
359649,
343270,
351466,
351479,
343306,
261389,
359694,
384275,
245020,
245029,
171302,
351534,
376110,
245040,
425276,
212291,
384323,
343365,
212303,
367965,
343393,
343398,
367980,
425328,
343409,
154999,
253303,
343417,
327034,
245127,
384397,
245136,
245142,
245145,
343450,
245148,
245151,
245154,
245157,
245162,
327084,
359865,
384443,
146876,
327107,
384453,
327110,
327115,
327117,
359886,
359890,
343507,
368092,
343534,
343539,
368119,
343544,
368122,
409091,
359947,
359955,
359983,
343630,
327275,
245357,
138864,
155254,
155273,
368288,
245409,
425638,
425649,
155322,
425662,
155327,
253943,
155351,
155354,
212699,
155363,
245475,
245483,
155371,
409335,
155393,
155403,
155422,
360223,
155438,
155442,
155447,
155461,
360261,
376663,
155482,
261981,
425822,
155487,
376671,
155490,
155491,
327531,
261996,
376685,
261999,
262002,
327539,
262005,
147317,
425845,
262008,
262011,
155516,
155521,
155525,
360326,
376714,
155531,
262027,
262030,
262033,
262036,
262039,
262042,
155549,
262045,
262048,
262051,
327589,
155559,
155562,
155565,
393150,
393169,
384977,
155611,
155619,
253923,
155621,
253926,
327654,
204784,
393203,
360438,
393206,
393212,
155646
] |
8ce3e32f2116f03b7362e88a6c69da08102e9006 | 8756beedb073770dc51fafe372b6a8bc5735c9b6 | /TodayNews/TodayNews/Classes/Login&Register/Controller/YMFirstIntroduceController.swift | 50e6f06b1ccbcf8f5b159f933f398a7b958e4287 | [
"MIT"
] | permissive | Fxxxxxx/MyTodayNews | f449f29b83a3dfc59b1a0fdb69ea7037b8bb6d7a | 45f0205f3b025c293da619a4a9b6f1c2f6410371 | refs/heads/master | 2020-12-03T16:47:34.461828 | 2016-09-12T09:45:35 | 2016-09-12T09:45:35 | 67,978,172 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,034 | swift | //
// YMFirstIntroduceController.swift
// TodayNews
//
// Created by Fxxx on 16/9/7.
// Copyright © 2016年 Fxxx. All rights reserved.
//
import UIKit
/// ![](http://obna9emby.bkt.clouddn.com/news/%E5%90%AF%E5%8A%A8_spec.png)
class YMFirstIntroduceController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func mobileButtonClick(sender: UIButton) {
}
@IBAction func wechatButtonClick(sender: UIButton) {
}
@IBAction func QQButtonClick(sender: UIButton) {
}
@IBAction func weiboButtonClick(sender: UIButton) {
}
@IBAction func enterButtonClick(sender: UIButton) {
UIApplication.sharedApplication().keyWindow?.rootViewController = YMTabBarController()
}
}
| [
-1
] |
a9d80313a23fcecc289ad7bc67555a1b5c635a9f | 11d94ec91b025646747561063525834e75d81f9e | /TidepoolServiceKit/Extensions/PersistedPumpEvent.swift | b9269974347f73b8dd55a42b6542249722d3870a | [
"BSD-2-Clause"
] | permissive | tidepool-org/TidepoolService | bf97a133e261e91b1e0d8ed978274fab59bb28f6 | c304e20eb2dc01c9e39e379bb14c58ae537de380 | refs/heads/dev | 2023-09-04T19:56:25.976727 | 2023-08-09T18:07:47 | 2023-08-09T18:07:47 | 198,491,037 | 3 | 2 | BSD-2-Clause | 2023-09-08T18:21:02 | 2019-07-23T18:57:12 | Swift | UTF-8 | Swift | false | false | 10,141 | swift | //
// PersistedPumpEvent.swift
// TidepoolServiceKit
//
// Created by Darin Krauss on 1/7/22.
// Copyright © 2022 LoopKit Authors. All rights reserved.
//
import LoopKit
import TidepoolKit
/*
PersistedPumpEvent
Properties:
- date Date .time
- persistedDate Date (N/A - unused)
- dose DoseEntry? -
- type DoseType .type, .subType (embedded suspend/resume)
- startDate Date (N/A - unused by pump event data)
- endDate Date (N/A - unused by pump event data)
- value Double (N/A - unused by pump event data)
- unit DoseUnit (N/A - unused by pump event data)
- deliveredUnits Double? (N/A - unused by pump event data)
- description String? (N/A - unused by pump event data)
- insulinType InsulinType? (N/A - unused by pump event data)
- automatic Bool? .reason["resumed"], .reason["suspended"]
- manuallyEntered Bool (N/A - unused by pump event data)
- syncIdentifier String? (N/A - unused by pump event data)
- scheduledBasalRate HKQuantity? (N/A - unused by pump event data)
- isMutable Bool (N/A - unused by pump event data)
- isUploaded Bool (N/A - unused)
- objectIDURL URL (N/A - unused)
- raw Data? .id, .origin.id, .payload["syncIdentifier"]
- title String? (N/A - unused)
- type PumpEventType? .type, .subType
- automatic Bool? (N/A - unused)
- alarmType PumpAlarmType? .alarmType, .payload["otherAlarmType"]
*/
extension PersistedPumpEvent: IdentifiableDatum {
func data(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
guard let type = type, syncIdentifier != nil else {
return []
}
switch type {
case .alarm:
return dataForAlarm(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .alarmClear:
return dataForAlarmClear(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .prime:
return dataForPrime(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .resume:
return dataForResume(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .rewind:
return dataForRewind(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
case .suspend:
return dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
default:
return []
}
}
private var syncIdentifier: String? { raw?.md5hash } // Actual sync identifier may be human readable and of variable length
var syncIdentifierAsString: String { syncIdentifier! }
private func dataForAlarm(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var data: [TDatum] = []
if dose?.type == .suspend {
data.append(contentsOf: dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
var payload = datumPayload
if let alarmType = alarmType, case .other(let details) = alarmType {
payload["otherAlarmType"] = details
}
var datum = TAlarmDeviceEventDatum(time: date, alarmType: datumAlarmType ?? .other)
let origin = datumOrigin(for: resolvedIdentifier(for: TAlarmDeviceEventDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TAlarmDeviceEventDatum.self),
payload: payload,
origin: origin)
data.append(datum)
if dose?.type == .resume {
data.append(contentsOf: dataForResume(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
return data
}
private func dataForAlarmClear(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
if dose?.type == .suspend {
return dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
} else if dose?.type == .resume {
return dataForResume(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion)
} else {
return []
}
}
private func dataForPrime(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var data: [TDatum] = []
if dose?.type == .suspend {
data.append(contentsOf: dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
var datum = TPrimeDeviceEventDatum(time: date, target: .tubing) // Default to tubing until we have further information
let origin = datumOrigin(for: resolvedIdentifier(for: TPrimeDeviceEventDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TPrimeDeviceEventDatum.self),
payload: datumPayload,
origin: origin)
data.append(datum)
if dose?.type == .resume {
data.append(contentsOf: dataForResume(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
return data
}
private func dataForResume(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
guard let dose = dose else {
return []
}
var reason = TDictionary()
reason["resumed"] = dose.automatic == true ? "automatic" : "manual"
var datum = TStatusDeviceEventDatum(time: datumTime,
name: .resumed,
reason: reason)
let origin = datumOrigin(for: resolvedIdentifier(for: TStatusDeviceEventDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TStatusDeviceEventDatum.self),
payload: datumPayload,
origin: origin)
return [datum]
}
private func dataForRewind(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
var data: [TDatum] = []
if dose?.type == .suspend {
data.append(contentsOf: dataForSuspend(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
var datum = TReservoirChangeDeviceEventDatum(time: date)
let origin = datumOrigin(for: resolvedIdentifier(for: TReservoirChangeDeviceEventDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TReservoirChangeDeviceEventDatum.self),
payload: datumPayload,
origin: origin)
data.append(datum)
if dose?.type == .resume {
data.append(contentsOf: dataForResume(for: userId, hostIdentifier: hostIdentifier, hostVersion: hostVersion))
}
return data
}
private func dataForSuspend(for userId: String, hostIdentifier: String, hostVersion: String) -> [TDatum] {
guard let dose = dose else {
return []
}
var reason = TDictionary()
reason["suspended"] = dose.automatic == true ? "automatic" : "manual"
var datum = TStatusDeviceEventDatum(time: datumTime,
name: .suspended,
reason: reason)
let origin = datumOrigin(for: resolvedIdentifier(for: TStatusDeviceEventDatum.self), hostIdentifier: hostIdentifier, hostVersion: hostVersion)
datum = datum.adornWith(id: datumId(for: userId, type: TStatusDeviceEventDatum.self),
payload: datumPayload,
origin: origin)
return [datum]
}
private var datumTime: Date { dose?.startDate ?? date }
private var datumAlarmType: TAlarmDeviceEventDatum.AlarmType? { alarmType?.datum ?? .other }
private var datumPayload: TDictionary {
var dictionary = TDictionary()
dictionary["syncIdentifier"] = syncIdentifier
return dictionary
}
}
fileprivate extension PumpAlarmType {
var datum: TAlarmDeviceEventDatum.AlarmType {
switch self {
case .autoOff:
return .autoOff
case .lowInsulin:
return .lowInsulin
case .lowPower:
return .lowPower
case .noDelivery:
return .noDelivery
case .noInsulin:
return .noInsulin
case .noPower:
return .noPower
case .occlusion:
return .occlusion
case .other:
return .other
}
}
}
extension TAlarmDeviceEventDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.deviceEvent.rawValue)/\(TDeviceEventDatum.SubType.alarm.rawValue)" }
}
extension TPrimeDeviceEventDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.deviceEvent.rawValue)/\(TDeviceEventDatum.SubType.prime.rawValue)" }
}
extension TReservoirChangeDeviceEventDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.deviceEvent.rawValue)/\(TDeviceEventDatum.SubType.reservoirChange.rawValue)" }
}
extension TStatusDeviceEventDatum: TypedDatum {
static var resolvedType: String { "\(TDatum.DatumType.deviceEvent.rawValue)/\(TDeviceEventDatum.SubType.status.rawValue)" }
}
| [
-1
] |
45f900eb74659c9010fc4bed9a8b7de49eabd198 | 05d07fdc317f7124e45fea9584cc97b26b37b025 | /NewShinple/Video_Detail/VideoDetailViewController.swift | 631a0de3e81f91b127291c8ee8e8953efbfe3e81 | [] | no_license | heabin/fake | 63d0824bb1e17fea52aa1d4ff9d395a89800c117 | f5b234b3e270da8cb4313ce5376524dc3340d7d7 | refs/heads/master | 2020-07-21T01:07:35.027634 | 2019-09-06T07:17:28 | 2019-09-06T07:17:28 | 206,735,313 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 17,724 | swift | //
// VideoDetailViewController.swift
// NewShinple
//
// Created by user on 30/08/2019.
// Copyright © 2019 veronica. All rights reserved.
//
import UIKit
import AVFoundation
import AWSDynamoDB
class VideoDetailViewController: UIViewController {
// 강의 url
let urlString = "https://shinpleios.s3.us-east-2.amazonaws.com/Culture/Cook/video/Chap1.mp4"
// videoView 의 위치를 잡아주기 위한 것들
@IBOutlet weak var LargeView: UIView!
@IBOutlet weak var SmallView: UIView!
@IBOutlet weak var videoView: UIView!
@IBOutlet weak var containerView: UIView!
// 미디어컨트롤
@IBOutlet weak var btnGoBack: UIButton!
@IBOutlet weak var btnBookmark: UIButton!
@IBOutlet weak var btnRewind: UIButton!
@IBOutlet weak var btnPlayPause: UIButton!
@IBOutlet weak var btnForward: UIButton!
@IBOutlet weak var lblCurrentTime: UILabel!
@IBOutlet weak var lblVideoLength: UILabel!
@IBOutlet weak var btnFullScreen: UIButton!
@IBOutlet weak var videoSlider: UISlider!
// 미디어 제어 관련 변수
var isPlaying:Bool = false
var isControlOn: Bool = true
var isBookmarked: Bool = false
var isFullScreen: Bool = false
let layer = CALayer()
var player: AVPlayer?
var playerLayer = AVPlayerLayer()
// 로딩화면
let activityIndicatorView: UIActivityIndicatorView = {
print("로딩중-----")
let aiv = UIActivityIndicatorView(style: .whiteLarge)
aiv.translatesAutoresizingMaskIntoConstraints = false
aiv.startAnimating()
return aiv
}()
// 평가관련
@IBOutlet weak var EvaluationView: UIView!
@IBOutlet weak var btnBad: UIButton!
@IBOutlet weak var btnNormal: UIButton!
@IBOutlet weak var btnGood: UIButton!
@IBOutlet weak var TabContainerView: UIView!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let containerVC = segue.destination as! VideoDetailTabViewController
if segue.identifier == "containerViewSegue"{
//containerVC.lecture = Any
}
}
override func viewDidLoad() {
super.viewDidLoad()
//print("========어디보자==========\(LectureDetail)=================")
//self.dbGetLectureDetail(lecture: LectureDetail, employeeNum:1100012)
print("videoDetailView viewDidLoad")
// 그냥 작은 화면일때 기준이 되는 뷰를 한개 더 만들었음
//SmallView.isHidden = true
// 시작시 위치 잡아주기
videoView.translatesAutoresizingMaskIntoConstraints = false
videoView.leadingAnchor.constraint(equalTo: SmallView.leadingAnchor).isActive = true
videoView.topAnchor.constraint(equalTo: SmallView.topAnchor).isActive = true
videoView.trailingAnchor.constraint(equalTo: SmallView.trailingAnchor).isActive = true
videoView.bottomAnchor.constraint(equalTo: SmallView.bottomAnchor).isActive = true
// 비디오 불러오기
setupPlayerView()
// 라이브러리 설정
settingLibrary()
controlOnOff()
// 뷰를 터치했을때
let gesture = UITapGestureRecognizer(target: self, action: Selector(("someAction:")))
self.videoView.addGestureRecognizer(gesture)
SmallView.backgroundColor = .black
LargeView.backgroundColor = .black
}
override func viewWillDisappear(_ animated: Bool) {
print("화면꺼질때")
let duration = player?.currentItem?.duration
let totalSeconds = CMTimeGetSeconds(duration!)
print("전체시간 : \(totalSeconds)")
let current = videoSlider.value
print("현재시간 : \(current)")
let temp: Float = Float(current) / Float(totalSeconds) * 100
let percent: Int = Int(temp)
print("진행률 : \(percent)")
}
// 동영상 불러오기
private func setupPlayerView(){
if let url = NSURL(string: "https://shinpleios.s3.us-east-2.amazonaws.com/Duty/Info/video/Chap2.mp4"){
player = AVPlayer(url: url as URL)
playerLayer = AVPlayerLayer(player: player)
playerLayer.name = "videoPlayerLayer"
videoView.layer.addSublayer(playerLayer)
playerLayer.frame = videoView.layer.bounds
//CGRect(x: 0, y: 0, width: videoView.frame.width, height: videoView.frame.height)
player?.pause()
isPlaying = false
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil)
// 현재재생시간
let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
let mainQueue = DispatchQueue.main
_ = player?.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue, using: {[weak self]
time in
guard let currentItem = self?.player?.currentItem else {return}
self?.videoSlider.maximumValue = Float(currentItem.duration.seconds)
self?.videoSlider.minimumValue = 0
self?.videoSlider.value = Float(currentItem.currentTime().seconds)
self?.lblCurrentTime.text = self?.getTimeString(from: currentItem.currentTime())
})
}
}
// 레이아웃 설정
func settingLibrary(){
print("*라이브러리 설정시작 >> ", separator: "", terminator: " ")
// 로딩표시
videoView.addSubview(activityIndicatorView)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.centerXAnchor.constraint(equalTo: videoView.centerXAnchor).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: videoView.centerYAnchor).isActive = true
// 이미지, 색 설정
btnGoBack.translatesAutoresizingMaskIntoConstraints = false
btnGoBack.setImage(UIImage(named: "icons8-expand-arrow-90"), for: .normal)
btnGoBack.tintColor = .white
btnBookmark.translatesAutoresizingMaskIntoConstraints = false
btnBookmark.setImage(UIImage(named: "heart_empty"), for: .normal)
btnBookmark.tintColor = .white
btnRewind.translatesAutoresizingMaskIntoConstraints = false
btnRewind.setImage(UIImage(named: "icons8-replay-10-100"), for: .normal)
btnRewind.tintColor = .white
btnPlayPause.translatesAutoresizingMaskIntoConstraints = false
btnPlayPause.setImage(UIImage(named: "icons8-play-100"), for: .normal)
btnPlayPause.tintColor = .white
btnForward.translatesAutoresizingMaskIntoConstraints = false
btnForward.setImage(UIImage(named: "icons8-forward-10-100"), for: .normal)
btnForward.tintColor = .white
btnFullScreen.translatesAutoresizingMaskIntoConstraints = false
btnFullScreen.setImage(UIImage(named: "icons8-full-screen-90"), for: .normal)
btnFullScreen.tintColor = .white
// videoSlider.translatesAutoresizingMaskIntoConstraints = false
// videoSlider.setThumbImage(UIImage(named: "thumb_circle"), for: .normal)
btnBad.setImage(UIImage(named: "bad_empty"), for: .normal)
btnBad.tintColor = .white
btnNormal.setImage(UIImage(named: "normal_empty"), for: .normal)
btnNormal.tintColor = .white
btnGood.setImage(UIImage(named: "good_empty"), for: .normal)
btnGood.tintColor = .white
EvaluationView.isHidden = true
print("설정끝*")
}
// MARK: - 함수
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "currentItem.loadedTimeRanges" {
// 동영상 로딩완료
activityIndicatorView.stopAnimating()
activityIndicatorView.isHidden = true
videoView.backgroundColor = .clear
isControlOn = false
controlOnOff()
if let duration = player?.currentItem?.duration {
let secondsText = getTimeString(from: duration)
lblVideoLength.text = secondsText
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
print("가로모드")
videoView.translatesAutoresizingMaskIntoConstraints = false
videoView.leadingAnchor.constraint(equalTo: LargeView.leadingAnchor).isActive = true
videoView.trailingAnchor.constraint(equalTo: LargeView.trailingAnchor).isActive = true
videoView.topAnchor.constraint(equalTo: LargeView.topAnchor).isActive = true
btnFullScreen.setImage(UIImage(named: "icons8-normal-screen-90"), for: .normal)
TabContainerView.isHidden = true
self.view.backgroundColor = .black
} else {
print("세로모드")
videoView.translatesAutoresizingMaskIntoConstraints = false
videoView.leadingAnchor.constraint(equalTo: SmallView.leadingAnchor).isActive = true
videoView.trailingAnchor.constraint(equalTo: SmallView.trailingAnchor).isActive = true
videoView.topAnchor.constraint(equalTo: SmallView.topAnchor).isActive = true
btnFullScreen.setImage(UIImage(named: "icons8-full-screen-90"), for: .normal)
TabContainerView.isHidden = false
self.view.backgroundColor = .white
}
}
@objc func someAction(_ sender:UITapGestureRecognizer){
// do other task
print("화면 터치")
controlOnOff()
}
func controlOnOff(){
if isControlOn {
print("컨트롤 끄기")
btnGoBack.isHidden = true
btnBookmark.isHidden = true
btnRewind.isHidden = true
btnPlayPause.isHidden = true
btnForward.isHidden = true
lblCurrentTime.isHidden = true
lblVideoLength.isHidden = true
btnFullScreen.isHidden = true
videoSlider.isHidden = true
if let sublayers = videoView.layer.sublayers {
for layer in sublayers {
if layer.name == "gradientLayer" {
layer.removeFromSuperlayer()
break
}
}
}
}else {
print("컨트롤 켜기")
layer.frame = videoView.layer.bounds
layer.backgroundColor = UIColor.black.cgColor
layer.opacity = 0.5
layer.name = "gradientLayer"
videoView.layer.addSublayer(layer)
btnGoBack.isHidden = false
btnBookmark.isHidden = false
btnRewind.isHidden = false
btnPlayPause.isHidden = false
btnForward.isHidden = false
lblCurrentTime.isHidden = false
lblVideoLength.isHidden = false
btnFullScreen.isHidden = false
videoSlider.isHidden = false
// 제일위로
btnGoBack.layer.zPosition = 1
btnBookmark.layer.zPosition = 1
btnRewind.layer.zPosition = 1
btnPlayPause.layer.zPosition = 1
btnForward.layer.zPosition = 1
lblCurrentTime.layer.zPosition = 1
lblVideoLength.layer.zPosition = 1
btnFullScreen.layer.zPosition = 1
videoSlider.layer.zPosition = 1
}
isControlOn = !isControlOn
}
// MARK: - 액션
@IBAction func GoPrevPage(_ sender: UIButton) {
print("이전페이지로")
self.dismiss(animated: true)
}
@IBAction func Bookmark(_ sender: UIButton) {
if isBookmarked {
print("북마크 삭제")
btnBookmark.setImage(UIImage(named: "heart_empty"), for: .normal)
}else {
print("북마크 추가")
btnBookmark.setImage(UIImage(named: "heart_fill"), for: .normal)
}
isBookmarked = !isBookmarked
}
@IBAction func Rewind10sec(_ sender: UIButton) {
print("뒤로 10초")
var newTime = videoSlider.value - 10.0
if newTime < 0 {
newTime = 0
}
player?.seek(to: CMTimeMake(value: Int64(newTime), timescale: 1))
videoView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
@IBAction func PlayPause(_ sender: UIButton) {
print("처음 재생 누름 \(isPlaying)")
if isPlaying {
player?.pause()
btnPlayPause.setImage(UIImage(named: "icons8-play-100"), for: .normal)
} else {
player?.play()
btnPlayPause.setImage(UIImage(named: "icons8-pause-100"), for: .normal)
}
isPlaying = !isPlaying
}
@IBAction func Forward10sec(_ sender: UIButton) {
print("앞으로 10초")
var newTime = videoSlider.value + 10.0
if newTime > videoSlider.maximumValue {
newTime = videoSlider.maximumValue
}
player?.seek(to: CMTimeMake(value: Int64(newTime), timescale: 1))
}
@IBAction func FullScreen(_ sender: UIButton) {
// videoView.translatesAutoresizingMaskIntoConstraints = false
// videoView.frame = SmallView.bounds
// var t = CGAffineTransform.identity
// t = t.translatedBy(x: 100, y: 0) // 세로형으로 보는 그대로 x,y
// t = t.translatedBy(x: 0, y: 0)
// t = t.rotated(by: .pi / 2)
// t = t.scaledBy(x: 1.5, y: 1.5)
//
// videoView.transform = t
//
// videoView.translatesAutoresizingMaskIntoConstraints = false
// videoView.leadingAnchor.constraint(equalTo: LargeView.leadingAnchor).isActive = true
// videoView.trailingAnchor.constraint(equalTo: LargeView.trailingAnchor).isActive = true
// videoView.topAnchor.constraint(equalTo: LargeView.topAnchor, constant: 10).isActive = true
if isFullScreen {
print("화면 최소 버튼 누르기")
btnFullScreen.setImage(UIImage(named: "icons8-full-screen-90"), for: .normal)
} else {
print("전체화면 버튼 누르기")
btnFullScreen.setImage(UIImage(named: "icons8-normal-screen-90"), for: .normal)
}
isFullScreen = !isFullScreen
}
@IBAction func SliderValueChanged(_ sender: UISlider) {
player?.seek(to: CMTimeMake(value: Int64(sender.value*1000), timescale: 1000))
}
// 영상 종료 완료 수강 완료
@objc func playerDidFinishPlaying(note: NSNotification) {
print("강의끝********")
EvaluationView.isHidden = false
EvaluationView.layer.zPosition = 1
}
@IBAction func BadEvaluation(_ sender: UIButton) {
print("강의 별로에요")
btnBad.setImage(UIImage(named: "bad_fill"), for: .normal)
btnBad.tintColor = .white
btnNormal.isEnabled = false
btnGood.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
self.closeEvaluation()
})
}
@IBAction func NormalEvaluation(_ sender: UIButton) {
print("강의 보통이에요")
btnNormal.setImage(UIImage(named: "normal_fill"), for: .normal)
btnNormal.tintColor = .white
btnBad.isEnabled = false
btnGood.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
self.closeEvaluation()
})
}
@IBAction func GoodEvaluation(_ sender: UIButton) {
print("강의 최고에요")
btnGood.setImage(UIImage(named: "good_fill"), for: .normal)
btnGood.tintColor = .white
btnBad.isEnabled = false
btnNormal.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
self.closeEvaluation()
})
}
func closeEvaluation(){
EvaluationView.isHidden = true
}
// MARK: - 기타함수
// 시간 포멧
func getTimeString(from time: CMTime) -> String {
let totalSeconds = CMTimeGetSeconds(time)
let hours = Int(totalSeconds / 3600 )
let minutes = Int(totalSeconds/60) % 60
let seconds = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
if hours > 0 {
return String(format: "%i:%02i:%02i", arguments: [hours, minutes, seconds])
}else{
return String(format: "%02i:%02i", arguments: [minutes, seconds])
}
}
// 레이어의 사이즈를 비디오뷰에 맞춘다
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
layer.frame = videoView.bounds
playerLayer.frame = videoView.bounds
// gradientLayer.frame = videoView.bounds
}
}
| [
-1
] |
758272c129d897067190c20aef6a900c7f828cb3 | dc941f54751019911326655c9e3a47f2930493b8 | /03-PlayLocalVideo/03-PlayLocalVideo/AppDelegate.swift | 632ef623bab195f5989a7c77b8e481e0cde2bfdc | [] | no_license | yanmingLiu/30App | 635055f7f21cfc09ff97c14e01a3f3178b6100c8 | 1f85766c2a2be338cf5a0c0e9782705286ceee1e | refs/heads/main | 2023-04-02T14:43:09.574761 | 2021-04-08T08:30:46 | 2021-04-08T08:30:46 | 355,820,910 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,348 | swift | //
// AppDelegate.swift
// 03-PlayLocalVideo
//
// Created by lym on 2021/4/1.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
393230,
393250,
344102,
393261,
393266,
213048,
385081,
376889,
393275,
376905,
254030,
286800,
368727,
180313,
368735,
180320,
376931,
286831,
368752,
286844,
417924,
262283,
286879,
286888,
377012,
164028,
327871,
180416,
377036,
180431,
377046,
418007,
418010,
377060,
327914,
205036,
393456,
393460,
418043,
336123,
385280,
336128,
262404,
180490,
164106,
368911,
262416,
262422,
377117,
262436,
336180,
262454,
393538,
262472,
344403,
213332,
65880,
262496,
418144,
262499,
213352,
246123,
262507,
262510,
213372,
385419,
393612,
262550,
262552,
385440,
385443,
262566,
385451,
262573,
393647,
385458,
262586,
344511,
262592,
360916,
369118,
328177,
328179,
328182,
328189,
328192,
164361,
410128,
393747,
254490,
188958,
385570,
33316,
377383,
197159,
352821,
197177,
418363,
188987,
369223,
385609,
385616,
352864,
369253,
262760,
352874,
352887,
254587,
377472,
148105,
377484,
352918,
98968,
344744,
361129,
336555,
385713,
434867,
164534,
336567,
328378,
164538,
328386,
352968,
344776,
352971,
418507,
352973,
385742,
385748,
361179,
189153,
369381,
361195,
418553,
344831,
336643,
344835,
344841,
361230,
336659,
418580,
418585,
434970,
369435,
418589,
262942,
418593,
336675,
328484,
418598,
418605,
336696,
361273,
328515,
336708,
328519,
361288,
336711,
328522,
336714,
426841,
254812,
361309,
197468,
361315,
361322,
328573,
377729,
369542,
361360,
222128,
345035,
386003,
345043,
386011,
386018,
386022,
435187,
328702,
328714,
361489,
386069,
386073,
336921,
336925,
345118,
377887,
345133,
345138,
386101,
361536,
189520,
345169,
156761,
361567,
148578,
345199,
386167,
361593,
410745,
361598,
214149,
345222,
386186,
337047,
345246,
214175,
337071,
337075,
345267,
386258,
328924,
66782,
222437,
386285,
328941,
386291,
345376,
353570,
345379,
410917,
345382,
337205,
345399,
378169,
369978,
337222,
337229,
337234,
263508,
402791,
345448,
271730,
378227,
271745,
181638,
353673,
181643,
181649,
181654,
230809,
181670,
181673,
181678,
181681,
337329,
181684,
181690,
361917,
181696,
337349,
181703,
337365,
271839,
329191,
361960,
329194,
116210,
337398,
337415,
329226,
419339,
419343,
419349,
345625,
419355,
370205,
419359,
394786,
419362,
370213,
419368,
419376,
206395,
214593,
419400,
419402,
353867,
419406,
419410,
394853,
345701,
222830,
370297,
403070,
353919,
403075,
345736,
198280,
403091,
345749,
419483,
345757,
345762,
419491,
345765,
419497,
419501,
370350,
419506,
419509,
419512,
337592,
419517,
337599,
419527,
419530,
419535,
272081,
419542,
394966,
419544,
181977,
345818,
419547,
419550,
419559,
337642,
419563,
337645,
370415,
337659,
337668,
362247,
395021,
362255,
116509,
345887,
378663,
345905,
354106,
354111,
247617,
354117,
370503,
329544,
345930,
370509,
354130,
247637,
337750,
370519,
313180,
354142,
354150,
354156,
345964,
345967,
345970,
345974,
403320,
354172,
247691,
337808,
247700,
329623,
436126,
436132,
337833,
362413,
337844,
346057,
247759,
346063,
329697,
354277,
190439,
247789,
354313,
346139,
436289,
378954,
395339,
338004,
100453,
329832,
329855,
329867,
329885,
346272,
362660,
100524,
387249,
379066,
387260,
256191,
395466,
346316,
411861,
411864,
411868,
411873,
379107,
411876,
387301,
346343,
338152,
387306,
387312,
346355,
436473,
321786,
379134,
411903,
411916,
379152,
395538,
387349,
338199,
387352,
182558,
338211,
248111,
362822,
436555,
190796,
379233,
354673,
321910,
248186,
420236,
379278,
272786,
354727,
338352,
330189,
338381,
338386,
256472,
338403,
338409,
248308,
199164,
330252,
199186,
420376,
330267,
354855,
10828,
199249,
346721,
174695,
248425,
191084,
338543,
191092,
346742,
330383,
354974,
150183,
174774,
248504,
174777,
223934,
355024,
273108,
355028,
264918,
183005,
256734,
436962,
338660,
338664,
264941,
363251,
207619,
264964,
338700,
256786,
199452,
363293,
396066,
346916,
396069,
215853,
355122,
355131,
355140,
355143,
338763,
355150,
330580,
355166,
265055,
265058,
355175,
387944,
355179,
330610,
330642,
355218,
412599,
207808,
379848,
396245,
330710,
248792,
248798,
347105,
257008,
183282,
265207,
330748,
265214,
330760,
330768,
248862,
396328,
347176,
158761,
199728,
396336,
330800,
396339,
339001,
388154,
388161,
347205,
248904,
330826,
248914,
412764,
339036,
257120,
265320,
248951,
420984,
330889,
347287,
248985,
339097,
44197,
380070,
339112,
249014,
126144,
330958,
330965,
265432,
265436,
388319,
388347,
175375,
159005,
175396,
208166,
273708,
347437,
372015,
347441,
372018,
199988,
44342,
175415,
396600,
437566,
175423,
437570,
437575,
437583,
331088,
437587,
331093,
396633,
175450,
437595,
175457,
208227,
175460,
175463,
265580,
437620,
175477,
249208,
175483,
175486,
249214,
175489,
249218,
249224,
249227,
249234,
175513,
175516,
396705,
175522,
355748,
380332,
396722,
208311,
388542,
372163,
216517,
380360,
216522,
339404,
372176,
208337,
339412,
413141,
339417,
339420,
249308,
339424,
249312,
339428,
339434,
249328,
69113,
372228,
208398,
380432,
175635,
265778,
265795,
396872,
265805,
224853,
224857,
257633,
224870,
372327,
257646,
372337,
224884,
224887,
224890,
224894,
224897,
372353,
216707,
126596,
421508,
224904,
11918,
159374,
224913,
126610,
339601,
224916,
224919,
126616,
224922,
208538,
224926,
224929,
224932,
224936,
257704,
224942,
257712,
224947,
257716,
257720,
257724,
224959,
257732,
224965,
224969,
339662,
224975,
257747,
224981,
224986,
257761,
224993,
257764,
224999,
339695,
225012,
257787,
225020,
339710,
257790,
225025,
257794,
339721,
257801,
257804,
225038,
257807,
225043,
372499,
167700,
225048,
257819,
225053,
184094,
225058,
257833,
225066,
257836,
413484,
225070,
225073,
372532,
257845,
225079,
397112,
225082,
397115,
225087,
225092,
225096,
323402,
257868,
225103,
257871,
397139,
225108,
225112,
257883,
257886,
225119,
257890,
339814,
225127,
274280,
257896,
257901,
225137,
257908,
225141,
257912,
225148,
257916,
257920,
225155,
339844,
225165,
397200,
225170,
380822,
225175,
225180,
118691,
184244,
372664,
372702,
372706,
356335,
380918,
372738,
405533,
430129,
266294,
266297,
421960,
356439,
430180,
421990,
266350,
356466,
266362,
381068,
225423,
250002,
250004,
225429,
356506,
225437,
135327,
225441,
438433,
225444,
438436,
225447,
438440,
225450,
258222,
225455,
430256,
225458,
225461,
225466,
389307,
225470,
381120,
372929,
430274,
225475,
389320,
225484,
225487,
225490,
225493,
266453,
225496,
225499,
225502,
225505,
356578,
225510,
217318,
225514,
225518,
372976,
381176,
397571,
389380,
61722,
356637,
356640,
356643,
356646,
266536,
356649,
356655,
332080,
340275,
356660,
397622,
332090,
225597,
332097,
201028,
348488,
332106,
332117,
348502,
250199,
250202,
332125,
250210,
348522,
348525,
348527,
332152,
389502,
250238,
332161,
356740,
332172,
373145,
340379,
389550,
324030,
266687,
160234,
127471,
340472,
381436,
324094,
266754,
324111,
340500,
381481,
356907,
324142,
356916,
324149,
324155,
348733,
324164,
356934,
348743,
381512,
324173,
324176,
389723,
332380,
373343,
381545,
340627,
373398,
184982,
258721,
332453,
332459,
389805,
332463,
381617,
332471,
332483,
332486,
373449,
332493,
357069,
357073,
332511,
332520,
340718,
332533,
348924,
389892,
373510,
389926,
348978,
152370,
340789,
348982,
398139,
127814,
357201,
357206,
389978,
430939,
357211,
357214,
201579,
201582,
349040,
340849,
201588,
430965,
381813,
324472,
398201,
340858,
324475,
430972,
340861,
324478,
119674,
324481,
373634,
398211,
324484,
324487,
381833,
324492,
324495,
324498,
430995,
324501,
324510,
422816,
324513,
398245,
201637,
324524,
340909,
324533,
324538,
324541,
398279,
340939,
340941,
209873,
340957,
431072,
398306,
340963,
209895,
201711,
349172,
381946,
349180,
439294,
431106,
209943,
357410,
250914,
185380,
357418,
209965,
209968,
209971,
209975,
209979,
209987,
209990,
209995,
341071,
349267,
250967,
210010,
341091,
210025,
210027,
210030,
210036,
210039,
349308,
210044,
349311,
160895,
152703,
210052,
349319,
210055,
218247,
210067,
210071,
210077,
210080,
251044,
210084,
185511,
210088,
210095,
210098,
210107,
210115,
332997,
210127,
333009,
210131,
333014,
210138,
210143,
218354,
218360,
251128,
275706,
275712,
275715,
275721,
349459,
333078,
251160,
349484,
349491,
251189,
415033,
251210,
357708,
210260,
365911,
259421,
365921,
333154,
251235,
374117,
333162,
234866,
390516,
333175,
357755,
136590,
374160,
112020,
349590,
357792,
259515,
415166,
415185,
366034,
366038,
415191,
415193,
415196,
415199,
423392,
333284,
415207,
366056,
366061,
415216,
210420,
415224,
423423,
415257,
415263,
366117,
415270,
144939,
415278,
415281,
415285,
210487,
415290,
415293,
349761,
415300,
333386,
366172,
333413,
423528,
423532,
210544,
415353,
333439,
415361,
267909,
153227,
333498,
210631,
333511,
259788,
358099,
153302,
333534,
366307,
366311,
431851,
366318,
210672,
366321,
366325,
210695,
268041,
210698,
366348,
210706,
399128,
210719,
358191,
366387,
210739,
399159,
358200,
325440,
366401,
341829,
325446,
46920,
341834,
341838,
341843,
415573,
358234,
341851,
350045,
399199,
259938,
399206,
268143,
358255,
399215,
358259,
341876,
333689,
243579,
325504,
333698,
333708,
333724,
382890,
350146,
333774,
358371,
350189,
350193,
350202,
350206,
350213,
268298,
350224,
350231,
333850,
350237,
350240,
350244,
350248,
178218,
350251,
350256,
350259,
350271,
243781,
350285,
374864,
342111,
374902,
432271,
334011,
260289,
260298,
350410,
350416,
350422,
211160,
350425,
268507,
334045,
350445,
375026,
358644,
350458,
350461,
350464,
325891,
350467,
350475,
375053,
268559,
350480,
432405,
350486,
325914,
350490,
325917,
350493,
325919,
350498,
194852,
350504,
358700,
391468,
350509,
358704,
358713,
358716,
383306,
334161,
383321,
383330,
383333,
391530,
383341,
334203,
268668,
194941,
391563,
366990,
416157,
342430,
268701,
375208,
375216,
334262,
334275,
326084,
358856,
195039,
334304,
334311,
375277,
334321,
350723,
391690,
186897,
334358,
342550,
342554,
334363,
358941,
350761,
252461,
334384,
383536,
358961,
334394,
252482,
219718,
334407,
334420,
350822,
375400,
334465,
334468,
162445,
326290,
342679,
342683,
260766,
342710,
244409,
260797,
260801,
350917,
391894,
154328,
416473,
64230,
342766,
375535,
203506,
342776,
391937,
391948,
375568,
326416,
375571,
375574,
162591,
326441,
383793,
326451,
326454,
326460,
260924,
375612,
244540,
326467,
244551,
326473,
326477,
326485,
416597,
326490,
342874,
326502,
375656,
433000,
326507,
326510,
211825,
211831,
351097,
392060,
359295,
351104,
342915,
400259,
236430,
342930,
252822,
392091,
400285,
252836,
359334,
211884,
400306,
351168,
359361,
326598,
359366,
359382,
359388,
383967,
343015,
359407,
261108,
244726,
261111,
383997,
261129,
359451,
261147,
211998,
261153,
261159,
359470,
359476,
343131,
384098,
384101,
384107,
367723,
187502,
343154,
384114,
212094,
351364,
384135,
384139,
384143,
351381,
384160,
384168,
367794,
384181,
367800,
384191,
351423,
384198,
326855,
244937,
253130,
343244,
146642,
359649,
343270,
351466,
351479,
384249,
343306,
261389,
359694,
384269,
253200,
261393,
384275,
245020,
245029,
171302,
351534,
376110,
245040,
384314,
425276,
384323,
212291,
343365,
212303,
367965,
343393,
343398,
367980,
425328,
343409,
253303,
154999,
343417,
327034,
245127,
384397,
245136,
245142,
245145,
343450,
245148,
245151,
245154,
245157,
245162,
327084,
359865,
384443,
146876,
327107,
384453,
327110,
327115,
327117,
359886,
359890,
343507,
368092,
343534,
343539,
368119,
343544,
368122,
409091,
359947,
359955,
359983,
343630,
179802,
155239,
327275,
245357,
138864,
155254,
155273,
368288,
245409,
425638,
425649,
155322,
425662,
155327,
155351,
155354,
212699,
155363,
245475,
155371,
245483,
409335,
155393,
155403,
155422,
360223,
155438,
155442,
155447,
417595,
155461,
360261,
376663,
155482,
261981,
425822,
155487,
376671,
155490,
155491,
327531,
261996,
376685,
261999,
262002,
327539,
262005,
147317,
425845,
262008,
262011,
155516,
155521,
155525,
360326,
376714,
155531,
262027,
262030,
262033,
262036,
262039,
262042,
155549,
262045,
262048,
262051,
327589,
155559,
155562,
155565,
393150,
393169,
384977,
155611,
155619,
253923,
155621,
253926,
204784,
393203,
360438,
253943,
393206,
393212,
155646
] |
4f55445ee087dbd7330f37ea31077c6ff2263bb4 | d4723116651c0ee1172abe1454b1564bbef9259f | /Package.swift | 664089fb59350d450581e8a1dbbd79e7934c28e3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | aserdobintsev/credit-card-scanner | 3989d66c444110464530fe48c00548cddc3cc720 | 481037a26e17bdf79689529bd058af875d2dbae0 | refs/heads/main | 2023-02-18T06:35:23.154793 | 2021-01-14T11:40:03 | 2021-01-14T11:40:03 | 329,585,829 | 0 | 0 | NOASSERTION | 2021-01-14T11:40:04 | 2021-01-14T10:49:37 | null | UTF-8 | Swift | false | false | 623 | swift | // swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "CreditCardScanner",
platforms: [.iOS(.v10)],
products: [
.library(
name: "CreditCardScanner",
targets: ["CreditCardScanner"]
),
],
dependencies: [
.package(url: "https://github.com/yhkaplan/Reg.git", from: "0.3.0")
],
targets: [
.target(
name: "CreditCardScanner",
dependencies: ["Reg"]
),
.testTarget(
name: "CreditCardScannerTests",
dependencies: ["CreditCardScanner"]
),
]
)
| [
-1
] |
49722cc4a4ee2c88bfa518bfc83955d0682a2ab4 | 9d45468cc46befb150ba2af648c575c7f5bcd986 | /Rescue_the_mouse/GameMode/ItemView.swift | ce8da9188409ee84b8d158a1f61eb1a7513392cd | [] | no_license | yamanyooo/Rescue_the_mouse | e85cc806e5953bc00bfe111cdfd6381167470adb | db34be81aebe297d174bf464ef8321a1d6f851d7 | refs/heads/master | 2020-03-26T07:45:21.908866 | 2019-07-14T09:03:40 | 2019-07-14T09:03:40 | 144,669,387 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,780 | swift | //
// ItemView.swift
// NH_Takashi
//
// Created by yohei on 2016/10/30.
// Copyright © 2016年 yohei. All rights reserved.
//
import Foundation
import UIKit
protocol TapImgDelegate{
func tapImgEvent(item: ItemView)
}
class ItemView: UIView{
var itemCnt: Int = 0{
didSet{
self.text.text = "×" + self.itemCnt.description
}
}
var text: UILabel = UILabel()
var iconImg: UIImageView = UIImageView()
var touchImg: Bool = false{
didSet{
self.setItemImg()
}
}
var itemSelect: Bool = false{
didSet{
self.setItemImg()
}
}
var itemID: Int = -1
var img: UIImage = UIImage()
var delegate: TapImgDelegate?
init(frame: CGRect, id: Int, itemNum: Int) {
super.init(frame: frame)
itemID = id
self.setItemImg()
self.itemCnt = itemNum
let ratioMargin: CGFloat = 1
let ratioIconWidth: CGFloat = 16
let ratioIconHeight: CGFloat = 14
let ratioTextHeight: CGFloat = 6
let ratioWidthSum: CGFloat = ratioMargin * 2 + ratioIconWidth
let ratioHeightSum: CGFloat = ratioMargin * 2 + ratioIconHeight + ratioTextHeight
let iconSizeWidth = self.frame.width * ratioIconWidth / ratioWidthSum
let iconSizeHeight = self.frame.height * ratioIconHeight / ratioHeightSum
let widthNm = iconSizeWidth / img.size.width
let heightNm = iconSizeHeight / img.size.height
let scale: CGFloat = widthNm < heightNm ? widthNm : heightNm
let resultIconSizeWidth = floor(img.size.width * scale)
let resultIconSizeHeight = floor(img.size.height * scale)
let resultTextHeight = floor(resultIconSizeWidth * ratioTextHeight / ratioIconHeight)
let resultMarginWidth = floor((self.frame.width - resultIconSizeWidth) / 2)
let resultMarginHeight = floor((self.frame.height - resultIconSizeHeight - resultTextHeight) / 2)
self.iconImg.frame = CGRect(x: resultMarginWidth, y: resultMarginHeight, width: resultIconSizeWidth, height: resultIconSizeHeight)
iconImg.image = img
self.addSubview(iconImg)
text.frame = CGRect(x: resultMarginWidth, y: resultMarginHeight + resultIconSizeHeight, width: resultIconSizeWidth, height: resultTextHeight )
text.textAlignment = NSTextAlignment.right
text.font = UIFont.systemFont(ofSize: resultTextHeight)
text.font = UIFont.boldSystemFont(ofSize: resultTextHeight)
text.textColor = UIColor.black
text.text = "×" + itemCnt.description
self.addSubview(text)
}
required init(coder aDecoder: NSCoder) {
fatalError("init error")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var tapLocation: CGPoint
let touch = touches.first
tapLocation = touch!.location(in: self)
if(true == self.iconImg.frame.contains(tapLocation)){
touchImg = true
}else{
// NONE
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
var tapLocation: CGPoint
let touch = touches.first
tapLocation = touch!.location(in: self)
if(false == self.iconImg.frame.contains(tapLocation)){
touchImg = false
}else{
// NONE
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
var tapLocation: CGPoint
let touch = touches.first
tapLocation = touch!.location(in: self)
if((true == self.iconImg.frame.contains(tapLocation))
&& (true == touchImg)){
self.delegate?.tapImgEvent(item: self)
}else{
// NONE
}
touchImg = false
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
touchImg = false
}
func setItemImg(){
var fileName: String
let fileImg: UIImage
if(true == self.itemSelect){
fileName = (true == touchImg) ? itemData[itemID].itemImgActiveTap : itemData[itemID].itemImgActive
}else{
fileName = (true == touchImg) ? itemData[itemID].itemImgInactiveTap : itemData[itemID].itemImgInactive
}
fileImg = UIImage(named: fileName)!
img = fileImg
iconImg.image = img
}
}
| [
-1
] |
d9aca2fbbb51049d7e0a3fd5df9be4d6b9e58c52 | 454c726aba127040919daf325509c80e8c8a1f3d | /AppApp/Scripts/Components/UITableViewCell/LabelSetting/LabelSettingAdditionalTableViewCell.swift | d596a97681f4beb4727bcff35e4898feca11ca7a | [] | no_license | uruly/AppApp | 5a3dc71b23d2408b83f2a49235d3f0569fc34e74 | be7076f8aacc834a9350249a8294094f5c1e2172 | refs/heads/develop | 2023-02-08T21:33:47.561110 | 2023-02-06T10:24:41 | 2023-02-06T10:24:41 | 173,506,317 | 5 | 1 | null | 2021-10-17T12:19:18 | 2019-03-02T22:35:12 | Swift | UTF-8 | Swift | false | false | 358 | swift | //
// LabelSettingAdditionalTableViewCell.swift
// AppApp
//
// Created by Reona Kubo on 2020/08/03.
// Copyright © 2020 Reona Kubo. All rights reserved.
//
import UIKit
final class LabelSettingAdditionalTableViewCell: UITableViewCell {
func set(text: String) {
textLabel?.text = text
accessoryType = .disclosureIndicator
}
}
| [
-1
] |
a2985ec88a1cd6163e735514e34119079ef644eb | c6c0979a609f395a5d9fcbf5d506bd7e4345bf60 | /Swiftris/LShape.swift | 75a511ed1a5735a3f8f43d95d3fe944dc18469e9 | [] | no_license | ChristinaSaylor/Swiftris | e7d8559532892d4d425a9df93c0180f492a0316a | 3e069945a7bb1e0e46aef7b16cfca224a98b1043 | refs/heads/master | 2020-05-24T18:54:32.517413 | 2017-03-31T01:51:26 | 2017-03-31T01:51:26 | 84,865,714 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,088 | swift | //
// LShape.swift
// Swiftris
//
// Created by Christina Saylor on 3/7/17.
// Copyright © 2017 Christina Saylor. All rights reserved.
//
class LShape:Shape {
override var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] {
return [
Orientation.Zero: [ (0, 0), (0, 1), (0, 2), (1, 2)],
Orientation.Ninety: [ (1, 1), (0, 1), (-1,1), (-1, 2)],
Orientation.OneEighty: [ (0, 2), (0, 1), (0, 0), (-1,0)],
Orientation.TwoSeventy: [ (-1,1), (0, 1), (1, 1), (1,0)]
]
}
override var bottomBlocksForOrientations: [Orientation: Array<Block>] {
return [
Orientation.Zero: [blocks[ThirdBlockIdx], blocks[FourthBlockIdx]],
Orientation.Ninety: [blocks[FirstBlockIdx], blocks[SecondBlockIdx], blocks[FourthBlockIdx]],
Orientation.OneEighty: [blocks[FirstBlockIdx], blocks[FourthBlockIdx]],
Orientation.TwoSeventy: [blocks[FirstBlockIdx], blocks[SecondBlockIdx], blocks[ThirdBlockIdx]]
]
}
} | [
223328,
223330,
276131,
276132,
282682,
276134,
276138,
276140,
223324,
282675,
282676,
281685,
282678,
223321,
223322,
282683,
282684,
281694
] |
076a56a942758f956a2d1e0be39e660da106d787 | d95fa812c0ee2becc66810a7429223eeb7bb135c | /Slate/SceneDelegate.swift | abc3fe3190c603d9424902568460455839686d75 | [] | no_license | timmyvc123/Slate | 2c702c804001f027da130611a785ed3ab2984456 | 84548fa62acc7ebed3972b5d0f536e60342e8113 | refs/heads/master | 2021-08-06T19:53:36.921292 | 2021-07-08T16:47:29 | 2021-07-08T16:47:29 | 214,065,596 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,355 | swift | //
// SceneDelegate.swift
// PenPals
//
// Created by Tim Van Cauwenberge on 2/6/20.
// Copyright © 2020 SeniorProject. All rights reserved.
//
import UIKit
import Firebase
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var authListener: AuthStateDidChangeListenerHandle?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
autoLogin()
restBudge()
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
restBudge()
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
LocationManager.shared.startUpdating()
restBudge()
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
LocationManager.shared.stopUpdating()
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
restBudge()
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
LocationManager.shared.stopUpdating()
restBudge()
}
//MARK: - Autologin
func autoLogin() {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil && userDefaults.object(forKey: kCURRENTUSER) != nil {
DispatchQueue.main.async {
self.goToApp()
}
}
})
}
//MARK: Go To App
func goToApp() {
print("Third Print")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: USER_DID_LOGIN_NOTIFICATION), object: nil, userInfo: [kUSERID : FUser.currentId])
// present app
let mainView = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainApplication") as! UITabBarController
mainView.modalPresentationStyle = .fullScreen
// setting root view controller to main app screen
self.window?.rootViewController = mainView
}
private func restBudge() {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
// func autoLogin() {
// // AutoLogin
// authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
//
// Auth.auth().removeStateDidChangeListener(self.authListener!)
// print("First Print")
// if user != nil {
//
// if UserDefaults.standard.object(forKey: kCURRENTUSER) != nil {
// // there is a user logged in locally
// // skip log in screen and go to app
//
// if user != nil && userDefaults.object(forKey: kCURRENTUSER) != nil {
// print("Second Print")
// DispatchQueue.main.async {
// self.goToApp()
//
// }
//
// }
// }
// }
//
// })
// }
| [
-1
] |
de6fe617a5f770c92011c313dcb500071c06fd04 | 2a084e7ee8bc7b627eb6e2d54fa255ef788c0284 | /BookFinder/InterfaceAdapters/Repositories/Networking/Product/BookSummaryRepository.swift | 81f0151e6bd3b30c8755300ca2998d970fc8c65f | [] | no_license | sweetptios/BookFinder | 32772b23789a7d720eb3de33c975b5e26e4cb19b | bcb8ec7f7bdba1a2b3c97114e6064b3c1fcfe2d8 | refs/heads/master | 2022-04-08T12:46:04.590579 | 2020-03-21T01:39:12 | 2020-03-21T05:30:03 | 237,408,197 | 4 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,215 | swift | //
// BookSummaryRepository.swift
// BookFinder
//
// Created by mine on 2020/02/01.
// Copyright © 2019 sweetpt365. All rights reserved.
//
import Foundation
class BookSummaryRepository: IBookSummaryRepository {
private let networking: NetworkingServiceAvailable
private let apiKey: String = "AIzaSyCdyRfz2EwdpHesMXGGxgsaT37G-NsOy_4"
required init(networking: NetworkingServiceAvailable) {
self.networking = networking
}
func fetchBooks(page: Int, keyword: String, maxResultCount:Int, completion: ((Result<(books: [Book], totalCount: Int), RepositoryError>) -> Void)?) {
let params = makeParams(page, keyword, maxResultCount)
networking.request(.books, parameters: params)?
.response{(result :Result<BookIndexAPIModel, ServerAPIResponseError>) in
DispatchQueue.main.async {
switch(result) {
case .success(let data):
if data.isEmpty() {
completion?(.failure(RepositoryError(kind: .emptySearchResult(keyword: keyword))))
} else {
completion?(.success((books: data.toBooks(), totalCount: data.totalItems ?? 0)))
}
case .failure(let error):
completion?(.failure(error.toRepositoryError()))
}
}
}
}
private func makeParams(_ page: Int, _ keyword: String, _ maxResultCount:Int) -> [String: Any] {
var params = [String: Any]()
params["startIndex"] = (page - 1) * maxResultCount
params["maxResults"] = maxResultCount
if keyword.isEmpty == false {
params["q"] = keyword
}
params["key"] = apiKey
return params
}
}
// MARK: - APIModel
struct BookIndexAPIModel: IServerAPIModel {
let totalItems: Int?
let items: [Volume]?
struct Volume: Codable {
let id: String?
let volumeInfo: VolumeInfo?
struct VolumeInfo: Codable {
let title: String?
let authors: [String]?
let publishedDate: String?
let imageLinks: ImageLinks?
let infoLink: String?
struct ImageLinks: Codable {
let smallThumbnail: String?
}
}
}
func isValid() -> Bool { true }
func isEmpty() -> Bool { items?.isEmpty ?? true }
}
extension BookIndexAPIModel {
func toBooks() -> [Book] {
guard let items = items, isValid() else { return [] }
return items.map{
let thumbnailUrl = URL(string: $0.volumeInfo?.imageLinks?.smallThumbnail ?? "")
let detailUrl = URL(string: $0.volumeInfo?.infoLink ?? "")
var date = Date(from: $0.volumeInfo?.publishedDate, format: "yyyy-MM-dd")
if date == nil {
date = Date(from: $0.volumeInfo?.publishedDate, format: "yyyy")
}
return Book(id: $0.id, title: $0.volumeInfo?.title, authors: $0.volumeInfo?.authors, publishedDate: date, thumbnailImage: thumbnailUrl, detailInfo: detailUrl)
}
}
}
| [
-1
] |
8fb1c4db73e671962108d62488d7909ae78a3325 | a63883a7c88ac9e71dc22cfac81672bc1745e060 | /9. App-Entwicklung/Mask-Detector IOS App/ObjectDetection/ViewControllers/ViewController.swift | 7857922e64a7771d9eedff0e1d01751c862da383 | [] | no_license | SwiftJimmy/IOS-Deep-Learning-App-Mask-Detector | b359005d1cb0f5a20475dc96b1189b775a73816f | 8350d02da987e09fe2c4eace15cf3491ee0056a6 | refs/heads/master | 2023-01-05T22:04:27.598526 | 2020-11-03T11:11:40 | 2020-11-03T11:11:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 22,497 | swift | // 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 UIKit
import TensorFlowLite
import FirebaseStorage
import FirebaseFirestore
extension Notification.Name {
static let PhotoWasAddedToDisk = Notification.Name("PhotoWasAddedToDisk")
}
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
@IBOutlet weak var overlayView: OverlayView!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var bottomSheetStateImageView: UIImageView!
@IBOutlet weak var bottomSheetView: UIView!
@IBOutlet weak var bottomSheetViewBottomSpace: NSLayoutConstraint!
let dateFormat = "dd.MM.yyyy_HH:mm:ss"
var name = ""
var interval:Double = 0
var unit = "" {
didSet {
if interval > 0 && unit == "Minuten" {
interval *= 60
}
}
}
private weak var timer: Timer?
private var objectOverlays = [ObjectOverlay]()
private var resultArray = [Inference]()
private var maskImage: MaskImage? {
didSet {
save()
}
}
// MARK: Constants
private let displayFont = UIFont.systemFont(ofSize: 14.0, weight: .medium)
private let edgeOffset: CGFloat = 2.0
private let labelOffset: CGFloat = 10.0
private let animationDuration = 0.5
private let collapseTransitionThreshold: CGFloat = -30.0
private let expandThransitionThreshold: CGFloat = 30.0
private let delayBetweenInferencesMs: Double = 200
// MARK: Instance Variables
private var initialBottomSpace: CGFloat = 0.0
// Holds the results at any time
private var result: Result?
private var previousInferenceTimeMs: TimeInterval = Date.distantPast.timeIntervalSince1970 * 1000
// MARK: Controllers that manage functionality
private lazy var cameraFeedManager = CameraFeedManager(previewView: previewView)
private var modelDataHandler: ModelDataHandler? =
ModelDataHandler(modelFileInfo: MobileNetSSD.modelInfo, labelsFileInfo: MobileNetSSD.labelsInfo)
private var inferenceViewController: InferenceViewController?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
guard modelDataHandler != nil else {
fatalError("Failed to load model")
}
cameraFeedManager.delegate = self
overlayView.clearsContextBeforeDrawing = true
addPanGesture()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
changeBottomViewState()
cameraFeedManager.checkCameraConfigurationAndStartSession()
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(takePicture), userInfo: nil, repeats: true)
}
@objc private func takePicture() {
cameraFeedManager.capturePhoto()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer?.invalidate()
cameraFeedManager.stopSession()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: Button Actions
@IBAction func onClickResumeButton(_ sender: Any) {
cameraFeedManager.resumeInterruptedSession { (complete) in
if complete {
self.resumeButton.isHidden = true
self.cameraUnavailableLabel.isHidden = true
}
else {
self.presentUnableToResumeSessionAlert()
}
}
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
// MARK: Storyboard Segue Handlers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if segue.identifier == "EMBED" {
guard let tempModelDataHandler = modelDataHandler else {
return
}
inferenceViewController = segue.destination as? InferenceViewController
inferenceViewController?.wantedInputHeight = tempModelDataHandler.inputHeight
inferenceViewController?.wantedInputWidth = tempModelDataHandler.inputWidth
inferenceViewController?.threadCountLimit = tempModelDataHandler.threadCountLimit
inferenceViewController?.currentThreadCount = tempModelDataHandler.threadCount
inferenceViewController?.delegate = self
guard let tempResult = result else {
return
}
inferenceViewController?.inferenceTime = tempResult.inferenceTime
}
}
}
// MARK: InferenceViewControllerDelegate Methods
extension ViewController: InferenceViewControllerDelegate {
func didChangeThreadCount(to count: Int) {
if modelDataHandler?.threadCount == count { return }
modelDataHandler = ModelDataHandler(
modelFileInfo: MobileNetSSD.modelInfo,
labelsFileInfo: MobileNetSSD.labelsInfo,
threadCount: count
)
}
}
// MARK: CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
//Aufnahme des Photos
func tookPhoto(from data: Data) {
var maskImageInfoArray = [MaskImage.ImageInfo]()
objectOverlays.forEach({overlay in
let completeLabelArray = overlay.name.components(separatedBy: " ")
if completeLabelArray.count == 2 {
var withoutPercentage = completeLabelArray[1]
withoutPercentage.removeFirst()
withoutPercentage.removeLast(2)
let maskInfo = MaskImage.ImageInfo(
labelMapName: completeLabelArray[0],
confidenceValue: withoutPercentage)
maskImageInfoArray.append(maskInfo)
}
})
// Das Image wird aus dem Data Object erstellt
var image = UIImage(data: data)
let imageName = String(Date().timeIntervalSince1970).replacingOccurrences(of: ".", with: "") + ".jpg"
self.uploadImageToFirebase(image: image!,imageName: imageName,folder: "original")
/**
Draw Rectangle over each object
*/
resultArray.forEach { (overlay) in
let cgRect = overlay.rect
let cgPoint = CGPoint(x: cgRect.minX, y:cgRect.minY - 30 )
// Rectangle wird eingezeichnet
image = drawRectangleOnImage(image: image!, withFrame: cgRect,rectColor: overlay.displayColor)
// Rectangles werden mit Kategorienamen versehen
image = textToImage(drawText:overlay.className, inImage: image!, atPoint: cgPoint, textColor: overlay.displayColor,textFont: UIFont(name: "Times New Roman", size: 30.0)!)
}
// - das neue Image wird wieder in ein Data Object umgewandelt zur Speicherung
self.uploadImageToFirebase(image: image!,imageName: imageName,folder: "annotated")
let data = image!.jpegData(compressionQuality: 1)
maskImage = MaskImage(imageData: data!, name: name, date: Date(), infos: maskImageInfoArray)
}
/**
In jedes Bild werden die erkannten Kategorien mit einem Rahmen eingezeichnet und benannt.
*/
func drawRectangleOnImage(image: UIImage, withFrame: CGRect,rectColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions( image.size, false, 0)
let context = UIGraphicsGetCurrentContext()
image.draw(at: CGPoint.zero)
context!.setStrokeColor(rectColor.cgColor)
//Line Width
context!.setLineWidth(5)
context!.addRect(withFrame)
context!.drawPath(using: .stroke)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/**
Die Funktion lädt ein UIImage als jpg auf Firebase Storage
*/
func uploadImageToFirebase( image: UIImage, imageName: String, folder: String){
if Reachability.isConnectedToNetwork(){ // überprüft, ob das Gerät mit dem Wifi verbunden ist
DispatchQueue.global(qos: .background).async {
do {
// wandelt UIImage in jpg um
guard let uploadData = image.jpegData(compressionQuality: 1.0) else {
print("Issue while uploading")
return }
// erstellt Firebase Reference
let imageReference = Storage.storage().reference().child(folder)
.child(imageName)
// lädt due Datei in den Firebase Storeage
imageReference.putData(uploadData, metadata:nil) { (metadata, err) in
if let err = err {
print("error while put data" + err.localizedDescription)
return
}
}
NotificationCenter.default.post(name: .PhotoWasAddedToDisk,object: nil)
print(folder + " uploaded successfully")
}
}
}
}
/**
Bennenung der einzelnen Kategorie-Rahmen
*/
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint,textColor: UIColor, textFont: UIFont ) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
/**
Das Image wird als Json Datei gesichert.
*/
private func save() {
if let stringDate = self.maskImage?.date?.getTimeAndDateFormatted(dateFormat: "dd.MM.yyyy_HH:mm:ss") {
if let json = self.maskImage?.json {
if let url = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
.appendingPathComponent(stringDate + ".json") {
DispatchQueue.global(qos: .background).async {
do {
try json.write(to: url)
NotificationCenter.default.post(name: .PhotoWasAddedToDisk,object: nil)
print("saved successfully")
} catch let error {
print("couldn`t save \(error)")
}
}
}
}
}
}
func didOutput(pixelBuffer: CVPixelBuffer) {
runModel(onPixelBuffer: pixelBuffer)
}
// MARK: Session Handling Alerts
func sessionRunTimeErrorOccured() {
timer?.invalidate()
// Handles session run time error by updating the UI and providing a button if session can be manually resumed.
self.resumeButton.isHidden = false
}
func sessionWasInterrupted(canResumeManually resumeManually: Bool) {
timer?.invalidate()
// Updates the UI when session is interupted.
if resumeManually {
self.resumeButton.isHidden = false
}
else {
self.cameraUnavailableLabel.isHidden = false
}
}
func sessionInterruptionEnded() {
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(takePicture), userInfo: nil, repeats: true)
// Updates UI once session interruption has ended.
if !self.cameraUnavailableLabel.isHidden {
self.cameraUnavailableLabel.isHidden = true
}
if !self.resumeButton.isHidden {
self.resumeButton.isHidden = true
}
}
func presentVideoConfigurationErrorAlert() {
timer?.invalidate()
let alertController = UIAlertController(title: "Confirguration Failed", message: "Configuration of camera has failed.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func presentCameraPermissionsDeniedAlert() {
timer?.invalidate()
let alertController = UIAlertController(title: "Camera Permissions Denied", message: "Camera permissions have been denied for this app. You can change this by going to Settings", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (action) in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
/** This method runs the live camera pixelBuffer through tensorFlow to get the result.
*/
@objc func runModel(onPixelBuffer pixelBuffer: CVPixelBuffer) {
// Run the live camera pixelBuffer through tensorFlow to get the result
let currentTimeMs = Date().timeIntervalSince1970 * 1000
guard (currentTimeMs - previousInferenceTimeMs) >= delayBetweenInferencesMs else {
return
}
previousInferenceTimeMs = currentTimeMs
result = self.modelDataHandler?.runModel(onFrame: pixelBuffer)
resultArray.removeAll()
resultArray = result!.inferences
guard let displayResult = result else {
return
}
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
DispatchQueue.main.async {
// Display results by handing off to the InferenceViewController
self.inferenceViewController?.resolution = CGSize(width: width, height: height)
var inferenceTime: Double = 0
if let resultInferenceTime = self.result?.inferenceTime {
inferenceTime = resultInferenceTime
}
self.inferenceViewController?.inferenceTime = inferenceTime
self.inferenceViewController?.tableView.reloadData()
// Draws the bounding boxes and displays class names and confidence scores.
self.drawAfterPerformingCalculations(onInferences: displayResult.inferences, withImageSize: CGSize(width: CGFloat(width), height: CGFloat(height)))
}
}
/**
This method takes the results, translates the bounding box rects to the current view, draws the bounding boxes, classNames and confidence scores of inferences.
*/
func drawAfterPerformingCalculations(onInferences inferences: [Inference], withImageSize imageSize:CGSize) {
self.overlayView.objectOverlays = []
self.overlayView.setNeedsDisplay()
guard !inferences.isEmpty else {
return
}
objectOverlays.removeAll()
for inference in inferences {
// Translates bounding box rect to current view.
var convertedRect = inference.rect.applying(CGAffineTransform(scaleX: self.overlayView.bounds.size.width / imageSize.width, y: self.overlayView.bounds.size.height / imageSize.height))
if convertedRect.origin.x < 0 {
convertedRect.origin.x = self.edgeOffset
}
if convertedRect.origin.y < 0 {
convertedRect.origin.y = self.edgeOffset
}
if convertedRect.maxY > self.overlayView.bounds.maxY {
convertedRect.size.height = self.overlayView.bounds.maxY - convertedRect.origin.y - self.edgeOffset
}
if convertedRect.maxX > self.overlayView.bounds.maxX {
convertedRect.size.width = self.overlayView.bounds.maxX - convertedRect.origin.x - self.edgeOffset
}
let confidenceValue = Int(inference.confidence * 100.0)
let string = "\(inference.className) (\(confidenceValue)%)"
let size = string.size(usingFont: self.displayFont)
let numberOfRect = String(inferences.count)
let objectOverlay = ObjectOverlay(name: string, borderRect: convertedRect, nameStringSize: size, color: inference.displayColor, font: self.displayFont,count:numberOfRect)
objectOverlays.append(objectOverlay)
}
// Hands off drawing to the OverlayView
self.draw(objectOverlays: objectOverlays)
}
/** Calls methods to update overlay view with detected bounding boxes and class names.
*/
func draw(objectOverlays: [ObjectOverlay]) {
self.overlayView.objectOverlays = objectOverlays
self.overlayView.setNeedsDisplay()
}
}
// MARK: Bottom Sheet Interaction Methods
extension ViewController {
// MARK: Bottom Sheet Interaction Methods
/**
This method adds a pan gesture to make the bottom sheet interactive.
*/
private func addPanGesture() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.didPan(panGesture:)))
bottomSheetView.addGestureRecognizer(panGesture)
}
/** Change whether bottom sheet should be in expanded or collapsed state.
*/
private func changeBottomViewState() {
guard let inferenceVC = inferenceViewController else {
return
}
if bottomSheetViewBottomSpace.constant == inferenceVC.collapsedHeight - bottomSheetView.bounds.size.height {
bottomSheetViewBottomSpace.constant = 0.0
}
else {
bottomSheetViewBottomSpace.constant = inferenceVC.collapsedHeight - bottomSheetView.bounds.size.height
}
setImageBasedOnBottomViewState()
}
/**
Set image of the bottom sheet icon based on whether it is expanded or collapsed
*/
private func setImageBasedOnBottomViewState() {
if bottomSheetViewBottomSpace.constant == 0.0 {
if #available(iOS 13.0, *) {
bottomSheetStateImageView.image = UIImage(named: "down_icon")?.withTintColor(.label, renderingMode: .alwaysTemplate)
} else {
// Fallback on earlier versions
}
}
else {
if #available(iOS 13.0, *) {
bottomSheetStateImageView.image = UIImage(named: "up_icon")?.withTintColor(.label, renderingMode: .alwaysTemplate)
} else {
// Fallback on earlier versions
}
}
}
/**
This method responds to the user panning on the bottom sheet.
*/
@objc func didPan(panGesture: UIPanGestureRecognizer) {
// Opens or closes the bottom sheet based on the user's interaction with the bottom sheet.
let translation = panGesture.translation(in: view)
switch panGesture.state {
case .began:
initialBottomSpace = bottomSheetViewBottomSpace.constant
translateBottomSheet(withVerticalTranslation: translation.y)
case .changed:
translateBottomSheet(withVerticalTranslation: translation.y)
case .cancelled:
setBottomSheetLayout(withBottomSpace: initialBottomSpace)
case .ended:
translateBottomSheetAtEndOfPan(withVerticalTranslation: translation.y)
setImageBasedOnBottomViewState()
initialBottomSpace = 0.0
default:
break
}
}
/**
This method sets bottom sheet translation while pan gesture state is continuously changing.
*/
private func translateBottomSheet(withVerticalTranslation verticalTranslation: CGFloat) {
let bottomSpace = initialBottomSpace - verticalTranslation
guard bottomSpace <= 0.0 && bottomSpace >= inferenceViewController!.collapsedHeight - bottomSheetView.bounds.size.height else {
return
}
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
This method changes bottom sheet state to either fully expanded or closed at the end of pan.
*/
private func translateBottomSheetAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat) {
// Changes bottom sheet state to either fully open or closed at the end of pan.
let bottomSpace = bottomSpaceAtEndOfPan(withVerticalTranslation: verticalTranslation)
setBottomSheetLayout(withBottomSpace: bottomSpace)
}
/**
Return the final state of the bottom sheet view (whether fully collapsed or expanded) that is to be retained.
*/
private func bottomSpaceAtEndOfPan(withVerticalTranslation verticalTranslation: CGFloat) -> CGFloat {
// Calculates whether to fully expand or collapse bottom sheet when pan gesture ends.
var bottomSpace = initialBottomSpace - verticalTranslation
var height: CGFloat = 0.0
if initialBottomSpace == 0.0 {
height = bottomSheetView.bounds.size.height
}
else {
height = inferenceViewController!.collapsedHeight
}
let currentHeight = bottomSheetView.bounds.size.height + bottomSpace
if currentHeight - height <= collapseTransitionThreshold {
bottomSpace = inferenceViewController!.collapsedHeight - bottomSheetView.bounds.size.height
}
else if currentHeight - height >= expandThransitionThreshold {
bottomSpace = 0.0
}
else {
bottomSpace = initialBottomSpace
}
return bottomSpace
}
/**
This method layouts the change of the bottom space of bottom sheet with respect to the view managed by this controller.
*/
func setBottomSheetLayout(withBottomSpace bottomSpace: CGFloat) {
view.setNeedsLayout()
bottomSheetViewBottomSpace.constant = bottomSpace
view.setNeedsLayout()
}
}
| [
-1
] |
5baf33ffabb61c4343f84b3ddf6ffb1042f6e837 | eb0553f14bad846612ff4e2bb66a558346955b2c | /homework-8/homework-8/Helpers/TableViewUpdateType.swift | a6a3730b8a407380ffe78948994e41ad25c2cf54 | [] | no_license | alecsmirnov/FocusStartHomeworks | c21476f1410b993bc1edf74504024f1665ea036c | 21f2d8cd354dd2fb9e54d129610068de749591e7 | refs/heads/master | 2023-06-16T07:51:44.303607 | 2021-07-10T06:48:52 | 2021-07-10T06:48:52 | 304,413,219 | 0 | 1 | null | 2021-01-11T05:06:11 | 2020-10-15T18:20:44 | null | UTF-8 | Swift | false | false | 218 | swift | //
// TableViewUpdateType.swift
// homework-8
//
// Created by Admin on 05.12.2020.
//
enum TableViewUpdateType {
case insertNewRow
case updateRow(index: Int)
case deleteRow(index: Int)
case none
}
| [
-1
] |
70865dce4f618d622dbd669bbff3b88298e1489c | 08250d84ece9c4cb1c5b2163168f75c56211435e | /fearless/Modules/Wallet/AccountList/ViewModel/WalletAssetViewModelFactory.swift | a74982458cb9df8e7b79efa1c5d047b3175852cf | [
"Apache-2.0"
] | permissive | DiamondNetwork/fearless-iOS | c20f302d3cc42c4c6daaa8e089eb17f41c7ea5bd | e625de6f60aedf3d9aa9fa74648e787fac5e1212 | refs/heads/master | 2023-09-06T07:19:57.048043 | 2021-09-23T12:59:00 | 2021-09-23T12:59:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,045 | swift | import Foundation
import CommonWallet
import RobinHood
import SoraFoundation
import FearlessUtils
final class WalletAssetViewModelFactory: BaseAssetViewModelFactory {
let assetCellStyleFactory: AssetCellStyleFactoryProtocol
let amountFormatterFactory: NumberFormatterFactoryProtocol
let priceAsset: WalletAsset
let accountCommandFactory: WalletSelectAccountCommandFactoryProtocol
init(
address: String,
chain: Chain,
assetCellStyleFactory: AssetCellStyleFactoryProtocol,
amountFormatterFactory: NumberFormatterFactoryProtocol,
priceAsset: WalletAsset,
accountCommandFactory: WalletSelectAccountCommandFactoryProtocol,
purchaseProvider: PurchaseProviderProtocol
) {
self.assetCellStyleFactory = assetCellStyleFactory
self.amountFormatterFactory = amountFormatterFactory
self.priceAsset = priceAsset
self.accountCommandFactory = accountCommandFactory
super.init(address: address, chain: chain, purchaseProvider: purchaseProvider)
}
private func creatRegularViewModel(
for asset: WalletAsset,
balance: BalanceData,
commandFactory: WalletCommandFactoryProtocol,
locale: Locale
) -> AssetViewModelProtocol? {
let style = assetCellStyleFactory.createCellStyle(for: asset)
let amountFormatter = amountFormatterFactory.createDisplayFormatter(for: asset)
.value(for: locale)
let priceFormater = amountFormatterFactory.createTokenFormatter(for: priceAsset)
.value(for: locale)
let decimalBalance = balance.balance.decimalValue
let amount: String
if let balanceString = amountFormatter.stringFromDecimal(decimalBalance) {
amount = balanceString
} else {
amount = balance.balance.stringValue
}
let platform: String = asset.platform?.value(for: locale) ?? ""
let balanceContext = BalanceContext(context: balance.context ?? [:])
let priceString = priceFormater.stringFromDecimal(balanceContext.price) ?? ""
let totalPrice = balanceContext.price * balance.balance.decimalValue
let totalPriceString = priceFormater.stringFromDecimal(totalPrice)
let priceChangeString = NumberFormatter.signedPercent
.localizableResource()
.value(for: locale)
.string(from: balanceContext.priceChange as NSNumber) ?? ""
let priceChangeViewModel = balanceContext.priceChange >= 0.0 ?
WalletPriceChangeViewModel.goingUp(displayValue: priceChangeString) :
WalletPriceChangeViewModel.goingDown(displayValue: priceChangeString)
let imageViewModel: WalletImageViewModelProtocol?
if let assetId = WalletAssetId(rawValue: asset.identifier), let icon = assetId.assetIcon {
imageViewModel = WalletStaticImageViewModel(staticImage: icon)
} else {
imageViewModel = nil
}
let assetDetailsCommand = commandFactory.prepareAssetDetailsCommand(for: asset.identifier)
assetDetailsCommand.presentationStyle = .push(hidesBottomBar: true)
return WalletAssetViewModel(
assetId: asset.identifier,
amount: amount,
symbol: asset.symbol,
accessoryDetails: totalPriceString,
imageViewModel: imageViewModel,
style: style,
platform: platform,
details: priceString,
priceChangeViewModel: priceChangeViewModel,
command: assetDetailsCommand
)
}
private func createTotalPriceViewModel(
for asset: WalletAsset,
balance: BalanceData,
commandFactory: WalletCommandFactoryProtocol,
locale: Locale
) -> AssetViewModelProtocol? {
let style = assetCellStyleFactory.createCellStyle(for: asset)
let priceFormater = amountFormatterFactory.createTokenFormatter(for: priceAsset)
.value(for: locale)
let decimalBalance = balance.balance.decimalValue
let amount: String
if let balanceString = priceFormater.stringFromDecimal(decimalBalance) {
amount = balanceString
} else {
amount = balance.balance.stringValue
}
let iconGenerator = PolkadotIconGenerator()
let icon = (try? iconGenerator.generateFromAddress(address))?
.imageWithFillColor(
R.color.colorWhite()!,
size: CGSize(width: 40.0, height: 40.0),
contentScale: UIScreen.main.scale
)
let imageViewModel: WalletImageViewModelProtocol?
if let accountIcon = icon {
imageViewModel = WalletStaticImageViewModel(staticImage: accountIcon)
} else {
imageViewModel = nil
}
let details = R.string.localizable
.walletAssetsTotalTitle(preferredLanguages: locale.rLanguages)
let accountCommand = accountCommandFactory.createCommand(commandFactory)
return WalletTotalPriceViewModel(
assetId: asset.identifier,
details: details,
amount: amount,
imageViewModel: imageViewModel,
style: style,
command: nil,
accountCommand: accountCommand
)
}
override func createAssetViewModel(
for asset: WalletAsset,
balance: BalanceData,
commandFactory: WalletCommandFactoryProtocol,
locale: Locale
) -> WalletViewModelProtocol? {
if asset.identifier == priceAsset.identifier {
return createTotalPriceViewModel(
for: asset,
balance: balance,
commandFactory: commandFactory,
locale: locale
)
} else {
return creatRegularViewModel(
for: asset,
balance: balance,
commandFactory: commandFactory,
locale: locale
)
}
}
}
| [
-1
] |
ae353a8d87aac55f7075987a54b37c6227de1a5f | 0cf79b8bae117c8bcc774953af8869bb30c7d5a0 | /SwiftDemo/ViewController.swift | 2d4713225ecb7c77e8695e7d1780399bad1a9cf8 | [] | no_license | ElGrecode/SwiftFood | c9526d24d76665d8b81f70b61f59c77999384d07 | 565ae6ec6fbfd2fec00738f031a42355b844dff1 | refs/heads/master | 2016-09-05T10:29:02.521284 | 2014-09-28T02:35:31 | 2014-09-28T02:35:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 10,592 | swift | //
// ViewController.swift
// SwiftDemo
//
// Created by Root on 17/08/14.
// Copyright (c) 2014 Root. All rights reserved.
//
import UIKit
class ViewController: UIViewController, FBLoginViewDelegate,PFLogInViewControllerDelegate, UITextFieldDelegate {
// var profilePictureView:FBProfilePictureView = FBProfilePictureView()
var fbloginView:FBLoginView = FBLoginView()
var facebookLogin:Bool = false
@IBOutlet weak var textfieldUserName: UITextField!
@IBOutlet weak var textfieldPassword: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
println("viewDidLoad");
fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
fbloginView.delegate = self
/*fbloginView.readPermissions = ["email",
"basic_info",
"user_location",
"user_birthday",
"user_likes"]*/
self.view.addSubview(fbloginView)
// profilePictureView = FBProfilePictureView(frame: CGRectMake(70.0, fbloginView.frame.size.height + fbloginView.frame.origin.y, 180.0, 200.0))
// self.view.addSubview(profilePictureView)
GlobalVariableSharedInstance.initLocationManager()
}
override func viewWillAppear(animated: Bool)
{
println("viewWillAppear");
//fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
//profilePictureView.frame = CGRectMake(70.0, 450.0, 180.0, 200.0)
let user = PFUser.currentUser() as PFUser!
if (user != nil) //if (self.facebookLogin == true)//if (FBSession.activeSession().isOpen)
{
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayTabs"), userInfo: nil, repeats: false)
self.facebookLogin = false
}
else {
FBSession.activeSession().closeAndClearTokenInformation()
}
}
@IBAction func signIn(sender: UIButton)
{
println("signIn");
// self.displayTabs()
self.signInButton.enabled = false
self.signUpButton.enabled = false
var message = ""
if (self.textfieldPassword.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "Password should not be empty"
}
if (self.textfieldUserName.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "User Name should not be empty"
}
if (message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
else
{
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
PFUser.logInWithUsernameInBackground(self.textfieldUserName.text , password:self.textfieldPassword.text)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
self.displayTabs()
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
}
override func viewWillLayoutSubviews()
{
super.viewWillAppear(false)
//println("viewWillLayoutSubviews")
}
func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!)
{
//self.profilePictureView.profileID = user.id
println("loginViewFetchedUserInfo")
var query = PFUser.query()
query.whereKey("fbID", equalTo: user.id)
//
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in
if (error != nil) {
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
else{
if (objects.count == 0)
{
/* fbloginView.readPermissions = ["email"];
var me:FBRequest = FBRequest.requestForMe()
me.startWithCompletionHandler({(NSArray my, NSError error) in*/
println(user)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let imageUploaderView = storyboard.instantiateViewControllerWithIdentifier("ImageSelectorViewController") as ImageSelectorViewController
var email:String? = user.objectForKey("email") as String?
var birthday:String? = user.birthday
if (email==nil) {
email = user.first_name + "@user.com"
}
if (birthday==nil) {
birthday = "10/10/1987"
}
imageUploaderView.setUserName(user.name, password: user.id, Email: email!, andDateOfBirth: birthday!)
imageUploaderView.facebookLogin = true
self.facebookLogin = true
imageUploaderView.user = user
MBProgressHUD.hideHUDForView(self.view, animated:false)
imageUploaderView.loginScreen = self;
self.navigationController!.pushViewController(imageUploaderView, animated: true)
}
else
{
PFUser.logInWithUsernameInBackground(user.name , password:user.id)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
/*
var alert:UIAlertView = UIAlertView(title: "Message", message: "Hi " + user.username + ". You logged in", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
*/
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.displayTabs()
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated:false)
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
}
}
})
}
func loginViewShowingLoggedInUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedInUser")
}
func loginViewShowingLoggedOutUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedOutUser")
// self.profilePictureView.profileID = nil
}
func displayTabs()
{
println("displayTabs")
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var tabbarController = UITabBarController()
let profileSelectorViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileSelectorViewController") as ProfileSelectorViewController
let chatViewController = storyboard.instantiateViewControllerWithIdentifier("ChatViewController") as ChatViewController
let settingsViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsViewController") as SettingsViewController
let profileSelectorNavigationController = UINavigationController(rootViewController: profileSelectorViewController)
let chatNavigationController = UINavigationController(rootViewController: chatViewController)
tabbarController.viewControllers = [ profileSelectorNavigationController, chatNavigationController, settingsViewController]
var tabbarItem = tabbarController.tabBar.items![0] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("groups", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![1] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("chat", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![2] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("settings", ofType: "png")!)
tabbarItem.title = nil
//println(tabbarController.viewControllers)
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.presentViewController(tabbarController, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
-1
] |
4c347d3169eb6fb8d6df01de76bc182734956550 | 919ceeb3fb6fa0424b74e15f1fb3c8c166f69988 | /RobuHub/RobuHub/Modules/Search/Route/SearchRoute.swift | 192ac1191033eb21b8085a1a27e532277936e5f2 | [
"MIT"
] | permissive | KarimEbrahemAbdelaziz/RobuHub | 260cc7e4658d5838587f32ffef554103a8c8d005 | 237b06297fca99d0f9a1e9607c8ee636d3bbcd14 | refs/heads/main | 2023-01-06T03:24:00.968115 | 2020-10-27T13:59:37 | 2020-10-27T13:59:37 | 306,727,248 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 632 | swift | //
// SearchRoute.swift
// RobuHub
//
// Created by KarimEbrahem on 10/27/20.
//
import Foundation
import UIKit
import Domain
enum SearchRoute: Route {
case repositoryDetails(repository: Repository)
var defaultStyle: PresentingStyle {
switch self {
default:
return .modal(modalPresentationStyle: .formSheet, animated: true)
}
}
var destination: UIViewController {
switch self {
case let .repositoryDetails(repository):
return RepositoryDetailsConfigurator.repositoryDetailsViewController(repository: repository).viewController
}
}
}
| [
-1
] |
ebce215e60fb28bf4c6f54cd47b70ba30cbef45c | 15cb3319455d099001385225a2c997f355224c71 | /ObjectMapper/Core/Mapper.swift | 030634f02ad94fc6bfc4e9b869ed2b2aa797ccc1 | [
"MIT"
] | permissive | aler/ObjectMapper | 4643e548fcc358c326f4b830dd8b1d9b3bbe9bbf | 1b8267b68170cb1023881dcc65c93881a8938436 | refs/heads/master | 2020-11-30T16:21:49.679557 | 2016-02-01T21:37:35 | 2016-02-01T21:37:35 | 50,872,839 | 0 | 0 | null | 2016-02-01T21:34:09 | 2016-02-01T21:34:09 | null | UTF-8 | Swift | false | false | 14,018 | swift | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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 enum MappingType {
case FromJSON
case ToJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public init(){}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true)
object.mapping(map)
return object
}
//MARK: Mapping functions that create an object
/// Map an optional JSON string to an object that conforms to Mappable
public func map(JSONString: String?) -> N? {
if let JSONString = JSONString {
return map(JSONString)
}
return nil
}
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
return map(JSONString as String)
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
// check if N is of type MappableCluster
if let klass = N.self as? MappableCluster.Type {
if var object = klass.objectForMapping(map) as? N {
object.mapping(map)
return object
}
}
if var object = N(map) {
object.mapping(map)
return object
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return nil
}
/// Maps a optional JSON String into an array of objects that conforms to Mappable
public func mapArray(JSONString: String?) -> [N]? {
if let JSONString = JSONString {
return mapArray(JSONString)
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String : N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
return mapDictionary(parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], var toDictionary dictionary: [String : N]) -> [String : N] {
for (key, value) in JSONDictionary {
if let object = dictionary[key] {
Mapper().map(value, toObject: object)
} else {
dictionary[key] = Mapper().map(value)
}
}
return dictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap {
mapArray($0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? {
if let JSONArray = JSON as? [[[String : AnyObject]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSON)
return Mapper.parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
switch JSON {
case let dict as [String: AnyObject]:
return dict
case let arr as [[String: AnyObject]]:
return arr.count != 0 ? arr[0] : [:]
default:
return nil
}
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
let parsedJSON: AnyObject?
do {
parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(var object: N) -> [String : AnyObject] {
let map = Map(mappingType: .ToJSON, JSONDictionary: [:])
object.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
if NSJSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: NSData?
do {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
if let JSON = JSONData {
return String(data: JSON, encoding: NSUTF8StringEncoding)
}
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON){
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSON: AnyObject?) -> Set<N>? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapSet(JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]]
public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
if let newValue = f(value){
mapped[key] = newValue
}
}
return mapped
}
}
| [
286372,
296368,
208113,
282962,
227603,
141203,
299799,
296415
] |
03c562fe5e468d9e7f9cf8fba0bd110ce3c94997 | b095d4236adc97af474815aeae39af9efa4afbfe | /Ex45/Ex45/main.swift | a96ae092d1a740f53706ac438d56b19787309066 | [] | no_license | danielly-machado/exerciciosSwift | ab35399898461a7edab348953d81db15e12fdd0e | ed5061200cb10c670e281dca86b42947a78d7929 | refs/heads/master | 2023-07-05T06:19:39.502785 | 2021-08-17T19:03:01 | 2021-08-17T19:03:01 | 395,310,977 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 942 | swift | //
// main.swift
// Ex45
//
// Created by Lidiomar Fernando dos Santos Machado on 03/08/21.
//
import Foundation
usuarioFazContadorInicioVariavel()
func usuarioFazContadorInicioVariavel(){
print("Digite um numero inteiro para iniciar a contagem: ")
let numeroInicial = readLine()
print("Digite um numero inteiro para finalizar a contagem: ")
let numeroFinal = readLine()
print("Digite um numero inteiro para incrementar a contagem: ")
let numeroIncremento = readLine()
print("----")
let numeroInicialInt = Int(numeroInicial ?? "0") ?? 0
let numeroFinalInt = Int(numeroFinal ?? "0") ?? 0
let numeroIncrementoInt = Int(numeroIncremento ?? "0") ?? 0
for i in stride(from: numeroInicialInt, to: numeroFinalInt, by: +numeroIncrementoInt) {
print(i)
}
if numeroInicialInt > numeroFinalInt {
for i in stride(from: numeroInicialInt, to: numeroFinalInt, by: -numeroIncrementoInt){
print(i)
}
}
print("Acabou!")
}
| [
-1
] |
000dd210264d5924d552bb38892722971eb20931 | 856aa295dcf0fe742f1a4798c3e5431c0e2ff72d | /Demo4Aster/CollectionView/CustomCell.swift | a3ac22acc906168521ba4e71bb71f1c36e72016c | [] | no_license | kaaustubh/demo4aster | cf980b02b7241393974905852b9a76a4503924e8 | 32af156f788c74d52c584c5fb2b7d8238aa06e91 | refs/heads/master | 2023-03-02T07:17:16.368926 | 2021-02-05T21:47:07 | 2021-02-05T21:47:07 | 335,077,124 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 867 | swift | //
// CollectionViewCell.swift
// Demo4Aster
//
// Created by Kaustubh on 02/02/21.
//
import Foundation
import UIKit
class CustomCell: UICollectionViewCell {
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var imageHeight: NSLayoutConstraint!
@IBOutlet weak var descriptionHeight: NSLayoutConstraint!
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)
layoutAttributes.frame.size = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
return layoutAttributes
}
}
| [
-1
] |
fdb069b95d790dd1d535431df803970210e7b789 | 72369a3429a81dce883b62ab8177df68773a7027 | /EndlessDarkness/Managers/LevelManager.swift | 8a3e838e88d2ae8b7724843f3a6ef489f1f7060c | [] | no_license | pnwoodsum/EndlessDarkness | f4f5e97512e37cdc3a9edcbfad0cbff7abe72b94 | c3b747375eb317fa0d165f3be65a823f25006845 | refs/heads/master | 2020-03-09T20:36:43.202426 | 2018-05-04T03:36:07 | 2018-05-04T03:36:07 | 128,989,387 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 14,071 | swift | //
// LevelManager.swift
// EndlessDarkness
//
// Created by Student on 4/12/18.
// Copyright © 2018 Peter Woodsum (RIT Student). All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
import GameplayKit
class LevelManager {
var level = [Chunk]()
var collectibleManager = CollectibleManager()
let perlinNoiseObject: GKNoise?
var isUpdating = false
init(skScene: SKScene, seed: UInt32) {
// Create PerlinNoiseObject used to generate chunks for this map
perlinNoiseObject = GKNoise(GKPerlinNoiseSource(frequency: 0.15, octaveCount: 3, persistence: 2, lacunarity: 0.9, seed: Int32(seed)))
// Load 9 chunks at the start
level.append(Chunk(position: CGPoint(x: 0.0, y: 0.0), skScene: skScene, collectibleManager: collectibleManager, perlinNoiseObject: perlinNoiseObject!))
let adjacentChunks = GetAdjacentPositions(point: CGPoint(x: 0, y: 0), displacement: Double(GameData.ChunkPixelSize))
for position in adjacentChunks {
level.append(Chunk(position: position, skScene: skScene, collectibleManager: collectibleManager, perlinNoiseObject: perlinNoiseObject!))
}
}
// Calls CheckCollisionsInChunk for necesarry chunks
func CheckPlayerCollisions(player: Player) {
// Check collisions in current chunk
let currentChunk: Chunk = ChunkContainsPoint(point: player.position)
CheckCollisionsInChunk(currentChunk: currentChunk, player: player)
// Check collisions in adjecent chunnks (for edge cases)
let adjacentPoints = GetAdjacentPositions(point: player.position, displacement: Double(GameData.ChunkPixelSize))
for point in adjacentPoints {
let adjacentChunk = ChunkContainsPoint(point: point)
CheckCollisionsInChunk(currentChunk: adjacentChunk, player: player)
}
}
// Currently checks collisions between player and tiles in given chunk
func CheckCollisionsInChunk(currentChunk: Chunk, player: Player) {
for i in 0...GameData.ChunkTileWidth - 1 {
for j in 0...GameData.ChunkTileWidth - 1 {
// Is the tile close enough to the player to care about
let tilePosition = currentChunk.tiles[i][j].tilePosition
let xDifference = Float(tilePosition.x - player.position.x)
let yDifference = Float(tilePosition.y - player.position.y)
let magnitudeSquared = powf(xDifference, 2) + powf(yDifference, 2)
if magnitudeSquared < powf((GameData.TilePixelSize * 2), 2) {
if !currentChunk.tiles[i][j].pathable {
// Find the direction towards center of tile and closest distance to the center of the tile
// from the closest point on the colliding circle
let magnitude = sqrt(magnitudeSquared)
let xDirection = (xDifference / magnitude)
let yDirection = (yDifference / magnitude)
let closestX = CGFloat(xDirection * player.collisionRadius)
let closestY = CGFloat(yDirection * player.collisionRadius)
let closestPlayerPosition = player.position + CGPoint(x: closestX, y: closestY)
let halfTile = CGFloat(GameData.TilePixelSize / 2)
// Displace the character depending on relative position to the colliding tile
if (closestPlayerPosition.x < tilePosition.x + halfTile &&
closestPlayerPosition.x > tilePosition.x - halfTile &&
closestPlayerPosition.y < tilePosition.y + halfTile &&
closestPlayerPosition.y > tilePosition.y - halfTile) {
if abs(closestX) > abs(closestY) {
let xDisplacement = abs(currentChunk.tiles[i][j].tilePosition.x) - abs(closestPlayerPosition.x)
let absXDisplacement = CGFloat(GameData.TilePixelSize) / 2 - abs(xDisplacement)
player.position.x += absXDisplacement * CGFloat(-xDirection)
}
else {
let yDisplacement = abs(currentChunk.tiles[i][j].tilePosition.y) - abs(closestPlayerPosition.y)
let absYDisplacement = CGFloat(GameData.TilePixelSize) / 2 - abs(yDisplacement)
player.position.y += absYDisplacement * CGFloat(-yDirection)
}
}
}
}
}
}
}
// Create adjacent chunks if they do not exist and remove extra chunks
func UpdateLevel(point: CGPoint, skScene: SKScene) {
let currentChunk: Chunk = ChunkContainsPoint(point: point)
let adjacentPoints = GetAdjacentPositions(point: currentChunk.position, displacement: Double(GameData.ChunkPixelSize))
// Find the chunks to be removed
// Remove their node from the scene
// Remove chunk from level array
var currentChunkIndex = 0
for chunk in level {
if !adjacentPoints.contains(chunk.position) && chunk.position != currentChunk.position {
chunk.chunkNode.removeFromParent()
level.remove(at: currentChunkIndex)
}
else {
currentChunkIndex += 1
}
}
// Create missing chunks
for point in adjacentPoints {
if !ChunkExists(point: point) {
level.append(Chunk(position: point, skScene: skScene, collectibleManager: collectibleManager, perlinNoiseObject: perlinNoiseObject!))
}
}
}
// Originally tried to remove chunks in the background, but ran into some issues
// You can ONLY update SKNodes on the main thread
// func RemoveChunksBackground(chunkTileWidth: Int) {
// }
// Check to see which chunk is at the given point
func ChunkContainsPoint(point: CGPoint) -> Chunk {
for chunk in level {
if point.x > ((chunk.position.x - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.x < (chunk.position.x + CGFloat(GameData.ChunkPixelSize) / 2)) {
if point.y > ((chunk.position.y - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.y < (chunk.position.y + CGFloat(GameData.ChunkPixelSize) / 2)) {
return chunk
}
}
}
return level[0]
}
// Check to see if a chunk exists at a given point
func ChunkExists(point: CGPoint) -> Bool {
for chunk in level {
if point.x > ((chunk.position.x - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.x < (chunk.position.x + CGFloat(GameData.ChunkPixelSize) / 2)) {
if point.y > ((chunk.position.y - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.y < (chunk.position.y + CGFloat(GameData.ChunkPixelSize) / 2)) {
return true
}
}
}
return false
}
// Check to see which tile contains the given point
func TileContainsPoint(chunk: Chunk, point: CGPoint) -> Tile? {
for tileRows in chunk.tiles {
for tile in tileRows {
if point.x > ((tile.tilePosition.x - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.x < (tile.tilePosition.x + CGFloat(GameData.ChunkPixelSize) / 2)) {
if point.y > ((tile.tilePosition.y - CGFloat(GameData.ChunkPixelSize) / 2)) && (point.y < (tile.tilePosition.y + CGFloat(GameData.ChunkPixelSize) / 2)) {
return tile
}
}
}
}
return nil
}
func GetAdjacentTiles(currentTile: Tile) {
}
// Return array of points of adjects positions
func GetAdjacentPositions(point: CGPoint, displacement: Double) -> [CGPoint] {
var adjacentPoints = [CGPoint]()
adjacentPoints.append(point + CGPoint(x: displacement, y: 0.0))
adjacentPoints.append(point + CGPoint(x: displacement, y: -displacement))
adjacentPoints.append(point + CGPoint(x: 0.0, y: -displacement))
adjacentPoints.append(point + CGPoint(x: -displacement, y: -displacement))
adjacentPoints.append(point + CGPoint(x: -displacement, y: 0.0))
adjacentPoints.append(point + CGPoint(x: -displacement, y: displacement))
adjacentPoints.append(point + CGPoint(x: 0.0, y: displacement))
adjacentPoints.append(point + CGPoint(x: displacement, y: displacement))
return adjacentPoints
}
// Is this given point "near" the center of the given chunk
func IsDistantFromCurrentChunk(currentChunk: Chunk, position: CGPoint) -> Bool {
let xDifference = abs(Float(currentChunk.position.x - position.x))
let yDifference = abs(Float(currentChunk.position.y - position.y))
let MaxDistance = GameData.TilePixelSize * Float(((GameData.ChunkTileWidth / 2) + 4))
if (xDifference > MaxDistance) {
return true
}
else if (yDifference > MaxDistance) {
return true
}
return false
}
}
// Chunk that contains tiles based on the number of tiles per chunk
class Chunk {
let chunkNode: SKNode
var position: CGPoint
var tiles = Array(repeating: Array(repeating: Tile(), count: GameData.ChunkTileWidth), count: GameData.ChunkTileWidth)
var perlinNoiseMap: GKNoiseMap
var isUpdating: Bool
init(position: CGPoint, skScene: SKScene, collectibleManager: CollectibleManager, perlinNoiseObject: GKNoise) {
self.position = position
self.chunkNode = SKNode()
self.chunkNode.position = self.position
let leftSide = Float(position.x) - GameData.ChunkPixelSize / 2
let bottomSide = Float(position.y) - GameData.ChunkPixelSize / 2
self.perlinNoiseMap = GKNoiseMap(perlinNoiseObject,
size: vector_double2(Double(GameData.ChunkTileWidth), Double(GameData.ChunkTileWidth)),
origin: vector_double2(Double(leftSide / GameData.TilePixelSize), Double(bottomSide / GameData.TilePixelSize)), // Origin is the "bottom left" of the noise map
sampleCount: vector_int2(50, 50),
seamless: true)
for i in 0 ..< GameData.ChunkTileWidth {
for j in 0 ..< GameData.ChunkTileWidth {
let noiseValue = perlinNoiseMap.value(at: vector_int2(Int32(i), Int32(j)))
var tilePosition: CGPoint = CGPoint(x: 0.0, y: 0.0)
tilePosition.x = CGFloat((Float(i) * GameData.TilePixelSize) - (GameData.ChunkPixelSize / 2))
tilePosition.y = CGFloat((Float(j) * GameData.TilePixelSize) - (GameData.ChunkPixelSize / 2))
self.tiles[i][j] = Tile(chunkParentNode: self.chunkNode, noiseValue: noiseValue, position: tilePosition, collectibleManager: collectibleManager)
}
}
skScene.addChild(chunkNode)
self.isUpdating = false
}
}
// Contains information about each unique tile.
// Information is created when initialized based on the given type.
struct Tile {
var tileSpriteNode: SKSpriteNode
var pathable: Bool
var type: String = "Grass"
var tilePosition: CGPoint
// Default constructor (used to initialize arrays, etc...)
init () {
self.tileSpriteNode = SKSpriteNode(texture: GameData.BackgroundTextures[0])
self.pathable = true
self.tilePosition = CGPoint(x: 0, y: 0)
}
init (chunkParentNode: SKNode, noiseValue: Float, position: CGPoint, collectibleManager: CollectibleManager) {
// Tile for grass
if noiseValue < -0.1 {
self.tileSpriteNode = SKSpriteNode(texture: GameData.BackgroundTextures[0])
pathable = true
}
// Tile for grassOne
else if noiseValue >= -0.1 && noiseValue < 0.35{
self.tileSpriteNode = SKSpriteNode(texture: GameData.BackgroundTextures[1])
pathable = true
}
// Tile for grassTwo
else if noiseValue >= 0.35 && noiseValue < 0.7 {
self.tileSpriteNode = SKSpriteNode(texture: GameData.BackgroundTextures[2])
pathable = true
// Adds collectible gold coin on this tile
if noiseValue >= 0.55 && noiseValue < 0.6 {
collectibleManager.CreateNewCollectible(type: "GoldCoin", position: position, parentNode: chunkParentNode)
}
}
// Tile for impassable rock tile
else if noiseValue >= 0.7 {
self.tileSpriteNode = SKSpriteNode(texture: GameData.RockTextures[0])
pathable = false
}
// Default tile is grass
else {
self.tileSpriteNode = SKSpriteNode(texture: GameData.BackgroundTextures[0])
pathable = true
}
// Initialize node data
self.tileSpriteNode.scale(to: CGSize(width: CGFloat(GameData.TilePixelSize), height: CGFloat(GameData.TilePixelSize)))
self.tileSpriteNode.position = position
self.tileSpriteNode.zPosition = 0.1
chunkParentNode.addChild(self.tileSpriteNode)
self.tilePosition = position + chunkParentNode.position
}
}
| [
-1
] |
2ebcef88d6724e37edb7a5c4a76634f3641bced0 | 1cc47fc7a92adbfa10a0a22e53a435b7fff68058 | /NLPlayground.playground/Pages/Tokens.xcplaygroundpage/Contents.swift | 09730216ef6ad0454882775429c2e009307b075d | [] | no_license | langyx/Swift-NLP-Introduction | 48e5822fc70813e73a2259cae83619f696ef8303 | bf088d5a0608d6cc7a4ee7fded11a59a9e61e34c | refs/heads/master | 2023-03-22T11:01:58.969971 | 2021-03-23T15:04:43 | 2021-03-23T15:04:43 | 350,754,745 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 609 | swift | import Foundation
import NaturalLanguage
let text = "Hi, everyone ! My name is Yannis."
func retrieveTokens(from text: String, unit: NLTokenUnit = .word) -> [String] {
let tokenizer = NLTokenizer(unit: unit)
tokenizer.string = text
var tokens = [String]()
tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { (tokenRange, _) -> Bool in
tokens.append(String(text[tokenRange].lowercased()))
return true
}
return tokens
}
let sentences = retrieveTokens(from: text, unit: .sentence)
print(sentences)
let words = retrieveTokens(from: text)
print(words)
| [
-1
] |
711a7e8968ab75e017d6e237eca897c8439d143d | b0c78bddc76972420032a5ea750501fa86dee647 | /MafiaRising/Tutorial3ViewController.swift | 2781ba1c33908668b6301fa7abb906c5cbd87f28 | [] | no_license | jhyuen/m_r | f9ee0aea1aaab1a46f197e8e80520796bf530667 | cac8613b4a5d9d4441bd249a44b22327976a03ea | refs/heads/master | 2020-04-17T10:28:13.498183 | 2019-01-22T02:27:35 | 2019-01-22T02:27:35 | 166,502,372 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 876 | swift | //
// Tutorial3ViewController.swift
// MafiaRising
//
// Created by Joseph Yuen on 6/2/17.
// Copyright © 2017 Joseph Yuen. All rights reserved.
//
import UIKit
class Tutorial3ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| [
233869,
302865,
217109,
188313,
300057,
286256,
286257,
286271,
298359,
288331,
239308,
288332,
239310,
292428,
292432,
239312,
239313,
239314,
292429,
292431,
302927,
289112,
279386,
298202,
298206,
298207,
188897,
291556,
289519,
290160,
281073,
291569,
166643,
234483,
314351,
294518,
290166,
185464,
40574
] |
148a413fb79c412a999a6cd3e3af17b2d8cd1ae0 | 300748c0593403ab9139e48a68f5a4e67d2d9da4 | /FFVE/Sources/Search/SearchBar/CityMemberTableDataSource.swift | 04d0cf054bfe8191235628aa6623831f49311907 | [] | no_license | Frederic06/FFVE-collector-vehicle- | 3df0d3c5b90fef3c8dfc79fa16ae67de3d0b5450 | 8498c24e28efdbec8a446ad2072609f1eb66d146 | refs/heads/master | 2020-08-31T15:44:46.237333 | 2020-06-17T06:10:43 | 2020-06-17T06:10:43 | 218,724,826 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,818 | swift |
//
// CityMemberTable.swift
// FFVE
//
// Created by Margarita Blanc on 01/12/2019.
// Copyright © 2019 Frederic Blanc. All rights reserved.
//
import UIKit
final class CityMemberTableDataSource: NSObject{
private var cities: [City]?
private var members: [MemberItem]?
let sectionHeaderHeight: CGFloat = 25
var selectedCity: ((String) -> Void)?
var selectedMember: ((MemberItem) -> Void)?
func setCities(cities: [City]) {
self.cities = cities
}
func setMembers(members:[MemberItem]) {
self.members = members
}
}
extension CityMemberTableDataSource: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return cities?.count ?? 0
case 1:
return members?.count ?? 0
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return sectionHeaderHeight
case 1:
return sectionHeaderHeight
default:
return 0
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: sectionHeaderHeight))
view.backgroundColor = UIColor(red: 253.0/255.0, green: 240.0/255.0, blue: 196.0/255.0, alpha: 1)
let label = UILabel(frame: CGRect(x: 15, y: 0, width: tableView.bounds.width - 30, height: sectionHeaderHeight))
label.font = UIFont.boldSystemFont(ofSize: 15)
label.textColor = UIColor.black
switch section {
case 0:
label.text = "Ville"
case 1:
label.text = "Adhérent"
default:
label.text = ""
}
view.addSubview(label)
return view
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
switch indexPath.section {
case 0:
if let titleLabel = cell.viewWithTag(1) as? UILabel {
titleLabel.text = cities?[indexPath.row].cityName
}
if let subtitleLabel = cell.viewWithTag(2) as? UILabel {
if let cityDepartment = cities?[indexPath.row].departmentNumber {
switch cityDepartment.count {
case 1:
subtitleLabel.text = "0\(cityDepartment)"
default:
subtitleLabel.text = cities?[indexPath.row].departmentNumber
}
}
}
case 1:
if let titleLabel = cell.viewWithTag(1) as? UILabel {
titleLabel.text = members?[indexPath.row].name
}
if let subtitleLabel = cell.viewWithTag(2) as? UILabel {
subtitleLabel.text = members?[indexPath.row].city
}
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
guard let city = cities?[indexPath.row].cityName else { return }
selectedCity?(city)
case 1:
guard let member = members?[indexPath.row] else { return }
selectedMember?(member)
default:
break
}
}
}
| [
-1
] |
a1b401b18408ad65a47b42bce25d48d54f7ff95d | 037e873125b8eeb6828b1f439ae42a4d98918700 | /FilterCam/Models/GridStyle.swift | 5dc3e8a627d66fae7a218fad3e5248179c6c2903 | [] | no_license | nateemma/FilterCam | 151ddfe8e8bfd6bdc5797a948fba357a3c9787f5 | f25e4c875e44a1b7027878e4ff3426c3cdbc554f | refs/heads/master | 2021-01-12T12:36:44.557272 | 2018-06-18T20:53:46 | 2018-06-18T20:53:46 | 69,611,292 | 10 | 3 | null | null | null | null | UTF-8 | Swift | false | false | 598 | swift | //
// GridStyle.swift
// FilterCam
//
// Created by Philip Price on 9/26/16.
// Copyright © 2016 Nateemma. All rights reserved.
//
// enum type defining the different types of grid overlay
enum GridStyle {
case none
case thirds
case center
case golden
func getIconName() -> String{
switch self {
case .none:
return "ic_grid_none.png"
case .thirds:
return "ic_grid_thirds.png"
case .center:
return "ic_grid_center.png"
case .golden:
return "ic_grid_golden.png"
}
}
}
| [
-1
] |
b12c583c7995177255c6c28cdeb786ee88f582bd | 8c0253628ebd561cf15c7def2298f98663e223bd | /verison2UITests/verison2UITests.swift | 48b782dcb56d7de892441910a1c8cc46885ccd2e | [] | no_license | StIssac/Flipper-v5.3 | 374e1652a8253ac3ecee1266c0deae55312bbe99 | c96bd621a6d8f2e7e3af356b6b76c2f971d14d2e | refs/heads/master | 2020-03-17T10:48:42.124587 | 2018-05-15T14:12:32 | 2018-05-15T14:12:32 | 133,526,305 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,248 | swift | //
// verison2UITests.swift
// verison2UITests
//
// Created by 尹笑康 on 2018/3/31.
// Copyright © 2018年 尹笑康. All rights reserved.
//
import XCTest
class verison2UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| [
333827,
243720,
282634,
313356,
155665,
305173,
237599,
241695,
292901,
223269,
354342,
229414,
315433,
354346,
278571,
325675,
102441,
102446,
282671,
124974,
229425,
243763,
241717,
180279,
229431,
215095,
319543,
213051,
288829,
325695,
286787,
288835,
307269,
237638,
313415,
239689,
233548,
311373,
315468,
278607,
333902,
196687,
311377,
354386,
329812,
315477,
223317,
285362,
200795,
323678,
315488,
315489,
45154,
321632,
280676,
313446,
215144,
307306,
194667,
233578,
278637,
288878,
319599,
278642,
284789,
284790,
131190,
288890,
215165,
131199,
194692,
235661,
278669,
241809,
323730,
278676,
311447,
153752,
327834,
284827,
278684,
329884,
299166,
278690,
311459,
215204,
233635,
284840,
278698,
284843,
278703,
278707,
278713,
258233,
280761,
223418,
295099,
227517,
280767,
299197,
180409,
299202,
139459,
309443,
227525,
131270,
301255,
176325,
280779,
233678,
282832,
321744,
227536,
301270,
229591,
301271,
280792,
311520,
325857,
334049,
280803,
307431,
182503,
338151,
319719,
317676,
286957,
125166,
125170,
313595,
184574,
309504,
125184,
217352,
125192,
125197,
194832,
227601,
325904,
125200,
319764,
278805,
125204,
334104,
282908,
311582,
299294,
282912,
278817,
233761,
125215,
211239,
282920,
125225,
317738,
311596,
321839,
315698,
98611,
332084,
125236,
307514,
278843,
282938,
168251,
287040,
319812,
280903,
227655,
323914,
201037,
282959,
229716,
289109,
168280,
379224,
323934,
391521,
239973,
381286,
285031,
416103,
313703,
280938,
242027,
242028,
321901,
354671,
278895,
287089,
199030,
227702,
315768,
315769,
291194,
223611,
248188,
291193,
313726,
311679,
211327,
291200,
158087,
313736,
227721,
242059,
311692,
285074,
227730,
240020,
190870,
315798,
190872,
291225,
293275,
317851,
285083,
242079,
283039,
289185,
293281,
285089,
305572,
227743,
300490,
156069,
301482,
311723,
289195,
377265,
338359,
299449,
311739,
319931,
293309,
278974,
311744,
317889,
291266,
278979,
326083,
278988,
289229,
281038,
281039,
278992,
283088,
283089,
326093,
279000,
176602,
242138,
285152,
279009,
369121,
160224,
195044,
188899,
279014,
291297,
319976,
279017,
311787,
281071,
319986,
236020,
279030,
311800,
279033,
317949,
283138,
279042,
233987,
287237,
377352,
322057,
309770,
342537,
279053,
283154,
303634,
303635,
279061,
182802,
279060,
188954,
279066,
291359,
227881,
293420,
236080,
283185,
279092,
234037,
23093,
244279,
244280,
338491,
301635,
309831,
55880,
322119,
377419,
281165,
303693,
301647,
281170,
326229,
309847,
189016,
115287,
287319,
332379,
111197,
295518,
287327,
242274,
244326,
279143,
279150,
281200,
287345,
287348,
301688,
244345,
189054,
287359,
297600,
303743,
291455,
301702,
164487,
311944,
279176,
334473,
316044,
311950,
184974,
316048,
311953,
316050,
287379,
326288,
227991,
295575,
289435,
303772,
205469,
221853,
285348,
279207,
295591,
248494,
279215,
285360,
293552,
299698,
295598,
287412,
166581,
318127,
154295,
164532,
342705,
303802,
314043,
287418,
66243,
291529,
287434,
225996,
363212,
287438,
242385,
303826,
279253,
158424,
230105,
299737,
322269,
342757,
295653,
289511,
230120,
330473,
234216,
285419,
330476,
289517,
312046,
170735,
279278,
215790,
125683,
230133,
199415,
234233,
279293,
205566,
322302,
291584,
299777,
228099,
285443,
291591,
295688,
322312,
285450,
264971,
312076,
326413,
322320,
285457,
295698,
166677,
291605,
283418,
285467,
326428,
221980,
281378,
234276,
283431,
262952,
262953,
279337,
293673,
289580,
262957,
318247,
164655,
301872,
242481,
234290,
303921,
318251,
285493,
230198,
328495,
285496,
301883,
201534,
281407,
289599,
295745,
342846,
293702,
318279,
283466,
281426,
279379,
244569,
201562,
281434,
322396,
295769,
230238,
230239,
301919,
279393,
293729,
275294,
349025,
281444,
279398,
303973,
351078,
177002,
308075,
242540,
310132,
295797,
201590,
207735,
228214,
295799,
279418,
177018,
269179,
308093,
314240,
158594,
240517,
287623,
228232,
299912,
279434,
320394,
416649,
316299,
252812,
308111,
234382,
308113,
293780,
310166,
289691,
209820,
283551,
240543,
310177,
289699,
189349,
289704,
279465,
293801,
326571,
304050,
177074,
326580,
289720,
326586,
289723,
189373,
213956,
281541,
19398,
345030,
213961,
279499,
56270,
191445,
183254,
304086,
234469,
314343,
304104,
324587,
183276,
289773,
320492,
234476,
320495,
203758,
287730,
240631,
320504,
214009,
312313,
312315,
312317,
328701,
328705,
234499,
293894,
320520,
230411,
320526,
330766,
234513,
238611,
140311,
293911,
316441,
197658,
238617,
132140,
113710,
281647,
189487,
322609,
312372,
203829,
238646,
300087,
238650,
320571,
21567,
308288,
336962,
160834,
314437,
349254,
238663,
300109,
234578,
207954,
296023,
205911,
314458,
156763,
281698,
281699,
285795,
214116,
230500,
322664,
228457,
279659,
318571,
234606,
300145,
230514,
238706,
279666,
312435,
187508,
300147,
302202,
285819,
314493,
285823,
150656,
234626,
279686,
222344,
285833,
285834,
318602,
228492,
337037,
234635,
177297,
162962,
187539,
326803,
308375,
324761,
285850,
296091,
119965,
302239,
300192,
330912,
339106,
306339,
234655,
234662,
300200,
249003,
238764,
208044,
322733,
3243,
294069,
300215,
64699,
294075,
228541,
283841,
148674,
283846,
312519,
279752,
283849,
148687,
290001,
189651,
316628,
279766,
189656,
279775,
304352,
298209,
304353,
310496,
279780,
228587,
279789,
290030,
302319,
251124,
316661,
283894,
234741,
208123,
292092,
279803,
228608,
320769,
234756,
322826,
242955,
177420,
312588,
318732,
126229,
245018,
320795,
318746,
239610,
320802,
130342,
304422,
130344,
292145,
298290,
312628,
300342,
159033,
333114,
222523,
333115,
286012,
279872,
181568,
279874,
300355,
193858,
216387,
300354,
372039,
294210,
304457,
230730,
294220,
296269,
222542,
234830,
238928,
224591,
296274,
314708,
318804,
283990,
314711,
357720,
300379,
294236,
234330,
316764,
314721,
292194,
230757,
281958,
314727,
134504,
306541,
284015,
296304,
312688,
314740,
230772,
327030,
314742,
314745,
310650,
224637,
306558,
290176,
243073,
179586,
314752,
306561,
294278,
314759,
296328,
296330,
298378,
368012,
318860,
314765,
304523,
292242,
112019,
306580,
279955,
224662,
234902,
282008,
314776,
314771,
318876,
282013,
290206,
148899,
314788,
298406,
282023,
314790,
245160,
333224,
241067,
279980,
314797,
279979,
286128,
279988,
173492,
286133,
284086,
284090,
310714,
228796,
302523,
54719,
302530,
292291,
228804,
415170,
306630,
310725,
300488,
280003,
370122,
310731,
302539,
339403,
306634,
310735,
329168,
280011,
222674,
327122,
280020,
329170,
312785,
280025,
310747,
239069,
144862,
286176,
187877,
320997,
310758,
280042,
280043,
191980,
329198,
337391,
300526,
282097,
308722,
296434,
306678,
40439,
288248,
191991,
286201,
300539,
288252,
312830,
290304,
245249,
228868,
292359,
218632,
323079,
302602,
230922,
323083,
294413,
304655,
329231,
323088,
282132,
230933,
302613,
282135,
316951,
374297,
302620,
222754,
282147,
306730,
245291,
312879,
230960,
288305,
239159,
290359,
323132,
235069,
157246,
288319,
288322,
280131,
349764,
310853,
282182,
194118,
288328,
286281,
292426,
124486,
333389,
224848,
224852,
290391,
128600,
196184,
235096,
306777,
239192,
212574,
345697,
300643,
300645,
282214,
312937,
204394,
224874,
243306,
312941,
206447,
310896,
314997,
294517,
288377,
290425,
325246,
333438,
235136,
280193,
282244,
239238,
288391,
282248,
286344,
323208,
179853,
286351,
188049,
229011,
239251,
280217,
323226,
179868,
229021,
302751,
282272,
198304,
282279,
298664,
212649,
298666,
317102,
286387,
300725,
337590,
286392,
300729,
302778,
306875,
280252,
280253,
282302,
323262,
286400,
321217,
296636,
280259,
321220,
282309,
333508,
323265,
239305,
280266,
306891,
296649,
212684,
302798,
9935,
241360,
282321,
313042,
286419,
241366,
280279,
282330,
18139,
280285,
294621,
282336,
321250,
294629,
153318,
333543,
181992,
337638,
12009,
282347,
288492,
282349,
323315,
67316,
34547,
286457,
284410,
288508,
282366,
286463,
319232,
288515,
280326,
282375,
323335,
284425,
300810,
116491,
282379,
280333,
216844,
300812,
284430,
161553,
124691,
284436,
278292,
116502,
118549,
278294,
325403,
321308,
321309,
282399,
241440,
282401,
325411,
315172,
186149,
186148,
241447,
333609,
286507,
294699,
284460,
280367,
300849,
282418,
282424,
280377,
321338,
319289,
282428,
280381,
345918,
413500,
241471,
280386,
280391,
153416,
315209,
325449,
159563,
280396,
307024,
317268,
237397,
307030,
18263,
241494,
188250,
284508,
300893,
307038,
237411,
284515,
276326,
282471,
296807,
292713,
282476,
292719,
296815,
313200,
325491,
313204,
333687,
317305,
317308,
339840,
315265,
280451,
327556,
188293,
243590,
282503,
67464,
305032,
315272,
315275,
243592,
184207,
311183,
282517,
294806,
214936,
294808,
337816,
239515,
214943,
298912,
319393,
333727,
294820,
333734,
219046,
284584,
294824,
298921,
313257,
292783,
126896,
200628,
300983,
343993,
288698,
98240,
294849,
214978,
280517,
280518,
214983,
282572,
282573,
153553,
24531,
231382,
329696,
323554,
292835,
6116,
190437,
292838,
294887,
317416,
313322,
278507,
329707,
311277,
296942,
298987,
124912,
327666,
278515,
325620,
313338
] |
58712f19bf037cfd3cd484845a7a3b62d253a2e0 | bcd6f0571c203843febf4f384bcb25f40a79a977 | /MadLib/MadLibTests/MadLibTests.swift | d125b358dc2540aea28871b4418381594c23fbb6 | [] | no_license | nicolezurita/dojo_ios | 76d78f51f944c381c38534aa2cae1632f6adbde3 | ce8d2caae95b73c3d4c12ea656712cef03c802bf | refs/heads/master | 2021-01-20T14:16:48.450656 | 2017-05-30T17:05:27 | 2017-05-30T17:05:27 | 90,582,959 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 969 | swift | //
// MadLibTests.swift
// MadLibTests
//
// Created by Nicole Zurita on 5/16/17.
// Copyright © 2017 Nicole Zurita. All rights reserved.
//
import XCTest
@testable import MadLib
class MadLibTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| [
333828,
43014,
282633,
358410,
354316,
313357,
360462,
399373,
145435,
317467,
229413,
204840,
315432,
325674,
344107,
102445,
155694,
176175,
233517,
346162,
129076,
241716,
229430,
243767,
163896,
180280,
358456,
288828,
436285,
376894,
288833,
288834,
436292,
403525,
352326,
225351,
315465,
436301,
338001,
196691,
338003,
280661,
329814,
307289,
385116,
237663,
254048,
315487,
356447,
280675,
280677,
43110,
319591,
321637,
436329,
194666,
221290,
438377,
260207,
432240,
299121,
204916,
233589,
266357,
131191,
215164,
292988,
215166,
422019,
280712,
415881,
104587,
235662,
241808,
381073,
196760,
284826,
426138,
346271,
436383,
362659,
233636,
299174,
333991,
239793,
377009,
405687,
182456,
131256,
295098,
258239,
379071,
389313,
299203,
149703,
299209,
346314,
372941,
266449,
321745,
139479,
229597,
194782,
301279,
311519,
317664,
280802,
379106,
387296,
346346,
205035,
307435,
321772,
438511,
381172,
436470,
327929,
243962,
344313,
184575,
149760,
375039,
411906,
147717,
368905,
325905,
254226,
272658,
368916,
262421,
325912,
381208,
377114,
151839,
237856,
237857,
233762,
211235,
217380,
432421,
211238,
338218,
311597,
358703,
321840,
98610,
332083,
379186,
332085,
358709,
180535,
336183,
332089,
321860,
332101,
438596,
323913,
348492,
323920,
344401,
366930,
377169,
348500,
368981,
155990,
289110,
368984,
168281,
215385,
332123,
332127,
98657,
383332,
242023,
383336,
270701,
160110,
242033,
270706,
354676,
199029,
139640,
291192,
179587,
211326,
291198,
436608,
362881,
240002,
436611,
311685,
225670,
317831,
106888,
340357,
242058,
385417,
373134,
385422,
108944,
252308,
178582,
190871,
293274,
213403,
149916,
121245,
242078,
420253,
141728,
61857,
315810,
315811,
381347,
289189,
61859,
108972,
272813,
340398,
385454,
377264,
299441,
342450,
338356,
436661,
293303,
311738,
33211,
293306,
293310,
336320,
311745,
291265,
127427,
416197,
254406,
188871,
324039,
129483,
342476,
373197,
289232,
278999,
328152,
256477,
287198,
160225,
342498,
358882,
334309,
391655,
432618,
375276,
319981,
291311,
293367,
254456,
377338,
377343,
174593,
254465,
291333,
340490,
139792,
420369,
303636,
258581,
393751,
289304,
416286,
377376,
207393,
180771,
375333,
377386,
293419,
244269,
197167,
375343,
385588,
289332,
234036,
375351,
174648,
338489,
338490,
244281,
315960,
242237,
348732,
70209,
115270,
70215,
293448,
55881,
301638,
309830,
348742,
348749,
381517,
385615,
426576,
369235,
416341,
297560,
332378,
201308,
416351,
139872,
436832,
436834,
268899,
111208,
39530,
184940,
373358,
420463,
295536,
346737,
389745,
313971,
139892,
346740,
420471,
287352,
344696,
209530,
244347,
373375,
189057,
152195,
311941,
336518,
348806,
311945,
369289,
330379,
344715,
311949,
287374,
326287,
375440,
316049,
311954,
334481,
117396,
111253,
316053,
346772,
230040,
264856,
111258,
111259,
271000,
289434,
303771,
205471,
318106,
318107,
342682,
139939,
344738,
377500,
176808,
205487,
295599,
303793,
318130,
299699,
293556,
336564,
383667,
299700,
314040,
287417,
158394,
39614,
287422,
377539,
422596,
422599,
291530,
225995,
363211,
164560,
242386,
385747,
361176,
418520,
422617,
287452,
363230,
264928,
422626,
295652,
375526,
234217,
330474,
342762,
293612,
342763,
289518,
299759,
369385,
377489,
312052,
154359,
172792,
344827,
221948,
432893,
205568,
162561,
291585,
295682,
430849,
291592,
197386,
383754,
62220,
117517,
434957,
322319,
422673,
377497,
430865,
166676,
291604,
310036,
197399,
207640,
422680,
426774,
426775,
326429,
293664,
326433,
197411,
400166,
289576,
293672,
295724,
152365,
197422,
353070,
164656,
295729,
422703,
191283,
422709,
152374,
197431,
273207,
375609,
160571,
293693,
289598,
160575,
336702,
430910,
295746,
160580,
252741,
381773,
201551,
293711,
353109,
377686,
244568,
230234,
189275,
244570,
435039,
295776,
242529,
349026,
357218,
303972,
385893,
342887,
230248,
308076,
242541,
330609,
246643,
207732,
295798,
361337,
177019,
185211,
308092,
398206,
400252,
291712,
158593,
254850,
359298,
260996,
359299,
113542,
369538,
381829,
416646,
316298,
392074,
295824,
224145,
349072,
355217,
256922,
289690,
318364,
390045,
310176,
185250,
310178,
420773,
185254,
289703,
293800,
140204,
236461,
363438,
347055,
377772,
304051,
326581,
373687,
289722,
326587,
230332,
377790,
289727,
273344,
330689,
353215,
363458,
379844,
213957,
19399,
326601,
345033,
373706,
316364,
359381,
386006,
418776,
433115,
248796,
343005,
50143,
347103,
123881,
326635,
203757,
187374,
383983,
347123,
240630,
271350,
201720,
127992,
295927,
349175,
328700,
318461,
293886,
257024,
328706,
330754,
320516,
293893,
295942,
357379,
386056,
410627,
353290,
330763,
377869,
433165,
384016,
238610,
308243,
418837,
140310,
433174,
252958,
300068,
369701,
357414,
248872,
238639,
300084,
312373,
203830,
359478,
238651,
308287,
377926,
218186,
300111,
314448,
341073,
339030,
439384,
304222,
392290,
253029,
257125,
300135,
316520,
322663,
273515,
173166,
357486,
144496,
351344,
404593,
377972,
285814,
291959,
300150,
300151,
363641,
160891,
363644,
300158,
377983,
392318,
150657,
248961,
384131,
349316,
402565,
349318,
302216,
330888,
386189,
373903,
169104,
177296,
162961,
326804,
363669,
238743,
187544,
119962,
300187,
300188,
339100,
351390,
199839,
380061,
429214,
296092,
265379,
300201,
249002,
253099,
253100,
238765,
3246,
300202,
306346,
238769,
318639,
402613,
367799,
421048,
373945,
113850,
294074,
230588,
302274,
367810,
259268,
265412,
353479,
402634,
283852,
259280,
290000,
316627,
333011,
189653,
419029,
189652,
148696,
296153,
304351,
195808,
298208,
310497,
298212,
298213,
222440,
330984,
328940,
298221,
298228,
302325,
234742,
386294,
128251,
386301,
261377,
320770,
386306,
437505,
322824,
439562,
292107,
328971,
414990,
353551,
251153,
177428,
349462,
257305,
320796,
222494,
253216,
339234,
372009,
412971,
353584,
261425,
351537,
382258,
345396,
298291,
300343,
386359,
378172,
286013,
306494,
382269,
216386,
312648,
337225,
304456,
230729,
146762,
224586,
177484,
294218,
259406,
234831,
238927,
294219,
331090,
353616,
406861,
318805,
314710,
372054,
425304,
159066,
374109,
314720,
378209,
163175,
333160,
386412,
230765,
380271,
327024,
296307,
116084,
208244,
249204,
316787,
111993,
290173,
306559,
314751,
318848,
337281,
148867,
357762,
253317,
298374,
314758,
314760,
142729,
296329,
368011,
384393,
388487,
314766,
296335,
318864,
112017,
234898,
9619,
259475,
275859,
318868,
370071,
357786,
290207,
314783,
251298,
310692,
314789,
333220,
314791,
396711,
245161,
396712,
374191,
286129,
380337,
173491,
286132,
150965,
304564,
353719,
380338,
228795,
425405,
302531,
292292,
380357,
339398,
361927,
300487,
300489,
425418,
306639,
413137,
222675,
23092,
210390,
210391,
210393,
286172,
144867,
271843,
429542,
296433,
251378,
308723,
300536,
286202,
359930,
290301,
302590,
300542,
230913,
372227,
323080,
329225,
230921,
253451,
296461,
359950,
259599,
304656,
329232,
146964,
308756,
370197,
175639,
253463,
374296,
388632,
374299,
308764,
396827,
134686,
431649,
306723,
286244,
245287,
402985,
394794,
245292,
169518,
347694,
431663,
288309,
312889,
194110,
349763,
196164,
265798,
288327,
218696,
292425,
292423,
128587,
265804,
333388,
396882,
128599,
179801,
44635,
239198,
343647,
333408,
396895,
99938,
300644,
323172,
310889,
415338,
243307,
312940,
54893,
204397,
138863,
188016,
222832,
325231,
224883,
314998,
323196,
325245,
337534,
337535,
339584,
263809,
294529,
194180,
288392,
229001,
415375,
188048,
239250,
419478,
425626,
298654,
302754,
153251,
298661,
40614,
290471,
300714,
210603,
224946,
337591,
384695,
296632,
110268,
415420,
224958,
327358,
333503,
274115,
259781,
306890,
403148,
212685,
333517,
9936,
9937,
241361,
302802,
333520,
272085,
345814,
370388,
384720,
212688,
345821,
294622,
321247,
298720,
321249,
325346,
153319,
325352,
345833,
345834,
212716,
212717,
360177,
67315,
173814,
325371,
288512,
319233,
339715,
288516,
360195,
339720,
243472,
372496,
323346,
161554,
321302,
345879,
366360,
398869,
325404,
286494,
321310,
255776,
339745,
257830,
421672,
362283,
378668,
399147,
431916,
294700,
300848,
409394,
296755,
259899,
319292,
360252,
325439,
345919,
436031,
403267,
307011,
153415,
360264,
345929,
341836,
415567,
325457,
317269,
18262,
216918,
241495,
341847,
362327,
346779,
350044,
128862,
245599,
345951,
362337,
376669,
345955,
425825,
300894,
296806,
302946,
292712,
425833,
423789,
296814,
214895,
313199,
362352,
325492,
276341,
417654,
341879,
241528,
317304,
333688,
112509,
55167,
182144,
325503,
305026,
339841,
188292,
333701,
243591,
315273,
315274,
325518,
372626,
380821,
329622,
294807,
337815,
333722,
376732,
118685,
298909,
311199,
319392,
350109,
292771,
436131,
294823,
415655,
436137,
327596,
362417,
323507,
243637,
290745,
294843,
188348,
362431,
237504,
294850,
274371,
384964,
214984,
151497,
362443,
344013,
212942,
301008,
153554,
24532,
372701,
329695,
436191,
292836,
292837,
298980,
313319,
317415,
380908,
436205,
296941,
311281,
311282,
325619,
432116,
292858,
415741,
352917
] |
f57a20351278184e32a44210adfc33eff7fcea8b | 894740b3499834711d760d347f3212e03b1066db | /CalculatorUITests/CalculatorUITests.swift | 30602972dddd308a488faeda58b8145cd1eddcb6 | [] | no_license | Clumsyndicate/Calculator | f45ac6c0185a2235424032cd644788d0206b6960 | 71104d7127defb1e7183d8a98a57cf76d28d39c5 | refs/heads/master | 2020-09-21T23:26:45.943080 | 2016-09-05T11:48:45 | 2016-09-05T11:48:45 | 67,199,329 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,258 | swift | //
// CalculatorUITests.swift
// CalculatorUITests
//
// Created by Johnson Zhou on 14/08/2016.
// Copyright © 2016 Johnson Zhou. All rights reserved.
//
import XCTest
class CalculatorUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| [
243720,
282634,
155665,
305173,
241695,
237599,
223269,
354342,
229414,
315433,
354346,
278571,
325675,
313388,
102446,
282671,
124974,
229425,
243763,
321589,
180279,
229431,
319543,
213051,
288829,
325695,
288835,
286787,
307269,
237638,
313415,
239689,
315468,
311373,
333902,
196687,
278607,
311377,
354386,
233548,
329812,
315477,
223317,
200795,
323678,
315488,
315489,
45154,
321632,
280676,
313446,
215144,
307306,
194667,
233578,
278637,
288878,
319599,
284789,
284790,
131190,
288890,
292987,
215165,
131199,
194692,
235661,
278669,
241809,
323730,
278676,
311447,
153752,
327834,
284827,
278684,
329884,
299166,
278690,
311459,
215204,
284840,
299176,
278698,
284843,
184489,
278703,
323761,
184498,
278707,
125108,
258233,
278713,
280761,
223418,
295099,
227517,
280767,
180409,
299197,
299202,
139459,
309443,
227525,
131270,
301255,
176325,
280779,
282832,
321744,
227536,
229591,
280792,
301271,
311520,
325857,
334049,
280803,
307431,
182503,
319719,
295147,
317676,
286957,
125166,
125170,
313595,
125180,
184574,
309504,
125184,
217352,
125192,
194832,
227601,
325904,
319764,
278805,
125204,
315674,
282908,
311582,
299294,
282912,
278817,
233761,
211239,
282920,
125225,
317738,
321839,
315698,
98611,
332084,
282938,
278843,
307514,
168251,
287040,
319812,
332100,
311622,
227655,
280903,
319816,
323914,
201037,
229716,
289109,
168280,
379224,
323934,
332128,
391521,
239973,
381286,
285031,
416103,
313703,
280938,
242027,
242028,
321901,
354671,
278895,
287089,
199030,
227702,
315768,
315769,
291194,
223611,
248188,
291193,
139641,
211327,
291200,
311679,
240003,
158087,
313736,
227721,
242059,
311692,
227730,
285074,
240020,
190870,
315798,
190872,
291225,
293275,
285083,
317851,
242079,
227743,
293281,
285089,
289185,
305572,
156069,
283039,
301482,
311723,
289195,
377265,
338359,
311739,
319931,
293309,
278974,
311744,
317889,
291266,
278979,
326083,
278988,
289229,
281038,
281039,
278992,
283088,
283089,
326093,
279000,
242138,
176602,
160224,
279009,
369121,
188899,
195044,
291297,
279014,
285152,
319976,
279017,
242150,
311787,
281071,
319986,
236020,
279030,
311800,
279033,
317949,
279042,
283138,
233987,
287237,
377352,
322057,
309770,
342537,
279053,
283154,
303634,
303635,
279061,
182802,
279060,
279066,
188954,
322077,
291359,
227881,
293420,
236080,
283185,
289328,
279092,
23093,
234037,
244279,
244280,
338491,
234044,
301635,
309831,
55880,
377419,
281165,
303693,
301647,
281170,
115287,
309847,
189016,
332379,
111197,
295518,
287327,
242274,
244326,
279143,
279150,
281200,
287345,
301688,
244345,
189054,
287359,
297600,
303743,
291455,
301702,
164487,
311944,
279176,
316044,
311948,
311950,
184974,
316048,
311953,
316050,
287379,
326288,
227991,
295575,
289435,
303772,
205469,
221853,
285348,
314020,
279207,
295591,
248494,
279215,
293552,
295598,
299698,
318127,
164532,
166581,
342705,
154295,
285360,
287412,
287418,
314043,
303802,
66243,
291529,
287434,
225996,
363212,
287438,
242385,
303826,
279249,
279253,
158424,
230105,
299737,
322269,
295653,
342757,
289511,
230120,
330473,
234216,
285419,
330476,
289517,
312046,
170735,
279278,
215790,
125683,
230133,
199415,
234233,
242428,
279293,
205566,
322302,
291584,
299777,
289534,
228099,
285443,
322312,
285450,
264971,
312076,
326413,
322320,
285457,
295698,
166677,
283418,
285467,
326428,
221980,
281378,
234276,
283431,
318247,
279337,
293673,
318251,
289580,
262952,
262953,
164655,
301872,
303921,
234290,
328495,
262957,
285493,
230198,
285496,
301883,
201534,
281407,
289599,
295745,
342846,
222017,
293702,
318279,
281426,
279379,
244569,
281434,
295769,
322396,
201562,
230238,
230239,
275294,
279393,
293729,
349025,
281444,
303973,
279398,
301919,
351078,
177002,
308075,
242540,
310132,
295797,
201590,
228214,
295799,
207735,
177018,
269179,
279418,
308093,
314240,
291713,
158594,
240517,
287623,
299912,
416649,
279434,
316299,
252812,
228232,
320394,
308111,
189327,
308113,
293780,
310166,
289691,
209820,
283551,
240543,
310177,
289699,
189349,
289704,
293801,
279465,
326571,
177074,
304050,
326580,
289720,
326586,
289723,
189373,
213956,
281541,
19398,
345030,
213961,
279499,
56270,
191445,
183254,
304086,
234469,
314343,
304104,
324587,
183276,
320492,
234476,
203758,
320495,
289773,
287730,
240631,
320504,
214009,
312313,
312315,
312317,
328701,
328705,
234499,
320520,
230411,
322571,
320526,
330766,
234513,
238611,
140311,
293911,
238617,
197658,
316441,
113710,
281647,
189487,
322609,
312372,
203829,
238646,
300087,
238650,
320571,
21567,
308288,
160834,
336962,
314437,
349254,
238663,
300109,
234578,
207954,
205911,
296023,
314458,
156763,
281698,
285795,
214116,
230500,
281699,
322664,
228457,
279659,
318571,
234606,
300145,
279666,
312435,
187508,
238706,
300147,
230514,
302202,
285819,
314493,
285823,
150656,
234626,
279686,
222344,
285833,
318602,
285834,
228492,
337037,
234635,
177297,
162962,
187539,
326803,
308375,
324761,
285850,
296091,
119965,
302239,
300192,
339106,
306339,
234662,
300200,
249003,
208044,
238764,
322733,
302251,
3243,
294069,
300215,
64699,
294075,
228541,
283841,
283846,
312519,
279752,
283849,
148687,
290001,
189651,
316628,
279766,
189656,
279775,
304352,
298209,
310496,
304353,
279780,
228587,
279789,
290030,
302319,
251124,
316661,
283894,
208123,
292092,
279803,
228608,
320769,
234756,
322826,
242955,
177420,
312588,
318732,
126229,
245018,
320795,
318746,
239610,
320802,
130342,
304422,
292145,
298290,
312628,
300342,
159033,
333114,
333115,
286012,
222523,
279872,
181568,
193858,
216387,
279874,
300354,
300355,
372039,
294210,
304457,
230730,
294220,
296269,
234830,
224591,
238928,
222542,
296274,
314708,
318804,
283990,
314711,
357720,
300378,
300379,
294236,
314721,
292194,
230757,
281958,
134504,
306541,
284015,
296304,
327023,
234864,
316786,
314740,
230772,
327030,
310650,
290170,
224637,
306558,
290176,
243073,
179586,
306561,
294278,
314759,
296328,
296330,
298378,
368012,
318860,
304523,
292242,
112019,
306580,
224662,
234902,
282008,
314776,
318876,
282013,
290206,
148899,
314788,
298406,
314790,
245160,
333224,
282023,
241067,
279980,
314797,
279979,
286128,
279988,
173492,
286133,
284086,
284090,
302523,
228796,
310714,
54719,
302530,
292291,
228804,
415170,
310725,
306630,
280003,
300488,
370122,
302539,
339403,
306634,
300490,
310735,
329168,
312785,
222674,
327122,
280020,
329170,
234957,
280025,
310747,
239069,
144862,
286176,
187877,
320997,
310758,
280042,
280043,
191980,
329198,
337391,
282097,
296434,
308722,
306678,
40439,
191991,
288248,
286201,
300539,
288252,
312830,
290304,
245249,
228868,
292359,
218632,
230922,
302602,
323083,
294413,
304655,
329231,
282132,
230933,
302613,
316951,
282135,
374297,
302620,
222754,
306730,
245291,
312879,
230960,
288305,
290359,
323132,
235069,
157246,
288319,
288322,
280131,
349764,
310853,
282182,
124486,
288328,
286281,
292426,
194118,
333389,
224848,
224852,
290391,
128600,
196184,
235096,
306777,
239192,
212574,
345697,
204386,
300643,
300645,
282214,
204394,
224874,
243306,
312941,
206447,
310896,
314997,
294517,
288377,
290425,
325246,
235136,
280193,
282244,
239238,
288391,
282248,
286344,
323208,
179853,
286351,
229011,
239251,
280217,
323226,
179868,
229021,
302751,
198304,
282272,
282279,
298664,
212649,
298666,
317102,
286387,
300725,
337590,
286392,
300729,
302778,
306875,
280252,
280253,
282302,
323262,
286400,
321217,
296636,
280259,
321220,
333508,
282309,
323265,
239305,
296649,
280266,
306891,
212684,
302798,
9935,
241360,
282321,
313042,
286419,
241366,
280279,
282330,
18139,
280285,
294621,
282336,
321250,
294629,
153318,
333543,
181992,
337638,
282347,
288492,
282349,
323315,
67316,
34547,
286457,
284410,
288508,
200444,
282366,
286463,
288515,
280326,
323335,
282375,
284425,
300810,
116491,
216844,
280333,
300812,
282379,
284430,
161553,
124691,
278292,
118549,
116502,
278294,
284436,
282390,
325403,
321308,
321309,
282399,
241440,
282401,
325411,
315172,
186149,
280011,
241447,
333609,
286507,
294699,
284460,
280367,
300849,
282418,
280373,
282424,
321338,
282428,
280381,
345918,
413500,
241471,
280386,
280391,
153416,
315209,
325449,
159563,
280396,
307024,
317268,
237397,
241494,
18263,
307030,
188250,
284508,
300893,
307038,
237411,
284515,
276326,
282471,
296807,
292713,
282476,
292719,
296815,
325491,
333687,
317305,
124795,
317308,
339840,
315265,
280451,
188293,
243590,
282503,
305032,
67464,
315272,
315275,
325514,
311183,
279218,
184207,
124816,
282517,
294806,
337816,
294808,
124826,
239515,
214943,
298912,
319393,
333727,
294820,
219046,
284584,
294824,
313257,
298921,
310731,
292783,
126896,
200628,
300983,
343993,
288698,
98240,
294849,
214978,
280517,
280518,
214983,
282572,
282573,
153553,
24531,
231382,
329696,
292835,
6116,
190437,
292838,
294887,
317416,
313322,
329707,
278507,
311277,
296942,
298987,
124912,
278515,
325620,
313338
] |
fa61c548936275320c796012fc353f928a835c6a | 409059c0b0b357e7f53453780146dad77bb316d3 | /WhiteBloodcellCount/MacawChartView.swift | aab918d8c37c8e0e478760bfa3612940b60c3d59 | [] | no_license | leyenphi2000/HemoCount | 2769419ef494f09d3c447c4a5628547bde567801 | b0d30c36d84136924e3d30017e9056e19b6c6074 | refs/heads/master | 2023-01-05T20:52:25.532594 | 2020-10-31T21:42:43 | 2020-10-31T21:42:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,997 | swift | //
// MacawChartView.swift
// WhiteBloodcellCount
//
// Created by Tom Riddle on 10/17/20.
//
import Foundation
import Macaw
class MacawChartView: MacawView {
static var lastFiveShows = createDummyData()
static let maxValue = 1200
static let maxValueLineHeight = 300
static let lineWidth: Double = 400
static let dataDivisor = Double(maxValue/maxValueLineHeight)
static let adjustedData: [Double] = lastFiveShows.map({$0.amount / dataDivisor})
static var animations: [Animation] = []
required init?(coder aDecoder: NSCoder) {
super.init(node: MacawChartView.createChart(), coder: aDecoder)
backgroundColor = .clear
}
public static func setData(_ data : [BloodCell]) {
print("Called set Data")
lastFiveShows = data
}
private static func createChart() -> Group {
var items: [Node] = addYAxisItems() + addXAxisItems()
items.append(createBars())
return Group(contents: items, place: .identity)
}
private static func addYAxisItems() -> [Node] {
let maxLines = 10
let lineInterval = Int(maxValue/maxLines)
let yAxisHeight: Double = 300
let lineSpacing: Double = 30
var newNodes: [Node] = []
for i in 0...maxLines {
let y = yAxisHeight - (Double(i) * lineSpacing)
let valueLine = Line(x1: -5, y1: y, x2: lineWidth, y2: y).stroke(fill: Color.black.with(a: 0.10))
let valueText = Text(text: "\(i * lineInterval / 10)", align: .max, baseline: .mid, place: .move(dx: -10, dy: y))
valueText.fill = Color.black
newNodes.append(valueLine)
newNodes.append(valueText)
}
let yAxis = Line(x1: 0, y1: 0, x2: 0, y2: yAxisHeight).stroke(fill: Color.black.with(a: 0.25))
newNodes.append(yAxis)
return newNodes
}
private static func addXAxisItems() -> [Node] {
let chartBaseY: Double = 300
var newNodes: [Node] = []
for i in 1...adjustedData.count {
let x = (Double(i) * 100)
let nameText = Text(text: (lastFiveShows[i-1].name), align: .max, baseline: .mid, place: .move(dx: x - 25, dy: chartBaseY + 15))
nameText.fill = Color.black
newNodes.append(nameText)
let valueText = Text(text: "\(Int(lastFiveShows[i-1].amount))", align: .max, baseline: .mid, place: .move(dx: x - 55, dy: chartBaseY - adjustedData[i-1]*10 - 10.0))
valueText.fill = Color.black
newNodes.append(valueText)
}
//add label
//TODO: change font size
let chartLabelText = Text(text: "Blood Cell Count", align: .max, baseline: .mid, place: .move(dx: 200 + 20, dy: chartBaseY + 60))
chartLabelText.fill = Color.blue
newNodes.append(chartLabelText)
//
let xAxis = Line(x1: 0, y1: chartBaseY, x2: lineWidth, y2: chartBaseY).stroke(fill: Color.black.with(a: 0.25))
newNodes.append(xAxis)
return newNodes
}
private static func createBars() -> Group {
let fill = LinearGradient(degree: 90, from: Color(val: 0x2C71EA), to: Color(val: 0x2C71EA).with(a: 0.33))
let items = adjustedData.map { _ in Group() }
animations = items.enumerated().map { (i: Int, item: Group) in
item.contentsVar.animation(delay: Double(i) * 0.1) { t in
let height = adjustedData[i] * t
let rect = Rect(x: Double(i) * 100 + 25, y: 300 - height * 10, w: 30, h: height * 10)
return [rect.fill(with: fill)]
}
}
return items.group()
}
static func playAnimation() {
animations.combine().play()
}
private static func createDummyData() -> [BloodCell] {
let one = BloodCell(name: "Eosinophil", amount: 522)
let two = BloodCell(name: "Lymphocyte", amount: 620)
let three = BloodCell(name: "Lymphocyte", amount: 456)
let four = BloodCell(name: "Neutrophil", amount: 568)
return [one, two, three, four]
}
}
/*
*Data to visualize:
*blood cell names - percentage : [Basophil, Eosinophil, Lymphocyte, Monocyte, Neutrophil] - [5,10,20,30,40]
*/
| [
-1
] |
c215670f2659b9cd5dfa6a80d43ccab07773b83a | 096e6a761d01e6269bcf5aab24b47c1f9b2ca603 | /Sources/AWSSDKSwift/Services/ElasticsearchService/ElasticsearchService_API.swift | 2d9ede58fa8f363d07c06e33e3b4abc55f1de5ee | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | lfernandez148/aws-sdk-swift | a5c2a39de8027df50f4d5fcffccfd883cf0308cb | d20b163e245b81d5b874e1adabe31106adc94262 | refs/heads/master | 2022-07-31T10:49:33.781512 | 2020-05-16T13:23:17 | 2020-05-16T13:23:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 16,977 | swift | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
@_exported import AWSSDKSwiftCore
import NIO
/**
Client object for interacting with AWS ElasticsearchService service.
Amazon Elasticsearch Configuration Service Use the Amazon Elasticsearch Configuration API to create, configure, and manage Elasticsearch domains. For sample code that uses the Configuration API, see the Amazon Elasticsearch Service Developer Guide. The guide also contains sample code for sending signed HTTP requests to the Elasticsearch APIs. The endpoint for configuration service requests is region-specific: es.region.amazonaws.com. For example, es.us-east-1.amazonaws.com. For a current list of supported regions and endpoints, see Regions and Endpoints.
*/
public struct ElasticsearchService {
//MARK: Member variables
public let client: AWSClient
//MARK: Initialization
/// Initialize the ElasticsearchService client
/// - parameters:
/// - accessKeyId: Public access key provided by AWS
/// - secretAccessKey: Private access key provided by AWS
/// - sessionToken: Token provided by STS.AssumeRole() which allows access to another AWS account
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - middlewares: Array of middlewares to apply to requests and responses
/// - httpClientProvider: HTTPClient to use. Use `createNew` if the client should manage its own HTTPClient.
public init(
accessKeyId: String? = nil,
secretAccessKey: String? = nil,
sessionToken: String? = nil,
region: AWSSDKSwiftCore.Region? = nil,
partition: AWSSDKSwiftCore.Partition = .aws,
endpoint: String? = nil,
middlewares: [AWSServiceMiddleware] = [],
httpClientProvider: AWSClient.HTTPClientProvider = .createNew
) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
partition: region?.partition ?? partition,
service: "es",
serviceProtocol: .restjson,
apiVersion: "2015-01-01",
endpoint: endpoint,
middlewares: middlewares,
possibleErrorTypes: [ElasticsearchServiceErrorType.self],
httpClientProvider: httpClientProvider
)
}
//MARK: API Calls
/// Attaches tags to an existing Elasticsearch domain. Tags are a set of case-sensitive key value pairs. An Elasticsearch domain may have up to 10 tags. See Tagging Amazon Elasticsearch Service Domains for more information.
@discardableResult public func addTags(_ input: AddTagsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return client.send(operation: "AddTags", path: "/2015-01-01/tags", httpMethod: "POST", input: input, on: eventLoop)
}
/// Associates a package with an Amazon ES domain.
public func associatePackage(_ input: AssociatePackageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AssociatePackageResponse> {
return client.send(operation: "AssociatePackage", path: "/2015-01-01/packages/associate/{PackageID}/{DomainName}", httpMethod: "POST", input: input, on: eventLoop)
}
/// Cancels a scheduled service software update for an Amazon ES domain. You can only perform this operation before the AutomatedUpdateDate and when the UpdateStatus is in the PENDING_UPDATE state.
public func cancelElasticsearchServiceSoftwareUpdate(_ input: CancelElasticsearchServiceSoftwareUpdateRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CancelElasticsearchServiceSoftwareUpdateResponse> {
return client.send(operation: "CancelElasticsearchServiceSoftwareUpdate", path: "/2015-01-01/es/serviceSoftwareUpdate/cancel", httpMethod: "POST", input: input, on: eventLoop)
}
/// Creates a new Elasticsearch domain. For more information, see Creating Elasticsearch Domains in the Amazon Elasticsearch Service Developer Guide.
public func createElasticsearchDomain(_ input: CreateElasticsearchDomainRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateElasticsearchDomainResponse> {
return client.send(operation: "CreateElasticsearchDomain", path: "/2015-01-01/es/domain", httpMethod: "POST", input: input, on: eventLoop)
}
/// Create a package for use with Amazon ES domains.
public func createPackage(_ input: CreatePackageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePackageResponse> {
return client.send(operation: "CreatePackage", path: "/2015-01-01/packages", httpMethod: "POST", input: input, on: eventLoop)
}
/// Permanently deletes the specified Elasticsearch domain and all of its data. Once a domain is deleted, it cannot be recovered.
public func deleteElasticsearchDomain(_ input: DeleteElasticsearchDomainRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteElasticsearchDomainResponse> {
return client.send(operation: "DeleteElasticsearchDomain", path: "/2015-01-01/es/domain/{DomainName}", httpMethod: "DELETE", input: input, on: eventLoop)
}
/// Deletes the service-linked role that Elasticsearch Service uses to manage and maintain VPC domains. Role deletion will fail if any existing VPC domains use the role. You must delete any such Elasticsearch domains before deleting the role. See Deleting Elasticsearch Service Role in VPC Endpoints for Amazon Elasticsearch Service Domains.
@discardableResult public func deleteElasticsearchServiceRole(on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return client.send(operation: "DeleteElasticsearchServiceRole", path: "/2015-01-01/es/role", httpMethod: "DELETE", on: eventLoop)
}
/// Delete the package.
public func deletePackage(_ input: DeletePackageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePackageResponse> {
return client.send(operation: "DeletePackage", path: "/2015-01-01/packages/{PackageID}", httpMethod: "DELETE", input: input, on: eventLoop)
}
/// Returns domain configuration information about the specified Elasticsearch domain, including the domain ID, domain endpoint, and domain ARN.
public func describeElasticsearchDomain(_ input: DescribeElasticsearchDomainRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeElasticsearchDomainResponse> {
return client.send(operation: "DescribeElasticsearchDomain", path: "/2015-01-01/es/domain/{DomainName}", httpMethod: "GET", input: input, on: eventLoop)
}
/// Provides cluster configuration information about the specified Elasticsearch domain, such as the state, creation date, update version, and update date for cluster options.
public func describeElasticsearchDomainConfig(_ input: DescribeElasticsearchDomainConfigRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeElasticsearchDomainConfigResponse> {
return client.send(operation: "DescribeElasticsearchDomainConfig", path: "/2015-01-01/es/domain/{DomainName}/config", httpMethod: "GET", input: input, on: eventLoop)
}
/// Returns domain configuration information about the specified Elasticsearch domains, including the domain ID, domain endpoint, and domain ARN.
public func describeElasticsearchDomains(_ input: DescribeElasticsearchDomainsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeElasticsearchDomainsResponse> {
return client.send(operation: "DescribeElasticsearchDomains", path: "/2015-01-01/es/domain-info", httpMethod: "POST", input: input, on: eventLoop)
}
/// Describe Elasticsearch Limits for a given InstanceType and ElasticsearchVersion. When modifying existing Domain, specify the DomainName to know what Limits are supported for modifying.
public func describeElasticsearchInstanceTypeLimits(_ input: DescribeElasticsearchInstanceTypeLimitsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeElasticsearchInstanceTypeLimitsResponse> {
return client.send(operation: "DescribeElasticsearchInstanceTypeLimits", path: "/2015-01-01/es/instanceTypeLimits/{ElasticsearchVersion}/{InstanceType}", httpMethod: "GET", input: input, on: eventLoop)
}
/// Describes all packages available to Amazon ES. Includes options for filtering, limiting the number of results, and pagination.
public func describePackages(_ input: DescribePackagesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePackagesResponse> {
return client.send(operation: "DescribePackages", path: "/2015-01-01/packages/describe", httpMethod: "POST", input: input, on: eventLoop)
}
/// Lists available reserved Elasticsearch instance offerings.
public func describeReservedElasticsearchInstanceOfferings(_ input: DescribeReservedElasticsearchInstanceOfferingsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReservedElasticsearchInstanceOfferingsResponse> {
return client.send(operation: "DescribeReservedElasticsearchInstanceOfferings", path: "/2015-01-01/es/reservedInstanceOfferings", httpMethod: "GET", input: input, on: eventLoop)
}
/// Returns information about reserved Elasticsearch instances for this account.
public func describeReservedElasticsearchInstances(_ input: DescribeReservedElasticsearchInstancesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReservedElasticsearchInstancesResponse> {
return client.send(operation: "DescribeReservedElasticsearchInstances", path: "/2015-01-01/es/reservedInstances", httpMethod: "GET", input: input, on: eventLoop)
}
/// Dissociates a package from the Amazon ES domain.
public func dissociatePackage(_ input: DissociatePackageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DissociatePackageResponse> {
return client.send(operation: "DissociatePackage", path: "/2015-01-01/packages/dissociate/{PackageID}/{DomainName}", httpMethod: "POST", input: input, on: eventLoop)
}
/// Returns a list of upgrade compatible Elastisearch versions. You can optionally pass a DomainName to get all upgrade compatible Elasticsearch versions for that specific domain.
public func getCompatibleElasticsearchVersions(_ input: GetCompatibleElasticsearchVersionsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetCompatibleElasticsearchVersionsResponse> {
return client.send(operation: "GetCompatibleElasticsearchVersions", path: "/2015-01-01/es/compatibleVersions", httpMethod: "GET", input: input, on: eventLoop)
}
/// Retrieves the complete history of the last 10 upgrades that were performed on the domain.
public func getUpgradeHistory(_ input: GetUpgradeHistoryRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetUpgradeHistoryResponse> {
return client.send(operation: "GetUpgradeHistory", path: "/2015-01-01/es/upgradeDomain/{DomainName}/history", httpMethod: "GET", input: input, on: eventLoop)
}
/// Retrieves the latest status of the last upgrade or upgrade eligibility check that was performed on the domain.
public func getUpgradeStatus(_ input: GetUpgradeStatusRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetUpgradeStatusResponse> {
return client.send(operation: "GetUpgradeStatus", path: "/2015-01-01/es/upgradeDomain/{DomainName}/status", httpMethod: "GET", input: input, on: eventLoop)
}
/// Returns the name of all Elasticsearch domains owned by the current user's account.
public func listDomainNames(on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDomainNamesResponse> {
return client.send(operation: "ListDomainNames", path: "/2015-01-01/domain", httpMethod: "GET", on: eventLoop)
}
/// Lists all Amazon ES domains associated with the package.
public func listDomainsForPackage(_ input: ListDomainsForPackageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDomainsForPackageResponse> {
return client.send(operation: "ListDomainsForPackage", path: "/2015-01-01/packages/{PackageID}/domains", httpMethod: "GET", input: input, on: eventLoop)
}
/// List all Elasticsearch instance types that are supported for given ElasticsearchVersion
public func listElasticsearchInstanceTypes(_ input: ListElasticsearchInstanceTypesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListElasticsearchInstanceTypesResponse> {
return client.send(operation: "ListElasticsearchInstanceTypes", path: "/2015-01-01/es/instanceTypes/{ElasticsearchVersion}", httpMethod: "GET", input: input, on: eventLoop)
}
/// List all supported Elasticsearch versions
public func listElasticsearchVersions(_ input: ListElasticsearchVersionsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListElasticsearchVersionsResponse> {
return client.send(operation: "ListElasticsearchVersions", path: "/2015-01-01/es/versions", httpMethod: "GET", input: input, on: eventLoop)
}
/// Lists all packages associated with the Amazon ES domain.
public func listPackagesForDomain(_ input: ListPackagesForDomainRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPackagesForDomainResponse> {
return client.send(operation: "ListPackagesForDomain", path: "/2015-01-01/domain/{DomainName}/packages", httpMethod: "GET", input: input, on: eventLoop)
}
/// Returns all tags for the given Elasticsearch domain.
public func listTags(_ input: ListTagsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsResponse> {
return client.send(operation: "ListTags", path: "/2015-01-01/tags/", httpMethod: "GET", input: input, on: eventLoop)
}
/// Allows you to purchase reserved Elasticsearch instances.
public func purchaseReservedElasticsearchInstanceOffering(_ input: PurchaseReservedElasticsearchInstanceOfferingRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PurchaseReservedElasticsearchInstanceOfferingResponse> {
return client.send(operation: "PurchaseReservedElasticsearchInstanceOffering", path: "/2015-01-01/es/purchaseReservedInstanceOffering", httpMethod: "POST", input: input, on: eventLoop)
}
/// Removes the specified set of tags from the specified Elasticsearch domain.
@discardableResult public func removeTags(_ input: RemoveTagsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return client.send(operation: "RemoveTags", path: "/2015-01-01/tags-removal", httpMethod: "POST", input: input, on: eventLoop)
}
/// Schedules a service software update for an Amazon ES domain.
public func startElasticsearchServiceSoftwareUpdate(_ input: StartElasticsearchServiceSoftwareUpdateRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartElasticsearchServiceSoftwareUpdateResponse> {
return client.send(operation: "StartElasticsearchServiceSoftwareUpdate", path: "/2015-01-01/es/serviceSoftwareUpdate/start", httpMethod: "POST", input: input, on: eventLoop)
}
/// Modifies the cluster configuration of the specified Elasticsearch domain, setting as setting the instance type and the number of instances.
public func updateElasticsearchDomainConfig(_ input: UpdateElasticsearchDomainConfigRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateElasticsearchDomainConfigResponse> {
return client.send(operation: "UpdateElasticsearchDomainConfig", path: "/2015-01-01/es/domain/{DomainName}/config", httpMethod: "POST", input: input, on: eventLoop)
}
/// Allows you to either upgrade your domain or perform an Upgrade eligibility check to a compatible Elasticsearch version.
public func upgradeElasticsearchDomain(_ input: UpgradeElasticsearchDomainRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpgradeElasticsearchDomainResponse> {
return client.send(operation: "UpgradeElasticsearchDomain", path: "/2015-01-01/es/upgradeDomain", httpMethod: "POST", input: input, on: eventLoop)
}
}
| [
-1
] |
054c988c432463ae195e92106f8b3a750ada19c6 | 3ee498b2d2fd5eb4ee884c0664437e5a70eed249 | /Swift 习题集/SwiftProblemSet.playground/Pages/Challenge.xcplaygroundpage/Contents.swift | f94ca573445ac694bf21be74ed904f0241da0781 | [] | no_license | LarryEmerson/Udacity | d2a63ee5e426e181a2f90f4e54cc3fb8235c21b6 | cc10b7cfd6df2c3d97c5464bbfcf3f9514cc98bd | refs/heads/master | 2021-01-22T19:09:31.951217 | 2017-03-16T08:56:21 | 2017-03-16T08:56:21 | 85,173,547 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,023 | swift | /*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous)
****
*/
import Foundation
//: ## Challenge
//: **This exercise is completely optional and is not required for completing the Swift Problem Set.**
//: ### Challenge 1
//: Mystery code! What does this code do? Briefly, using comments, describe what is happening in each line. **Hint**: You may need to look up [Int initializers](http://stackoverflow.com/questions/30739460/toint-removed-in-swift-2).
let array = ["A", "13", "B", "5", "87", "t", "41"]//initialize an array of strings with different values
var sum = 0 // define a var that holds the sum value
for string in array {//iterate through the array
if Int(string) != nil {//if the int value converted from the string is valid
let intToAdd = Int(string)!//set intToAdd to the int value converted from the string
sum += intToAdd//calculate the sum value
}
}
print(sum)//print out the sum
/*:
****
[Table of Contents](Table%20of%20Contents) | [Previous](@previous)
*/
| [
-1
] |
608cc928e2ecfd0ffafd34f9ed07802cbf3ccae9 | a31e04935b6f2467d48c086a3bb8faffc80a7d7e | /TinkoffNews/UI/NewsArticlesListViewController.swift | 418c1df150230a1090e4e77ba1e9f453d10104b1 | [] | no_license | Shedward/TinkoffNews | a7914f62d640cb17d2ca8029d45aaa63c2e2c941 | d550a0d3b64432b0d0dfbe96ee7db9af40769251 | refs/heads/master | 2021-07-12T10:09:49.849146 | 2017-10-17T01:36:55 | 2017-10-17T01:36:55 | 107,202,371 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 5,200 | swift | //
// ArticlesListViewController.swift
// TinkoffNews
//
// Created by Vladislav Maltsev on 16.10.17.
// Copyright © 2017 Shedward. All rights reserved.
//
import UIKit
enum NewsArticlesListViewControllerSegue: Segue {
case showArticleDetails(NewsArticle)
var segueIdentifier: String {
switch self {
case .showArticleDetails: return "ShowArticleDetails"
}
}
}
class NewsArticlesListViewController: UITableViewController, ArticlesListDataSourceDelegate {
var articlesDataSource: ArticlesListDataSource!
override func viewDidLoad() {
configurePullToRefresh()
self.articlesDataSource = ArticlesListDataSource(delegate: self)
tableView.dataSource = articlesDataSource
tableView.delegate = self
showRefreshing()
articlesDataSource.reload()
NotificationCenter.default.addObserver(self, selector: #selector(repositoriesDidFinishInitialization), name: ApplicationNotification.repositoriesAreReady.name, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func didPullToRefresh() {
articlesDataSource.reload(droppingCache: true)
}
@objc private func repositoriesDidFinishInitialization() {
articlesDataSource.reload()
}
private func configurePullToRefresh() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
self.refreshControl = refreshControl
}
private func showRefreshing() {
guard let refreshControl = self.refreshControl else {
return
}
tableView.setContentOffset(CGPoint(x: 0, y: -refreshControl.frame.size.height), animated: true)
refreshControl.beginRefreshing()
}
// ArticlesListDataSourceDelegate
func dataSourceDidUpdateArticles(_ dataSource: ArticlesListDataSource) {
tableView.reloadData()
refreshControl?.endRefreshing()
}
func dataSource(_ dataSource: ArticlesListDataSource, didFailedWithError error: Error) {
refreshControl?.endRefreshing()
show(error: error)
}
// Navigation
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let article = articlesDataSource.article(at: indexPath)
performSegue(NewsArticlesListViewControllerSegue.showArticleDetails(article))
}
override func prepare(for storyboardSegue: UIStoryboardSegue, sender: Any?) {
guard let segue = sender as? NewsArticlesListViewControllerSegue else {
return
}
switch segue {
case .showArticleDetails(let article):
let destinationViewController = storyboardSegue.destination as! NewsArticleDetailsViewController
destinationViewController.articleId = article.id
destinationViewController.title = article.title
}
}
}
protocol ArticlesListDataSourceDelegate: class {
func dataSourceDidUpdateArticles(_ dataSource: ArticlesListDataSource)
func dataSource(_ dataSource: ArticlesListDataSource, didFailedWithError error: Error)
}
class ArticlesListDataSource: NSObject, UITableViewDataSource {
private var articles: [NewsArticle] = []
weak var delegate: ArticlesListDataSourceDelegate?
init(delegate: ArticlesListDataSourceDelegate) {
self.delegate = delegate
}
func reload(droppingCache: Bool = false) {
guard let newsRepository = Application.shared.newsRepository else {
self.delegate?.dataSourceDidUpdateArticles(self)
return
}
let loadData = { () in
newsRepository.articles { [weak self] result in
DispatchQueue.main.async {
guard let `self` = self else { return }
switch result {
case .success(let articles):
self.articles = articles
self.delegate?.dataSourceDidUpdateArticles(self)
case .failure(let error):
self.delegate?.dataSource(self, didFailedWithError: error)
}
}
}
}
if droppingCache {
newsRepository.clearCache {
loadData()
}
} else {
loadData()
}
}
func article(at indexPath: IndexPath) -> NewsArticle {
return articles[indexPath.item]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let articleCell = tableView.dequeueReusableCell(withIdentifier: String(describing: NewsArticlesListCell.self)) as! NewsArticlesListCell
let article = self.article(at: indexPath)
articleCell.configure(with: article)
return articleCell
}
}
| [
-1
] |
cbfaa55760bd8ee515df82a262512e07145eef41 | 82101e9870f22290f0f92c9b7fd2a8a63558c256 | /NewSwiftUI/NewSwiftUI/NewSwiftUI/AddSightingView.swift | f631b4bc2092f60b8ba0fa734f7f4718bec64e58 | [] | no_license | stevencurtis/SwiftCoding | d1948f43ed3f7fa92c1a029bc9898e513d1d6908 | 5359a6cd7a4de5e830491a7e1448d9882f1cf860 | refs/heads/master | 2023-08-30T20:28:38.279385 | 2023-08-25T16:16:50 | 2023-08-25T16:16:50 | 272,769,641 | 537 | 182 | null | 2023-03-19T10:00:37 | 2020-06-16T17:21:51 | Swift | UTF-8 | Swift | false | false | 1,171 | swift | //
// AddSightingView.swift
// NewSwiftUI
//
// Created by Steven Curtis on 07/06/2023.
//
import SwiftData
import SwiftUI
struct AddSightingView: View {
@State private var model = DogDetails()
var body: some View {
Form {
Section {
TextField("Name", text: $model.dogName)
DogBreedPicker(selection: $model.dogBreed)
}
Section {
TextField("Location", text: $model.location)
}
}
}
struct DogBreedPicker: View {
@Binding var selection: DogBreed
var body: some View {
Picker("Breed", selection: $selection) {
ForEach(DogBreed.allCases) {
Text($0.rawValue.capitalized)
.tag($0.id)
}
}
}
}
@Observable
class DogDetails {
var dogName = ""
var dogBreed = DogBreed.mutt
var location = ""
}
enum DogBreed: String, CaseIterable, Identifiable {
case mutt
case husky
case beagle
var id: Self { self }
}
}
#Preview {
AddSightingView()
}
| [
-1
] |