text
stringlengths
8
1.32M
// // SheetNavigator.swift // SwiftUINavigationViewWork // // Created by Sinan Ulusan on 7.01.2021. // import SwiftUI class SheetNavigator: ObservableObject { // MARK: - Enumaretions enum SheetDestination { case firstView case secondView } // MARK: - Properties static let shared = SheetNavigator() @Published var firstViewIsPresented = false @Published var secondViewIsPresented = false var sheetDestination: SheetDestination = .secondView }
// // ButtonView.swift // Calculator // // Created by Nikita Semenov on 12.01.2021. // import SwiftUI // View of single number button in calculator struct ButtonView: View { var backgroundColor: Color var fontWeight: Font.Weight? var fontColor: Color var sign = "" var action: () -> Void init(bgColor: Color, fW: Font.Weight?, fColor: Color, sign: String, action: @escaping () -> Void) { backgroundColor = bgColor fontWeight = fW fontColor = fColor self.action = action self.sign = sign } var body: some View { GeometryReader { geom in Button(action: { action() }, label: { if sign == "TIP" || sign == "," || sign == "C" { Text(sign) .fontWeight(fontWeight) } else if let _ = Int(sign) { Text(sign) .fontWeight(fontWeight) } else if let _ = Double(sign) { Text(sign) .fontWeight(fontWeight) } else { Image(systemName: sign) } }) .font(.title) .foregroundColor(fontColor) .frame(width: geom.size.width, height: 80) .background(backgroundColor) .clipShape(Capsule()) } } } struct ButtonView_Previews: PreviewProvider { static var previews: some View { ButtonView(bgColor: .orange, fW: .semibold, fColor: .white, sign: "equal", action: { }) } }
// // SubPayTableViewCell.swift // huicheng // // Created by lvxin on 2018/3/18. // Copyright © 2018年 lvxin. All rights reserved. // 报销申请 import UIKit class SubPayTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state self.stateLabel.hc_makeRadius(radius: 1) } func setData(model :expense_getlistModel) { if let typeStr = model.type ,let money = model.money { self.titleLabel.text = "\(typeStr) \(money)元 " } if let total = model.total { self.subLabel.text = "共\(total)张附件" } if let time = model.addtime { self.timeLabel.text = time } if let stateStr = model.stateStr { self.stateLabel.text = stateStr } if let state = model.state { if state == 0 { self.stateLabel.backgroundColor = darkblueColor } else if state == 1 { self.stateLabel.backgroundColor = UIColor.hc_colorFromRGB(rgbValue: 0x999999) } else { self.stateLabel.backgroundColor = orangeColor } } } func setData_finance(model : finance_getlistModel) { if let type = model.typeStr ,let money = model.money { self.titleLabel.text = "\(type) \(money)元 " } if let num = model.num { self.subLabel.text = num } if let time = model.addtime { self.timeLabel.text = time } if let stateStr = model.stateStr { HCLog(message: stateStr) self.stateLabel.text = stateStr } if let state = model.state{ if state == 3 { self.stateLabel.backgroundColor = UIColor.hc_ColorFromInt(red: 204, green: 204, blue: 204, alpha: 1) } else { self.stateLabel.backgroundColor = darkblueColor } } } }
// // form-screen.swift // Yoyag // // Created by delver on 16.4.2018. // Copyright © 2018 delver. All rights reserved. // import UIKit import Alamofire protocol FormScreenViewControllerDelegate { } class form_screen: UIViewController { @IBOutlet weak var textArea: UITextView! var userID:String = "" var delegate:FormScreenViewControllerDelegate? 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 SubmitFormButton(_ sender: UIButton) { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "M/d/yyyy, hh:mm:ss a" formatter.amSymbol = "AM" formatter.pmSymbol = "PM" let dateString = formatter.string(from: Date()) print(dateString) let text: String = textArea.text print(text) let parameters: [String: Any] = [ "token": "ABRAKADABR@1237" as AnyObject, "userID": userID, "timestamp": dateString, "data": ["text": text] ] let url = "http://193.106.55.122/post" Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in print(response) //to get status code if let status = response.response?.statusCode { switch(status){ case 204: print("example success") default: print("error with response status: \(status)") } } self.performSegue(withIdentifier: "moveToFinishSubmitScreen", sender: Any?.self) } } /* // 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. } */ }
// // APIService.swift // iOS Concurrency // // Created by Andrei Chenchik on 9/12/21. // import Foundation struct APIService { let urlString: String func getJSON<T: Decodable>(dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<T, APIError>) -> Void) { guard let url = URL(string: urlString) else { completion(.failure(.invalidURL)) return } URLSession.shared.dataTask(with: url) { data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else{ completion(.failure(.invalidResponseStatus)) return } guard error == nil else { completion(.failure(.dataTaskError)) return } guard let data = data else { completion(.failure(.corruptData)) return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy decoder.keyDecodingStrategy = keyDecodingStrategy do { let decodedData = try decoder.decode(T.self, from: data) completion(.success(decodedData)) } catch { completion(.failure(.decodingError)) } } .resume() } } enum APIError: Error { case invalidURL case invalidResponseStatus case dataTaskError case corruptData case decodingError }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import Foundation let asyncSymbolString = "KittEntryPoint" let kBrowserActionToBeClosedNotification = "BrowserActionToBeClosedNotification" public extension NSObject { @objc dynamic func webView(_ webView: AnyObject?, didCreateJavaScriptContext context: JSContext!, forFrame frame: WebKitFrame!) { assert(webView === (frame as? NSObject)?.value(forKeyPath: "webView") as AnyObject) // find the frame originating webview /*let frameInternalWebView = frame.valueForKeyPath:("webView")*/ var originatingWebView: UIWebView? = nil for knownWebView in WebViewManager.sharedInstance.webViews { // Skip views which are not UIWebView if knownWebView.value(forKeyPath: "documentView.webView") as AnyObject === webView { originatingWebView = knownWebView break } } if let originatingWebView = originatingWebView { assert(frame.responds(to: #selector(WebKitFrame.parentFrame)), "WebKit frame does not implemented the expected protocol") DispatchQueue.main.async { type(of: self).didCreateJavaScriptContext(context, forFrame: frame, inWebView: originatingWebView) } } else { Log.error("Frame originating webview not found") } } // swiftlint:disable:next cyclomatic_complexity static func createCallbackForWebView(_ wWebView: SAWebView, forFrame wFrame: WebKitFrame) -> @convention(block) (Any?, Any?) -> Any? { return { [weak wWebView, weak wFrame] (inputCommand: Any?, inputData: Any?) in guard let command = inputCommand as? String else { Log.error("Command should be defined") return nil } guard let inputData = inputData as? [AnyHashable: Any] else { Log.error("Data should be defined") return nil } // sync command - no need for special handling if command == "i18n.getMessage" { if let frame = wFrame { return i18nGetMessage(wWebView, forFrame: frame, reqCommand: command, reqData: inputData) } return nil } if !Thread.isMainThread { // Store reference to web thread let injector = wWebView?.bridgeSwitchboard?.injector if injector?.webThread == nil { injector?.webThread = Thread.current } } DispatchQueue.main.async { guard let sWebView = wWebView, let sFrame = wFrame else { return } // Handle JS events if command == "JSContextEvent" { if let contentWebView = sWebView as? ContentWebView { let result = contentWebView.handleEvent(inputData["raw"], fromFrame: sFrame) assert(result, "Event wasn't processed!") } return } // Handle window open/close if sWebView is SAPopupWebView && ["core.open", "core.close"].contains(command) { NotificationCenter.default.post(name: Notification.Name(rawValue: kBrowserActionToBeClosedNotification), object: nil) return } guard let sBridgeSwitchboard = sWebView.bridgeSwitchboard else { return } sBridgeSwitchboard.handle(command, withData: inputData, fromWebView: sWebView, frame: sFrame) } return nil } } // swiftlint:disable:next cyclomatic_complexity function_body_length static func didCreateJavaScriptContext(_ context: JSContext, forFrame frame: WebKitFrame, inWebView webView: UIWebView) { assert(Thread.isMainThread, "didCreateJavaScriptContext is expected to be run on main thread") guard let webView = webView as? SAWebView else { Log.warn("Unknown type of webView") return } if let symbol = context.globalObject?.forProperty(asyncSymbolString), !symbol.isUndefined && !symbol.isNull { Log.warn("Callback symbol already exists in JSContext global object") } else { let callback = createCallbackForWebView(webView, forFrame: frame) context.globalObject?.setValue(callback, forProperty: asyncSymbolString) } // We call this function to get reference to web thread. // Callback needs to be performed using setTimeout, otherwise it is executed on calling thread. weak var wBridgeSwitchboard = webView.bridgeSwitchboard if wBridgeSwitchboard?.injector.webThread == nil { let setWebThread: @convention(block) () -> Void = { assert(!Thread.isMainThread, "This function should not be run on main thread") wBridgeSwitchboard?.injector.webThread = Thread.current } _ = context.globalObject?.forProperty("setTimeout").call(withArguments: [unsafeBitCast(setWebThread, to: AnyObject.self), 0]) } switch webView { case let contentWebView as SAContentWebView: contentWebView.changeCookieStorage(in: context) // Add frame context first. Frame hierarchy must be maintained regardless of // content script injection success or failure. let kittFrame = contentWebView.mainThreadAdd(context, from: frame) if let urlStr = kittFrame.fullURLString, let url = URL(string: urlStr) { if let frameId = kittFrame.frameId?.uintValue, let parentFrameId = kittFrame.parentFrameId?.intValue { // @todo @fixme // This is a wrong place for "onBeforeNavigate", basically it is too late. It should happen _before_ the // navigation even starts. Correctly it should be in every single place which can initiate the navigation, // per the TransitionType enumeration in "onCommitted" and equally for "history" API // https://developer.chrome.com/extensions/history#transition_types // But Adblock extension just wants to get the event, and does not care as much when it gets it, // so this is Good Enough For Now(TM) contentWebView.webNavigationEventsDelegate?.beforeNavigate( to: url, tabId: contentWebView.identifier, frameId: frameId, parentFrameId: parentFrameId) // @todo @fixme // This is a correct place for "onCommited" because the document is already downloading. However, the TransitionType // and TransitionQualifiers are unknown. It would again require marking in every single place which can initiate the // navigation, basically along all calls to "onBeforeNavigate" if it was correctly placed per the comment above. // But Adblock extension just wants to get the event and is interested only in url, tabId and frameId, so let's // fake the most common TransitionType and no qualifiers (it's optional) contentWebView.webNavigationEventsDelegate?.committedNavigation( to: url, tabId: contentWebView.identifier, frameId: frameId, type: .TransitionTypeLink, qualifiers: []) } else { Log.error("Frame \(urlStr) has invalid (parent)frameId, not invoking webNavigation.onBeforeNavigate") } guard let model = contentWebView.contentScriptLoaderDelegate, model.injectContentScript(to: context, with: url, of: contentWebView) != -1 else { Log.warn("Content script injection failed, removing callback entry symbol") context.globalObject.setValue(JSValue(undefinedIn: context), forProperty: asyncSymbolString) return // Swift static analysis doesn't know that this condition is the last in branch } } else { let frameId = String(describing: kittFrame.frameId) let parentId = String(describing: kittFrame.parentFrameId) let urlString = String(describing: kittFrame.fullURLString) Log.error("Frame \(frameId),\(parentId) has invalid URL '\(urlString)', content scripts not injected") } case let backgroundWebView as SABackgroundWebView: if let injector = backgroundWebView.bridgeSwitchboard?.injector { if let chrome = context.globalObject?.forProperty("chrome"), !chrome.isUndefined && !chrome.isNull { Log.warn("Chrome symbol already exists in JSContext global object") } else { backgroundWebView.loadBackgroundApi(with: injector) } } if let window = context.globalObject, window.isEqual(to: window.forProperty("top")) { webView.mainThreadAdd(context, from: frame) } default: // not a content webview, scripts are already injected // this jsc callback is a result of that injection if let window = context.globalObject, window.isEqual(to: window.forProperty("top")) { webView.mainThreadAdd(context, from: frame) } } } // swiftlint:disable:next cyclomatic_complexity function_body_length static func i18nGetMessage(_ webView: SAWebView?, forFrame: WebKitFrame, reqCommand: String, reqData: [AnyHashable: Any]) -> Any? { // here, we can always assume, that the json is in correct format guard let webView = webView else { assert(false, "Webview doesn't exist") return nil } guard let switchboard = webView.bridgeSwitchboard else { assert(false, "Webview did not provide bridgeSwitchboard") return nil } let context = reqData["c"] as? [AnyHashable: Any] guard let extensionId = context?["extensionId"] as? String else { assert(false, "No extensionId in reqData") return nil } let `extension` = switchboard.browserExtension(for: extensionId, from: webView) guard let json = `extension`?.translations else { assert(false, "The translation file in missing, or corrupt") return nil } let data = reqData["d"] as? [AnyHashable: Any] guard let messageName = data?["messageName"] as? String else { Log.warn("messageName is not set") return nil } // https://developer.chrome.com/extensions/i18n#overview-predefined if let predefRange = messageName.range(of: "@@"), predefRange.lowerBound == messageName.startIndex { func directionName(_ ltr: Bool) -> String { return ltr ? "ltr" : "rtl" } func directionEdge(_ ltr: Bool) -> String { return ltr ? "left" : "right" } let isLeftToRight = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight switch messageName[predefRange.upperBound...] { case "extension_id": return extensionId case "ui_locale": return Locale.current.identifier case "bidi_dir": return directionName(isLeftToRight) case "bidi_reversed_dir": return directionName(!isLeftToRight) case "bidi_start_edge": return directionEdge(isLeftToRight) case "bidi_end_edge": return directionEdge(!isLeftToRight) default: Log.warn("Unknown predefined message \(messageName)") return "" } } guard let messageItem = (json as? [String: Any])?[messageName] as? [String: Any] else { Log.warn("Message key (\(messageName)) not found in the file") return nil } return messageItem } }
// // MusicCollectionViewCell.swift // pairsessionone // // Created by Jesus Parada on 11/08/20. // Copyright © 2020 Andres Rivas. All rights reserved. // import UIKit class MusicCollectionViewCell: UICollectionViewCell { private lazy var songTitleLabel: UILabel = { let songTitleLabel = UILabel() songTitleLabel.translatesAutoresizingMaskIntoConstraints = false return songTitleLabel }() override init(frame: CGRect) { super.init(frame: frame) setUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUI() { contentView.addSubview(songTitleLabel) NSLayoutConstraint.activate([ songTitleLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), songTitleLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), songTitleLabel.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor), songTitleLabel.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor) ]) } func setSong(_ song: Results) { songTitleLabel.text = song.trackCensoredName } }
// // Article.swift // QiitaClient // // Created by nishihara on 2018/10/14. // Copyright © 2018年 paranishian. All rights reserved. // import Foundation struct Article: Codable { let title: String let url: String }
// // EchoService.swift // Bohrium // // Created by 井川司 on 2017/12/13. // import Foundation import KituraWebSocket import LoggerAPI class EchoService: WebSocketService { private var connections = [String:WebSocketConnection]() public func connected(connection: WebSocketConnection) { Log.info("connected: connection.id{\(connection.id)}") self.connections[connection.id] = connection } public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) { Log.info("disconnected: connection.id{\(connection.id)} reason{\(reason)}") self.connections.removeValue(forKey: connection.id) } public func received(message: Data, from: WebSocketConnection) { Log.info("received(Data): connection.id{\(from.id)}") from.close(reason: .invalidDataType, description: "Chat-Server only accepts text messages") self.connections.removeValue(forKey: from.id) } public func received(message: String, from: WebSocketConnection) { Log.info("received(String): connection.id{\(from.id)} message{\(message)}") for (connectionId, connection) in self.connections { if connectionId != from.id { connection.send(message: message) } } } }
// // CommentDao.swift // Findout // // Created by Ramzy Kermad on 19/12/2019. // Copyright © 2019 Ramzy Kermad. All rights reserved. // import Foundation struct CommentDao { var comment: String = "" var score: Int = 0 var userID = "" var placeID = "" init?(jsonResponse: [String: Any]){ guard let message = jsonResponse["message"] as? String, let score = jsonResponse["score"] as? Int, let user_id = jsonResponse["user_id"] as? String, let place_id = jsonResponse["place_id"] as? String else{ return } self.comment = message self.score = score self.userID = user_id self.placeID = place_id } init(message: String, score: Int, userId: String, placeId: String){ self.comment = message self.score = score self.userID = userId self.placeID = placeId } }
import Foundation func judge_sign() { // 読み込んだ整数値の符号を表示 let n = Int(input("整数:"))! if n > 0 { print("その値は正です。") } else if n < 0 { print("その値は負です。") } else { print("その値は0です。") } }
// // 524. Longest Word in Dictionary through Deleting.swift // Shuati // // Created by Yankun Jin on 2017/10/8. // Copyright © 2017年 Yankun Jin. All rights reserved. // import Foundation class Longest_Word_Solution : Testable { func findLongestWord(_ s: String, _ d: [String]) -> String { //var longestKey = "" let d1 = d.sorted { (s1, s2) -> Bool in if s1.characters.count > s2.characters.count { return true } else { return false } } for str in d1 { if isSubSequence(s1: str, s2: s) { return str } } return "" } func isSubSequence(s1 : String, s2 : String) -> Bool { let chars1 = Array(s1.characters) let chars2 = Array(s2.characters) var p1 = 0 var p2 = 0 if chars1.count > chars2.count {return false} while p1 < chars1.count && p2 < chars2.count { if chars1[p1] == chars2[p2] { p1 += 1 p2 += 1 } else { p2 += 1 } } return p1 == chars1.count } func printResult(params: Any...) { let result = findLongestWord(params[0] as! String, params[1] as! [String]) print("Longest_Word_Solution result is : \(result)") } }
// // GroupDetailsViewController.swift // TheDocument // import UIKit import Firebase class GroupDetailsViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { var leaderboardDatasource = [TDUser]() var group = Group.empty() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var groupDetailsStackView: UIStackView! @IBOutlet weak var groupNameLabel: UILabel! @IBOutlet weak var groupImageView: UIImageView! @IBOutlet weak var groupNavigationView: UIView! @IBOutlet weak var startGroupChallengeButton: UIButton! @IBOutlet weak var tabStackView: UIStackView! @IBOutlet weak var chatterTabButton: TabButton! @IBOutlet weak var leaderboardTabButton: TabButton! @IBOutlet weak var commentFormContainer: UIView! @IBOutlet weak var commentForm: UIStackView! @IBOutlet weak var commentField: UITextField! @IBOutlet weak var commentSendButton: UIButton! @IBOutlet weak var commentFormBottomMargin: NSLayoutConstraint! let kSectionComments = 0 let kSectionInvitees = 1 let kSectionLeaderboard = 2 let dismissKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideControls)) var leaderboardReady: Bool = false var chatterMode = false var comments: Array<DataSnapshot> = [] var commentsRef: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() groupImageView.contentMode = .scaleAspectFill if let headerView = tableView.tableHeaderView { let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0.0, y: headerView.frame.height - 1, width: headerView.frame.width, height: 1.0) bottomLine.backgroundColor = Constants.Theme.separatorColor.cgColor headerView.layer.addSublayer(bottomLine) } self.navigationController?.navigationBar.backIndicatorImage = UIImage(named:"ArrowBack") self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named:"ArrowBack") let nib = UINib(nibName: "ItemCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "ItemTableViewCell") tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 70.0, right: 0) tableView.tableFooterView = UIView() tableView.refreshControl = UIRefreshControl() tableView.refreshControl?.addTarget(self, action: #selector(GroupDetailsViewController.refreshMembers), for: .valueChanged) setupChatter() if group.state == .invited { let alertView = NCVAlertView(appearance: NCVAlertView.NCVAppearance(kTitleFont: UIFont(name: "OpenSans-Bold", size: 16)!, kTextFont: UIFont(name: "OpenSans", size: 14)!, kButtonFont: UIFont(name: "OpenSans-Bold", size: 14)!, showCloseButton: false, showCircularIcon: false, titleColor: Constants.Theme.authButtonSelectedBGColor)) alertView.addButton("Yes",backgroundColor: Constants.Theme.authButtonSelectedBGColor) { self.acceptGroupInvitation() } alertView.addButton("No",backgroundColor: Constants.Theme.deleteButtonBGColor) { self.rejectGroupInvitation() } alertView.showInfo("Group Invite", subTitle: "Do you want to join this group?") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Load leaderboard data self.loadLeaderboardData() NotificationCenter.default.post(name: NSNotification.Name(rawValue: "\(UserEvents.hideToolbar)"), object: nil) // Add keyboard notifications NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil) groupNameLabel.text = group.name // Get a reference to the storage service using the default Firebase App let storage = Storage.storage() // Create a storage reference from our storage service let photoRef = storage.reference(forURL: "gs://the-document.appspot.com/groups/\(group.id)") self.groupImageView.sd_setImage(with: photoRef, placeholderImage: UIImage(named: "logo-mark-square")) comments.removeAll() // [START child_event_listener] // Listen for new comments in the Firebase database commentsRef.observe(.childAdded, with: { (snapshot) -> Void in self.comments.append(snapshot) self.tableView.reloadData() }) // Listen for deleted comments in the Firebase database commentsRef.observe(.childRemoved, with: { (snapshot) -> Void in let index = self.indexOfMessage(snapshot) self.comments.remove(at: index) self.tableView.reloadData() }) // [END child_event_listener] } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Remove Keyboard observers NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil) // Remove Firebase observers commentsRef.removeAllObservers() Database.database().reference().child("users").child(currentUser.uid).removeAllObservers() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshMembers() } func indexOfMessage(_ snapshot: DataSnapshot) -> Int { var index = 0 for comment in self.comments { if snapshot.key == comment.key { return index } index += 1 } return -1 } deinit { NotificationCenter.default.removeObserver(self) } fileprivate func setupChatter() { let nib = UINib(nibName: "CommentTableViewCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "CommentCell") tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 80 //tableView.tableFooterView = UIView() chatterMode = false leaderboardTabButton.isChecked = true chatterTabButton.isChecked = false startGroupChallengeButton.isHidden = false commentFormContainer.isHidden = true commentFormContainer.addBorder() // default is top, 1px, light gray commentsRef = Database.database().reference().child("group-comments").child(group.id) } @objc func hideControls() { view.endEditing(true) } func setImage(id: String, forCell cell: ItemTableViewCell, type: String = "photos") { cell.loader.isHidden = true // Get a reference to the storage service using the default Firebase App let storage = Storage.storage() // Create a storage reference from our storage service let photoRef = storage.reference(forURL: "gs://the-document.appspot.com/\(type)/\(id)") cell.itemImageView!.sd_setImage(with: photoRef, placeholderImage: UIImage(named: "logo-mark-square")) } @objc func refreshMembers() { self.startActivityIndicator() API().getGroupMembers(group: group){ members in self.tableView.refreshControl?.endRefreshing() self.stopActivityIndicator() if let groupIndex = currentUser.groups.index(where: { $0.id == self.group.id }) { currentUser.groups[groupIndex].members = members } self.group.members = members self.leaderboardDatasource = self.group.members.sorted { let recordA = self.getMemberRecord(uid: $0.uid) let recordB = self.getMemberRecord(uid: $1.uid) return (recordA[0] - recordA[1]) > (recordB[0] - recordB[1]) } self.tableView.reloadData() } } func acceptGroupInvitation() { API().acceptGroupInvitation(group: self.group) { success in if success { var newGroup = self.group newGroup.state = .member currentUser.groups.removeObject(newGroup) currentUser.groups.append(newGroup) } } } func rejectGroupInvitation() { API().removeGroup(group: self.group) { success in currentUser.groups.removeObject(self.group) self.navigationController?.popViewController(animated: true) } } @IBAction func unwindToGroupDetails(segue: UIStoryboardSegue) { if let fromVC = segue.source as? InviteFriendsTableViewController { var groupMembersIds = Set<String>(group.members.map{$0.uid}) fromVC.selectedFriendsIds.forEach{ groupMembersIds.insert($0) } tableView.reloadData() } } @IBAction func chatterTabButtonTapped(_ sender:TabButton) { view.isUserInteractionEnabled = true view.addGestureRecognizer(dismissKeyboardGesture) leaderboardTabButton.isChecked = false chatterTabButton.isChecked = true chatterMode = true startGroupChallengeButton.isHidden = true self.commentFormContainer.isHidden = false self.view.bringSubview(toFront: self.commentFormContainer) self.tableView.reloadData() self.scrollToMostRecentComment() } @IBAction func leaderboardTabButtonTapped(_ sender:TabButton) { view.endEditing(true) view.isUserInteractionEnabled = true view.removeGestureRecognizer(dismissKeyboardGesture) leaderboardTabButton.isChecked = true chatterTabButton.isChecked = false chatterMode = false self.commentFormContainer.isHidden = true startGroupChallengeButton.isHidden = false leaderboardDatasource = group.members.sorted { let recordA = getMemberRecord(uid: $0.uid) let recordB = getMemberRecord(uid: $1.uid) return (recordA[0] - recordA[1]) > (recordB[0] - recordB[1]) } tableView.reloadData() } @IBAction func didTapSend(_ sender: UIButton) { if let commentField = self.commentField, let txt = commentField.text, txt != "" { commentField.resignFirstResponder() commentField.isEnabled = false sender.isEnabled = false let comment = [ "uid": currentUser.uid, "author": currentUser.name, "text": txt ] self.commentsRef.childByAutoId().setValue(comment, withCompletionBlock: { (error, ref) in commentField.isEnabled = true sender.isEnabled = true if error == nil { commentField.text = "" Notifier().sendGroupChatter(group: self.group) } }) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { didTapSend(commentSendButton) return true } @objc func keyboardWillShow(notification: NSNotification) { let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue commentFormBottomMargin.constant = keyboardRect.height tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardRect.height + 10, right: 0) self.view.layoutIfNeeded() self.scrollToMostRecentComment() } @objc func keyboardWillHide(notification: NSNotification) { commentFormBottomMargin.constant = 0 tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) self.view.layoutIfNeeded() self.scrollToMostRecentComment() } func scrollToMostRecentComment() { if comments.count > 0 { let bottomIndexPath = IndexPath(row: comments.count - 1, section: kSectionComments) tableView.scrollToRow(at: bottomIndexPath, at: .bottom, animated: false) } } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == kSectionComments && chatterMode { return comments.count } else if section == kSectionInvitees && !chatterMode { return group.invitees.count } else if section == kSectionLeaderboard && !chatterMode { return group.members.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == kSectionComments { let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell") as! CommentTableViewCell let commentDict = comments[(indexPath as NSIndexPath).row].value as? [String : AnyObject] if let author = commentDict?["author"], let commentText = commentDict?["text"] { cell.authorLabel.text = String(describing: author) cell.commentLabel.text = String(describing: commentText) } if let imageId = commentDict?["uid"] as? String { // Get a reference to the storage service using the default Firebase App let storage = Storage.storage() // Create a storage reference from our storage service let photoRef = storage.reference(forURL: "gs://the-document.appspot.com/photos/\(imageId)") cell.authorImageView.backgroundColor = .clear cell.authorImageView.contentMode = .scaleAspectFill cell.authorImageView.layer.cornerRadius = cell.authorImageView.frame.size.height / 2.0 cell.authorImageView.layer.masksToBounds = true cell.authorImageView.layer.borderWidth = 0 cell.authorImageView.isHidden = false cell.authorImageView.sd_setImage(with: photoRef, placeholderImage: UIImage(named: "logo-mark-square")) } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell") as! ItemTableViewCell if indexPath.section == kSectionLeaderboard && indexPath.row < leaderboardDatasource.count { let member = leaderboardDatasource[indexPath.row] cell.setup(member, cellId: Int(indexPath.row) + 1) cell.bottomLabel.text = "0-0" setRecordData(uid: member.uid, cell: cell) setImage(id: member.uid, forCell: cell) } else if indexPath.section == kSectionInvitees && indexPath.row < self.group.invitees.count { let member = self.group.invitees[indexPath.row] cell.setup(member) setImage(id: member.uid, forCell: cell) } return cell } } func loadLeaderboardData() { Database.database().reference().child("groups/\(group.id)/leaderboard/").observeSingleEvent(of: .value, with: { (snapshot) in guard let recordData = snapshot.value as? [String: [Int]] else { return } UserDefaults.standard.set(recordData, forKey: "leaderboard-\(self.group.id)") UserDefaults.standard.synchronize() }) } func getMemberRecord(uid: String) -> [Int] { guard let groupLeaderboard = UserDefaults.standard.dictionary(forKey: "leaderboard-\(self.group.id)") as? [String: [Int]], let memberRecord = groupLeaderboard["\(uid)"], memberRecord.count == 2 else { return [0, 0] } return memberRecord } func setRecordData(uid: String, cell: ItemTableViewCell) { Database.database().reference().child("groups/\(group.id)/leaderboard/\(uid)").observeSingleEvent(of: .value, with: { (snapshot) in guard let recordData = snapshot.value as? [Int], recordData.count == 2 else { return } DispatchQueue.main.async { guard let ip = self.tableView.indexPath(for: cell) else { return } if self.tableView.indexPathsForVisibleRows?.contains(ip) == true { cell.bottomLabel.text = "\(recordData[0])-\(recordData[1])" } } }) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { switch indexPath.section { case kSectionComments: return false case kSectionInvitees: return group.state == .own && group.invitees[indexPath.row].uid != currentUser.uid case kSectionLeaderboard: return group.state == .own && group.members[indexPath.row].uid != currentUser.uid default: return false } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { var member: TDUser if indexPath.section == kSectionLeaderboard { member = group.members[indexPath.row] group.members.removeObject(member) } else { member = group.invitees[indexPath.row] group.invitees.removeObject(member) } tableView.reloadData() API().removeMemberFromGroup(member: member, group: group){[weak self] success in if !success { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "\(UserEvents.groupsRefresh)"), object: nil) self?.navigationController?.popViewController(animated: true) } } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == kSectionLeaderboard && indexPath.row < leaderboardDatasource.count { let friend = leaderboardDatasource[indexPath.row] self.performSegue(withIdentifier: "show_group_user_profile", sender: friend) } else if indexPath.section == kSectionInvitees && indexPath.row < group.invitees.count { let friend = group.invitees[indexPath.row] self.performSegue(withIdentifier: "show_group_user_profile", sender: friend) } } @IBAction func startGroupChallenge(_ sender: Any) { if let newChallengeNavVC = self.storyboard?.instantiateViewController(withIdentifier: "NewChallengeNavVC") as? UINavigationController, let newChallengeVC = newChallengeNavVC.viewControllers.first as? NewChallengeViewController { newChallengeVC.groupId = group.id self.present(newChallengeNavVC, animated: true, completion: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.inviteFriendsStoryboardIdentifier, let destinationVC = segue.destination as? InviteFriendsTableViewController { destinationVC.selectedFriendsIds = Set(group.members.map{ $0.uid }) destinationVC.mode = .group(group) } else if segue.identifier == "show_group_user_profile", let profileVC = segue.destination as? HeadToHeadViewController, let friend = sender as? TDUser { profileVC.playerTwo = friend } } }
// // CoreDataManager.swift // RPG_Health_Tracker // // Created by steven Hoover on 9/27/17. // Copyright © 2017 steven Hoover. All rights reserved. // import Foundation import CoreData class CoreDataManager { //MARK: SharedInstance static var singleton : CoreDataManager = CoreDataManager() //MARK: - Properities //MARK: - Methods private init(){} //MARK: Loading func loadPlayers() -> [Player] { var players : [CharacterEntity] = [CharacterEntity]() let request : NSFetchRequest<CharacterEntity> = CharacterEntity.fetchRequest() do{ let searchResult = try self.persistentContainer.viewContext.fetch(request) if searchResult.count != 0 { players.append(contentsOf: searchResult) } } catch { print("Error with request: \(error)") //TODO add error messaging } return CharacterBuilder.buildPlayers(entities: players) } lazy var persistentContainer : NSPersistentContainer = { let container = NSPersistentContainer(name: "RPG_Health_Tracker") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error - \(error) , \(error.userInfo)") } }) return container }() //MARK: Saving func saveContext() { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error - \(nserror) , \(nserror.userInfo)") } } } func grabPlayerEntity() -> CharacterEntity { return CharacterEntity(context: persistentContainer.viewContext) } func grabTrackEntity() -> HealthTrackEntity { return HealthTrackEntity(context: persistentContainer.viewContext) } func grabResistEntity() -> ResistEntity { return ResistEntity(context: persistentContainer.viewContext) } //MARK: Deleting func deleteEntity( entity: NSManagedObject) { persistentContainer.viewContext.delete(entity) saveContext() } }
// // VacationViewController.swift // IntergalacticTravelSwift // // Created by Peter Hitchcock on 9/30/14. // Copyright (c) 2014 Peter Hitchcock. All rights reserved. // import UIKit class VacationViewController: UIViewController { @IBOutlet weak var vacationImageView: UIImageView! 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 unwindButton(sender: UIStoryboardSegue) { } }
// // DayFour.swift // AdventOfCode2017 // // Created by Shawn Veader on 12/4/17. // Copyright © 2017 v8logic. All rights reserved. // extension DayFour: Testable { func runTests() { let data = [ "aa bb cc dd ee", "aa bb cc dd aa", "aa bb cc dd aaa", ] guard Passphrase(data[0]).isValid(), !Passphrase(data[1]).isValid(), Passphrase(data[2]).isValid(), testValue(2, equals: partOne(input: data)), true else { print("Part 1 Tests Failed!") return } guard Passphrase("abcde fghij").isValid(blockAnnagrams: true), !Passphrase("abcde xyz ecdab").isValid(blockAnnagrams: true), Passphrase("a ab abc abd abf abj").isValid(blockAnnagrams: true), Passphrase("iiii oiii ooii oooi oooo").isValid(blockAnnagrams: true), !Passphrase("oiii ioii iioi iiio").isValid(blockAnnagrams: true), true else { print("Part 2 Tests Failed!") return } print("Done with tests... all pass") } }
// // LinkTableViewCell.swift // Experiment Go // // Created by luojie on 9/30/15. // Copyright © 2015 LuoJie. All rights reserved. // import UIKit import CloudKit class LinkTableViewCell: CKItemTableViewCell { var link: CKLink? { get { return item as? CKLink } set { item = newValue } } @IBOutlet weak var fromUserProfileImageButton: UIButton! { didSet { fromUserProfileImageButton.layer.borderColor = UIColor.globalTintColor().CGColor fromUserProfileImageButton.layer.borderWidth = fromUserProfileImageButton.bounds.size.height / 32 } } @IBOutlet weak var fromUserNameLabel: UILabel! @IBOutlet weak var subheadLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! var fromUserProfileImage: UIImage { get { return fromUserProfileImageButton.backgroundImageForState(.Normal) ?? UIImage() } set { fromUserProfileImageButton.setBackgroundImage(newValue, forState: .Normal) } } var fromUserProfileImageURL: NSURL? { return link?.creatorUser?.profileImageAsset?.fileURL } }
// // BaseButton.swift // Buckey // // Created by tunay alver on 16.04.2020. // Copyright © 2020 tunay alver. All rights reserved. // import UIKit class BaseButton: UIButton { override var isHighlighted: Bool { didSet { if isHighlighted { self.alpha = 0.5 }else { self.alpha = 1.0 } } } override var isEnabled: Bool { didSet { if isEnabled { self.alpha = 1.0 }else { self.alpha = 0.5 } } } }
// // NetApi.swift // LQLRequset // // Created by hou on 2018/4/11. // Copyright © 2018年 hou. All rights reserved. // import UIKit //状态 let Code_Key = "code" let Message_Key = "msg" let Data_Key = "data" let Request_Sucess = 1// 请求成功 let DATA_FORMAT_ERROR = "数据格式错误" let HTTPBASEURL = "http://47.95.254.216:8889/" let TOKEN = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjIsImV4cCI6MTUwODMxNDA4MywiaWF0IjoxNTA1NzIyMDgzLCJqdGkiOiIxM2Y4ZjY2OThjYTZmMWM3NzQ4ZWEwZmFmZGFhMzIyOWVjNmFhNDk0Y2QzZGFiNGUzMzBjMTU4ZWJiODkwM2IyMDMyNDAzNmZlYTliMmM0NSJ9.kysa1lJoyn8v5erPSxZ32u9f5MSRl--niUCe8_HwxJRsLCkUq3E9QfBL2GTSpPNvI2Pal-gXqN5bh7720n4AjS3B9TlPg3563eMU1HhoBIRYEJGGKn_FxHwA1rwZ8Bx73-y95Pz_3_zGwqaOKpZdQZMXCRWsxP7mU3SYeTnCNvT4eYOHpBdFTBBqxbhNpxixPQ095TH_cKnkOqI3iI0mSaxNH7y-GggawZINKTK2hZbyW2tGmQrFXgnfuUtDV7z2naLM8F-MCUk2MByafAJMcMMRwlvS8NDpVKknNljJ-Jg8JijEz-QbLZzuIcoEg5-dxnUdSuZGvRLw_2kQtWmnmItdBHo8GZzMmceoIR0xwOuWsmHeQZTcIIk66YPl_gfYMlp5wCgntBF275XOlFaQQL_0TxaGTh4snyzd27TQg0SA5u67iV7irnS5bxCANyKoErT7Wm3wQ1fXWDRSSKTm8yvtZl0P0acqAhamPnY4IT8rPbss9PTlxU9Dx46EteE7ogwlvC4GokD0ti6WjCRSocTE-gSsPj0kLs7HrrQYbT-S-yeNbBloJJIQFr0RxuOrzXxOTIpDQnHrHYkp-x-gzw2HoYq0XMqII3X5Ctym7ZTeP_Thvaew4_B7xy2uFBJpVfe9KM-eRdMjZqBb8JzX58eQwu2-TDLmvXsFDEUUlDs";
// // Dictionary+Extension.swift // WatsonDemo // // Created by Etay Luz on 11/15/16. // Copyright © 2016 Etay Luz. All rights reserved. // import Foundation extension Dictionary { /// Build string representation of HTTP parameter dictionary of keys and objects /// /// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped func stringFromHttpParameters() -> String { var parametersString = "" for (key, value) in self { if let key = key as? String, let value = value as? String { parametersString = parametersString + key + "=" + value + "&" } } parametersString = parametersString.substring(to: parametersString.index(before: parametersString.endIndex)) return parametersString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } }
// // CustomerTest.swift // MercadoPagoSDK // // Created by Maria cristina rodriguez on 1/3/16. // Copyright © 2016 MercadoPago. All rights reserved. // import XCTest class CustomerTest: BaseTest { func testFromJSON() { var json: NSDictionary = MockManager.getMockFor("Customer")! var customerFromJSON = Customer.fromJSON(json) let customer = MockBuilder.buildCustomer() XCTAssertEqual(customerFromJSON.cards![0].idCard, customer.cards![0].idCard) XCTAssertEqual(customerFromJSON.cards![0].paymentMethod!._id!, customer.cards![0].paymentMethod!._id!) XCTAssertEqual(customerFromJSON.defaultCard!, customer.defaultCard!) XCTAssertEqual(customerFromJSON._description!, customer._description!) XCTAssertEqual(customerFromJSON.dateCreated, customer.dateCreated) XCTAssertEqual(customerFromJSON.dateLastUpdated, customer.dateLastUpdated) XCTAssertEqual(customerFromJSON.email!, customer.email!) XCTAssertEqual(customerFromJSON.firstName!, customer.firstName!) XCTAssertEqual(customerFromJSON.lastName!, customer.lastName!) XCTAssertEqual(customerFromJSON._id!, customer._id!) XCTAssertEqual(customerFromJSON.liveMode!, customer.liveMode!) XCTAssertEqual(customerFromJSON.identification!.number!, customer.identification!.number!) XCTAssertEqual(customerFromJSON.address!.streetName!, customer.address!.streetName!) // Convert to String and to Dictionary again let customerJson = customerFromJSON.toJSONString() json = MockManager.getDictionaryFor(string: customerJson)! customerFromJSON = Customer.fromJSON(json) XCTAssertEqual(customerFromJSON.cards![0].idCard, customer.cards![0].idCard) XCTAssertEqual(customerFromJSON.cards![0].paymentMethod!._id!, customer.cards![0].paymentMethod!._id!) XCTAssertEqual(customerFromJSON.defaultCard!, customer.defaultCard!) XCTAssertEqual(customerFromJSON._description!, customer._description!) XCTAssertEqual(customerFromJSON.dateCreated, customer.dateCreated) XCTAssertEqual(customerFromJSON.dateLastUpdated, customer.dateLastUpdated) XCTAssertEqual(customerFromJSON.email!, customer.email!) XCTAssertEqual(customerFromJSON.firstName!, customer.firstName!) XCTAssertEqual(customerFromJSON.lastName!, customer.lastName!) XCTAssertEqual(customerFromJSON._id!, customer._id!) XCTAssertEqual(customerFromJSON.liveMode!, customer.liveMode!) XCTAssertEqual(customerFromJSON.identification!.number!, customer.identification!.number!) XCTAssertEqual(customerFromJSON.address!.streetName!, customer.address!.streetName!) } func testFromJSONNoCards() { var json: NSDictionary = MockManager.getMockFor("Customer")! var customerFromJSON = Customer.fromJSON(json) customerFromJSON.cards = nil let customer = MockBuilder.buildCustomer() // Convert to String and to Dictionary again let customerJson = customerFromJSON.toJSONString() json = MockManager.getDictionaryFor(string: customerJson)! customerFromJSON = Customer.fromJSON(json) XCTAssertNil(customerFromJSON.cards) XCTAssertEqual(customerFromJSON.defaultCard!, customer.defaultCard!) XCTAssertEqual(customerFromJSON._description!, customer._description!) XCTAssertEqual(customerFromJSON.dateCreated, customer.dateCreated) XCTAssertEqual(customerFromJSON.dateLastUpdated, customer.dateLastUpdated) XCTAssertEqual(customerFromJSON.email!, customer.email!) XCTAssertEqual(customerFromJSON.firstName!, customer.firstName!) XCTAssertEqual(customerFromJSON.lastName!, customer.lastName!) XCTAssertEqual(customerFromJSON._id!, customer._id!) XCTAssertEqual(customerFromJSON.liveMode!, customer.liveMode!) XCTAssertEqual(customerFromJSON.identification!.number!, customer.identification!.number!) XCTAssertEqual(customerFromJSON.address!.streetName!, customer.address!.streetName!) } }
// // UserDao.swift // UsersApp-SwiftUI // // Created by Jorge Luis Rivera Ladino on 4/09/21. // import Foundation import CoreData enum LoginErrors: Error { case badUsername case badPassword } class UserDao { private var managedContext: NSManagedObjectContext init(managedContext: NSManagedObjectContext) { self.managedContext = managedContext } // Create func saveUsers(_ users: [UserList.User.Domain]) throws { deleteUsers() users.forEach { let user = UserCoreData(context: managedContext) $0.toCoreDataUser(user) } try saveContext() } // Read func getUsers() throws -> [UserCoreData] { let fetchRequest: NSFetchRequest<UserCoreData> = UserCoreData.fetchRequest() do { let coreDataUsers = try managedContext.fetch(fetchRequest) return coreDataUsers } catch { throw error } } // Delete func deleteUsers() { let fetchRequest: NSFetchRequest<UserCoreData> = UserCoreData.fetchRequest() do { let coreDataUsers = try managedContext.fetch(fetchRequest) coreDataUsers.forEach { managedContext.delete($0) } try managedContext.save() } catch let error as NSError { print(error.localizedDescription) } } } private extension UserDao { func saveContext() throws { do { try managedContext.save() } catch { throw error } } }
// Copyright © 2018 Nazariy Gorpynyuk. // All rights reserved. import Foundation import Cornerstones import ReactiveSwift import Result import ReactiveCocoa /// It's sufficient for conforming classes to contain a nested `Event` type, without the need of typealiasing. Events can be listened on /// through `eventSignal` property and emitted through `eventEmitter` property. public protocol EventEmitter: StoredProperties { associatedtype Event } private struct StoredPropertyKeys { static let eventEmitterIsInitialized = "eventEmitterIsInitialized" static let eventSignal = "eventSignal" static let eventEmitter = "eventEmitter" } public extension EventEmitter { var eventSignal: Si<Event> { let (signal, _) = initializeOrGetPipe() return signal } var eventEmitter: Ob<Event> { let (_, emitter) = initializeOrGetPipe() return emitter } private func initializeOrGetPipe() -> (signal: Si<Event>, emitter: Ob<Event>) { return synchronized(self) { if let isInitialized = sp.bool[StoredPropertyKeys.eventEmitterIsInitialized], isInitialized { let signal = sp.any[StoredPropertyKeys.eventSignal] as! Si<Event> let emitter = sp.any[StoredPropertyKeys.eventEmitter] as! Ob<Event> return (signal, emitter) } else { let (newSignal, newEmitter) = Si<Event>.pipe() sp.any[StoredPropertyKeys.eventSignal] = newSignal sp.any[StoredPropertyKeys.eventEmitter] = newEmitter sp.bool[StoredPropertyKeys.eventEmitterIsInitialized] = true return (newSignal, newEmitter) } } } }
// // ItemCell.swift // MyLoqta // // Created by Ashish Chauhan on 08/08/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit class ItemCell: BaseTableViewCell, NibLoadableView, ReusableView { @IBOutlet weak var imgViewItem: UIImageView! @IBOutlet weak var lblItemPrice: UILabel! @IBOutlet weak var lblQuantity: UILabel! @IBOutlet weak var lblCondition: UILabel! @IBOutlet weak var lblColor: UILabel! @IBOutlet weak var lblItemName: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(order: Product) { let lightGryColor = UIColor.colorWithAlpha(color: 163.0, alfa: 1.0) let blackColor = UIColor.colorWithAlpha(color: 38.0, alfa: 1.0) let lightFont = UIFont.font(name: .SFProText, weight: .Regular, size: .size_12) let mediumFont = UIFont.font(name: .SFProText, weight: .Medium, size: .size_12) self.lblItemName.text = order.itemName if let color = order.color { let colorAtt = NSMutableAttributedString(string: "Color".localize() + ": ", attributes: [NSAttributedStringKey.font: lightFont, NSAttributedStringKey.foregroundColor: lightGryColor]) let valueAtt = NSAttributedString(string: color, attributes: [NSAttributedStringKey.font: mediumFont, NSAttributedStringKey.foregroundColor: blackColor]) colorAtt.append(valueAtt) self.lblColor.attributedText = colorAtt } else { self.lblColor.text = "" } if let condition = order.condition { let condition = Helper.returnConditionTitle(condition: condition) let conditionAtt = NSMutableAttributedString(string: "Сondition".localize() + ": ", attributes: [NSAttributedStringKey.font: lightFont, NSAttributedStringKey.foregroundColor: lightGryColor]) let valueAtt = NSAttributedString(string: condition, attributes: [NSAttributedStringKey.font: mediumFont, NSAttributedStringKey.foregroundColor: blackColor]) conditionAtt.append(valueAtt) self.lblCondition.attributedText = conditionAtt } else { self.lblCondition.text = "" } if let quantity = order.quantity { let quantity = "\(quantity)" let quantityAtt = NSMutableAttributedString(string: "QTY".localize() + ": ", attributes: [NSAttributedStringKey.font: lightFont, NSAttributedStringKey.foregroundColor: lightGryColor]) let valueAtt = NSAttributedString(string: quantity, attributes: [NSAttributedStringKey.font: mediumFont, NSAttributedStringKey.foregroundColor: blackColor]) quantityAtt.append(valueAtt) self.lblQuantity.attributedText = quantityAtt } else { self.lblQuantity.text = "" } if let price = order.price { let intPrice = Int(price) let usPrice = intPrice.withCommas() self.lblItemPrice.text = usPrice } if let arrayImage = order.imageUrl, arrayImage.count > 0 { let imageUrl = arrayImage[0] self.imgViewItem.setImage(urlStr: imageUrl, placeHolderImage: UIImage()) } } }
import Foundation // Template for solving a Hacker Rank Problem class LinkedListsDetectACycle: HackerRank { // NOT YET IMPLEMENTED class Node { var next: Node? init(next: Node? = nil) { self.next = next } } let node3, node2, node1, node0: Node var roots = [Node]() override init (named directoryName: String) { node3 = Node() node2 = Node(next: node3) node1 = Node(next: node2) node0 = Node() roots = [node0, node1] super.init(named: directoryName) } var rootIndex = 0 var currentNode = Node() // Read in values to the inputs // Don't forget to reset all variable to assumed default values override func setUpInputs() { currentNode = roots[rootIndex] } override func addSolutions() { solutions.append(solution) } // Example solution func solution() -> String { let hasCycle = false // TO BE IMPLEMENTED if hasCycle { // true return "1" } else { // false return "0" } } // Optionally override a custom solve() method override func solve() { addSolutions() for i in 0..<roots.count { setUpInputs() for j in 0..<solutions.count { let result = measure(name: "Solution \(j)", block: solutions[j]) if result == outputs[i] { print("PASS") } else { print("FAIL") } } } } }
// // RegistrableCellTests.swift // RegistrableCellTests // // Created by minjuniMac on 08/10/2018. // Copyright © 2018 mjun. All rights reserved. // import XCTest import SimpleCell class RegistrableCellTests: XCTestCase { var tableViewController: UITableViewController? override func setUp() { super.setUp() tableViewController = TestTableViewController() tableViewController?.tableView.reloadData() _ = tableViewController?.view } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. tableViewController = nil super.tearDown() } func test_IdentifierIsValidWhenRegisteringCell() { let cell = tableViewController?.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) XCTAssertNotNil(cell) XCTAssertEqual(cell?.reuseIdentifier, "TestTableViewCell") } func test_IdentifierIsValidWhenRegisteringHeader() { _ = tableViewController?.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) let header = tableViewController?.tableView.headerView(forSection: 0) XCTAssertNotNil(header) XCTAssertEqual(header?.reuseIdentifier, "TestHeaderFooter") } }
// // LoadingViewController.swift // LoadUIFramework // // Created by Chris Gonzales on 3/25/20. // Copyright © 2020 Chris Gonzales. All rights reserved. // import UIKit class LoadingViewController: UIViewController { private let loadingView = IndeterminateLoadingView() override func viewDidLoad() { super.viewDidLoad() loadingView.translatesAutoresizingMaskIntoConstraints = false loadingView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loadingView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true loadingView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8).isActive = true loadingView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8) loadingView.heightAnchor.constraint(equalTo: loadingView.widthAnchor, multiplier: 1, constant: 0) } public func startAnimation() { loadingView.startAnimating() } public func stopAnimation() { loadingView.stopAnimating() } }
// SPDX-License-Identifier: MIT // Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. import Cocoa class customcell: NSTableCellView { @IBOutlet weak var mainview: NSView! @IBOutlet weak var countryflagimgview: CustomImgLoader! @IBOutlet weak var countrynamelbl: NSTextField! @IBOutlet weak var tickimgview: NSImageView! override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } }
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit class MessagesViewController: UIViewController { private let defaultBackgroundColor = UIColor( red: 249/255.0, green: 249/255.0, blue: 249/255.0, alpha: 1) private var messages: [Message] = [] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = defaultBackgroundColor tableView.backgroundColor = defaultBackgroundColor loadMessages() } func loadMessages() { messages.append(Message(text: "Hello, it's me", sentByMe: true)) messages.append(Message(text: "I was wondering if you'll like to meet, to go over this new tutorial I'm working on", sentByMe: true)) messages.append(Message(text: "I'm in California now, but we can meet tomorrow morning, at your house", sentByMe: false)) messages.append(Message(text: "Sound good! Talk to you later", sentByMe: true)) messages.append(Message(text: "Ok :]", sentByMe: false)) } } //MARK: - UITableView Delegate & Data Source extension MessagesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //1 let message = messages[indexPath.row] //2 let cellIdentifier = message.sentByMe ? "RightBubble" : "LeftBubble" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MessageBubbleTableViewCell cell.messageLabel.text = message.text cell.backgroundColor = defaultBackgroundColor return cell } }
import Foundation import TimKit struct APIConfigDefault: APIConfig { var scheme: URLScheme = .https var hostname = Hostname(rawValue: "www.rijksmuseum.nl")! var path = "/api/en" var queryItems = [ "key": "VV23OnI1", "format": "json" ] }
// // Copyright (c) 2018. Aleksandr Darmeiko // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public enum ServiceResponse<T> : Equatable { case error(Int, String) case inProgress case none case success(T) case canceled public static func ==(lhs: ServiceResponse<T>, rhs: ServiceResponse<T>) -> Bool { switch (lhs, rhs) { case (.success(_), .success(_)), (.none, .none), (.inProgress, .inProgress), (.canceled, .canceled), (.error(_, _), .error(_, _)): return true default: return false } } }
//test import UIKit import Alamofire import SwiftyJSON class PostManager: NSObject { // impostazioni globali let myPizzinoURL = "https://pizzino.pw/app/test.php" // Salvataggio dati Json di ritorno //inizialzzo vuoto var myResultJsonArray : [ResultModel] = [] var uc : RecentiController! //indirizzo file locale private var filePath : String! // questo è il codice speciale che lo rende un singleton class var sharedInstance : PostManager { get { struct Static { static var instance : PostManager? = nil static var token : dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = PostManager() } return Static.instance! } } //init dblocale se presente carica altrimenti nulla o inizializza func startDataManager(){ filePath = cartellaDocuments() + "/myUrl.plist" if NSFileManager.defaultManager().fileExistsAtPath(filePath) == true { myResultJsonArray = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! [ResultModel] } else { let esempio = ResultModel(urlfinale: "ciao", urlcheck: "culo") let esempio2 = ResultModel(urlfinale: "ciao2", urlcheck: "culo2") myResultJsonArray = [esempio,esempio2] salva() } } //metodo passaggio dei dati e salvataggio response in Json con Alamo func postForm (messaggio : String, impostazioni : OpzioniModel) { //testo e parametri let parameters = [ "testo": messaggio ] Alamofire.request(.POST, myPizzinoURL, parameters: parameters) .responseJSON { response in // print(response.request) // original URL request // print(response.response) // URL response // print(response.data) // server data // print(response.result) // result of response serialization // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = response.result.error { print(er.localizedDescription) } // controlliamo che il JSON sia correttamente arrivato, in caso contrario fermiamo il caricamento (se no va in crash) // l'_ è un trucco per evitare di fare una var a "ufo" che non verrà mai usata if let _ = response.result.value { print("JSON OK") } else { print("JSON Nil") return } // JSON() - in verde - è uno struct presente nella libreria SwiftyJSON.swift // gli viene passato JSONn che è la var di risposta di Alamofire che contiene il JSON scaricato // analizzando il JSON dell'App Store ho trovato una chiave principale feed ed una sottochave entry che contiene tutte le App // la sintassi di SwiftyJSON per passare da una chiave all'altra sembra di fare un array con una stringa! Non confonderti! // dentro alla chiave entry c'è l'array delle App, quindi la let json diventa un array if let JSON = response.result.value { print("JSON: \(JSON) ---fine stampa raw dati---") } // tutto il json let rispostaJSON = JSON(response.result.value!) //salvo su oggetto di tipo let urlTinyUrl = rispostaJSON["urlTinyUrl"].string! let salvaDati = ResultModel(urlfinale: urlTinyUrl, urlcheck: "ccc") //salvaDati.urlTinyUrl = rispostaJSON["urlTinyUrl"].string! //salvaDati.urlPizzinoCheck = "da leggere" self.myResultJsonArray.append(salvaDati) self.salva() } } func salva(){ NSKeyedArchiver.archiveRootObject(myResultJsonArray, toFile: filePath) } func cartellaDocuments() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) //print(paths[0] as String) return paths[0] as String } }
class Solution { func reverse(_ x: Int) -> Int { var num = x < 0 ? -x : x var result = 0 while num > 0 { result = result * 10 + num % 10 num = num / 10 } result = x < 0 ? -result : result if result < Int32.min || result > Int32.max { return 0 } return result } } // class Solution { // func reverse(_ x: Int) -> Int { // let s = Array("\(x)".reversed()) // var result = 0 // for (i, c) in s.enumerated() { // if c == "0" { continue } // if x < 0 { result = Int("-" + s[i..<s.count-1])! } // else { result = Int(String(s[i..<s.count]))! } // break // } // if result < Int32.min || result > Int32.max { return 0 } // return result // } // } let inputs = [123, -123, 120, 1534236469] inputs.map(Solution().reverse) .forEach{ print($0) }
// // TableViewCells.swift // Melk // // Created by Ilya Kos on 7/2/17. // Copyright © 2017 Ilya Kos. All rights reserved. // import UIKit class TitleTableViewCell: UITableViewCell { var titleText: String = "" { didSet { title.text = titleText setNeedsLayout() } } private let title = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { title.font = UIFont.systemFont(ofSize: 28, weight: UIFontWeightHeavy) // UIFont.preferredFont(forTextStyle: .title1) // print(title.font.pointSize) // 28 super.init(style: style, reuseIdentifier: TitleTableViewCell.identifier) contentView.addSubview(title) setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() title.sizeToFit() title.frame.origin = CGPoint(x: 16, y: 16) print(title.frame.height) } override func prepareForReuse() { } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static let identifier = "io.Melk.titleTableViewCell" static let height: CGFloat = 33.5 + 16 + 8 } class TagTableViewCell: UITableViewCell { var tagString: String? { set { textField.text = newValue setNeedsLayout() } get { return textField.text } } var tagDidChange: ((String?) -> ())? @objc private func textDidChange() { tagDidChange?(tagString) } var style: TagStyle = .normal { didSet { updateStyle() } } private let textField = UITextField() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) textField.borderStyle = .roundedRect textField.adjustsFontSizeToFitWidth = false textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.addTarget(self, action: #selector(self.textDidChange), for: .editingChanged) contentView.addSubview(textField) // textField.delegate = self // textField.font } private func updateStyle() { textField.font = style.font setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() let label = UILabel() label.text = "MH" label.font = style.font let height = label.textRect(forBounds: CGRect.infinite, limitedToNumberOfLines: 1) .height + 2*2 let frame = CGRect(x: 16, y: style == .large ? 32 : 4, width: bounds.width - 16*2, height: height) textField.frame = frame print(textField.frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static let identifier = "io.Melk.tagTableViewCell" static let largeHeight: CGFloat = 37.5 + 16 + 32 static let normalHeight: CGFloat = 28.0 + 4*2 } //extension TagTableViewCell: UITextFieldDelegate { // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // // return true // } //} enum TagStyle { case normal case large private static let largeFont = UIFont.systemFont(ofSize: 28, weight: UIFontWeightHeavy) private static let normalFont = UIFont.systemFont(ofSize: 20, weight: UIFontWeightSemibold) var font: UIFont { switch self { case .normal: return TagStyle.normalFont case .large: return TagStyle.largeFont } } }
// // GameDetailsViewModel.swift // MyLeaderboard // // Created by Joseph Roque on 2019-08-21. // Copyright © 2019 Joseph Roque. All rights reserved. // import Foundation import myLeaderboardApi enum GameDetailsAction: BaseAction { case dataChanged case playerSelected(GraphID) case graphQLError(GraphAPIError) case openPlays(PlayListFilter) } enum GameDetailsViewAction: BaseViewAction { case initialize case reload case selectPlayer(GraphID) case showPlays(PlayListFilter) } class GameDetailsViewModel: ViewModel { typealias GameDetailsQuery = MyLeaderboardApi.GameDetailsQuery typealias ActionHandler = (_ action: GameDetailsAction) -> Void let boardId: GraphID var handleAction: ActionHandler private(set) var dataLoading: Bool = false { didSet { handleAction(.dataChanged) } } private(set) var gameID: GraphID private(set) var game: GameDetails? private(set) var plays: [RecentPlay] = [] private(set) var players: [Opponent] = [] private(set) var standings: GameDetailsStandings? init(gameID: GraphID, boardId: GraphID, handleAction: @escaping ActionHandler) { self.gameID = gameID self.boardId = boardId self.handleAction = handleAction } func postViewAction(_ viewAction: GameDetailsViewAction) { switch viewAction { case .initialize, .reload: loadData() case .selectPlayer(let player): handleAction(.playerSelected(player)) case .showPlays(let filter): handleAction(.openPlays(filter)) } } private func loadData(retry: Bool = true) { self.dataLoading = true GameDetailsQuery(id: gameID, board: boardId, ignoreBanished: true).perform { [weak self] result in switch result { case .success(let response): self?.handle(response: response) case .failure(let error): self?.handleAction(.graphQLError(error)) } self?.dataLoading = false } } private func handle(response: MyLeaderboardApi.GameDetailsResponse) { guard let game = response.game?.asGameDetailsFragmentFragment else { return handleAction(.graphQLError(.missingData)) } self.game = game self.players = response.game?.standings.records.map { $0.player.asOpponentFragmentFragment } ?? [] self.standings = response.game?.standings.asGameDetailsStandingsFragmentFragment self.plays = response.game?.recentPlays.map { $0.asRecentPlayFragmentFragment } ?? [] } }
// // ContentView.swift // TryDiffableDataSource // // Created by Andrea Stevanato on 15/10/2019. // Copyright © 2019 Andrea Stevanato. All rights reserved. // import Combine import SwiftUI struct ContentView: View { var body: some View { Text("Hello World") } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // PickEventViewController.swift // Go // // Created by Logan Isitt on 6/9/15. // Copyright (c) 2015 Logan Isitt. All rights reserved. // import UIKit import Haneke import MaterialKit class PickEventViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var titleLabel: GOLabel! var collectionView: UICollectionView! var eventTypes: [EventType] = [] var eventType: EventType! override func viewDidLoad() { super.viewDidLoad() setupViews() layoutViews() Client.sharedInstance.getAllEventTypes({ (eventTypes, error) -> () in self.eventTypes = eventTypes self.collectionView.reloadData() }) } // MARK: - Views func setupViews() { titleLabel = GOLabel() titleLabel.text = self.title titleLabel.font = UIFont.boldSystemFontOfSize(20) let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.scrollDirection = .Vertical collectionView = UICollectionView(frame: CGRect.zeroRect, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.registerClass(EventTypeCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView.backgroundColor = UIColor.go_main_color() view.addSubview(collectionView) view.addSubview(titleLabel) } // MARK: - Layout func layoutViews() { titleLabel.autoPinToTopLayoutGuideOfViewController(self, withInset: 0) titleLabel.autoPinEdgeToSuperviewEdge(.Left) titleLabel.autoPinEdgeToSuperviewEdge(.Right) titleLabel.autoSetDimension(.Height, toSize: 50) collectionView.autoPinEdge(.Top, toEdge: .Bottom, ofView: titleLabel) collectionView.autoPinEdgeToSuperviewEdge(.Left) collectionView.autoPinEdgeToSuperviewEdge(.Right) collectionView.autoPinToBottomLayoutGuideOfViewController(self, withInset: 0) } // MARK: - UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return count(eventTypes) } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell: EventTypeCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! EventTypeCollectionViewCell cell.titleLabel.text = eventTypes[indexPath.row].name let url: NSURL = NSURL(string: Client.sharedInstance.baseUrl + eventTypes[indexPath.row].imagePath)! cell.imageView.hnk_setImageFromURL(url, placeholder: UIImage(named: "Logo"), format: nil, failure: { (error: NSError?) -> () in println("Error: \(error)") }, success: { (image: UIImage) -> () in cell.imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) }) return cell } // MARK: - UICollectionView Delegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { eventType = eventTypes[indexPath.row] } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let dim = CGFloat(collectionView.bounds.width / 4.0) return CGSizeMake(dim, dim) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSizeZero } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSizeZero } }
// // ViewController.swift // ProjekKu // // Created by fauzanfaurezs on 19/10/2018. // Copyright © 2018 fauzanfaurezs. All rights reserved. // import UIKit import AVKit import AVFoundation class ViewController: UIViewController { var video: AVPlayer? @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. label.text = "Avengar infinity war" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Segmen(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: label.text = "Avenger infinity war" let alert = UIAlertController(title: "Yakin Mau Masuk", message: "Hati-Hati", preferredStyle: UIAlertControllerStyle.alert) let actOK = UIAlertAction(title: "OK", style: .default) { (actOK) in let source = Bundle.main.path(forResource: "aEx3yGM_460svh265", ofType: "m4v") self.video = AVPlayer(url: URL(fileURLWithPath: source!)) let controller = AVPlayerViewController() controller.player = self.video self.present(controller, animated: true, completion: nil) } let actCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(actCancel) alert.addAction(actOK) present(alert, animated: true, completion: nil) case 1: label.text = "Fitnah Main VR" let alert = UIAlertController(title: "Yakin Mau Masuk", message: "Semoga Beruntung", preferredStyle: UIAlertControllerStyle.alert) let actOK = UIAlertAction(title: "OK", style: .default) { (actOK) in let source = Bundle.main.path(forResource: "a1o4qzb_460svh265", ofType: "mp4") self.video = AVPlayer(url: URL(fileURLWithPath: source!)) let controller = AVPlayerViewController() controller.player = self.video self.present(controller, animated: true, completion: nil) } let actCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(actOK) alert.addAction(actCancel) present(alert, animated: true, completion: nil) case 2: label.text = "Projek StopWatch" let alert = UIAlertController(title: "Yakin Mau Masuk", message: "Semoga Beruntung", preferredStyle: UIAlertControllerStyle.alert) let actOK = UIAlertAction(title: "OK", style: .default) { (actOK) in let source = Bundle.main.path(forResource: "mamen", ofType: "mp4") self.video = AVPlayer(url: URL(fileURLWithPath: source!)) let controller = AVPlayerViewController() controller.player = self.video self.present(controller, animated: true, completion: nil) } let actCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(actOK) alert.addAction(actCancel) present(alert, animated: true, completion: nil) case 3: label.text = "Hawa Nafsu" let alert = UIAlertController(title: "Yakin Mau Masuk", message: "Semoga Beruntung", preferredStyle: UIAlertControllerStyle.alert) let actOK = UIAlertAction(title: "OK", style: .default) { (actOK) in let source = Bundle.main.path(forResource: "nafsu", ofType: "mp4") self.video = AVPlayer(url: URL(fileURLWithPath: source!)) let controller = AVPlayerViewController() controller.player = self.video self.present(controller, animated: true, completion: nil) } let actCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(actCancel) alert.addAction(actOK) present(alert, animated: true, completion: nil) case 4: label.text = "Basket Ball" let alert = UIAlertController(title: "Yakin Mau Masuk", message: "Semoga Beruntung", preferredStyle: UIAlertControllerStyle.alert) let actOK = UIAlertAction(title: "OK", style: .default) { (actOK) in let source = Bundle.main.path(forResource: "aku", ofType: "mp4") self.video = AVPlayer(url: URL(fileURLWithPath: source!)) let controller = AVPlayerViewController() controller.player = self.video self.present(controller, animated: true, completion: nil) } let actCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(actOK) alert.addAction(actCancel) present(alert, animated: true, completion: nil) default: break } } }
// // ViewController.swift // Messenger // // Created by Szymon Szysz on 20/10/2018. // Copyright © 2018 Szymon Szysz. All rights reserved. // import UIKit class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
// // ViewController.swift // Magic 8 Ball // // Created by Jordan Romero on 1/12/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var magicBall: UIImageView! @IBOutlet var toggleView: UIView! let ballArray = [#imageLiteral(resourceName: "ball5"), #imageLiteral(resourceName: "ball2"), #imageLiteral(resourceName: "ball4"), #imageLiteral(resourceName: "ball3"), #imageLiteral(resourceName: "ball5")] @IBAction func askButtonPressed(_ sender: UIButton) { magicBall.image = ballArray[Int.random(in: 0...4)] } @IBAction func toggleLightMode(_ sender: UISwitch) { toggleView.backgroundColor = .white } }
// // ViewController.swift // HealthClub // // Created by markd on 5/7/18. // Copyright © 2018 Borkware. All rights reserved. // import UIKit import HealthKit class ViewController: UIViewController { var hkstore: HKHealthStore! @IBOutlet var messageLabel: UILabel! var workouts: [HKWorkout] = [] @IBOutlet var workoutsTableView : UITableView! private let cellReuseIdentifier = "Cell" let formatter = DateComponentsFormatter() private func setMessage(_ message: String) { DispatchQueue.main.async { self.messageLabel.text = message } } private func setupHealthStore() { hkstore = HKHealthStore() let readTypes = Set([HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.bloodType)!, ]) let writeTypes = Set([HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!]) hkstore.requestAuthorization(toShare: writeTypes, read: readTypes) { (success, error) in if !success { var messageText = "Couldn't access health store." if let error = error { messageText += " \(error)" } self.setMessage(messageText) } else { self.setMessage("YAY") } } } private func processWorkoutSamples(_ samples: [HKSample]) { workouts = samples.compactMap { $0 as? HKWorkout }.reversed() // comes sorted by time let workoutCounts = workouts.reduce(into: [String: Int]()) { $0[$1.workoutActivityType.humanReadableName(), default: 0] += 1 } let workoutMessage = workoutCounts.reduce("", { $0 + "\($1.key) : \($1.value)\n" }) setMessage("Workouts: " + workoutMessage) DispatchQueue.main.async { self.workoutsTableView.reloadData() } } @IBAction func fetchWorkouts() { let sampleType = HKWorkoutType.workoutType() let query = HKSampleQuery.init(sampleType: sampleType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, samples, error) in guard let samples = samples else { self.setMessage("so sad") return } self.processWorkoutSamples(samples) } hkstore.execute(query) } @IBAction func getCharacteristicData() { do { let bloodtype = try hkstore.bloodType() setMessage(bloodtype.bloodType.humanReadableName()) } catch { setMessage("Could not get blood type: \(error)") } } private func addWorkout() { let finish = Date() let start = finish.addingTimeInterval(-3600) // public convenience init(activityType workoutActivityType: HKWorkoutActivityType, start startDate: Date, end endDate: Date) // good luck trying to do completion with HKWorkout.init... #ilyxc let workout = HKWorkout(activityType: .americanFootball, start: start, end: finish) // let workout = HKWorkout.init(activityType: .americanFootball, start: start, end: finish, workoutEvents: workoutEvents, totalEnergyBurned: nil, totalDistance: nil, metadata: nil) hkstore.save(workout) { (success, error) in guard success else { self.setMessage("Bummer, couldn't make workout") return } self.setMessage("WOO!") // now add the heart rates var fakeSamples: [HKQuantitySample] = [] for x in 0..<360 { let hrStart = start.addingTimeInterval(TimeInterval(x * 10)) // 10 seconds per heart rate guard let heartRateQuantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { fatalError("*** Unable to create a heart rate type ***") } let heartRate = 100 + 20 * sin(Double(x) / 50) let heartRateForIntervalQuantity = HKQuantity(unit: HKUnit(from: "count/min"), doubleValue: heartRate) let heartRateForIntervalSample = HKQuantitySample(type: heartRateQuantityType, quantity: heartRateForIntervalQuantity, start: hrStart, end: hrStart) // Ethel the Aardvark goes Quantity Surveying fakeSamples.append(heartRateForIntervalSample) } self.hkstore.add(fakeSamples, to: workout) { (success, error) in guard success else { self.setMessage("Bummer, couldn't add samples") return } self.setMessage("Woo2") } } } @IBAction func makeWorkout() { addWorkout() } override func viewDidLoad() { super.viewDidLoad() guard HKHealthStore.isHealthDataAvailable() else { setMessage("OH NOES no health data available!") return } setupHealthStore() self.workoutsTableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return workouts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as UITableViewCell let workout = workouts[indexPath.row] let name = workout.workoutActivityType.humanReadableName() let duration = workout.duration let durationString = formatter.string(from: duration) ?? "-" let start = workout.startDate cell.textLabel?.text = "\(name) - \(durationString) - \(start)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let workout = workouts[indexPath.row] let vc = self.storyboard?.instantiateViewController(withIdentifier: "WorkoutDetailViewController") as! WorkoutDetailViewController vc.workout = workout vc.hkstore = hkstore self.navigationController?.pushViewController(vc, animated: true) } }
// // AppTheme.swift // Night Mode // // Created by Michael on 01/04/2018. // Copyright © 2018 Late Night Swift. All rights reserved. // import UIKit struct AppTheme { var name: String var statusBarStyle: UIStatusBarStyle var barBackgroundColor: UIColor var barForegroundColor: UIColor var backgroundColor: UIColor var textColor: UIColor var cellBackgroundColor: UIColor var headerFooterTextColor: UIColor var cellSelectedColor: UIColor var textFieldBackgroundColor: UIColor var keyboardAppearance: UIKeyboardAppearance var alertBackgroundColor: UIColor var alertSeparatorColor: UIColor var textViewBorderColor: CGColor var alertTextColor: UIColor } extension AppTheme { static let light = AppTheme( name: "light", statusBarStyle: .`default`, barBackgroundColor: .white, barForegroundColor: .black, backgroundColor: UIColor(white: 0.9, alpha: 1), textColor: .darkText, cellBackgroundColor: .white, headerFooterTextColor: UIColor(white: 0.2, alpha: 1), cellSelectedColor: .lightGreenDay, textFieldBackgroundColor: .white, keyboardAppearance: .light, alertBackgroundColor: .white, alertSeparatorColor: UIColor(white: 0.9, alpha: 1), textViewBorderColor: UIColor(white: 0.8, alpha: 1).cgColor, alertTextColor: .darkText ) static let dark = AppTheme( name: "dark", statusBarStyle: .lightContent, barBackgroundColor: UIColor(white: 0, alpha: 1), barForegroundColor: .white, backgroundColor: UIColor(white: 0.1, alpha: 1), textColor: .lightText, cellBackgroundColor: UIColor(white: 0.2, alpha: 1), headerFooterTextColor: UIColor(white: 0.8, alpha: 1), cellSelectedColor: .darkGreenNight, textFieldBackgroundColor: UIColor(white: 0.4, alpha: 1), keyboardAppearance: .dark, alertBackgroundColor: UIColor(white: 0.3, alpha: 1), alertSeparatorColor: UIColor(white: 0.4, alpha: 1), textViewBorderColor: UIColor(white: 0.4, alpha: 1).cgColor, alertTextColor: .white ) }
// // Technology.swift // Capital Pride // // Created by John Cloutier on 4/27/15. // Copyright (c) 2015 John Cloutier. All rights reserved. // import Foundation import CoreData @objc(Technology) class Technology: NSManagedObject { @NSManaged var image: String @NSManaged var name: String @NSManaged var poc: String @NSManaged var pocEmail: String @NSManaged var techDescription: String @NSManaged var url: String }
// // SearchMovieNetTask.swift // VisaMovie // // Created by Jiao on 23/7/16. // Copyright © 2016 Jiao. All rights reserved. // import UIKit class UploadUserScoreNetTask: BaseNetTask { var name : String? var score : Int? override func uri() -> String! { return "new" } override func query() -> [AnyHashable: Any]!{ var dic = Dictionary<String , Any>() if let tmp = name { dic["name"] = tmp } if let tmp = score { dic["score"] = tmp } return dic } }
// // Birdble.swift // MockApp // // Created by Egor Gorskikh on 07.09.2021. // import Foundation protocol Birdble { var canFly: Bool { get } func fly() }
// // String+Extensions.swift // MikroblogViewer // // Created by Marcin Mucha on 19/06/2019. // Copyright © 2019 Marcin Mucha. All rights reserved. // import Foundation extension String{ var htmlAttributedString: NSAttributedString { guard let data = data(using: .unicode) else { return NSAttributedString() } do { return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } catch { debugPrint(error) return NSAttributedString() } } }
// // UIView+Shadow.swift // SharedNews // // Created by Alexey Sklyarenko on 05.01.2018. // Copyright © 2018 Alexey Sklyarenko. All rights reserved. // import UIKit public extension UIView { public enum ViewShadowSides { case top case right case bottom case left } public func addShadow(sides: ViewShadowSides ..., radius: CGFloat, color: UIColor, offset: CGSize, opacity: Float) { self.layer.shadowColor = color.cgColor self.layer.shadowRadius = radius self.layer.shadowOffset = offset self.layer.shadowOpacity = opacity self.layer.masksToBounds = false let path = CGMutablePath() let shadowTopRect = CGRect(x: self.bounds.minX, y: self.bounds.origin.y - radius / 2, width: self.bounds.width, height: self.layer.shadowRadius) let shadowLeftRect = CGRect(x: self.bounds.minX - radius / 2, y: self.bounds.origin.y, width: self.layer.shadowRadius, height: self.bounds.height) let shadowRightRect = CGRect(x: self.bounds.maxX, y: self.bounds.origin.y, width: self.layer.shadowRadius, height: self.bounds.height) let shadowBottomRect = CGRect(x: self.bounds.minX, y: self.bounds.maxY, width: self.bounds.width, height: self.layer.shadowRadius) for side in sides { switch side { case .top : path.addRect(shadowTopRect) case .left: path.addRect(shadowLeftRect) case .right: path.addRect(shadowRightRect) case .bottom: path.addRect(shadowBottomRect) } } self.layer.shadowPath = path } }
// // ChatMessage.swift // ChatEmulationDemo // // Created by Sergey Monastyrskiy on 03.06.2020. // Copyright © 2020 Sergey Monastyrskiy. All rights reserved. // import Foundation struct ChatMessage: Codable, Hashable { // MARK: - Properties var line: String let author: String? }
// // ViewController.swift // SwiftApp // // Created by Michael Harper on 10/7/14. // Copyright (c) 2014 Radius Networks. All rights reserved. // import UIKit import SimpleFramework class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let sc = SimpleClass("Hello Swift framework from Swift!!!") sc.printMessage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // MessageEntity.swift // Sample Clean Architecture // // Created by Quipper Indonesia on 11/07/21. // import Foundation struct MessageEntity { var welcomeMessage: String }
// // Glide.swift // GlideUI // // Created by Osama Naeem on 24/10/2019. // Copyright © 2019 NexThings. All rights reserved. // import UIKit enum State { case closed case compressed case open } class Glide : NSObject, UIGestureRecognizerDelegate, UIScrollViewDelegate { private var configuration: GlideConfiguration! private weak var parentViewController: UIViewController? private var card: (Glideable & UIViewController)? private weak var containerView: UIView? private weak var cardTopAnchorConstraint: NSLayoutConstraint! private var headerHeight: CGFloat? private var window = UIWindow() private var anotherWindow: UIWindow? private let blackView = UIView() private var startingConstant : CGFloat = 0 private var calculatedSegmentHeightsDictionary : [State: CGFloat] = [ : ] private var currentState: State = .closed private var gestureRecognizer : UIPanGestureRecognizer! weak var delegate: GlideDelegate? var shouldHandleGesture: Bool = true init(parentViewController: UIViewController, configuration: GlideConfiguration, card: Glideable & UIViewController) { super.init() self.parentViewController = parentViewController self.configuration = configuration self.card = card addCardToContainer() } private func addCardToContainer() { guard let card = self.card else { return } self.containerView = parentViewController?.view self.setupPreviewLayer(parentViewController: self.parentViewController!, cardViewController: card) guard let container = containerView else { print("No Parent Container View Available") return } self.headerHeight = card.headerHeight addChildToContainer(containerView: container, card: card.view) self.setupRecognizer(card: card.view) } private func setupPreviewLayer(parentViewController: UIViewController, cardViewController: UIViewController) { window = UIApplication.shared.keyWindow! blackView.backgroundColor = UIColor.black blackView.alpha = 0 window.addSubview(blackView) blackView.frame = window.frame blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapRecognizer))) window.addSubview(cardViewController.view) showPopUpIndicator() } private func addChildToContainer(containerView: UIView, card: UIView) { guard let safeAreaLayout = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.height else { return } guard let bottomAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return } ///Calculating Segment Heights if Segmentation is enabled in Configuration file calculateSegmentHeights() ///The headerheight is over written if segmentation is enabled ///Segmentation closed height then becomes the headerHeight let visibleHeight = configuration.segmented ? (calculatedSegmentHeightsDictionary[.closed] ?? 0) : (safeAreaLayout + bottomAreaInset - (self.headerHeight ?? 0)) card.translatesAutoresizingMaskIntoConstraints = false cardTopAnchorConstraint = card.topAnchor.constraint(equalTo: window.safeAreaLayoutGuide.topAnchor, constant: visibleHeight) card.leadingAnchor.constraint(equalTo: window.leadingAnchor).isActive = true card.trailingAnchor.constraint(equalTo: window.trailingAnchor).isActive = true card.bottomAnchor.constraint(equalTo: window.bottomAnchor).isActive = true cardTopAnchorConstraint.isActive = true } private func configureCardSize(parentView: UIView, configuration: GlideConfiguration) -> CGFloat { return configuration.concreteDimension.translateView(containerView: parentView, navControllerPresent: true) } private func setupRecognizer(card : UIView) { guard let controller = self.card else { return } gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanRecognizer(recognizer: ))) gestureRecognizer.delegate = self card.addGestureRecognizer(gestureRecognizer) } @objc func handleTapRecognizer() { dismissCard() } func triggerCard() { configuration.segmented ? showCard(state: .compressed) : showCard(state: .open) } func collapseCard() { self.dismissCard() } func triggerOpenState() { self.currentState == .compressed ? showCard(state: .open) : showCard(state: .open) } private func showPopUpIndicator() { guard let card = self.card else { return } if configuration.popUpIndicator { let grayView = UIView() let width: CGFloat = 50 grayView.backgroundColor = .lightGray grayView.layer.cornerRadius = 3 grayView.frame = CGRect(x: (card.view.frame.width / 2) - (width / 2), y: 8, width: width, height: 6) card.view.addSubview(grayView) } } private func calculateSegmentHeights() { guard let safeAreaLayout = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.height else { return } guard let bottomAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return } if configuration.segmented { let segmentationHeights = configuration.segmentHeightDictionary guard let compressedHeight = segmentationHeights[.compressed] else { print("No Compressed Heights Available in Configuration File") return } guard let openHeight = segmentationHeights[.open] else { print("No Open Heights Available in Configuration File") return } guard let closeHeight = segmentationHeights[.closed] else { print("No closed Heights Available in Configuration File") return } let compressedStateConstraintConstant = (safeAreaLayout + bottomAreaInset - compressedHeight) let openStateConstraintConstant = (safeAreaLayout + bottomAreaInset - openHeight) let closedStateConstraintConstant = (safeAreaLayout + bottomAreaInset - closeHeight) calculatedSegmentHeightsDictionary[.compressed] = compressedStateConstraintConstant calculatedSegmentHeightsDictionary[.open] = openStateConstraintConstant calculatedSegmentHeightsDictionary[.closed] = closedStateConstraintConstant } } /// MARK: - Animations @objc func handlePanRecognizer(recognizer: UIPanGestureRecognizer) { guard let safeAreaLayout = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.height else { return } guard let bottomAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return } guard shouldHandleGesture else { return } // KEY STUFF HERE guard let container = self.containerView else { return } guard let card = self.card else { return } switch recognizer.state { case .began: startingConstant = (cardTopAnchorConstraint?.constant)! case .changed: let translationY = recognizer.translation(in: card.view).y if self.startingConstant + translationY > 0 { self.cardTopAnchorConstraint!.constant = self.startingConstant + translationY blackView.alpha = dimAlphaWithCardTopConstraint(value: cardTopAnchorConstraint!.constant) } case .ended: let velocityY = recognizer.velocity(in: card.view).y let topAnchorConstant = configuration.segmented ? calculatedSegmentHeightsDictionary[.compressed]! : configureCardSize(parentView: container, configuration: configuration) if cardTopAnchorConstraint!.constant < topAnchorConstant { if velocityY > 0 { //card moving down showCard(state: .compressed) }else { //card moving up showCard(state: .open) } } else if cardTopAnchorConstraint!.constant < (safeAreaLayout) { if velocityY > 0 { //Card moving down showCard(state: .closed) }else { //card moving upwards configuration.segmented ? showCard(state: .compressed) : showCard(state: .open) } }else { dismissCard() } default: break } } private func showCard(state: State) { guard let safeAreaLayout = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.height else { return } guard let bottomAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return } guard let card = self.card else { return } guard let container = self.containerView else { return } self.window.layoutIfNeeded() if (configuration.segmented) { switch state { case .compressed: guard let compressedSegmentHeight = calculatedSegmentHeightsDictionary[.compressed] else { print("No Compressed Segment Height in Configuration File") return } cardTopAnchorConstraint!.constant = compressedSegmentHeight let showCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded() }) showCard.addAnimations { card.view.layer.cornerRadius = 15 self.blackView.alpha = 0.4 } showCard.addCompletion { position in switch position { case .end: self.currentState = .compressed // print(self.currentState) default: () } } showCard.startAnimation() if showCard.isRunning { self.delegate?.glideStateChangingFromOpenToCompress() if let detectedScrollView = detectScrollView() { detectedScrollView.panGestureRecognizer.isEnabled = false } } break case .open: guard let openSegmentHeight = calculatedSegmentHeightsDictionary[.open] else { print("No Open Segment Height in Configuration File") return } cardTopAnchorConstraint.constant = openSegmentHeight let showCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded()}) showCard.addAnimations { card.view.layer.cornerRadius = 15 self.blackView.alpha = 0.4 } showCard.addCompletion { position in switch position { case .end: self.currentState = .open // print(self.currentState) default: () } } showCard.startAnimation() break case .closed: guard let closedSegmentHeight = calculatedSegmentHeightsDictionary[.closed] else { print("No Closed Segment Height in Configuration File") return } cardTopAnchorConstraint.constant = closedSegmentHeight let showCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded()}) showCard.addAnimations { card.view.layer.cornerRadius = 0 self.blackView.alpha = 0 } showCard.addCompletion { position in switch position { case .end: self.currentState = .closed self.delegate?.glideDidClose() // print(self.currentState) default: () } } showCard.startAnimation() break } // Segmentation is not enabled } else { switch state { case .open: cardTopAnchorConstraint.constant = configureCardSize(parentView: container, configuration: configuration) let showCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded()}) showCard.addAnimations { card.view.layer.cornerRadius = 15 self.blackView.alpha = 0.4 } showCard.addCompletion { position in switch position { case .end: self.currentState = .open default: () } } showCard.startAnimation() break case .compressed: //Nothing should take place here! fallthrough case .closed: cardTopAnchorConstraint.constant = (safeAreaLayout + bottomAreaInset - (self.headerHeight ?? 0)) let dismissCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded()}) dismissCard.addAnimations { card.view.layer.cornerRadius = 0 self.blackView.alpha = 0 } dismissCard.addCompletion { position in switch position { case .end: self.currentState = .closed default: () } } dismissCard.startAnimation() } } } private func dismissCard() { self.window.layoutIfNeeded() guard let safeAreaLayout = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.height else { return } guard let bottomAreaInset = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return } guard let card = self.card else { return } let dismissConstant = (safeAreaLayout + bottomAreaInset - (headerHeight ?? 0)) let dismissHeight = configuration.segmented ? (calculatedSegmentHeightsDictionary[.closed] ?? dismissConstant) : dismissConstant cardTopAnchorConstraint!.constant = dismissHeight let dismissCard = UIViewPropertyAnimator(duration: 0.8, dampingRatio: 1, animations: { self.window.layoutIfNeeded() }) // run the animation dismissCard.addAnimations { card.view.layer.cornerRadius = 0 self.blackView.alpha = 0 } dismissCard.addCompletion { position in switch position { case .end: self.currentState = .closed self.delegate?.glideDidClose() default: () } } shouldHandleGesture = true dismissCard.startAnimation() } private func dimAlphaWithCardTopConstraint(value: CGFloat) -> CGFloat { let fullDimAlpha : CGFloat = 0.4 guard let safeAreaHeight = UIApplication.shared.keyWindow?.safeAreaLayoutGuide.layoutFrame.size.height, let bottomPadding = UIApplication.shared.keyWindow?.safeAreaInsets.bottom else { return fullDimAlpha } let fullDimPosition = (safeAreaHeight + bottomPadding) / 2.0 let noDimPosition = (safeAreaHeight + bottomPadding - (headerHeight ?? 0)) if value < fullDimPosition { return fullDimAlpha } if value > noDimPosition { return 0.0 } return fullDimAlpha - fullDimAlpha * ((value - fullDimPosition) / fullDimPosition) } func detectScrollView() -> UIScrollView? { guard let cardViewController = self.card as? UINavigationController else { return nil } var detectedScrollView : UIScrollView? = UIScrollView() var detectedVC = UIViewController() for vc in cardViewController.viewControllers { if let vc = vc as? SelectSourceViewController { detectedVC = vc } } for subview in detectedVC.view.subviews { if let view = subview as? UIScrollView { detectedScrollView = view } } return detectedScrollView } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { guard let panGestureRecognzier = gestureRecognizer as? UIPanGestureRecognizer else { return true } guard let cardViewController = self.card else { return false} guard let detectedScrollView = detectScrollView() else { return false} let velocity = panGestureRecognzier.velocity(in: cardViewController.view) detectedScrollView.panGestureRecognizer.isEnabled = true if otherGestureRecognizer == detectedScrollView.panGestureRecognizer { switch currentState { case .compressed: detectedScrollView.panGestureRecognizer.isEnabled = false return false case .closed: detectedScrollView.panGestureRecognizer.isEnabled = false return false case .open: if velocity.y > 0 { if detectedScrollView.contentOffset.y > 0.0 { return true } shouldHandleGesture = true detectedScrollView.panGestureRecognizer.isEnabled = false return false }else { shouldHandleGesture = false return true } default: () } } return false } }
// // Joystick.swift // TwinStick_Shooter // // Created by William Leet on 1/27/20. // Copyright © 2020 William Leet. All rights reserved. // // This class holds and handles tragic yet all too necessary joystick chicanery... import UIKit import SpriteKit import GameplayKit class Joystick: SKSpriteNode { private var base: SKSpriteNode! private var stick_position_X: CGFloat = 0.0 private var stick_position_Y: CGFloat = 0.0 private var stick_angle: CGFloat? private var inUse = false var disabled = false convenience init(base_name: String, stick_name: String, opacity: CGFloat, scale: CGFloat){ self.init(imageNamed: stick_name) self.isUserInteractionEnabled = true self.base = SKSpriteNode(imageNamed: base_name) self.alpha = opacity self.base.alpha = opacity self.base.setScale(scale) self.setScale(scale) } func get_xPos() -> CGFloat{ return stick_position_X } func get_yPos() -> CGFloat{ return stick_position_Y } func get_angle() -> CGFloat{ return stick_angle! } func is_inUse() -> Bool{ return inUse } func get_base() -> SKSpriteNode{ return base } func move_joystick(location: CGPoint){ if(self.disabled){ return } //Sets joystick to 'in use' inUse = true //Sets up joystick bounds let vect = CGVector(dx: location.x - base.position.x, dy: location.y - base.position.y) stick_angle = atan2(vect.dy,vect.dx) let stick_length: CGFloat = base.frame.size.height / 2 let xDist: CGFloat = sin (stick_angle! - CGFloat(Double.pi/2)) * stick_length let yDist: CGFloat = cos (stick_angle! - CGFloat(Double.pi/2)) * stick_length //Determines joystick location within bounds if (base.frame.contains(location)){ self.position = location } else { self.position = CGPoint(x: base.position.x - xDist, y: base.position.y + yDist) } //Updates joystick position vars stick_position_X = (position.x - base.position.x) stick_position_Y = (position.y - base.position.y) } //Determines if a touch is within the joystick's bounds func isWithinBounds(touch: CGPoint) -> Bool { let xDist_to_stick = abs(touch.x - base.position.x) let yDist_to_stick = abs(touch.y - base.position.y) let stick_bounds = base.frame.size.height - 10 return xDist_to_stick < stick_bounds && yDist_to_stick < stick_bounds } //Moves joystick to default position, resets vars accordingly func reset_joystick() { let reset_position: SKAction = SKAction.move(to: base.position, duration: 0.15) reset_position.timingMode = .easeOut stick_position_X = 0 stick_position_Y = 0 stick_angle = nil inUse = false //self.run(reset_position) self.position = base.position } }
// // FirstData.swift // TennisGuide // // Created by Vladimir Saprykin on 16.07.16. // Copyright © 2016 Vladimir Saprykin. All rights reserved. // import UIKit class FirstDataCell: UITableViewCell { @IBOutlet weak var factorsLabel: UILabel! @IBOutlet weak var imageLabel: UIImageView! }
// // ModalViewControllerDelegate.swift // Royals // // Created by Bruno Thuma on 15/09/21. // import Foundation protocol ModalViewControllerDelegate: AnyObject { func sendValue(selectedType: MapPinType) }
// // ViewMonitor.swift // LaunchSms // // Created by SantiagoDls on 03/09/15. // Copyright © 2015 ConstruApps. All rights reserved. // import UIKit class ViewMonitor: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.lbInfo.text="Binvenido " + user } @IBOutlet var lbInfo: UILabel! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goToViewMenu(sender: AnyObject) { performSegueWithIdentifier("segueMonitorToMain", sender: self) } }
// // UserAccountController.swift // RumahHokie // // Created by Hadron Megantara on 14/10/18. // Copyright © 2018 Hadron Megantara. All rights reserved. // import Foundation import UIKit class UserAccountController: UIViewController, UITextFieldDelegate { @IBOutlet weak var userImg: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var userJoinedFrom: UILabel! @IBOutlet weak var userPropertyTotal: UILabel! @IBOutlet weak var userPropertySold: UILabel! @IBOutlet weak var bottomMenu: BottomMenu! var sideIsOpened: Bool = false override func viewDidLoad() { super.viewDidLoad() let decoded = UserDefaults.standard.object(forKey: "User") as! Data let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) userName.text = (decodedTeams as AnyObject).value(forKey: "agt_name") as? String let propertyTotal: Int = (decodedTeams as AnyObject).value(forKey: "published_cnt_listing_count") as! Int let propertySold: Int = (decodedTeams as AnyObject).value(forKey: "sold_cnt_listing_count") as! Int userPropertyTotal.text = String(propertyTotal) userPropertySold.text = String(propertySold) let pictUrl = URL(string: "http://rumahhokie.com/"+((decodedTeams as AnyObject).value(forKey: "agt_image") as? String)!)! DispatchQueue.global().async { if let data = try? Data(contentsOf: pictUrl){ if let dataImage = UIImage(data: data){ DispatchQueue.main.async { self.userImg.image = dataImage } } } } navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: self, action: nil) if UserDefaults.standard.object(forKey: "User") != nil{ navigationController?.navigationBar.isHidden = false self.navigationItem.title = "Akun" self.navigationController?.navigationBar.barTintColor = UIColor(red: 34/255, green: 54/255, blue: 128/255, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] let btnFilter = UIButton(type: .custom) btnFilter.titleLabel?.font = UIFont(name: "FontAwesome", size: 20) btnFilter.setTitle("", for: .normal) btnFilter.addTarget(self, action: #selector(openFilter), for: UIControlEvents.touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btnFilter) if let bottomMenuView = Bundle.main.loadNibNamed("BottomMenuUser", owner: nil, options: nil)?[0] as? UIView{ bottomMenuView.frame.size.width = bottomMenu.frame.width bottomMenu.addSubview(bottomMenuView) } } else{ navigationController?.navigationBar.isHidden = true let bottomMenuView = Bundle.main.loadNibNamed("BottomMenu", owner: nil, options: nil)![0] as! UIView bottomMenu.addSubview(bottomMenuView) } } @objc func openFilter(){ if(!sideIsOpened){ sideIsOpened = true let sideMenu = Bundle.main.loadNibNamed("SideBar", owner: nil, options: nil)![0] as! UIView sideMenu.frame.size.width = self.view.frame.width * 4/5 sideMenu.frame.size.height = self.view.frame.height sideMenu.tag = 100 self.view.superview?.isUserInteractionEnabled = true self.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped))) UIView.transition(with: self.view, duration: 0.5, options:[],animations: {self.view.addSubview(sideMenu)}, completion: nil) } else{ sideIsOpened = false let sideView = view.viewWithTag(100) sideView?.removeFromSuperview() } } @objc func alertControllerBackgroundTapped(){ sideIsOpened = false let sideView = view.viewWithTag(100) sideView?.removeFromSuperview() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func logoutAction(_ sender: Any) { let prefs = UserDefaults.standard prefs.removeObject(forKey:"User") let vc = storyboard!.instantiateViewController(withIdentifier: "homeView") as? HomeController navigationController!.pushViewController(vc!, animated: true) } @IBAction func resetPasswordAction(_ sender: Any) { let vc = storyboard!.instantiateViewController(withIdentifier: "resetPasswordView") as? ResetPasswordController navigationController!.pushViewController(vc!, animated: true) } }
// // CallstatsConfig.swift // Callstats // // Created by Amornchai Kanokpullwad on 9/22/18. // Copyright © 2018 callstats. All rights reserved. // import Foundation /** Library configurations */ public class CallstatsConfig: NSObject { /// Send keep alive event every x second var keepAlivePeriod: TimeInterval = 10 /// Stats submission period var statsSubmissionPeriod: TimeInterval = 30 /// Send keep alive event every x second var systemStatsSubmissionPeriod: TimeInterval = 30 }
// // AddSkillsCellManager.swift // OSOM_app // // Created by Miłosz Bugla on 18.11.2017. // import Foundation import UIKit fileprivate struct LocalizedStrings { static let header = "NAME OF SKILL" static let labelText = "skill" } protocol AddSkillsCellManagerDelegate: class { } protocol AddSkillsCellManager: class { func buildCell(indexPath: IndexPath, delegate: AddEducationCellDelegate, skillsSection: SkillsSection?) -> UITableViewCell func checkCellAtRow(row: Int) -> Bool func getSkillNameFor(row: Int) -> String? } final class AddSkillsCellManagerImpl: AddSkillsCellManager { let tableView: UITableView init(tableView: UITableView) { self.tableView = tableView registerCells() } fileprivate func registerCells() { tableView.registerCell(AddEducationCell.self) } func buildCell(indexPath: IndexPath, delegate: AddEducationCellDelegate, skillsSection: SkillsSection?) -> UITableViewCell { guard let cell = tableView.getCell(AddEducationCell.self) else { return UITableViewCell() } cell.mainView.label.headerLabel.text = LocalizedStrings.header cell.mainView.label.textField.text = skillsSection?.name ?? "" cell.mainView.label.setAttributedPlaceholder(string: LocalizedStrings.labelText) cell.mainView.addButton.tag = indexPath.row cell.mainView.label.textField.isUserInteractionEnabled = true cell.delegate = delegate return cell } func checkCellAtRow(row: Int) -> Bool { guard let cell = tableView.cellForRow(at: IndexPath(item: row, section: 0)) as? AddEducationCell else { return false } cell.validate() return cell.validator.errors.isEmpty } func getSkillNameFor(row: Int) -> String? { guard let cell = tableView.cellForRow(at: IndexPath(item: row, section: 0)) as? AddEducationCell else { return nil } return cell.mainView.label.textField.text } }
// // CartCell.swift // OnlineStore // // Created by Stanislav Grigorov on 9.01.18. // Copyright © 2018 Stanislav Grigorov. All rights reserved. // import UIKit class CartCell: UITableViewCell { @IBOutlet weak var containerView: UIView! @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var itemNameLabel: UILabel! @IBOutlet weak var itemsQuantity: UILabel! @IBOutlet weak var itemPriceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() containerView.layer.cornerRadius = 12 } func setupView(product: Product) { itemImage.image = UIImage(named: product.imageName) itemNameLabel.text = product.title itemPriceLabel.text = "Price: \(product.price)$" itemsQuantity.text = String("Pieces: \(product.productQuantity)") } }
// // CTFBARTStepViewController.swift // Impulse // // Created by James Kizer on 10/17/16. // Copyright © 2016 James Kizer. All rights reserved. // import UIKit import ResearchKit extension Array where Element: Integer { /// Returns the sum of all elements in the array var total: Element { return reduce(0, +) } } extension Collection where Iterator.Element == Int, Index == Int { /// Returns the average of all elements in the array var average: Float { return isEmpty ? 0 : Float(reduce(0, +)) / Float(endIndex-startIndex) } } struct CTFBARTTrial { var earningsPerPump: Float var maxPayingPumps: Int var trialIndex: Int var canExplodeOnFirstPump: Bool } struct CTFBARTTrialResult { var trial: CTFBARTTrial! var numPumps: Int! var payout: Float! var exploded: Bool! } class CTFBARTResult: ORKResult { var trialResults: [CTFBARTTrialResult]? } class CTFBARTStepViewController: ORKStepViewController { let initialScalingFactor: CGFloat = 10.0 @IBOutlet weak var balloonContainerView: UIView! var balloonImageView: UIImageView! var balloonConstraints: [NSLayoutConstraint]? @IBOutlet weak var trialPayoutLabel: UILabel! @IBOutlet weak var totalPayoutLabel: UILabel! @IBOutlet weak var taskProgressLabel: UILabel! @IBOutlet weak var pumpButton: CTFBorderedButton! var _pumpButtonHandler:(() -> ())? @IBOutlet weak var collectButton: CTFBorderedButton! var _collectButtonHandler:(() -> ())? @IBOutlet weak var skipButton: UIButton! var trials: [CTFBARTTrial]? var trialsCount:Int { return self.trials?.count ?? 0 } var trialResults: [CTFBARTTrialResult]? //pending trials and results var pendingTrials: [CTFBARTTrial]? var pendingResults: [CTFBARTTrialResult]? var canceled = false override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override convenience init(step: ORKStep?) { let framework = Bundle(for: CTFBARTStepViewController.self) self.init(nibName: "CTFBARTStepViewController", bundle: framework) self.step = step self.restorationIdentifier = step!.identifier guard let bartStep = self.step as? CTFBARTStep, let params = bartStep.params else { return } self.trials = self.generateTrials(params: params) } override convenience init(step: ORKStep?, result: ORKResult?) { self.init(step: step) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // func generateSummary(slice: ArraySlice<(CTFBARTTrialResult, CTFBARTTrialResult?)>) -> CTFBARTResultSummary? { // // guard slice.count > 0 else { // return nil // } // // var summary = CTFBARTResultSummary() // // let pumpsArray: [Int] = slice.map({$0.0.numPumps}) // // //mean // summary.meanNumberOfPumps = pumpsArray.average // // //range // summary.numberOfPumpsRange = pumpsArray.max()! - pumpsArray.min()! // // //std dev // let stdDevExpression = NSExpression(forFunction:"stddev:", arguments:[NSExpression(forConstantValue: pumpsArray)]) // summary.numberOfPumpsStdDev = stdDevExpression.expressionValue(with: nil, context: nil) as? Float // // let pumpsAfterExplode: [Int] = slice.filter { (pair) -> Bool in // if let previousResult = pair.1 { // return previousResult.exploded // } // else { // return false // } // }.map({$0.0.numPumps}) // // summary.meanNumberOfPumpsAfterExplosion = pumpsAfterExplode.average // // let pumpsAfterNoExplode: [Int] = slice.filter { (pair) -> Bool in // if let previousResult = pair.1 { // return !previousResult.exploded // } // else { // return false // } // }.map({$0.0.numPumps}) // // summary.meanNumberOfPumpsAfterNoExplosion = pumpsAfterNoExplode.average // // summary.numberOfExplosions = slice.map({$0.0}).filter({$0.exploded}).count // // summary.numberOfBalloons = slice.count // // summary.totalWinnings = slice.map({$0.0.payout}).reduce(0.0, +) // // return summary // } override var result: ORKStepResult? { guard let parentResult = super.result else { return nil } if let trialResults = self.trialResults { // var lastResult: CTFBARTTrialResult? = nil // // let pairArray: [(CTFBARTTrialResult, CTFBARTTrialResult?)] = // trialResults.map { result in // // let returnPair = (result, lastResult) // lastResult = result // return returnPair // // } // // let bartResult = CTFBARTResult(identifier: step!.identifier) // bartResult.startDate = parentResult.startDate // bartResult.endDate = parentResult.endDate // // bartResult.totalSummary = self.generateSummary(slice: ArraySlice(pairArray)) // // bartResult.firstThirdSummary = self.generateSummary(slice: pairArray[0..<(pairArray.count/3)]) // bartResult.secondThirdSummary = self.generateSummary(slice: pairArray[(pairArray.count/3)..<((2*pairArray.count)/3)]) // bartResult.lastThirdSummary = self.generateSummary(slice: pairArray[((2*pairArray.count)/3)..<pairArray.count]) let bartResult = CTFBARTResult(identifier: step!.identifier) bartResult.startDate = parentResult.startDate bartResult.endDate = parentResult.endDate bartResult.trialResults = trialResults parentResult.results = [bartResult] } return parentResult } func generateTrials(params: CTFBARTStepParams) -> [CTFBARTTrial]? { if let numTrials = params.numTrials { return (0..<numTrials).map { index in return CTFBARTTrial( earningsPerPump: params.earningsPerPump, maxPayingPumps: params.maxPayingPumpsPerTrial, trialIndex: index, canExplodeOnFirstPump: params.canExplodeOnFirstPump ) } } else { return nil } } override func viewDidLoad() { super.viewDidLoad() // self.pumpButton.configuredColor = self.view.tintColor // self.collectButton.configuredColor = self.view.tintColor if let step = self.step, step.isOptional == false { self.skipButton.isHidden = true } self.pumpButton.tintColor = self.view.tintColor self.collectButton.tintColor = self.view.tintColor // Do any additional setup after loading the view. if let trials = self.trials { self.setup(trials) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //if there are pending trials, don't reset if let _ = self.pendingTrials, let _ = self.pendingResults { return } //clear results if let trials = self.trials { self.performTrials(trials, results: [], completion: { (results) in // print(results) self.pendingTrials = nil self.pendingResults = nil if !self.canceled { //set results // results is a list that contains all the trial results - Francesco // self.calculateAggregateResults(results) self.trialResults = results self.goForward() } }) } } func setup(_ trials: [CTFBARTTrial]) { self.collectButton.isEnabled = false self.pumpButton.isEnabled = false self.taskProgressLabel.text = "Ballon 1 out of \(self.trialsCount)." self.totalPayoutLabel.text = "$0.00" } func setupImage() { if let oldConstraints = self.balloonConstraints?.filter({$0.isActive}), oldConstraints.count > 0 { NSLayoutConstraint.deactivate(oldConstraints) } if let imageView = self.balloonImageView, let _ = imageView.superview { imageView.removeFromSuperview() } self.balloonImageView = UIImageView(image: UIImage(named: "balloon")) self.balloonImageView.alpha = 0.0 let transform = self.balloonImageView.transform.scaledBy( x: 1.0 / self.initialScalingFactor, y: 1.0 / self.initialScalingFactor ) self.balloonImageView.transform = transform self.balloonContainerView.addSubview(self.balloonImageView) self.balloonImageView.center = CGPoint(x: self.balloonContainerView.bounds.width/2.0, y: self.balloonContainerView.bounds.height/2.0) } func performTrials(_ trials: [CTFBARTTrial], results: [CTFBARTTrialResult], completion: @escaping ([CTFBARTTrialResult]) -> ()) { self.pendingTrials = trials self.pendingResults = results //set the task progress label and total payout label self.taskProgressLabel.text = "Ballon \(results.count + 1) out of \(self.trialsCount)." let totalPayout: Float = results.reduce(0.0) { (acc, trialResult) -> Float in return acc + trialResult.payout } let monitaryValueString = String(format: "%.2f", totalPayout) self.totalPayoutLabel.text = "$\(monitaryValueString)" if self.canceled { completion([]) return } if let head = trials.first { let tail = Array(trials.dropFirst()) self.doTrial(head, results.count, completion: { (result) in var newResults = Array(results) newResults.append(result) self.performTrials(tail, results: newResults, completion: completion) }) } else { completion(results) } } //impliment trial func doTrial(_ trial: CTFBARTTrial, _ index: Int, completion: @escaping (CTFBARTTrialResult) -> ()) { self.trialPayoutLabel.text = "$0.00" self.setupImage() func setupForPump(_ pumpCount: Int) { self._pumpButtonHandler = { //compute probability of pop //function of pump count //probability starts low and eventually gets to 1/2 let popProb = ((trial.maxPayingPumps) >= pumpCount) ? 1.0 / Float( (trial.maxPayingPumps+2) - pumpCount) : 1.0 / 2.0 // print(popProb) //note for coinFlip, p1 = bias = popProb, p2 = (1.0-bias) = !popProb let popped: Bool = { if !trial.canExplodeOnFirstPump && pumpCount == 0 { return false } else { return coinFlip(true, obj2: false, bias: popProb) } }() if popped { // print("should pop here") self.collectButton.isEnabled = false self.pumpButton.isEnabled = false self.balloonImageView.lp_explode(callback: { let result = CTFBARTTrialResult( trial: trial, numPumps: pumpCount+1, payout: 0.0, exploded: true ) // self.setupImage() completion(result) }) } else { //set potential gain label let monitaryValueString = String(format: "%.2f", trial.earningsPerPump * Float( min(trial.maxPayingPumps, pumpCount+1))) self.trialPayoutLabel.text = "$\(monitaryValueString)" let increment: CGFloat = (self.view.frame.width / CGFloat(trial.maxPayingPumps * 1000)) * (8.0/(1.0 + CGFloat(pumpCount))) UIView.animate( withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.curveEaseIn, animations: { let transform = self.balloonImageView.transform.scaledBy( x: 1.0025 * (1.0+increment), y: (1.0+increment) ) self.balloonImageView.transform = transform }, completion: { (comleted) in setupForPump(pumpCount + 1) }) } } self._collectButtonHandler = { self.collectButton.isEnabled = false self.pumpButton.isEnabled = false // remove balloon UIView.animate(withDuration: 0.3, animations: { self.balloonImageView.alpha = 0.0 }, completion: { (completed) in self.balloonImageView.removeFromSuperview() let result = CTFBARTTrialResult( trial: trial, numPumps: pumpCount, payout: Float(min(trial.maxPayingPumps, pumpCount)) * trial.earningsPerPump, exploded: false ) completion(result) }) } self.view.isUserInteractionEnabled = true self.collectButton.isEnabled = pumpCount > 0 self.pumpButton.isEnabled = true } UIView.animate( withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.curveEaseIn, animations: { self.balloonImageView.alpha = 1.0 let transform = self.balloonImageView.transform.scaledBy( x: self.initialScalingFactor, y: self.initialScalingFactor ) self.balloonImageView.transform = transform }, completion: { (comleted) in setupForPump(0) }) } @IBAction func pumpButtonPressed(_ sender: AnyObject) { self.view.isUserInteractionEnabled = false self._pumpButtonHandler?() } @IBAction func collectButtonPressed(_ sender: AnyObject) { self.view.isUserInteractionEnabled = false self._collectButtonHandler?() } @IBAction func skipButtonPressed(_ sender: Any) { self.goForward() } }
// // SettingsView.swift // FlashZilla // // Created by Zaheer Moola on 2021/08/12. // import SwiftUI struct SettingsView: View { @Environment(\.presentationMode) var presentationMode @State private var requeueCards = false var body: some View { NavigationView { List { Section(header: Text("Card settings")) { Toggle("Put incorrect cards back in pile", isOn: $requeueCards) .onChange(of: requeueCards, perform: { _ in saveData() }) } } .navigationBarTitle("Settings") .navigationBarItems(trailing: Button("Done", action: dismiss)) .listStyle(GroupedListStyle()) .onAppear(perform: loadData) } } func loadData() { if let data = UserDefaults.standard.data(forKey: "Settings") { if let decoded = try? JSONDecoder().decode(Bool.self, from: data) { self.requeueCards = decoded } } } func saveData() { if let data = try? JSONEncoder().encode(requeueCards) { UserDefaults.standard.set(data, forKey: "Settings") } } func dismiss() { presentationMode.wrappedValue.dismiss() } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } }
// // GameScene.swift // GameDevConcepts // // Created by Gabriel Anderson on 8/7/15. // Copyright (c) 2015 Gabriel Anderson. All rights reserved. // import SpriteKit class GameScene: SKScene { var entities = [Entity]() var entityIndex: Int = 0; var image: SKSpriteNode! override func didMoveToView(view: SKView) { /* Setup your scene here */ /*let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Hello, World!"; myLabel.fontSize = 65; myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(myLabel)*/ //entities.append(Entity(x: 100, y: 100, color: SKColor.purpleColor())) //entities[entities.count-1].addParent(self) self.backgroundColor = NSColor.blackColor() //image = SKSpriteNode(imageNamed: "uyen.jpg") //image.size = self.frame.size //image.position = CGPointMake(self.size.width / 2, self.size.height / 2) //self.addChild(image) } override func mouseDown(theEvent: NSEvent) { /* Called when a mouse click occurs */ //let location = theEvent.locationInNode(self) //entities.append(Entity(x: location.x, y: location.y, color: SKColor.purpleColor())) // entities[entities.count-1].addParent(self) /* let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.position = location; sprite.setScale(0.5) let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite)*/ } override func mouseUp(theEvent: NSEvent) { let location = theEvent.locationInNode(self) entities.append(Entity(x: location.x, y: location.y, color: SKColor.purpleColor())) self.addChild(entities[entities.count-1]) NSLog("Location: \(location.x), \(location.y)") //NSLog("Original Loc: \(entities[entities.count-1].body.x), \(entities[entities.count-1].body.y)") NSLog("Original Node Loc: \(entities[entities.count-1].body.shapeNode.position.x), \(entities[entities.count-1].body.shapeNode.position.y)") } override func keyDown(theEvent: NSEvent) { NSLog("Key: \(theEvent.charactersIgnoringModifiers), \(theEvent.keyCode)") var key = theEvent.charactersIgnoringModifiers! //var a = if theEvent.keyCode == 0 { NSLog("A") } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ if !entities.isEmpty { var sign1: Int, sign2: Int var randomX: Float, randomY: Float sign1 = arc4random_uniform(2) == 1 ? 1 : -1 randomX = Float(sign1 * Int(arc4random_uniform(40))) sign2 = arc4random_uniform(2) == 1 ? 1 : -1 randomY = Float(sign2 * Int(arc4random_uniform(40))) detectDanger(entities,entityIndex) entities[entityIndex].animate(self, x: randomX, y: randomY) entityIndex++ entityIndex %= entities.count } //NSLog("Index: \(entityIndex)") } func detectDanger(e: [Entity], _ index: Int) { for i in 0..<e.count { e[i].resetDetection() } for k in 0..<e.count { for i in k+1..<e.count { let dx = e[i].body.shapeNode.position.x - e[k].body.shapeNode.position.x let dy = e[i].body.shapeNode.position.y - e[k].body.shapeNode.position.y let distance = sqrt( pow(Double(dx),2) + pow(Double(dy),2) ) if distance <= Double(e[i].boundingCircle.radius+e[k].boundingCircle.radius) { //let angle = Double(atan2(Double(dy), Double(dx))) - M_PI e[k].alert() e[i].alert() if k == entityIndex { e[k].avoid(self) } if i == entityIndex { e[i].avoid(self) } } //NSLog("\ni: \(i)") } } } }
// // ViewController.swift // TableView // // Created by Robert on 10/17/18. // Copyright © 2018 Robert Vitali. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet var theTableView: UITableView! var myArray = ["Mary", "Billy", "Jane"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. theTableView.register(UITableViewCell.self, forCellReuseIdentifier: "theCell") theTableView.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let myCell = tableView.dequeueReusableCell(withIdentifier: "theCell")! as UITableViewCell myCell.textLabel!.text = myArray[indexPath.row] return myCell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// RUN: %target-swift-frontend -O -primary-file %s -emit-ir -g -o - | FileCheck %s import StdlibUnittest // CHECK-LABEL: define{{.*}}2fn public var i : UInt32 = 1 public func fn() { _blackHole(i) // CHECK-DAG: ![[LOC:.*]] = !DILocation(line: [[@LINE+1]], column: 16, _blackHole(0 - i) // CHECK-DAG: ![[LOC2:.*]] = !DILocation(line: [[@LINE+1]], column: 16, _blackHole(0 - i) _blackHole(i) } // CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC]] // CHECK-DAG: unreachable, !dbg ![[LOC]] // CHECK-DAG: call void @llvm.trap(), !dbg ![[LOC2]] // CHECK-DAG: unreachable, !dbg ![[LOC2]]
// // UserSubscription.swift // Cryptohopper-iOS-SDK // // Created by Kaan Baris Bayrak on 03/11/2020. // import Foundation public class UserSubscription : Codable { public private(set) var subscriptionId : String? public private(set) var planId : String? public private(set) var paymentTerm : String? public private(set) var paymentMethodId : String? public private(set) var startTime : String? public private(set) var endTime : String? public private(set) var subscriptionStatus : String? public private(set) var autoRenewal : String? public private(set) var planName : String? public private(set) var planDescription : String? private enum CodingKeys: String, CodingKey { case subscriptionId = "subscription_id" case planId = "plan_id" case paymentTerm = "payment_term" case paymentMethodId = "payment_method_id" case startTime = "start_time" case endTime = "end_time" case subscriptionStatus = "subscription_status" case autoRenewal = "auto_renewal" case planName = "plan_name" case planDescription = "plan_description" } }
import Foundation /// SwiftKit extensions to the standard library Dictionary public extension Dictionary { /// Transform this dictionary into another one by applying a transform on each key/value pair public func transform<K: Hashable, V>(transformation: (Key, Value) -> (key: K, value: V)) -> [K : V] { var transformed = [K : V]() for (key, value) in self { let transformedPair = transformation(key, value) transformed[transformedPair.key] = transformedPair.value } return transformed } } /// Extension to the standard library Dictionary that makes it easier to work with nested collections public extension Dictionary where Value: MutableIndexedCollectionType, Value: EmptyInitializable { /// Insert a value into a nested collection public mutating func insertValue(value: Value.Generator.Element, intoCollectionForKey key: Key) { var collection = self[key] ?? Value() collection.insert(value) self[key] = collection } /// Remove a value at a certain index from a nested collection public mutating func removeValueAtIndex(index: Value.Index, fromCollectionForKey key: Key) { guard var collection = self[key] else { return } collection.removeAtIndex(index) self[key] = collection } } /// Convenience APIs for nested mutable indexed collections where the values are equatable public extension Dictionary where Value: MutableIndexedCollectionType, Value.Generator.Element: Equatable { /// Remove a value from a nested collection by finding it public mutating func removeValue(value: Value.Generator.Element, fromCollectionForKey key: Key) { guard var collection = self[key] else { return } guard let index = collection.indexOf(value) else { return } collection.removeAtIndex(index) self[key] = collection } }
// // ControllerResolver.swift // countit // // Created by David Grew on 13/12/2018. // Copyright © 2018 David Grew. All rights reserved. // import Foundation import UIKit class ControllerResolver { private let serviceResolver: ServiceResolver private let properties: Properties private let messageBroker: MessageBroker private var primaryNavController: UINavigationController? private var progressTableController: ProgressTableController? init(serviceResolver: ServiceResolver, properties: Properties, messageBroker: MessageBroker) { self.serviceResolver = serviceResolver self.properties = properties self.messageBroker = messageBroker } func getPrimaryNavController() -> UINavigationController { if primaryNavController != nil { return primaryNavController! } else { primaryNavController = PrimaryNavigationController( rootViewController: getProgressTableController() as! UIViewController) return primaryNavController! } } func getProgressTableController() -> ProgressTableController { if progressTableController != nil { return progressTableController! } else { let newController = ProgressTableControllerImpl(self, serviceResolver.getProgressService(), serviceResolver.getItemService(), serviceResolver.getActivityService()) newController.set(instructionsDisplayed: properties.getInstructionsDisplayed()) progressTableController = newController return progressTableController! } } func getItemFormController() -> ItemFormController { return ItemFormControllerImpl(self, serviceResolver.getItemService(), messageBroker: messageBroker) } func getActivityHistoryController() -> ActivityHistoryController { return ActivityHistoryControllerImpl(activityService: serviceResolver.getActivityService()) } func getRecordActivityFormController(item: ItemDetailsDto) -> RecordActivityFormController { return RecordActivityFormControllerImpl(controllerResolver: self, activityService: serviceResolver.getActivityService(), item: item, messageBroker: messageBroker) } }
import UIKit import CPaaSSDK import KMPlaceholderTextView class SMSViewController: BaseViewController, SMSDelegate { @IBOutlet weak var tbBubbleDemo: LynnBubbleTableView! @IBOutlet weak var senderNumber: UITextField! @IBOutlet weak var destinationNumber: UITextField! @IBOutlet weak var chatInputView: UIView! @IBOutlet weak var inputTextView: KMPlaceholderTextView! var arrChatTest:Array<LynnBubbleData> = [] var cpaas: CPaaS! var sms_Handler = SMS_Handler() var userMe = LynnUserData(userUniqueId: "123", userNickName: "", userProfileImage: nil, additionalInfo: nil)//UIImage(named: "ico_girlprofile") var userSomeone = LynnUserData(userUniqueId: "234", userNickName: "", userProfileImage: UIImage(named: "ico_girlprofile"), additionalInfo: nil) @IBOutlet weak var bottomConstraint: NSLayoutConstraint! @IBOutlet weak var sendButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.setNavigationBarColorForViewController(viewController: self, type: 1, titleString: "SMS") // tbBubbleDemo.bubbleDelegate = self tbBubbleDemo.bubbleDataSource = self senderNumber.placeholder = "Sender Number" destinationNumber.placeholder = "Destination Number" sms_Handler.cpaas = self.cpaas sms_Handler.subscribeServices() sms_Handler.delegate_SMS = self NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil) inputTextView.layer.cornerRadius = 4.0 inputTextView.layer.borderColor = UIColor.gray.cgColor inputTextView.layer.borderWidth = 0.8 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } @IBAction func sendButtonTapped(_ sender: UIButton) { if NetworkState.isConnected() { if senderNumber.isEmpty(){ DispatchQueue.main.async { () -> Void in LoaderClass.sharedInstance.hideOverlayView() Alert.instance.showAlert(msg: "Please enter Sender Number", title: "", sender: self) } } else if destinationNumber.isEmpty(){ DispatchQueue.main.async { () -> Void in LoaderClass.sharedInstance.hideOverlayView() Alert.instance.showAlert(msg: "Please enter Destination Number", title: "", sender: self) } } else if inputTextView.text.count == 0 { DispatchQueue.main.async { () -> Void in LoaderClass.sharedInstance.hideOverlayView() Alert.instance.showAlert(msg: "Please enter text", title: "", sender: self) } }else{ LoaderClass.sharedInstance.showActivityIndicator() sms_Handler.sourceNumber = senderNumber.text sms_Handler.destinationNumber = destinationNumber.text sms_Handler.sendMessage(message:inputTextView.text) print(sms_Handler) } } else{ DispatchQueue.main.async { () -> Void in LoaderClass.sharedInstance.hideOverlayView() Alert.instance.showAlert(msg: "No Internet Connection", title: "", sender: self) } } } // MARK: SmsDelegate methods func inboundMessageReceived(message: String, senderNumber: String) { DispatchQueue.main.async { () -> Void in print("inboundMessageReceived"); self.userSomeone.userNickName = senderNumber let bubbleData:LynnBubbleData = LynnBubbleData(userData: self.userSomeone, dataOwner: .someone, message: message, messageDate: Date()) self.arrChatTest.append(bubbleData) self.tbBubbleDemo.reloadData() } } func deliveryStatusChanged() { print("deliveryStatusChanged"); } func outboundMessageSent() { print("outboundMessageSent"); } func sendMessage(isSuccess: Bool) { DispatchQueue.main.async { () -> Void in if isSuccess { LoaderClass.sharedInstance.hideOverlayView() self.userSomeone.userNickName = self.destinationNumber.text let bubbleData:LynnBubbleData = LynnBubbleData(userData: self.userMe, dataOwner: .me, message: self.inputTextView.text, messageDate: Date()) self.arrChatTest.append(bubbleData) self.tbBubbleDemo.reloadData() self.inputTextView.resignFirstResponder() } else { LoaderClass.sharedInstance.hideOverlayView() print("Failed to sent message") Alert.instance.showAlert(msg: "Failed to sent. Try again later.", title: "", sender: self) self.inputTextView.resignFirstResponder() } } } @objc func handleKeyboardNotification(_ notification: Notification) { if let userInfo = notification.userInfo { let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification bottomConstraint?.constant = isKeyboardShowing ? keyboardFrame!.height : 0 UIView.animate(withDuration: 0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.chatInputView.superview?.setNeedsLayout() } } extension SMSViewController: LynnBubbleViewDataSource { func bubbleTableView(dataAt index: Int, bubbleTableView: LynnBubbleTableView) -> LynnBubbleData { return self.arrChatTest[index] } func bubbleTableView(numberOfRows bubbleTableView: LynnBubbleTableView) -> Int { return self.arrChatTest.count } } extension SMSViewController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { print("print1") } func textViewDidEndEditing(_ textView: UITextView) { print("print2") } }
// // CustomRequestAdapter.swift // IOS_Weather // // Created by ThanhLong on 4/5/18. // Copyright © 2018 ThanhLong. All rights reserved. // import Foundation import Alamofire class CustomRequestAdapter: RequestAdapter { func adapt(_ urlRequest: URLRequest) throws -> URLRequest { var urlRequest = urlRequest // urlRequest.setValue(MY_API_KEY, forHTTPHeaderField: "X-AccessToken") urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") return urlRequest } }
import Foundation import Cocoa public class Horai { public var locale: Locale = Locale.current public init(locale: Locale = Locale.current) { self.locale = locale } private let dateFormatter = DateFormatter() public func GetDateFromNSDate(nsDate: NSDate = NSDate()) -> Date { return (nsDate as Date) } public func GetNSDateFromDate(date: Date = Date()) -> NSDate { return (date as NSDate) } public enum TimeFormats : String { case HOUR = "HH", MINUTE = "mm", SECOND = "ss", MILISECOND = "SS", HOUR_MINUTE_COMMA = "HH:mm", HOUR_MINUTE_SLASHED = "HH/mm", HOUR_MINUTE_DASHED = "HH-mm", HOUR_MINUTE_SECOND_COMMA = "HH:mm:ss", HOUR_MINUTE_SECOND_SLASHED = "HH/mm/ss", HOUR_MINUTE_SECOND_DASHED = "HH-mm-ss", HOUR_MINUTE_SECOND_MILLISECOND_COMMA = "HH:mm:ss:SS" } public enum DateFormats : String { case DAY = "dd", MONTH = "MMMM", YEAR = "yyyy", WEEK_DAY = "EEEE", WEEK_DAY_SHORT = "EE", WEEK_DAY_MONTH_YEAR_INTER = "EEEE, dd/MMMM/yyyy", DAY2_MONTH_YEAR_SLASHED = "dd/MMMM/yyyy", DAY2_MONTH2_YEAR_SLASHED = "dd/MM/yyyy", DAY2_MONTH2_YEAR2_SLASHED = "dd/MM/yy" } public enum DateTimeFormats : String { case HOUR_MINUTE_DAY_MONTH_YEAR_SPACED = "HH mm dd MM yyyy", HOUR_MINUTE_COMMA_DAY_MONTH_YEAR_SLASHED = "HH:mm dd/MMMM/yyyy" } public func PretifyDate(date: Date, dateFormat: DateFormats) -> String { self.dateFormatter.dateFormat = dateFormat.rawValue self.dateFormatter.locale = self.locale return self.getDateFormatted(date: date) } public func PretifyTime(date: Date, timeFormat: TimeFormats) -> String { self.dateFormatter.dateFormat = timeFormat.rawValue self.dateFormatter.locale = self.locale return self.getDateFormatted(date: date) } public func PretifyDateTime(date: Date, dateTimeFormat: DateTimeFormats) -> String { self.dateFormatter.dateFormat = dateTimeFormat.rawValue self.dateFormatter.locale = self.locale return self.getDateFormatted(date: date) } private func getDateFormatted(date: Date) -> String { return self.dateFormatter.string(from: date) } public func GetFormatedString(date: Date, formattingString: String, locale: Locale? = nil) -> String { let dateFormat = DateFormatter() dateFormat.locale = locale ?? self.locale dateFormat.dateFormat = formattingString return dateFormat.string(from: date) } }
// // EditCategoryViewController.swift // TaskManager // // Created by Tomas Sykora, jr. on 16/01/2020. // Copyright © 2020 AJTY. All rights reserved. // import UIKit import Combine import SnapKit let sampleColors = ["#ff1433", "#bc145a", "#ffb732", "#38acff", "#d42069", "#003366"] class EditCategoryViewController: UIViewController { private let textField: UITextField = { let textField = UITextField() textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) textField.placeholder = "Name" return textField }() private let errorLabel: UILabel = { let label = UILabel() label.textColor = .black label.backgroundColor = .red label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 14) return label }() private let colorCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = .clear collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.register(CategoryColorCollectionViewCell.self, forCellWithReuseIdentifier: CategoryColorCollectionViewCell.reuseIdentifier) return collectionView }() override var title: String? { get { viewModel.name == "" ? "New Category" : "Editing \(viewModel.name ?? "Category")" } set(newValue) { super.title = newValue } } var cancelables: [AnyCancellable] = [] let viewModel: EditCategoryViewModel init(viewModel: EditCategoryViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() layout() setButtons() bindToViewModel() colorCollectionView.delegate = self colorCollectionView.dataSource = self } private func layout() { let spacing: CGFloat = 16.0 view.backgroundColor = .white textField.translatesAutoresizingMaskIntoConstraints = false view.addSubview(textField) view.addSubview(colorCollectionView) view.addSubview(errorLabel) errorLabel.snp.makeConstraints { make in make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) make.height.equalTo(16) } textField.snp.makeConstraints { make in make.top.equalTo(errorLabel.snp.bottom) make.leading.trailing.equalTo(view.safeAreaLayoutGuide).inset(spacing) } colorCollectionView.snp.makeConstraints { make in make.top.equalTo(textField.snp.bottom).offset(spacing) make.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide).inset(spacing) } } private func setButtons() { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAction)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveAction)) } @objc private func cancelAction() { self.navigationController?.popViewController(animated: true) } @objc private func saveAction() { viewModel.action.send(.save) } private func bindToViewModel() { cancelables = [ viewModel.$name.assign(to: \.text, on: textField), viewModel.$color.sink(receiveValue: { _ in self.colorCollectionView.reloadData() }), viewModel.$errorText.assign(to: \.text, on: errorLabel), viewModel.$errorTextHidden.assign(to: \.isHidden, on: errorLabel) ] viewModel.didFinishEditing = { [weak self] in DispatchQueue.main.async { self?.navigationController?.popViewController(animated: true) } } } @objc func textFieldDidChange(_ sender: UITextField) { viewModel.name = sender.text ?? "" } } extension EditCategoryViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { CGSize(width: 50, height: 50) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { sampleColors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryColorCollectionViewCell.reuseIdentifier, for: indexPath) as? CategoryColorCollectionViewCell ?? CategoryColorCollectionViewCell() if let index = sampleColors.firstIndex(of: viewModel.color ?? "") { if index == indexPath.row { cell.isSelected = true } } cell.viewModel = CategoryColorCellViewModel(colorHex: sampleColors[indexPath.row]) return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { 1 } } extension EditCategoryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { viewModel.color = sampleColors[indexPath.row] } }
import Foundation import IGListKit import RealmSwift final class Result: Object{ @objc dynamic var id: Int = 0 @objc dynamic var totalVolume: String = "" @objc dynamic var totalTemp: String = "" @objc dynamic var waterTemp: String = "" @objc dynamic var boilingVolume: String = "" @objc dynamic var waterVolume: String = "" static func create(id: Int, totalVolume: Double, totalTemp: Double, waterTemp: Double, boilingVolume: Double, waterVolume: Double) -> Result { let result = Result() result.id = id result.totalVolume = totalVolume.toString() result.totalTemp = totalTemp.toString() result.waterTemp = waterTemp.toString() result.boilingVolume = boilingVolume.toString() result.waterVolume = waterVolume.toString() return result } static func incrementId() -> Int { let realm = try! Realm() return (realm.objects(Result.self).max(ofProperty: "id") as Int? ?? 0) + 1 } } extension Result: ListDiffable{ public func diffIdentifier() -> NSObjectProtocol { return self.id as NSObjectProtocol } public func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard let object = object as? Result else { return false } return self.id == object.id } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit public class PushPresentationStrategy { public let animated: Bool public init(animated: Bool = true) { self.animated = animated } } extension PushPresentationStrategy: PresentationStrategy { public func present( _ destinations: [AnyNavigationDestination], from source: AnyNavigationSource ) throws { let maybeController = source.navigationController ?? (source as? UINavigationController) guard let navigationController = maybeController else { throw NavigationError.missingNavigationController } var viewControllers = navigationController.viewControllers viewControllers.append(contentsOf: destinations) navigationController.setViewControllers( viewControllers, animated: self.animated ) } }
// // File.swift // Epintra // // Created by Maxime Junger on 30/01/16. // Copyright © 2016 Maxime Junger. All rights reserved. // import Foundation import SwiftyJSON class File { var title: String? var url: String? init(dict: JSON) { title = dict["title"].stringValue url = Configuration.epitechURL + dict["fullpath"].stringValue } }
// // QuizCategory.swift // Quizzler // // Created by Gaurav Prakash on 26/03/18. // Copyright © 2018 London App Brewery. All rights reserved. // import UIKit import Moya import RxSwift class QuizCategory: UIViewController { public var callback : ((TriviaCategory) -> ())? let disposeBag = DisposeBag() var triviaCategory:[TriviaCategory] = [TriviaCategory]() var tintedActivityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView() let numberOfCellsPerRow:CGFloat = 3 @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() configureTintedActivityIndicatorView() APIProvider.rx.request(Quizzler.CATEGORY).subscribe({[weak self] event in switch event{ case .success(let response): if let json = try? response.mapJSON() { if let dictionary = (json as? [String:Any]){ let data = Question(fromDictionary: dictionary) self?.triviaCategory = data.triviaCategories.map({$0}) let nib = UINib(nibName: "CategoryCell", bundle: nil) self?.collectionView.register(nib, forCellWithReuseIdentifier: "CategoryCell") self?.tintedActivityIndicatorView.stopAnimating() self?.collectionView.reloadData() } } case .error(let error): print(error.localizedDescription) } }).disposed(by: disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true self.title = "Select Any Category" } private func configureTintedActivityIndicatorView() { tintedActivityIndicatorView.activityIndicatorViewStyle = .whiteLarge tintedActivityIndicatorView.color = UIColor.red tintedActivityIndicatorView.center = self.view.center view.addSubview(tintedActivityIndicatorView) tintedActivityIndicatorView.startAnimating() } } extension QuizCategory:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return triviaCategory.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell", for: indexPath) as! CategoryCell cell.setUpData(data:triviaCategory[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout let horizontalSpacing = flowLayout?.scrollDirection == .vertical ? flowLayout?.minimumInteritemSpacing : flowLayout?.minimumLineSpacing let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1)*horizontalSpacing!)/numberOfCellsPerRow flowLayout?.itemSize = CGSize(width: cellWidth, height: cellWidth) return (flowLayout?.itemSize)! } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1.0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { callback?(triviaCategory[indexPath.row]) } } extension MutableCollection { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) let i = index(firstUnshuffled, offsetBy: d) swapAt(firstUnshuffled, i) } } } extension Sequence { /// Returns an array with the contents of this sequence, shuffled. func shuffled() -> [Element] { var result = Array(self) result.shuffle() return result } }
// // OrderType.swift // Yelnur // // Created by Дастан Сабет on 24.04.2018. // Copyright © 2018 Дастан Сабет. All rights reserved. // import Foundation struct OrderType: Codable { let id: Int let icon: String let name: String init(id: Int, icon: String, name: String) { self.id = id self.icon = icon self.name = name } }
// // ZGCollectionReusableView.swift // ZGUIDemo // // // import UIKit open class ZGCollectionReusableView: UICollectionReusableView { final var _object : ZGBaseUIItem? final public var item : ZGBaseUIItem?{ get { return _object } } //override open func setObject (_ obj:ZGBaseUIItem) -> Void { _object = obj } //override open class func tbbzIdentifier() -> String{ return "\(self)" } //override open class func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForObject object: ZGBaseUIItem) -> CGSize{ return object.size } open class func register(for collectionView:UICollectionView, kind:String) { collectionView.register(self, forSupplementaryViewOfKind: kind, withReuseIdentifier: self.tbbzIdentifier()); } }
// // ProfilePresenter.swift // WavesWallet-iOS // // Created by mefilt on 04/10/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxFeedback import RxSwift import RxCocoa import DomainLayer import Extensions protocol ProfileModuleOutput: AnyObject { func showAddressesKeys(wallet: DomainLayer.DTO.Wallet) func showAddressBook() func showLanguage() func showBackupPhrase(wallet: DomainLayer.DTO.Wallet, saveBackedUp: @escaping ((_ isBackedUp: Bool) -> Void)) func showChangePassword(wallet: DomainLayer.DTO.Wallet) func showChangePasscode(wallet: DomainLayer.DTO.Wallet) func showNetwork(wallet: DomainLayer.DTO.Wallet) func showRateApp() func showFeedback() func showSupport() func accountSetEnabledBiometric(isOn: Bool, wallet: DomainLayer.DTO.Wallet) func accountLogouted() func accountDeleted() func showAlertForEnabledBiometric() } protocol ProfilePresenterProtocol { typealias Feedback = (Driver<ProfileTypes.State>) -> Signal<ProfileTypes.Event> var moduleOutput: ProfileModuleOutput? { get set } func system(feedbacks: [Feedback]) } final class ProfilePresenter: ProfilePresenterProtocol { fileprivate typealias Types = ProfileTypes private let disposeBag: DisposeBag = DisposeBag() private let blockRepository: BlockRepositoryProtocol = UseCasesFactory.instance.repositories.blockRemote private let authorizationInteractor: AuthorizationUseCaseProtocol = UseCasesFactory.instance.authorization private let walletsRepository: WalletsRepositoryProtocol = UseCasesFactory.instance.repositories.walletsRepositoryLocal private var eventInput: PublishSubject<Types.Event> = PublishSubject<Types.Event>() weak var moduleOutput: ProfileModuleOutput? func system(feedbacks: [Feedback]) { var newFeedbacks = feedbacks newFeedbacks.append(reactQuries()) newFeedbacks.append(profileQuery()) newFeedbacks.append(blockQuery()) newFeedbacks.append(deleteAccountQuery()) newFeedbacks.append(logoutAccountQuery()) newFeedbacks.append(handlerEvent()) newFeedbacks.append(setBackupQuery()) newFeedbacks.append(setPushNotificationsQeury()) newFeedbacks.append(registerPushNotificationsQeury()) let initialState = self.initialState() let system = Driver.system(initialState: initialState, reduce: ProfilePresenter.reduce, feedback: newFeedbacks) system .drive() .disposed(by: disposeBag) } } // MARK: - Feedbacks fileprivate extension ProfilePresenter { static func needQuery(_ state: Types.State) -> Types.Query? { guard let query = state.query else { return nil } switch query { case .showAddressesKeys, .showAddressBook, .showLanguage, .showBackupPhrase, .showChangePassword, .showChangePasscode, .showNetwork, .showRateApp, .showFeedback, .showSupport, .setEnabledBiometric, .showAlertForEnabledBiometric: return query default: break } return nil } static func handlerQuery(owner: ProfilePresenter, query: Types.Query) { switch query { case .showAddressesKeys(let wallet): owner.moduleOutput?.showAddressesKeys(wallet: wallet) case .showAddressBook: owner.moduleOutput?.showAddressBook() case .showLanguage: owner.moduleOutput?.showLanguage() case .showBackupPhrase(let wallet): owner.moduleOutput?.showBackupPhrase(wallet: wallet) { [weak owner] isBackedUp in owner?.eventInput.onNext(.setBackedUp(isBackedUp)) } case .showChangePassword(let wallet): owner.moduleOutput?.showChangePassword(wallet: wallet) case .showChangePasscode(let wallet): owner.moduleOutput?.showChangePasscode(wallet: wallet) case .showNetwork(let wallet): owner.moduleOutput?.showNetwork(wallet: wallet) case .showRateApp: owner.moduleOutput?.showRateApp() case .showAlertForEnabledBiometric: owner.moduleOutput?.showAlertForEnabledBiometric() case .showFeedback: owner.moduleOutput?.showFeedback() case .showSupport: owner.moduleOutput?.showSupport() case .setEnabledBiometric(let isOn, let wallet): owner.moduleOutput?.accountSetEnabledBiometric(isOn: isOn, wallet: wallet) default: break } } func registerPushNotificationsQeury() -> Feedback { return react(request: { state -> Bool? in guard let query = state.query else { return nil } if case .registerPushNotifications = query { return true } else { return nil } }, effects: { _ -> Signal<Types.Event> in return PushNotificationsManager.rx.getNotificationsStatus() .flatMap { (status) -> Observable<Bool> in if status == .notDetermined { return PushNotificationsManager.rx.registerRemoteNotifications() } else { return PushNotificationsManager.rx.openSettings().map { _ in false } } } .map { Types.Event.setPushNotificationsSettings($0)} .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func setPushNotificationsQeury() -> Feedback { return react(request: { state -> Bool? in guard let query = state.query else { return nil } if case .updatePushNotificationsSettings = query { return true } else { return nil } }, effects: { _ -> Signal<Types.Event> in return PushNotificationsManager.rx.getNotificationsStatus().map { Types.Event.setPushNotificationsSettings($0 == .authorized)} .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func reactQuries() -> Feedback { return react(request: { state -> Types.Query? in return ProfilePresenter.needQuery(state) }, effects: { [weak self] query -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } ProfilePresenter.handlerQuery(owner: self, query: query) return Signal.just(.completedQuery) }) } func handlerEvent() -> Feedback { return react(request: { state -> Bool? in return true }, effects: { [weak self] isOn -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self.eventInput.asSignal(onErrorSignalWith: Signal.empty()) }) } func setBackupQuery() -> Feedback { return react(request: { state -> DomainLayer.DTO.Wallet? in guard let query = state.query else { return nil } guard let wallet = state.wallet else { return nil } if case .setBackedUp(let isBackedUp) = query { var newWallet = wallet newWallet.isBackedUp = isBackedUp return newWallet } else { return nil } }, effects: { [weak self] wallet -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self .authorizationInteractor .changeWallet(wallet) .map { $0.isBackedUp } .map { Types.Event.setBackedUp($0)} .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func profileQuery() -> Feedback { return react(request: { state -> Bool? in if state.displayState.isAppeared == true { return true } else { return nil } }, effects: { [weak self] isOn -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self .authorizationInteractor .authorizedWallet() .flatMap({ [weak self] wallet -> Observable<DomainLayer.DTO.Wallet> in guard let self = self else { return Observable.empty() } return self.walletsRepository.listenerWallet(by: wallet.wallet.publicKey) }) .map { Types.Event.setWallet($0) } .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func blockQuery() -> Feedback { return react(request: { state -> String? in if state.displayState.isAppeared == true, state.wallet != nil { return state.wallet?.address } else { return nil } }, effects: { [weak self] address -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self .blockRepository .height(accountAddress: address) .map { Types.Event.setBlock($0) } .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func logoutAccountQuery() -> Feedback { return react(request: { state -> Bool? in guard let query = state.query else { return nil } if case .logoutAccount = query { return true } else { return nil } }, effects: { [weak self] query -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self .authorizationInteractor .logout() .do(onNext: { [weak self] _ in self?.moduleOutput? .accountLogouted() }) .map { _ in return Types.Event.none } .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } func deleteAccountQuery() -> Feedback { return react(request: { state -> Bool? in guard let query = state.query else { return nil } if case .deleteAccount = query { return true } else { return nil } }, effects: { [weak self] query -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } return self .authorizationInteractor.logout() .flatMap({ [weak self] wallet -> Observable<Types.Event> in guard let self = self else { return Observable.empty() } return self .authorizationInteractor .deleteWallet(wallet) .map { _ in return Types.Event.none } }) .do(onNext: { [weak self] _ in self?.moduleOutput?.accountDeleted() }) .asSignal(onErrorRecover: { _ in return Signal.empty() }) }) } } // MARK: Core State private extension ProfilePresenter { static func reduce(state: Types.State, event: Types.Event) -> Types.State { var newState = state reduce(state: &newState, event: event) return newState } static func reduce(state: inout Types.State, event: Types.Event) { state.displayState.action = nil switch event { case .viewDidDisappear: state.displayState.isAppeared = false state.query = nil case .viewDidAppear: state.displayState.isAppeared = true state.query = .updatePushNotificationsSettings case .setWallet(let wallet): let generalSettings = Types.ViewModel.Section(rows: [.addressesKeys, .addressbook, .pushNotifications(isActive: state.isActivePushNotifications), .language(Language.currentLanguage)], kind: .general) var securityRows: [Types.ViewModel.Row] = [.backupPhrase(isBackedUp: wallet.isBackedUp), .changePassword, .changePasscode] if BiometricType.enabledBiometric != .none { securityRows.append(.biometric(isOn: wallet.hasBiometricEntrance)) } else { securityRows.append(.biometricDisabled) } securityRows.append(.network) let security = Types.ViewModel.Section(rows: securityRows, kind: .security) let other = Types.ViewModel.Section(rows: [.rateApp, .feedback, .supportWavesplatform, .info(version: Bundle.main.versionAndBuild, height: nil, isBackedUp: wallet.isBackedUp)], kind: .other) state.displayState.sections = [generalSettings, security, other] state.wallet = wallet state.displayState.action = .update case .tapRow(let row): guard let wallet = state.wallet else { return } switch row { case .addressbook: state.query = .showAddressBook case .addressesKeys: state.query = .showAddressesKeys(wallet: wallet) case .language: state.query = .showLanguage case .backupPhrase: state.query = .showBackupPhrase(wallet: wallet) case .changePassword: state.query = .showChangePassword(wallet: wallet) case .changePasscode: state.query = .showChangePasscode(wallet: wallet) case .network: state.query = .showNetwork(wallet: wallet) case .rateApp: state.query = .showRateApp case .feedback: state.query = .showFeedback case .supportWavesplatform: state.query = .showSupport case .biometricDisabled: state.query = .showAlertForEnabledBiometric case .pushNotifications(let isActive): guard isActive == false else { return } state.query = .registerPushNotifications default: break } case .setBlock(let block): state.block = block updateInfo(state: &state, block: block, isBackedUp: state.wallet?.isBackedUp ?? false) state .displayState.action = .update case .setBackedUp(let isBackedUp): guard let section = state .displayState .sections .enumerated() .first(where: { $0.element.kind == .security }) else { return } guard let index = section .element .rows .enumerated() .first(where: { element in if case .backupPhrase = element.element { return true } return false }) else { return } state .displayState .sections[section.offset] .rows[index.offset] = .backupPhrase(isBackedUp: isBackedUp) state.displayState.action = nil state.query = .setBackedUp(isBackedUp) case .setEnabledBiometric(let isOn): guard let section = state .displayState .sections .enumerated() .first(where: { $0.element.kind == .security }) else { return } guard let index = section .element .rows .enumerated() .first(where: { element in if case .biometric = element.element { return true } return false }) else { return } if let wallet = state.wallet { state.query = .setEnabledBiometric(isOn, wallet: wallet) } state .displayState .sections[section.offset] .rows[index.offset] = .biometric(isOn: isOn) state .displayState.action = nil case .tapLogout: state.query = Types.Query.logoutAccount case .tapDelete: state.query = Types.Query.deleteAccount case .completedQuery: state.query = nil case .setPushNotificationsSettings(let isActive): state.isActivePushNotifications = isActive updateInfo(state: &state, isActivePushNotifications: isActive) state.displayState.action = .update state.query = nil case .updatePushNotificationsSettings: state.query = .updatePushNotificationsSettings default: break } } static func updateInfo(state: inout Types.State, isActivePushNotifications: Bool) { guard let section = state .displayState .sections .enumerated() .first(where: { $0.element.kind == .general }) else { return } guard let index = section .element .rows .enumerated() .first(where: { element in if case .pushNotifications = element.element { return true } return false }) else { return } state .displayState .sections[section.offset] .rows[index.offset] = .pushNotifications(isActive: isActivePushNotifications) } static func updateInfo(state: inout Types.State, block: Int64, isBackedUp: Bool) { guard let section = state .displayState .sections .enumerated() .first(where: { $0.element.kind == .other }) else { return } guard let index = section .element .rows .enumerated() .first(where: { element in if case .info = element.element { return true } return false }) else { return } state .displayState .sections[section.offset] .rows[index.offset] = .info(version: Bundle.main.versionAndBuild, height: "\(block)", isBackedUp: isBackedUp) } } // MARK: UI State private extension ProfilePresenter { func initialState() -> Types.State { return Types.State(query: nil, wallet: nil, block: nil, displayState: initialDisplayState(), isActivePushNotifications: false) } func initialDisplayState() -> Types.DisplayState { return Types.DisplayState(sections: [], isAppeared: false, action: nil) } }
// // TableSection.swift // GworldSuperOffice // // Created by 陈琪 on 2020/7/15. // Copyright © 2020 Gworld. All rights reserved. // import Foundation struct TableViewSection { var header: String var items: [[String: Any]] }
// // NewsMenu.swift // RumahHokie // // Created by Hadron Megantara on 22/10/18. // Copyright © 2018 Hadron Megantara. All rights reserved. // import Foundation import UIKit class NewsMenu: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() } }
// // SideMenuModel.swift // 2DirectionScroll // // Created by Krishna Kushwaha on 14/06/21. // import Foundation import UIKit struct SideMenuModel { var icon: UIImage var title: String }
// // MemeTextFieldDelegate.swift // MemeMe // // Created by Troutslayer33 on 5/10/15. // Copyright (c) 2015 Troutslayer33. All rights reserved. // import Foundation import UIKit class MemeTextFieldDelegate: NSObject, UITextFieldDelegate { // function converts all text input to uppercase func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let newText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) textField.text = newText.uppercaseString return false } // if text fields set to default value clear input func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if (textField.text == "BOTTOM" || textField.text == "TOP") { textField.text = nil } return true } // resign first responder when return func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } }
// // SignalProducer+ModelMapper.swift // StoryReader // // Created by 020-YinTao on 2017/10/9. // Copyright © 2017年 020-YinTao. All rights reserved. // import Foundation import Moya import RxSwift import HandyJSON extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response { func mapResponse() -> Single<SingleResponseModel> { return observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .flatMap { response -> Single<SingleResponseModel> in return Single.just(try response.mapResponse()) } .observeOn(MainScheduler.instance) } func map<T: HandyJSON>(result type: T.Type) -> Single<DataModel<T>> { return observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .flatMap { response -> Single<DataModel<T>> in return Single.just(try response.map(result: type)) } .observeOn(MainScheduler.instance) } func map<T: HandyJSON>(resultList type: T.Type) -> Single<DataModel<[T]>> { return observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .flatMap { response -> Single<DataModel<[T]>> in return Single.just(try response.map(result: type)) } .observeOn(MainScheduler.instance) } func map<T: HandyJSON>(model type: T.Type) -> Single<T> { return observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .flatMap { response -> Single<T> in return Single.just(try response.map(model: type)) } .observeOn(MainScheduler.instance) } func map<T: HandyJSON>(models type: T.Type) -> Single<[T]> { return observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .flatMap { response -> Single<[T]> in return Single.just(try response.map(model: type)) } .observeOn(MainScheduler.instance) } }
// // TagsViewPresenter.swift // WebScraper // // Created by RSQ Technologies on 04/05/2019. // Copyright © 2019 RSQ Technologies. All rights reserved. // import UIKit class TagsViewPresenter: NSObject { weak var output: TagsViewController? func presentTags(_ tags: [String]) { output?.presentTags(tags) } func presentSuccess() { output?.displaySuccess() } }
import Foundation public enum ApiResult<Value, Error> { case success(Value) case failure(Error) init(value: Value) { self = .success(value) } init(error: Error) { self = .failure(error) } }
// // AES.swift // 密语输入法 // // Created by macsjh on 15/9/24. // Copyright © 2015年 macsjh. All rights reserved. // import Foundation /** AES_256_ECB加密API - Parameter plainText: 要加密的明文 - Parameter key: 密码(长度任意,会转换为MD5值) - Returns: 加密后的密文(base64编码字符串) */ func aesEncrypt(plainText:NSString, var key:String) -> NSString? { key = MessageDigest.md5(key) let base64PlainText = LowLevelEncryption.base64Encode(plainText) if(base64PlainText != nil) { let cipherText = NSAESString.aes256_encrypt(base64PlainText!, Key: key) if(cipherText != nil) { return LowLevelEncryption.base64Encode(cipherText!) } } return nil } /** AES_256_ECB解密API - Parameter plainText: 要解密的密文 - Parameter key: 密码(长度任意,会转换为MD5值) - Returns: 明文(base64编码字符串) */ func aesDecrypt(cipherText:NSString, var key:String) -> NSString? { key = MessageDigest.md5(key) let originCipherText = LowLevelEncryption.base64Decode(cipherText) if(originCipherText != nil) { let base64CipherText = NSAESString.aes256_decrypt(originCipherText!, key: key) if (base64CipherText != nil) { return LowLevelEncryption.base64Decode(base64CipherText!) } } return nil }
// // ListViewController.swift // ListableUI // // Created by Kyle Van Essen on 6/21/20. // import Foundation /// /// A class which provides an easy way to set up and display a `ListView`, /// The `ListViewController` itself manages setup and presentation of the list. /// /// As a consumer of the API, all you need to do is override one method: /// ``` /// func configure(list : inout ListProperties) { /// ... /// } /// ``` /// In which you set up and configure the list as needed. /// /// In order to reload the list when content changes or other display changes are required, call /// ``` /// func reload(animated : Bool = false) /// ``` /// Which will update the list with the new contents returned from your `configure` method. /// If the `ListViewController`'s view is not loaded, this method has no effect. /// open class ListViewController : UIViewController { // // MARK: Configuration // /// The default value for `clearsSelectionOnViewWillAppear` is true. /// This parameter allows mirroring the `clearsSelectionOnViewWillAppear` /// as available from `UITableViewController` or `UICollectionViewController`. public var clearsSelectionOnViewWillAppear : Bool = true // // MARK: Methods To Override // /// Override this method to configure your list how you'd like to. /// The properties on `ListProperties` closely mirror those on `ListView` /// itself, allowing you to fully configure and work with a list without needing to maintain /// and manage the view instance yourself. /// /// Example /// ------- /// ``` /// override func configure(list : inout ListProperties) /// { /// list.appearance = .myAppearance /// /// list.layout = .table { appearance in /// // Configure the appearance. /// } /// /// list.stateObserver.onContentChanged { info in /// MyLogger.log(...) /// } /// /// list("first-section") { section in /// section += self.myPodcasts.map { podcast in /// PodcastItem(podcast) /// } /// } /// } /// ``` /// You should not call super in your overridden implementation. /// open func configure(list : inout ListProperties) { fatalError("Subclasses of `ListViewController` must override `configure(list:)` to customize the content of their list view.") } // // MARK: Updating Content // public func reload(animated : Bool = false) { guard let listView = self.listView else { return } listView.configure { list in list.animatesChanges = animated self.configure(list: &list) } } // // MARK: - Internal & Private Methods - // // MARK: Initialization public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required public init?(coder: NSCoder) { fatalError() } // MARK: UIViewController private var listView : ListView? public override func loadView() { let listView = ListView() self.listView = listView self.view = listView } private var hasViewAppeared : Bool = false open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.hasViewAppeared == false { self.hasViewAppeared = true self.reload(animated: false) } else { if self.clearsSelectionOnViewWillAppear { self.listView?.clearSelectionDuringViewWillAppear(alongside: self.transitionCoordinator, animated: animated) } } } } public extension ListView { /// A method which provides `Behavior.SelectionMode.single`'s `clearsSelectionOnViewWillAppear` behaviour. /// By default, this method is called by `ListViewController`. However if you are not using `ListViewController` you /// will need to call this method yourself one of two ways: /// /// 1) If subclassing `UIViewController`: within your view controller's `viewWillAppear` method. /// /// 2) By invoking this same method on your `ListActions` that you have wired up to your list view. Use this /// in the case that you do not have access to your list view at all, such as when using `BlueprintUILists`. /// /// // Behaviour from UIKit Eng: https://twitter.com/smileyborg/status/1279473615553982464 /// func clearSelectionDuringViewWillAppear(alongside coordinator: UIViewControllerTransitionCoordinator?, animated : Bool) { guard case Behavior.SelectionMode.single = behavior.selectionMode else { return } guard let indexPath = storage.presentationState.selectedIndexPaths.first else { return } let item = storage.presentationState.item(at: indexPath) guard let coordinator = coordinator else { // No transition coordinator is available – we should just deselect return in this case. item.set(isSelected: false, performCallbacks: true) collectionView.deselectItem(at: indexPath, animated: animated) item.applyToVisibleCell(with: self.environment) return } coordinator.animate(alongsideTransition: { _ in item.set(isSelected: false, performCallbacks: true) self.collectionView.deselectItem(at: indexPath, animated: true) item.applyToVisibleCell(with: self.environment) }, completion: { context in if context.isCancelled { item.set(isSelected: true, performCallbacks: false) self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: []) item.applyToVisibleCell(with: self.environment) } }) } }
// // SignUpViewModel.swift // Frames-App // // Created by Tyler Zhao on 12/4/18. // Copyright © 2018 Tyler Zhao. All rights reserved. // import Foundation import RxSwift import RxCocoa struct FramesFormCellModel { let title: String let description: String let placeholder: String } final class SignUpViewModel: ViewModelType { let disposeBag = DisposeBag() struct Input { } struct Output { var formCellDataSource: Driver<[FramesFormCellModel]> } func transform(input: Input) -> Output { let formCellDataSource$ = Driver.just([FramesFormCellModel(title: "Email", description: "", placeholder: "enter your email..."), FramesFormCellModel(title: "Username", description: "can contain letters, numbers, underscores and dashes", placeholder: "create a username..."), FramesFormCellModel(title: "Password", description: "password must be 8+ characters", placeholder: "choose a password...")]) return Output(formCellDataSource: formCellDataSource$) } }
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. import XCTest @testable import VerizonVideoPartnerSDK class PlaybackCycleDetectorTests: XCTestCase { var sut: Detectors.AdPlaybackCycle! override func setUp() { super.setUp() sut = Detectors.AdPlaybackCycle() } override func tearDown() { sut = nil super.tearDown() } func testSuccessfulAd() { XCTAssertEqual(sut.process(streamPlaying: false, isSuccessfullyCompleted: false, isForceFinished: false), .nothing) XCTAssertEqual(sut.process(streamPlaying: true, isSuccessfullyCompleted: false, isForceFinished: false), .start) XCTAssertEqual(sut.process(streamPlaying: true, isSuccessfullyCompleted: false, isForceFinished: false), .nothing) XCTAssertEqual(sut.process(streamPlaying: false, isSuccessfullyCompleted: true, isForceFinished: false), .complete) XCTAssertEqual(sut.process(streamPlaying: false, isSuccessfullyCompleted: false, isForceFinished: false), .nothing) } func testBrokenAd() { XCTAssertEqual(sut.process(streamPlaying: false, isSuccessfullyCompleted: false, isForceFinished: false), .nothing) XCTAssertEqual(sut.process(streamPlaying: true, isSuccessfullyCompleted: false, isForceFinished: false), .start) XCTAssertEqual(sut.process(streamPlaying: true, isSuccessfullyCompleted: false, isForceFinished: false), .nothing) XCTAssertEqual(sut.process(streamPlaying: false, isSuccessfullyCompleted: false, isForceFinished: true), .nothing) } }
// // Preview_LightAndDarkMode.swift // 100Views // // Created by Mark Moeykens on 9/27/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Preview_LightAndDarkMode: View { var body: some View { VStack(spacing: 20) { Text("Previews").font(.largeTitle) Text("Light & Dark Modes Together").foregroundColor(.gray) Text("Group your views to preview more than one at a time.") .frame(maxWidth: .infinity) .padding() .background(Color.red) .layoutPriority(1) .foregroundColor(.white) }.font(.title) } } struct Preview_LightAndDarkMode_Previews: PreviewProvider { static var previews: some View { // Just use a Group container to instantiate your views in Group { Preview_LightAndDarkMode() // Light Mode Preview_LightAndDarkMode() .environment(\.colorScheme, .dark) } } }
// // LoginVC.swift // // // Created by dev tl on 4/18/18. // import UIKit import SlideMenuControllerSwift class LoginVC: UIViewController , UITableViewDelegate , UITableViewDataSource { @IBOutlet weak var newsTV: UITableView! @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! var news = [String]() override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) news.append("Dolibarr 7.0.1 now available") news.append("MultiCopmany Module now implemented") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(_ sender: UIButton) { let user = self.userName.text! let pass = self.password.text! LoginApi.login(username: user, password: pass){(error: Error?, success : Bool? , res : Array<Any>? ) in if success! { let mainVC = self.storyboard?.instantiateViewController(withIdentifier: "MainVC") as! MainVC let leftMenuVC = self.storyboard?.instantiateViewController(withIdentifier: "LeftMenuVC") as! LeftMenuVC let rightMenuVC = self.storyboard?.instantiateViewController(withIdentifier: "RightMenuVC") as! RightMenuVC let slideMenuController = SlideMenuController(mainViewController: mainVC, leftMenuViewController: leftMenuVC, rightMenuViewController: rightMenuVC) self.present(slideMenuController, animated: true, completion: nil) } else { self.setAlert(message: "Username or Password is incorrect , please try again") } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return news.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NewsTVCell", for: indexPath) as! NewsTVCell cell.newsTxt.text = news[indexPath.row] return cell } /* // 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. } */ }
//// //// DayDetailHubView.swift //// animalHealthLog //// //// Created by 細川聖矢 on 2020/06/26. //// Copyright © 2020 Seiya. All rights reserved. //// // //import SwiftUI // //struct DayDetailHubView: View { // // @Binding var doneDate:String // // var body: some View { // NavigationView{ // HStack{ // NavigationLink(destination:MemoByDayView( doneMemoDate:self.$doneDate)){ // Text("メモ") // } // Text("画像") // Text("血液検査") // } // } // } //} // //struct DayDetailHubView_Previews: PreviewProvider { // // @State var sampleDate = "sample" // // static var previews: some View { // DayDetailHubView(doneDate: .constant("sample")) // } //}
// // UITextField.swift // KifuSF // // Created by Alexandru Turcanu on 30/08/2018. // Copyright © 2018 Alexandru Turcanu. All rights reserved. // import UIKit.UITextField extension UITextField { func setUp(with style: TextStyle) { let textStyle = style.retrieve() self.font = textStyle.font self.textColor = textStyle.color } func setUp(with style: TextStyle, andColor color: UIColor) { setUp(with: style) backgroundColor = color } }
// // ZXHistoryOrderDetailModel.swift // YDHYK // // Created by 120v on 2017/11/28. // Copyright © 2017年 screson. All rights reserved. // import UIKit @objcMembers class ZXHistoryOrderDetailModel: NSObject { var approvalNumber: String = "" var attachFiles: String = "" var attachFilesStr: String = "" var attachStr: String = "" var drugId: Int = -1 var drugName: String = "" var keyId: Int = -1 var num: Int = -1 var orderId: Int = -1 var packingSpec: String = "" var price: String = "" var priceStr: String = "" override static func mj_replacedKeyFromPropertyName() -> [AnyHashable : Any]! { return ["keyId":"id"] } }
// // JSONDecoderExtension.swift // Rocket // // Created by 汤世昭 on 2020/3/2. // import Foundation extension JSONDecoder { convenience init(config: JSONDecoderConfig) { self.init() self.dateDecodingStrategy = config.dateDecodingStrategy self.dataDecodingStrategy = config.dataDecodingStrategy self.nonConformingFloatDecodingStrategy = config.nonConformingFloatDecodingStrategy self.keyDecodingStrategy = config.keyDecodingStrategy self.userInfo = config.userInfo } }
// // CharactersViewModelTests.swift // MarvelAppTests // // Created by Gabriel Miranda Silveira on 20/09/21. // import XCTest import Combine @testable import MarvelApp final class CharactersViewModelTests: XCTestCase { private var viewModel: CharactersViewModel! private var service: MockCharactersService! private var coordinator: MockCharactersCoordinatorNavigator! private var output: CharactersViewModelOutput! private var fakeViewDidLoadInput: CurrentValueSubject<Void, Never>! private var fakeDidSelectCellInput: PassthroughSubject<IndexPath, Never>! private var fakeWillDisplayCellInput: PassthroughSubject<IndexPath, Never>! private var fakeReloadButtonTappedInput: PassthroughSubject<Void, Never>! private var fakeSearchFilterTypedInput: PassthroughSubject<String, Never>! private var subscriptions = Set<AnyCancellable>() override func setUp() { super.setUp() setup() } override func tearDown() { fakeViewDidLoadInput = nil fakeWillDisplayCellInput = nil fakeReloadButtonTappedInput = nil fakeDidSelectCellInput = nil fakeSearchFilterTypedInput = nil service = nil viewModel = nil subscriptions = [] output = nil super.tearDown() } private func setup(serviceCharactersPublisher: AnyPublisher<[Character], Error>? = nil) { service = MockCharactersService() service.injectedCharactersPublisher = serviceCharactersPublisher coordinator = MockCharactersCoordinatorNavigator() viewModel = CharactersViewModel(service: service, coordinator: coordinator) setupInputAndOutput() } private func setupInputAndOutput() { fakeViewDidLoadInput = .init(()) fakeWillDisplayCellInput = .init() fakeReloadButtonTappedInput = .init() fakeSearchFilterTypedInput = .init() fakeDidSelectCellInput = .init() let input = CharactersViewModelInput(viewDidLoad: fakeViewDidLoadInput.eraseToAnyPublisher(), didSelectCell: fakeDidSelectCellInput.eraseToAnyPublisher(), willDisplayCell: fakeWillDisplayCellInput.eraseToAnyPublisher(), searchFilterTyped: fakeSearchFilterTypedInput.eraseToAnyPublisher(), reloadButtonTapped: fakeReloadButtonTappedInput.eraseToAnyPublisher()) output = viewModel.transform(input: input) } func testTransformReturnStaticOutputs() { XCTAssertEqual(output.title, "Marvel Characters") XCTAssertEqual(output.reloadButtonTitle, "There was an error. Tap to reload") } func testViewDidLoadFetchesItemsAndCellViewModelIsCorrectlyMapped() { let exp = expectation(description: "") self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 2)) .setFailureType(to: Error.self) .eraseToAnyPublisher() self.output.cellsViewModel .sink { items in XCTAssertEqual(items.count, 2) XCTAssertEqual(items[0].characterName, "fakeCharacter0") XCTAssertEqual(items[0].characterDescription, "fakeDescription0") XCTAssertEqual(items[0].imageUrl, URL(string: "http://fakePath0.fakeDescription0")) XCTAssertEqual(items[1].characterName, "fakeCharacter1") XCTAssertEqual(items[1].characterDescription, "fakeDescription1") XCTAssertEqual(items[1].imageUrl, URL(string: "http://fakePath1.fakeDescription1")) exp.fulfill() } .store(in: &self.subscriptions) wait(for: [exp], timeout: 5) } func testWillDisplayCellFetchesMoreItemsWhenMatchesCriteria() { let exp = expectation(description: "") var isFirstCall = true self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 50)) .setFailureType(to: Error.self) .eraseToAnyPublisher() output.cellsViewModel .sink { [weak self] items in guard !isFirstCall else { isFirstCall = false self?.fakeWillDisplayCellInput.send(IndexPath(row: 30, section: 0)) return } XCTAssertEqual(items.count, 100) exp.fulfill() } .store(in: &self.subscriptions) wait(for: [exp], timeout: 5) } func testWillDisplayCellDoesNotFetchMoreItemsWhenCriteriaIsNotMatch() { let notExpectation = expectation(description: "") notExpectation.isInverted = true var isFirstCall = true self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 50)) .setFailureType(to: Error.self) .eraseToAnyPublisher() output.cellsViewModel .sink { [weak self] items in guard !isFirstCall else { isFirstCall = false self?.fakeWillDisplayCellInput.send(IndexPath(row: 4, section: 0)) return } notExpectation.fulfill() } .store(in: &self.subscriptions) wait(for: [notExpectation], timeout: 5) } func testAnyCellIsReturnedAndErrorIsCalledWhenServiceReturnsError() { let notExpectation = expectation(description: "") notExpectation.isInverted = true let exp = expectation(description: "") self.service.injectedCharactersPublisher = Fail(error: TestError.fake).eraseToAnyPublisher() self.output.error .sink { error in XCTAssertEqual(error as? TestError, TestError.fake) exp.fulfill() } .store(in: &self.subscriptions) self.output.cellsViewModel .sink { _ in notExpectation.fulfill() } .store(in: &self.subscriptions) wait(for: [exp, notExpectation], timeout: 5) } func testReloadButtonTappedFetchesItems() { let exp = expectation(description: "") setup(serviceCharactersPublisher: Fail(error: TestError.fake).eraseToAnyPublisher()) self.output.cellsViewModel .sink { items in XCTAssertEqual(items.count, 2) exp.fulfill() } .store(in: &self.subscriptions) self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 2)) .setFailureType(to: Error.self) .eraseToAnyPublisher() fakeReloadButtonTappedInput.send(()) wait(for: [exp], timeout: 5) } func testSearchTypedFetchesItems() { let exp = expectation(description: "") self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 2)) .setFailureType(to: Error.self) .eraseToAnyPublisher() self.output.cellsViewModel .sink { items in XCTAssertEqual(items.count, 2) exp.fulfill() } .store(in: &self.subscriptions) fakeSearchFilterTypedInput.send("Fake Character") wait(for: [exp], timeout: 5) } func testCharacterSelectionSendsCharacterToCoordinator() { let exp = expectation(description: "") self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 2)) .setFailureType(to: Error.self) .eraseToAnyPublisher() self.output.cellsViewModel .sink { [weak self] _ in self?.fakeDidSelectCellInput.send(IndexPath(row: 0, section: 0)) XCTAssertTrue(self?.coordinator.coordinatorCalled ?? false) XCTAssertEqual(self?.coordinator.characterCalled?.id, 0) XCTAssertEqual(self?.coordinator.characterCalled?.name, "fakeCharacter0") XCTAssertEqual(self?.coordinator.characterCalled?.description, "fakeDescription0") XCTAssertEqual(self?.coordinator.characterCalled?.thumbnail.url, URL(string: "http://fakePath0.fakeDescription0")) XCTAssertEqual(self?.coordinator.characterCalled?.comics.items.first?.name, "comic") XCTAssertEqual(self?.coordinator.characterCalled?.series.items.first?.name, "serie") XCTAssertEqual(self?.coordinator.characterCalled?.stories.items.first?.name, "story") exp.fulfill() } .store(in: &self.subscriptions) wait(for: [exp], timeout: 5) } func testCharacterSelectingInvalidIndexPathDoesNothing() { let exp = expectation(description: "") self.service.injectedCharactersPublisher = Just(self.fakeCharacters(count: 2)) .setFailureType(to: Error.self) .eraseToAnyPublisher() self.output.cellsViewModel .sink { [weak self] _ in self?.fakeDidSelectCellInput.send(IndexPath(row: 2, section: 0)) XCTAssertFalse(self?.coordinator.coordinatorCalled ?? true) XCTAssertNil(self?.coordinator.characterCalled) exp.fulfill() } .store(in: &self.subscriptions) wait(for: [exp], timeout: 5) } } private extension CharactersViewModelTests { func fakeCharacters(count: Int) -> [Character] { (0..<count).indices.map { i in Character(id: i, name: "fakeCharacter\(i)", description: "fakeDescription\(i)", thumbnail: .init(path: "http://fakePath\(i)", extension: "fakeDescription\(i)"), resourceURI: "fakeResourceURI\(i)", comics: .init(items: [.init(name: "comic")]), series: .init(items: [.init(name: "serie")]), stories: .init(items: [.init(name: "story")])) } } }
import Foundation import MarketKit class BitcoinOutgoingTransactionRecord: BitcoinTransactionRecord { let value: TransactionValue let to: String? let sentToSelf: Bool init(token: Token, source: TransactionSource, uid: String, transactionHash: String, transactionIndex: Int, blockHeight: Int?, confirmationsThreshold: Int?, date: Date, fee: Decimal?, failed: Bool, lockInfo: TransactionLockInfo?, conflictingHash: String?, showRawTransaction: Bool, amount: Decimal, to: String?, sentToSelf: Bool, memo: String? = nil) { value = .coinValue(token: token, value: Decimal(sign: .minus, exponent: amount.exponent, significand: amount.significand)) self.to = to self.sentToSelf = sentToSelf super.init( source: source, uid: uid, transactionHash: transactionHash, transactionIndex: transactionIndex, blockHeight: blockHeight, confirmationsThreshold: confirmationsThreshold, date: date, fee: fee.flatMap { .coinValue(token: token, value: $0) }, failed: failed, lockInfo: lockInfo, conflictingHash: conflictingHash, showRawTransaction: showRawTransaction, memo: memo ) } override var mainValue: TransactionValue? { value } }
// // SignInService.swift // Wishlist // // Created by Kurtis Hill on 9/28/19. // Copyright © 2019 Kurtis Hill. All rights reserved. // import Foundation class LoginService { let proxy: ProxyProtocol = ProxyFactory.createServerProxy() func login(username: String, password: String) -> User? { do { let user = try proxy.login(username: username, password: password) UserState.instance.authenticate(user: user) return user } catch { print("Error: ", error) return nil } } }
import UIKit class BorderButton: UIButton { override func awakeFromNib() { super.awakeFromNib() // This can't be done on interface builder so need to // do this programatically. layer.borderWidth = 0.5 layer.borderColor = UIColor.white.cgColor } }
// // AnimationsFactoryTypedValueExtension.swift // TimelineAnimations // // Created by Georges Boumis on 11/01/2017. // Copyright © 2017 AbZorba Games. All rights reserved. // import Foundation import QuartzCore public protocol TypedValueConvertible { var asTypedValue: AnimationsFactory.TypedValue { get } } public extension CAKeyframeAnimation { public enum CalculationMode { case linear case discrete case paced case cubic case cubicPaced internal var value: CAAnimationCalculationMode { switch self { case CAKeyframeAnimation.CalculationMode.linear: return CAAnimationCalculationMode.linear case CAKeyframeAnimation.CalculationMode.discrete: return CAAnimationCalculationMode.discrete case CAKeyframeAnimation.CalculationMode.paced: return CAAnimationCalculationMode.paced case CAKeyframeAnimation.CalculationMode.cubic: return CAAnimationCalculationMode.cubic case CAKeyframeAnimation.CalculationMode.cubicPaced: return CAAnimationCalculationMode.cubicPaced } } } public enum RotationMode { case auto case autoreverse internal var value: CAAnimationRotationMode { switch self { case CAKeyframeAnimation.RotationMode.auto: return CAAnimationRotationMode.rotateAuto case CAKeyframeAnimation.RotationMode.autoreverse: return CAAnimationRotationMode.rotateAutoReverse } } } } public extension AnimationsFactory { public static func convertToTypedValues<T: TypedValueConvertible>(_ array: [T]) -> [AnimationsFactory.TypedValue] { return array.map { $0.asTypedValue } } public enum TypedValue { case point(CGPoint) // CGPoint case transform(CATransform3D) // CATransform3D case value(CGFloat) // CGFloat case frame(CGRect) // CGFloat case float(Float) // Float case size(CGSize) // CGSize case array([Any]) // [Any] case bool(Bool) // Bool case null // nil case custom(Any) public var value: Any? { switch self { case TypedValue.point(let point): return NSValue(cgPoint: point) case TypedValue.transform(let transform): return NSValue(caTransform3D: transform) case TypedValue.value(let v): return NSNumber(value: Double(v)) case TypedValue.frame(let frame): return NSValue(cgRect: frame) case TypedValue.float(let v): return NSNumber(value: Float(v)) case TypedValue.size(let size): return NSValue(cgSize: size) case TypedValue.array(let array): return array case TypedValue.bool(let b): return NSNumber(value: b) case TypedValue.null: return nil case let TypedValue.custom(o): return o } } } final public class func animate(keyPath: AnimationKeyPath, fromValue: AnimationsFactory.TypedValue?, toValue: AnimationsFactory.TypedValue?, duration: TimeInterval = TimeInterval(1.0), timingFunction tf: ECustomTimingFunction = ECustomTimingFunction.linear) -> CAPropertyAnimation { let animation = { () -> CAPropertyAnimation in if EasingTimingHandler.isSpecialTimingFunction(tf) { let animation = CAKeyframeAnimation.animation(keyPath: keyPath, function: EasingTimingHandler.easingFunction(from: tf), from: fromValue!, to: toValue!) return animation as CAPropertyAnimation } else { let animation = CABasicAnimation(keyPath: keyPath) animation.fromValue = fromValue?.value animation.toValue = toValue?.value animation.timingFunction = EasingTimingHandler.function(withType: tf) return animation as CAPropertyAnimation } }() animation.duration = CFTimeInterval(duration) return animation } final public class func keyframeAnimation(keyPath: AnimationKeyPath, values: [AnimationsFactory.TypedValue], keyTimes: [RelativeTime]? = nil, duration: TimeInterval = TimeInterval(1.0), calculationMode: CAKeyframeAnimation.CalculationMode = CAKeyframeAnimation.CalculationMode.linear, rotationMode: CAKeyframeAnimation.RotationMode? = nil, timingFunction tf: ECustomTimingFunction = ECustomTimingFunction.linear) -> CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath: keyPath) animation.duration = duration animation.values = values.map { $0.value as Any } if let kt = keyTimes { animation.keyTimes = kt.map { NSNumber(value: $0) } as [NSNumber] assert(values.count == kt.count) } animation.timingFunction = EasingTimingHandler.function(withType: tf) animation.calculationMode = calculationMode.value animation.rotationMode = rotationMode?.value return animation } final public class func keyframeAnimation(keyPath: AnimationKeyPath, path: CGPath, duration: TimeInterval = TimeInterval(1.0), calculationMode: CAKeyframeAnimation.CalculationMode = CAKeyframeAnimation.CalculationMode.linear, rotationMode: CAKeyframeAnimation.RotationMode? = nil, timingFunction tf: ECustomTimingFunction = ECustomTimingFunction.linear) -> CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath: keyPath) animation.duration = duration animation.path = path animation.timingFunction = EasingTimingHandler.function(withType: tf) animation.calculationMode = calculationMode.value animation.rotationMode = rotationMode?.value return animation } } extension CATransform3D: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.transform(self) } } extension CGAffineTransform: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.transform(CATransform3DMakeAffineTransform(self)) } } extension CGFloat: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.value(self) } } extension Double: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.value(CGFloat(self)) } } extension Float: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.float(self) } } extension Int: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.value(CGFloat(self)) } } extension CGPoint: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.point(self) } } extension CGRect: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.frame(self) } } extension CGSize: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.size(self) } } extension Bool: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.bool(self) } } extension Array: TypedValueConvertible { public var asTypedValue: AnimationsFactory.TypedValue { return AnimationsFactory.TypedValue.array(self) } } extension Optional where Wrapped: TypedValueConvertible { var asTypedValue: AnimationsFactory.TypedValue { if let value = self { return value.asTypedValue } else { return AnimationsFactory.TypedValue.null } } }