text
stringlengths
8
1.32M
// // Auth.swift // seugarcom // // Created by Alysson Nazareth on 23/03/16. // Copyright © 2016 RAH. All rights reserved. // import Foundation protocol AuthDelegate : ApiDelegate { func OnAuthSuccess(_ user: User!) -> Void func OnAuthError(_ error: String!) -> Void func OnRegisterSuccess(_ user: User!) -> Void func OnRegisterError(_ error: String!) -> Void } class Auth : Api<AuthDelegate> { override init(){ super.init() Route = "Auth" } func Auth(_ username: String, password: String){ let msg = CreateMessage() msg.AddParameter("username", value: username) msg.AddParameter("password", value: password) msg.Send(SuccessAuth, errorCallback: Delegate.OnAuthError) } fileprivate func SuccessAuth(_ result: NSDictionary!){ if (result["token"] == nil) { Delegate.OnAuthError(result["error"] as! String!) return } let user = User() Delegate.OnAuthSuccess(user) } func Register(_ username: String, password: String, email: String){ let msg = CreateMessage("register") msg.AddParameter("username", value: username) msg.AddParameter("password", value: password) msg.AddParameter("email", value: email) msg.Send(SuccessAuth, errorCallback: Delegate.OnAuthError) } }
// // MainVC.swift // Demo // // Created by abdurrahman on 06/05/2017. // Copyright © 2017 Abdurrahman. All rights reserved. // import UIKit class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource,BaseTVCDelegate { @IBOutlet weak var tableView: UITableView! var arrayOfFeedData = [FeedCard]() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 400 tableView.contentInset = UIEdgeInsetsMake(1, 0, 0, 0) // Dummy data initialization let feedCardLiked = FeedCard() feedCardLiked.isLiked = true let feedCardUnliked = FeedCard() feedCardUnliked.isLiked = false let feedCardLong = FeedCard() feedCardLong.textCaption = "Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome. Man this is awesome." arrayOfFeedData.append(feedCardLiked) arrayOfFeedData.append(feedCardLong) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardLiked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) arrayOfFeedData.append(feedCardUnliked) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayOfFeedData.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTVC") as! FeedTVC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.delegate = self cell.feedCard = arrayOfFeedData[indexPath.row] cell.refresh() return cell } func triggerAction(baseVC: BaseTVC, actionName: String, info: AnyObject?) { if actionName == "showToast" { self.showToast(message: info as! String) } } }
// // Application+Linking.swift // SugarLumpUIKit // // Created by Mario Chinchilla on 10/10/18. // // import Foundation import SugarLumpFoundation public enum ApplicationLinkScheme:String{ case mailApp = "message://" case mailAppSendEmail = "mailto://" case phone = "tel://" } public extension UIApplication{ func linkTo(scheme:ApplicationLinkScheme){ linkToRawURLIfPossible(scheme.rawValue) } func phoneCallTo(_ phoneNumber:String){ guard phoneNumber.isPhoneNumber else { return } linkToRawURLIfPossible("tel://"+phoneNumber) } @available(iOS 8.0, *) func openSettings(){ linkToRawURLIfPossible(UIApplicationOpenSettingsURLString) } func linkToRawURLIfPossible(_ rawURL:String){ guard let url:URL = URL(string: rawURL) else { return } linkToURLIfPossible(url) } @discardableResult func linkToURLIfPossible(_ url:URL) -> Bool{ guard canOpenURL(url) else { return false } openURL(url) return true } }
// // ContentView.swift // Project-8-Moonshot-SwiftUI // // Created by Baris Karalar on 21.06.2021. // import SwiftUI //Using generics to load any kind of Codable data //Loading a specific kind of Codable data struct ContentView: View { let astronauts: [Astronaut] = Bundle.main.decode("astronauts.json") let missions: [Mission] = Bundle.main.decode("missions.json") @State private var showingCrewNames = false var body: some View { NavigationView { List(missions) { mission in NavigationLink(destination: MissionView(mission: mission, astronauts: astronauts)) { Image(mission.image) .resizable() //Same as scaledToFit() // .aspectRatio(contentMode: .fit) .scaledToFit() .frame(width: 44, height: 44) VStack(alignment: .leading) { Text(mission.displayName) .font(.headline) Text(showingCrewNames ? crewNames(mission: mission): mission.formattedLaunchDate) } } } .navigationBarTitle("Moonshot") .navigationBarItems(trailing: Button(action: { showingCrewNames.toggle() }, label: { Text(showingCrewNames ? "Crew": "Date") })) } } func crewNames(mission: Mission) -> String { var missionNames = [String]() for crew in mission.crew { missionNames.append(crew.name.capitalized) } return missionNames.joined(separator: ", ") } } ////Pushing new views onto the stack using NavigationLink // //struct ContentView: View { // var body: some View { // // NavigationView { // List(0..<100) { row in // NavigationLink( // destination: Text("Detail \(row)"), // label: { // Text("Row \(row)") // }) // } // .navigationBarTitle("SwiftUI") // } // //// NavigationView { //// VStack { //// NavigationLink(destination: Text("Detail View"), label: { //// Text("Helloo oowowoow") //// }) //// } //// .navigationBarTitle("SwiftUI") //// } // // } //} ////How ScrollView lets us work with scrolling data // //struct CustomText: View { // // var text: String // // var body: some View { // // Text(text) // // } // // init(text: String) { // print("creating a new custom text") // self.text = text // } //} // //struct ContentView: View { // var body: some View { // // //is creating all of them at once // ScrollView(.vertical) { // VStack(spacing: 10) { // ForEach(0..<100) { // CustomText(text: "Item \($0)") // .font(.title) // } // } // .frame(maxWidth: .infinity) // } // // //creating it lazily //// List { //// ForEach(0..<100) { //// CustomText(text: "Item \($0)") //// .font(.title) //// } } // // } //} //struct ContentView: View { // var body: some View { // // ScrollView(.vertical) { // VStack(spacing: 10) { // ForEach(0..<100) { // Text("Item \($0)") // .font(.title) // } // } // .frame(maxWidth: .infinity) // } // // } //} ////Resizing images to fit the screen using GeometryReader // //struct ContentView: View { // var body: some View { // VStack { // GeometryReader { geo in // Image("pic1") // .resizable() // .aspectRatio(contentMode: .fit) // .frame(width: geo.size.width) // } // //// Image("pic1") //// .resizable() //// .aspectRatio(contentMode: .fit) //// .frame(width: 300, height: 300, alignment: .center) // // } // } //} struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // Habit.swift // Habits // // Created by Alexis Orellano on 6/7/21. // struct Habit { let name: String let category: Category let info: String }
import Foundation import DeepDiff import MarketKit struct BalanceViewItem { let element: WalletModule.Element let topViewItem: BalanceTopViewItem let lockedAmountViewItem: BalanceLockedAmountViewItem? let buttons: [WalletModule.Button: ButtonState]? } struct BalanceTopViewItem { let isMainNet: Bool let iconUrlString: String? let placeholderIconName: String let name: String let blockchainBadge: String? let syncSpinnerProgress: Int? let indefiniteSearchCircle: Bool let failedImageViewVisible: Bool let primaryValue: (text: String?, dimmed: Bool)? let secondaryInfo: BalanceSecondaryInfoViewItem } enum BalanceSecondaryInfoViewItem { case amount(viewItem: BalanceSecondaryAmountViewItem) case syncing(progress: Int?, syncedUntil: String?) case customSyncing(main: String, secondary: String?) } struct BalanceSecondaryAmountViewItem { let secondaryValue: (text: String?, dimmed: Bool)? let rateValue: (text: String?, dimmed: Bool) let diff: (text: String, type: BalanceDiffType)? } enum BalanceDiffType { case dimmed case positive case negative } struct BalanceLockedAmountViewItem { let coinValue: (text: String?, dimmed: Bool) let currencyValue: (text: String?, dimmed: Bool)? } struct BalanceButtonsViewItem { let sendButtonState: ButtonState let receiveButtonState: ButtonState let addressButtonState: ButtonState let swapButtonState: ButtonState let chartButtonState: ButtonState } extension BalanceTopViewItem: Equatable { static func ==(lhs: BalanceTopViewItem, rhs: BalanceTopViewItem) -> Bool { lhs.isMainNet == rhs.isMainNet && lhs.iconUrlString == rhs.iconUrlString && lhs.name == rhs.name && lhs.blockchainBadge == rhs.blockchainBadge && lhs.syncSpinnerProgress == rhs.syncSpinnerProgress && lhs.indefiniteSearchCircle == rhs.indefiniteSearchCircle && lhs.failedImageViewVisible == rhs.failedImageViewVisible && lhs.primaryValue?.text == rhs.primaryValue?.text && lhs.primaryValue?.dimmed == rhs.primaryValue?.dimmed && lhs.secondaryInfo == rhs.secondaryInfo } } extension BalanceSecondaryInfoViewItem: Equatable { static func ==(lhs: BalanceSecondaryInfoViewItem, rhs: BalanceSecondaryInfoViewItem) -> Bool { switch (lhs, rhs) { case (.amount(let lhsViewItem), .amount(let rhsViewItem)): return lhsViewItem == rhsViewItem case (.syncing(let lhsProgress, let lhsSyncedUntil), .syncing(let rhsProgress, let rhsSyncedUntil)): return lhsProgress == rhsProgress && lhsSyncedUntil == rhsSyncedUntil case (.customSyncing(let lMain, let lSecondary), .customSyncing(let rMain, let rSecondary)): return lMain == rMain && lSecondary ?? "" == rSecondary ?? "" default: return false } } } extension BalanceSecondaryAmountViewItem: Equatable { static func ==(lhs: BalanceSecondaryAmountViewItem, rhs: BalanceSecondaryAmountViewItem) -> Bool { lhs.secondaryValue?.text == rhs.secondaryValue?.text && lhs.secondaryValue?.dimmed == rhs.secondaryValue?.dimmed && lhs.rateValue.text == rhs.rateValue.text && lhs.rateValue.dimmed == rhs.rateValue.dimmed && lhs.diff?.text == rhs.diff?.text && lhs.diff?.type == rhs.diff?.type } } extension BalanceLockedAmountViewItem: Equatable { static func ==(lhs: BalanceLockedAmountViewItem, rhs: BalanceLockedAmountViewItem) -> Bool { lhs.coinValue.text == rhs.coinValue.text && lhs.coinValue.dimmed == rhs.coinValue.dimmed && lhs.currencyValue?.text == rhs.currencyValue?.text && lhs.currencyValue?.dimmed == rhs.currencyValue?.dimmed } } extension BalanceViewItem: DiffAware { public var diffId: WalletModule.Element { element } static func compareContent(_ a: BalanceViewItem, _ b: BalanceViewItem) -> Bool { a.topViewItem == b.topViewItem && a.lockedAmountViewItem == b.lockedAmountViewItem && a.buttons == b.buttons } } extension BalanceViewItem: CustomStringConvertible { var description: String { "[topViewItem: \(topViewItem); lockedAmountViewItem: ; buttonsViewItem: ]" } } extension BalanceTopViewItem: CustomStringConvertible { var description: String { "[iconUrlString: \(iconUrlString ?? "nil"); name: \(name); blockchainBadge: \(blockchainBadge ?? "nil"); syncSpinnerProgress: \(syncSpinnerProgress.map { "\($0)" } ?? "nil"); indefiniteSearchCircle: \(indefiniteSearchCircle); failedImageViewVisible: \(failedImageViewVisible); primaryValue: \(primaryValue.map { "[text: \($0.text ?? "nil"); dimmed: \($0.dimmed)]" } ?? "nil"); secondaryInfo: \(secondaryInfo)]" } } extension BalanceSecondaryInfoViewItem: CustomStringConvertible { var description: String { switch self { case .amount(let viewItem): return "[amount: \(viewItem)]" case .syncing(let progress, let syncedUntil): return "[syncing: [progress: \(progress.map { "\($0)" } ?? "nil"); syncedUntil: \(syncedUntil ?? "nil")]]" case .customSyncing(let left, let right): return "[\([left, right].compactMap { $0 }.joined(separator: " : "))]" } } } extension BalanceSecondaryAmountViewItem: CustomStringConvertible { var description: String { "[secondaryValue: \(secondaryValue.map { "[text: \($0.text ?? "nil"); dimmed: \($0.dimmed)]" } ?? "nil"); rateValue: \("[text: \(rateValue.text ?? "nil"); dimmed: \(rateValue.dimmed)]"); diff: \(diff.map { "[text: \($0.text); type: \($0.type)]" } ?? "nil")]" } }
// // ListViewController.swift // CavistaiosCodeChallenge // // Created by Sourabh Kumbhar on 12/08/20. // Copyright © 2020 Sourabh Kumbhar. All rights reserved. // import UIKit import SnapKit class ListViewController: UIViewController { // Variables private let tableView = UITableView() private var progreeView : ProgressHUD? private var responseModelArray = Array<ResponseDataModel>() override func loadView() { super.loadView() setupUI() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.callFetchData() } private func setupUI() { setupTableView() setupProgressView() } private func setupTableView() { // Add view to superView self.view.addSubview(tableView) // Add constraint to view tableView.snp.makeConstraints{ (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)) } // Add appearance to view self.tableView.delegate = self self.tableView.dataSource = self self.tableView.tableFooterView = UIView() self.tableView.register(ListTableViewCell.self, forCellReuseIdentifier: TableCellIdentifire.listTableViewCell) tableView.separatorColor = .clear tableView.backgroundView = getTableViewBackgroundLabel() } private func setupProgressView() { progreeView = ProgressHUD(text: ConstantHelper.fetchingData) self.view.addSubview(progreeView!) progreeView?.backgroundColor = UIColor.lightGray progreeView?.hide() } } extension ListViewController { // Network request private func callFetchData() { // Check if internet connection is there if yes then get data from webservice and no then get data from database if Connectivity.isConnectedToInternet() { let networkServices = NetworkSerives() networkServices.fetchData() networkServices.delegate = self progreeView?.show() } else { responseModelArray = RealmHelper.getResponseData() } } private func filterArray(dataModelArray: Array<ResponseDataModel>) { // filter according to empty data self.responseModelArray = dataModelArray.filter({ datamodel in !(datamodel.data?.isEmpty ?? false) }) // filter according valid image url self.responseModelArray = responseModelArray.filter({ datamodel in if datamodel.type == ConstantHelper.image { let status = datamodel.data?.isValidURL ?? false ? true : false return status } else { return true } }) } } // MARK:- Custom delegate extension ListViewController: NetworkServicesDelegate { // Here got the data from webservice and store into database func didGetData(dataModelArray: Array<ResponseDataModel>) { self.progreeView?.hide() // Filter array and assign to tableView array filterArray(dataModelArray: dataModelArray) tableView.backgroundView?.isHidden = true RealmHelper.storeResponseData(responseDataArray: responseModelArray) self.tableView.reloadData() } // Error from webservice func didGetError(error: String) { self.progreeView?.hide() tableView.backgroundView?.isHidden = false self.showAlert(title: ConstantHelper.error, message: error) } } // MARK:- UITableView delegates and datasource extension ListViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if responseModelArray.count == 0 { tableView.backgroundView?.isHidden = false } else { tableView.backgroundView?.isHidden = true } return responseModelArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TableCellIdentifire.listTableViewCell, for: indexPath) as! ListTableViewCell // check condition for indexPath out of bound then assign data to the cell if responseModelArray.count > indexPath.row { let responseModel = responseModelArray[indexPath.row] cell.configurCell(responseData: responseModel) } cell.separatorInset = .zero return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: true) // Navigate to details view controller let detailsVC = DetailsViewController() detailsVC.responseDataModel = responseModelArray[indexPath.row] self.navigationController?.pushViewController(detailsVC, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 140 } }
// // LeetCode_Sorting_Tests.swift // LeetCode-Tests // // Created by Vishal Patel on 1/11/17. // Copyright © 2017 Vishal Patel. All rights reserved. // import XCTest class LeetCode_Sorting_Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testForMergeSort() { var a = [2,9,6,4,3,7,1,8,5] mergeSort(a: &a, l: 0, r: a.count-1) XCTAssertEqual(a , [1,2,3,4,5,6,7,8,9]) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // HomeViewModel.swift // Assesment // // Created by Govindharaj Murugan on 10/01/21. // import Foundation import UIKit class HomeViewModel { let url = "https://gist.githubusercontent.com/ashwini9241/6e0f26312ddc1e502e9d280806eed8bc/raw/7fab0cf3177f17ec4acd6a2092fc7c0f6bba9e1f/saltside-json-data" var apiService: ApiService = { return ApiService()}() var reloadTableViewClosure: (()->())? var updateLoadingStatus: (()->())? var showAlertClosure: (()->())? var isLoading: Bool = false { didSet { self.updateLoadingStatus?() } } var alertMessage: String? { didSet { self.showAlertClosure?() } } lazy var arrTempDataSource = [UserDetails]() private var arrActiveDataSource: [UserDetails] = [UserDetails]() { didSet { self.arrSearchDataSource.removeAll() var arrViewModel = [UserTableCellViewModel]() for user in self.arrActiveDataSource { arrViewModel.append(self.createCellViewModel(user: user)) } self.arrUserCellModel = arrViewModel } } private var arrSearchDataSource: [UserDetails] = [UserDetails]() { didSet { var arrViewModel = [UserTableCellViewModel]() for user in self.arrSearchDataSource { arrViewModel.append(self.createCellViewModel(user: user)) } self.arrUserCellModel = arrViewModel } } private func createCellViewModel(user: UserDetails) -> UserTableCellViewModel { return UserTableCellViewModel(imageUrl: user.image, title: user.title, userDetailDescription: user.userDetailDescription) } private var arrUserCellModel: [UserTableCellViewModel] = [UserTableCellViewModel]() { didSet { self.reloadTableViewClosure?() } } // NUmber of tableview cell should be appear var numberOfCells: Int { return self.arrUserCellModel.count } // Get cellview Details func getCellViewModel(at indexPath: IndexPath ) -> UserTableCellViewModel { return arrUserCellModel[indexPath.row] } // Get Profile View Details func getDetailsViewModel(at indexpath: IndexPath) -> DetailsViewModel { if self.arrSearchDataSource.count > 0 { let data = self.arrSearchDataSource[indexpath.row] return DetailsViewModel(imageUrl: data.image, title: data.title, userDetailDescription: data.userDetailDescription) } let data = self.arrActiveDataSource[indexpath.row] return DetailsViewModel(imageUrl: data.image, title: data.title, userDetailDescription: data.userDetailDescription) } func loadLocalCacheIfHave() { self.loadMoreData(0) } func loadMoreData(_ offset: Int) { let newData = UserDetailModel().getLimitedEntryFromDB(offset) if offset == 0 { self.arrActiveDataSource = newData } else { self.arrActiveDataSource += newData } } // MARK:- API request func initFetch() { self.isLoading = true self.apiService.fetchAllDetails(url) { [weak self] (success, userList, error) in self?.isLoading = false if let error = error { self?.alertMessage = error.rawValue } else { self?.loadMoreData(0) } } } } // MARK:- Search Functionalities extension HomeViewModel { func searchTextDidChange(_ searchText: String) { if searchText == "" { self.arrActiveDataSource = self.arrTempDataSource } else { self.arrTempDataSource = self.arrActiveDataSource let arrStoredData = UserDetailModel().fetchAllListFromDB() let foundArray = arrStoredData.filter({$0.title.lowercased().contains(searchText.lowercased())}) self.arrSearchDataSource = foundArray } } }
// // NewsAPI.swift // Engage // // Created by Keenan Cookson on 2019/07/24. // Copyright © 2019 Keenan Cookson. All rights reserved. // import Foundation protocol ParameterValue { } struct NewsAPI { static let host = "newsapi.org" static let path = "/v2/top-headlines" static let scheme = "https" static let apiKeyKey = "apiKey" static let apiKeyValue = "0e18fe09898b4c638a04cb943c9d9d1e" enum ParameterKey: String { case country = "country" } enum Country: String, ParameterValue { case southAfrica = "za" case unitedStates = "us" } static func url(parameterKey: ParameterKey, parameterValue: Country) -> URL? { var urlComponents = URLComponents() urlComponents.scheme = self.scheme urlComponents.host = self.host urlComponents.path = self.path urlComponents.queryItems = [URLQueryItem(name: parameterKey.rawValue, value: parameterValue.rawValue), URLQueryItem(name: apiKeyKey, value: apiKeyValue)] return urlComponents.url } }
// // ImageInfo.swift // DemoChartOSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // Copyright © 2017 thierry Hentic. // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Cocoa struct ImageInfo { fileprivate(set) var thumbnail: NSImage? fileprivate(set) var nameController: String fileprivate(set) var name: String fileprivate(set) var type : TypeOfChart init(thumbnail : NSImage, nameController: String, name: String, type: TypeOfChart ) { self.thumbnail = thumbnail self.nameController = nameController self.name = name self.type = type } }
// // File.swift // // // Created by Mason Phillips on 6/9/20. // import Foundation /// The API key used for testing. Set in either the Run or Test enviroment variables let API_KEY = ProcessInfo.processInfo.environment["api_key"] ?? "APIKEYERR"
// // ImageVCell.swift // AutoScrollImages // // Created by PASHA on 30/11/18. // Copyright © 2018 Pasha. All rights reserved. // import UIKit class ImageVCell: UICollectionViewCell { @IBOutlet weak var bannerImageV: UIImageView! }
// // TwoMissingNumbers.swift // AlgorithmSwift // // Created by Liangzan Chen on 2/3/18. // Copyright © 2018 clz. All rights reserved. // import Foundation /* Given an array of n unique integers where each element in the array is in range [1, n]. The array has all distinct elements and size of array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers. Requirement: Time: O(n), Space: O(1) Examples: Input : arr[] = {1, 3, 5, 6}, n = 6 Output : 2 4 Input : arr[] = {1, 2, 4}, n = 5 Output : 3 5 Input : arr[] = {1, 2}, n = 4 Output : 3 4 */ func findTwoMissingNumbers(_ numbers: [Int]) -> (Int, Int) { let size = numbers.count + 2 if size == 2 { return (1,2) } var xorAll = 0 for i in 1...size { xorAll ^= i } for i in 0..<numbers.count{ xorAll ^= numbers[i] } let rightMostSetBit = xorAll & (~(xorAll - 1)) var x = 0 var y = 0 for i in 1...size { if i & rightMostSetBit > 0 { x ^= i } else { y ^= i } } for i in 0..<numbers.count { if numbers[i] & rightMostSetBit > 0 { x ^= numbers[i] } else { y ^= numbers[i] } } return (x,y) }
// Copyright © T-Mobile USA Inc. All rights reserved. import RIBs import SimpleRIBNetworking protocol NoNetworkRouting: ViewableRouting {} protocol NoNetworkPresentable: Presentable { var listener: NoNetworkPresentableListener? { get set } } protocol NoNetworkListener: AnyObject { func callBackApi() } final class NoNetworkInteractor: PresentableInteractor<NoNetworkPresentable>, NoNetworkInteractable { weak var router: NoNetworkRouting? weak var listener: NoNetworkListener? // TODO: Add additional dependencies to constructor. Do not perform any logic // in constructor. override init(presenter: NoNetworkPresentable) { super.init(presenter: presenter) presenter.listener = self } } extension NoNetworkInteractor: NoNetworkPresentableListener { func callApi() { if InternetStatusListener.shared.currentStatus == .reachable { listener?.callBackApi() } } }
// // ViewController.swift // UdderGit // // Created by sachin sharma on 07/05/19. // Copyright © 2019 sachin sharma. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //new changes are here } }
// // ContentBlockerRule.swift // Garden Wall // // Created by Francis Bailey on 2015-11-25. // Copyright © 2015 Francis Bailey. All rights reserved. // import Foundation import ObjectMapper /* * An enumeration representing the possible type values in a rule action */ enum ContentBlockerRuleActionType: String { case block = "block" case blockCookies = "block-cookies" case cssDisplayNone = "css-display-none" case ignoreRules = "ignore-previous-rules" } /* * An enumeration representing the possible load-type values in a rule trigger */ enum ContentBlockerRuleTriggerLoadType: String { case firstParty = "first-party" case thirdParty = "third-party" } /* * An enumeration representing the possible resource-type values in a rule trigger */ enum ContentBlockerRuleTriggerResourceType: String { case document = "document" case font = "font" case image = "image" case media = "media" case popup = "popup" case raw = "raw" case script = "script" case styleSheet = "style-sheet" case svgDoc = "svg-document" } /* * A JSON Mappable entity that represents the Trigger part of a Content Blocker rule */ struct ContentBlockerRuleTrigger: Mappable { var urlFilter: String! var urlFilterIsCaseSensitive: Bool? var loadType: [ContentBlockerRuleTriggerLoadType]? var resourceType: [ContentBlockerRuleTriggerResourceType]? var ifDomain: [String]? init?(_ map: Map) { } init() { } init(urlFilter: String, urlCase: Bool?, loadType: [ContentBlockerRuleTriggerLoadType]?, resourceType: [ContentBlockerRuleTriggerResourceType]?, ifDomain: [String]?) { self.urlFilter = urlFilter self.urlFilterIsCaseSensitive = urlCase self.loadType = loadType self.resourceType = resourceType self.ifDomain = ifDomain } mutating func mapping(map: Map) { urlFilter <- map["url-filter"] urlFilterIsCaseSensitive <- map["url-filter-is-case-sensitive"] loadType <- map["load-type"] resourceType <- map["resource-type"] ifDomain <- map["if-domain"] } } /* * A JSON Mappable entity that represents the Action part of a Content Blocker rule */ struct ContentBlockerRuleAction: Mappable { var type: ContentBlockerRuleActionType! var selector: String? init?(_ map: Map) { } init() { } init(type: ContentBlockerRuleActionType, selector: String?) { self.type = type self.selector = selector } mutating func mapping(map: Map) { type <- (map["type"], EnumTransform()) selector <- map["selector"] } } /* * A JSON Mappable entity that represents a Content Blocker Rule */ class ContentBlockerRule: Mappable { var trigger: ContentBlockerRuleTrigger! var action: ContentBlockerRuleAction! required init?(_ map: Map) { } init(trigger: ContentBlockerRuleTrigger, action: ContentBlockerRuleAction) { self.trigger = trigger self.action = action } func mapping(map: Map) { trigger <- map["trigger"] action <- map["action"] } }
// // PostDetailViewController.swift // Heyoe // // Created by Nam Phong on 7/23/15. // Copyright (c) 2015 Nam Phong. All rights reserved. // import UIKit import Social protocol PostDetailViewControllerDelegate { func didUpdatePost(post: PostObject) } class PostDetailViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, PostDetailHeaderViewDelegate, UIActionSheetDelegate { @IBOutlet weak var tableview: UITableView! @IBOutlet weak var commentView: UIView! private let HeaderIdentifier = "PostDetailHeaderView" private let CellIdentifier = "PostDetailCell" @IBOutlet weak var bottomConstraint: NSLayoutConstraint! var delegate: PostDetailViewControllerDelegate? var imgRatio: CGFloat = 0 var post:PostObject! var comments: [CommentObject] = [CommentObject]() @IBOutlet weak var comment: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tableview.registerNib(UINib(nibName: CellIdentifier, bundle: nil), forCellReuseIdentifier: CellIdentifier) self.tableview.registerNib(UINib(nibName: HeaderIdentifier, bundle: nil), forHeaderFooterViewReuseIdentifier: HeaderIdentifier) self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "hideKeyboard")) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) self.updateViewCount() self.configBackButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.getAllComment() } func configBackButton() { let btn = UIButton(type: UIButtonType.Custom) btn.setImage(UIImage(named: "backBtn"), forState: .Normal) btn.frame = CGRectMake(0, 0, 14, 22) btn.addTarget(self, action: "backToNews", forControlEvents: UIControlEvents.TouchUpInside) let barBtn = UIBarButtonItem(customView: btn) self.navigationItem.leftBarButtonItem = barBtn } func backToNews() { // self.navigationController?.popToRootViewControllerAnimated(true) let viewControllers = self.navigationController!.viewControllers let viewController = viewControllers[viewControllers.count - 2] self.navigationController?.popToViewController(viewController, animated: true) } func hideKeyboard() { self.view.endEditing(true) } // MARK: UPDATE VIEW COUNT func updateViewCount() { if self.post.userID != QMApi.instance().currentUser.ID { if !self.post.viewCount.contains(QMApi.instance().currentUser.ID) { self.post.viewCount.append(QMApi.instance().currentUser.ID) PostAPI.updatePost(self.post, completion: { (newPost) -> Void in self.tableview.reloadData() self.delegate?.didUpdatePost(self.post) }, failure: { (error) -> Void in }) } } } // GET COMMENT func getAllComment() { CommentAPI.getAllComment(self.post, completion: { (comment) -> Void in self.comments = comment self.tableview.reloadData() }) { (error) -> Void in self.view.makeToast(error, duration: 3, position: CSToastPositionTop) } } // MARK: TABLEVIEW func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.comments.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as! PostDetailCell cell.configCellWithComment(self.comments[indexPath.row]) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.comment.resignFirstResponder() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(HeaderIdentifier) as! PostDetailHeaderView headerView.backgroundColor = UIColor.whiteColor() headerView.configHeaderWithPost(self.post) headerView.delegate = self return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if self.post.photoURL != "" { // if self.post.isVideo { // self.imgRatio = 0 // } else { let img = SDImageCache.sharedImageCache().imageFromMemoryCacheForKey(self.post.photoURL) if img != nil { self.imgRatio = img.size.width/img.size.height } // } } return PostDetailHeaderView.calculateCellHeigh(self.post, ratio: self.imgRatio) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return PostDetailCell.calculateCellHeigh(self.comments[indexPath.row]) } // MARK: DELEGATE ACTION func didClickAvatar() { let userID = self.post.userID let selectedUser = QMApi.instance().userWithID(userID) let userProfileViewController = ProfileViewController() userProfileViewController.selectedUser = selectedUser userProfileViewController.userPage = true self.navigationController?.pushViewController(userProfileViewController, animated: true) } func didSelectLikeButton() { if post.likeCount.contains(QMApi.instance().currentUser.ID) { self.view.makeToast("You already like it", duration: 3, position: CSToastPositionTop) } else { // remove user id from dislike list if post.dislikeCount.contains(QMApi.instance().currentUser.ID) { post.dislikeCount.remove(QMApi.instance().currentUser.ID) } post.likeCount.append(QMApi.instance().currentUser.ID) PostAPI.updatePost(post, completion: { (newPost) -> Void in self.tableview.reloadData() self.delegate?.didUpdatePost(self.post) if self.post.userID != QMApi.instance().currentUser.ID { NotificationAPI.postNotification(1, receiverId: self.post.userID, postID: self.post.ID, completion: { () -> Void in }, failure: { (error) -> Void in }) } }, failure: { (error) -> Void in }) } } func didSelectDislikeButton() { if post.dislikeCount.contains(QMApi.instance().currentUser.ID) { self.view.makeToast("You already like it", duration: 3, position: CSToastPositionTop) } else { // remove user id from dislike list if post.likeCount.contains(QMApi.instance().currentUser.ID) { post.likeCount.remove(QMApi.instance().currentUser.ID) } post.dislikeCount.append(QMApi.instance().currentUser.ID) PostAPI.updatePost(post, completion: { (newPost) -> Void in self.tableview.reloadData() self.delegate?.didUpdatePost(self.post) if self.post.userID != QMApi.instance().currentUser.ID{ NotificationAPI.postNotification(2, receiverId: self.post.userID, postID: self.post.ID, completion: { () -> Void in }, failure: { (error) -> Void in }) } }, failure: { (error) -> Void in }) } } func didSelectShareButton() { let actionSheet = UIActionSheet(title: "", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Share on facebook", "Share on Twitter") actionSheet.showInView(self.view) } func didUpdateLayout(ratio: CGFloat) { self.imgRatio = ratio self.tableview.reloadData() } func didPlayVideo() { let videoController = VideoController() videoController.url = NSURL(string: self.post.photoURL!) self.navigationController?.pushViewController(videoController, animated: true) } // MARK: ACTIONSHEET DELEGATE func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { let headerView = self.tableview.headerViewForSection(0) as! PostDetailHeaderView if buttonIndex == 1 { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook) tweetSheet.setInitialText(post.status) tweetSheet.addImage(headerView.postPhoto.image) self.presentViewController(tweetSheet, animated: true, completion: nil) tweetSheet.completionHandler = { (result:SLComposeViewControllerResult) in if result == SLComposeViewControllerResult.Done { self.post.shareCount++ PostAPI.updatePost(self.post, completion: { (newPost) -> Void in self.tableview.reloadData() self.delegate?.didUpdatePost(self.post) if self.post.userID != QMApi.instance().currentUser.ID { NotificationAPI.postNotification(3, receiverId: self.post.userID, postID: self.post.ID, completion: { () -> Void in }, failure: { (error) -> Void in }) } }, failure: { (error) -> Void in self.view.makeToast(error) }) } else { print("Cancel cmnr") } } } } else if buttonIndex == 2 { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) { let tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter) tweetSheet.setInitialText(post.status) tweetSheet.addImage(headerView.postPhoto.image) self.presentViewController(tweetSheet, animated: true, completion: nil) tweetSheet.completionHandler = { (result:SLComposeViewControllerResult) in if result == SLComposeViewControllerResult.Done { self.post.shareCount++ PostAPI.updatePost(self.post, completion: { (newPost) -> Void in self.tableview.reloadData() self.delegate?.didUpdatePost(self.post) if self.post.userID != QMApi.instance().currentUser.ID { NotificationAPI.postNotification(3, receiverId: self.post.userID, postID: self.post.ID, completion: { () -> Void in }, failure: { (error) -> Void in }) } }, failure: { (error) -> Void in self.view.makeToast(error) }) } else { print("Cancel cmnr") } } } } } // MARK: KEYBOARD NOTIFICATION func keyboardWillShow(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { UIView.animateWithDuration(0.3, animations: { () -> Void in self.bottomConstraint.constant = keyboardSize.height self.view.layoutIfNeeded() }, completion: { (finished: Bool) -> Void in self.tableview.scrollRectToVisible(CGRectMake(0, self.tableview.contentSize.height-1, 1, 1), animated: true) }) } } } func keyboardWillHide(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { UIView.animateWithDuration(0.3, animations: { () -> Void in self.bottomConstraint.constant = 0 self.view.layoutIfNeeded() }, completion: { (finished: Bool) -> Void in self.tableview.scrollRectToVisible(CGRectMake(0, self.tableview.contentSize.height-1, 1, 1), animated: true) }) } } } @IBAction func doAddNewComment(sender: AnyObject) { self.view.endEditing(true) if self.comment.text.isEmpty || self.comment.text == ""{ self.view.makeToast("Please enter comment", duration: 3, position: CSToastPositionTop) return } CommentAPI.addNewComment(self.comment.text, post: self.post, completion: { (comment) -> Void in self.comments.insert(comment, atIndex: 0) self.tableview.reloadData() self.comment.text = "" self.delegate?.didUpdatePost(self.post) if self.post.userID != QMApi.instance().currentUser.ID { NotificationAPI.postNotification(4, receiverId: self.post.userID, postID: self.post.ID, completion: { () -> Void in }, failure: { (error) -> Void in }) } }) { (error) -> Void in self.view.makeToast(error, duration: 3, position: CSToastPositionTop) self.comment.text = "" } } }
// // Hoster.swift // BikeApp // // Created by Matheus Prates da Costa on 14/05/2018. // Copyright © 2018 BikeApp. All rights reserved. // import UIKit struct Hoster { var name: String var email: String var profilePhoto: UIImage var description: String var rating: Double var rentNumber: Int var horario: String var bikerEvaluations: [String] var latitude: Double var longitude: Double var address: String var price: Double var localPhotos: UIImage }
// // NotificationCell.swift // Qvafy // // Created by ios-deepak b on 01/09/20. // Copyright © 2020 IOS-Aradhana-cat. All rights reserved. // import UIKit import SDWebImage class NotificationCell: UITableViewCell { @IBOutlet weak var imgProfile: UIImageView! @IBOutlet weak var vwProfile: UIView! @IBOutlet weak var vwContainer: UIView! @IBOutlet weak var vwDotted: UIView! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblDate: UILabel! @IBOutlet weak var btnCell: UIButton! @IBOutlet weak var imgDotted: UIImageView! override func awakeFromNib() { super.awakeFromNib() self.vwDotted.creatDashedLine(view: vwDotted) // self.vwProfile.setSubProfileVerifyView(vwOuter: self.vwProfile, img: self.imgProfile ,radius : 4) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - Common function for Review List func NotificationListCell(obj:NotificationModel) { lblDate.text = obj.strRemainingTime // print(" obj.strRemainingTime is \(obj.strRemainingTime)") if obj.strbody.contains("[UNAME]"){ if obj.strRole == "1"{ print(obj.strType) if obj.strType == "rating_remind"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + obj.strFullName.capitalizingFirstLetter() + " " + fullNameArr[1] } else if obj.strbody.contains("[UNAME]") && obj.strbody.contains("[RNAME]") { if obj.strRole == "1"{ if obj.strTitle == "In Route"{ let swiftyString = obj.strbody.replacingOccurrences(of: "[UNAME]", with: "\(obj.strFullName.capitalizingFirstLetter())") let finalString = swiftyString.replacingOccurrences(of: "[RNAME]", with: "\(obj.strRestaurantName.capitalizingFirstLetter())") print(finalString) lblTitle.text = finalString } } }else if obj.strTitle == "Being Prepared"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + obj.strFullName.capitalizingFirstLetter() } else if obj.strTitle == "Order Accepted"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + obj.strFullName.capitalizingFirstLetter() } else if obj.strTitle == "Order Rejected"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + obj.strFullName.capitalizingFirstLetter() } else{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = obj.strFullName.capitalizingFirstLetter() + " " + fullNameArr[1] } }else if obj.strRole == "2"{ if obj.strTitle == "Trip Review"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = obj.strFullName.capitalizingFirstLetter() + " " + fullNameArr[1] }else{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + " " + obj.strFullName.capitalizingFirstLetter() + fullNameArr[1] } } else if obj.strRole == "3"{ // if obj.strTitle == "Order Review"{ // if obj.strType == "order_review"{ // let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") // lblTitle.text = obj.strFullName.capitalizingFirstLetter() + " " + fullNameArr[1] // }else if obj.strType == "new_order" { let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") lblTitle.text = fullNameArr[0] + " " + obj.strFullName.capitalizingFirstLetter() }else if obj.strType == "order_review" && obj.strCurrentStatus == "6"{ let fullNameArr = obj.strbody.components(separatedBy: "[UNAME]") let str1 = obj.strFullName.capitalizingFirstLetter() + " " + fullNameArr[1] let finalString = str1.replacingOccurrences(of: "[RNAME]", with: "\(obj.strRestaurantName.capitalizingFirstLetter())") print(finalString) lblTitle.text = finalString } } }else if obj.strbody.contains("[RNAME]"){ if obj.strRole == "1"{ print(obj.strType) if obj.strType == "Picked Up"{ let fullNameArr = obj.strbody.components(separatedBy: "[RNAME]") lblTitle.text = fullNameArr[0] + obj.strRestaurantName.capitalizingFirstLetter() + " " + fullNameArr[1] }else if obj.strTitle == "Food Delivered"{ let fullNameArr = obj.strbody.components(separatedBy: "[RNAME]") lblTitle.text = fullNameArr[0] + obj.strRestaurantName.capitalizingFirstLetter() }else if obj.strTitle == "Picked Up"{ let fullNameArr = obj.strbody.components(separatedBy: "[RNAME]") lblTitle.text = fullNameArr[0] + obj.strRestaurantName.capitalizingFirstLetter() } } } else{ lblTitle.text = obj.strbody } if obj.strIsRead == "1" { self.vwContainer.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) // self.vwDotted.isHidden = false /// self.imgDotted.isHidden = false }else{ self.vwContainer.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1) // self.vwDotted.isHidden = true /// self.imgDotted.isHidden = true } } func checkImages(obj:NotificationModel) { if objAppShareData.UserDetail.strRole == "1" { // for Customer side if obj.strReferenceType == "1"{ // for ride booking if obj.strCurrentStatus == "1" || obj.strCurrentStatus == "2" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "4" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "5" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "6" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "7" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") }else if obj.strCurrentStatus == "0" { if obj.strTitle == "Booking Rejected"{ imgProfile.image = #imageLiteral(resourceName: "cancelled_bookingRide") }else{ imgProfile.image = #imageLiteral(resourceName: "request_Type_ico") } } }else if obj.strReferenceType == "2" { // for order if obj.strCurrentStatus == "1" { imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") } else if obj.strCurrentStatus == "2" || obj.strCurrentStatus == "3" { imgProfile.image = #imageLiteral(resourceName: "Deliverd_Type") } // else if obj.strCurrentStatus == "3" { // // if obj.strVehicleType == "3" { // // imgProfile.image = #imageLiteral(resourceName: "bike_type") // // }else{ // imgProfile.image = #imageLiteral(resourceName: "moterCycle_type") // } // // } else if obj.strCurrentStatus == "4" { if obj.strVehicleType == "3" { imgProfile.image = #imageLiteral(resourceName: "bike_type") }else{ imgProfile.image = #imageLiteral(resourceName: "moterCycle_type") } } else if obj.strCurrentStatus == "5" { if obj.strVehicleType == "3" { imgProfile.image = #imageLiteral(resourceName: "bike_type") }else{ imgProfile.image = #imageLiteral(resourceName: "moterCycle_type") } } else if obj.strCurrentStatus == "6" { if obj.strVehicleType == "3" { imgProfile.image = #imageLiteral(resourceName: "bike_type") }else{ imgProfile.image = #imageLiteral(resourceName: "moterCycle_type") } // imgProfile.image = #imageLiteral(resourceName: "review_Type_ico") } else if obj.strCurrentStatus == "7" { // if obj.strVehicleType == "3" { // // imgProfile.image = #imageLiteral(resourceName: "bike_type") // // }else{ // imgProfile.image = #imageLiteral(resourceName: "moterCycle_type") // } imgProfile.image = #imageLiteral(resourceName: "cancel_order_ico") } } } else if objAppShareData.UserDetail.strRole == "2" { // for Taxi Driver side if obj.strReferenceType == "1"{ // for ride booking if obj.strCurrentStatus == "1" || obj.strCurrentStatus == "2" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") }else if obj.strCurrentStatus == "0" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") }else if obj.strCurrentStatus == "3" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "4" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } else if obj.strCurrentStatus == "5" { if obj.strType == "trip_review"{ imgProfile.image = #imageLiteral(resourceName: "review_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } } else if obj.strCurrentStatus == "6" { // imgProfile.image = #imageLiteral(resourceName: "taxi_Type") if obj.strType == "trip_review"{ imgProfile.image = #imageLiteral(resourceName: "review_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } } else if obj.strCurrentStatus == "7" { imgProfile.image = #imageLiteral(resourceName: "taxi_Type") } }else if obj.strReferenceType == "0" { // for other if obj.strType == "wallet"{ imgProfile.image = #imageLiteral(resourceName: "payment_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "document_Type_ico_new") } } }else if objAppShareData.UserDetail.strRole == "3" { // for Food Delivery side if obj.strReferenceType == "2"{ // for order if obj.strCurrentStatus == "1" || obj.strCurrentStatus == "2" { imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") }else if obj.strCurrentStatus == "0" { imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") }else if obj.strCurrentStatus == "3" { imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") } else if obj.strCurrentStatus == "4" { imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") } else if obj.strCurrentStatus == "5" { if obj.strTitle == "Order Review"{ imgProfile.image = #imageLiteral(resourceName: "review_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") } } else if obj.strCurrentStatus == "6" { if obj.strTitle == "Order Review"{ imgProfile.image = #imageLiteral(resourceName: "review_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "newOrder_Type_ico") } } else if obj.strCurrentStatus == "7" { imgProfile.image = #imageLiteral(resourceName: "cancel_order_ico") } }else if obj.strReferenceType == "0" { // for other if obj.strType == "wallet"{ imgProfile.image = #imageLiteral(resourceName: "payment_Type_ico") }else{ imgProfile.image = #imageLiteral(resourceName: "document_Type_ico_new") } } } } }
import Foundation protocol RequestManagerProtocol { func request(_ url: String, completion: @escaping (Result<[Movie], Error>) -> Void) }
// // BasketViewController.swift // BlackStarWearProject // // Created by Владислав Вишняков on 14.07.2021. // import UIKit import RealmSwift class BasketViewController: UIViewController, UITableViewDelegate { var itemData = [SubCategoryItems]() var imagesCell = Network.networkAccess.bucketResourse var salePrice = [Double]() var doubleE = Double() var resultRealm: Results <cacheData>! let realm = try! Realm() var summa = [Double]() var forMinus = Double() func getSum() -> Double { summa = [0.0] if resultRealm != nil { for el in resultRealm { summa.append(el.price) } } let strSumma = summa.reduce(0, +) forMinus = strSumma return strSumma } @IBOutlet weak var emptyBucketOutlet: UILabel! @IBOutlet weak var basketTableView: UITableView! @IBOutlet weak var sumBacket: UILabel! override func viewDidLoad() { super.viewDidLoad() resultRealm = realm.objects(cacheData.self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.basketTableView.reloadData() let formattedText = Network.networkAccess.fromDoubleToString(double: String(getSum())) sumBacket.text = formattedText print(forMinus) } } extension BasketViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if resultRealm?.count != 0 { emptyBucketOutlet.isHidden = true return resultRealm?.count ?? 0 } else { emptyBucketOutlet.isHidden = false return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BasketCell") as! BasketTableViewCell let cellIndex = resultRealm?[indexPath.row] let indexImg = cellIndex?.imageUrl ?? "" cell.basketNameCell.text = cellIndex?.name Network.networkAccess.getImage(url: API.mainURL + indexImg) { resourse in self.imagesCell.insert(resourse, at: 0) } cell.basketCell.kf.indicatorType = .activity cell.basketCell.kf.setImage(with: imagesCell.first, options: [.transition(.fade(0.7))]) cell.oldPrice.text = cellIndex?.priceOld if let dataCell = cellIndex?.price { cell.price.text = String(dataCell) } cell.sizeBasket.text = "Размер: \(cellIndex?.size ?? "Error")" cell.selectionStyle = .none let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: Network.networkAccess.fromDoubleToString(double: cellIndex?.priceOld ?? "Error")) attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) cell.price.text = Network.networkAccess.fromDoubleToString(double: String(cellIndex?.price ?? 0.0)) if cellIndex?.priceOld == nil { cell.oldPrice.isHidden = true } else { cell.oldPrice.isHidden = false cell.oldPrice.attributedText = attributeString cell.price.isHidden = false } return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let item = resultRealm?[indexPath.row] { try! realm.write { let sumString = String("\(forMinus - item.price)") let sumFormatted = Network.networkAccess.fromDoubleToString(double: sumString) sumBacket.text = sumFormatted forMinus = forMinus - item.price realm.delete(item) basketTableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) basketTableView.reloadData() } } } } }
import UIKit class APIErrorTypeTimeOut: BaseAPIError { }
// // LoanDocumentsPage.swift // MyBank // // Created by Sathriyan on 02/07/21. // import SwiftUI struct LoanDocumentsPage: View { var body: some View { NavigationView { GeometryReader { geo in VStack { HStack { Text("Documents") .foregroundColor(Color("CardBg")) .font(Font.system(size: geo.size.width * 0.075)) .fontWeight(.semibold) .frame(maxWidth : .infinity, alignment: .leading) .padding(.top, geo.size.height * 0.12) .padding(.leading, geo.size.width * 0.0556) Button(action: {}, label: { Image(systemName: "plus.app") .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color.black) .frame(width : geo.size.width * 0.06) .padding(.top, geo.size.height * 0.13) .padding(.trailing, geo.size.width * 0.0556) }) } VStack{ Text("No documents uploaded") } .frame(maxWidth : .infinity, maxHeight: .infinity, alignment: .center) } .frame(maxWidth : .infinity, maxHeight: .infinity, alignment: .top) } .background(Color("BgColor")) .edgesIgnoringSafeArea(.top) .ignoresSafeArea(.keyboard) .navigationBarHidden(true) } } } struct LoanDocumentsPage_Previews: PreviewProvider { static var previews: some View { LoanDocumentsPage() } }
// // NSObject+Saturn.swift // Saturn // // Created by Quinn McHenry on 11/14/15. // Copyright © 2015 Small Planet. All rights reserved. // extension NSObject: SaturnObject { private struct AssociatedKeys { static var id = "SaturnAssociatedKey:id" } public func loadIntoParent(parent: AnyObject) { } public func setAttribute(value: String, forProperty property:String) { switch property { case "id": id = value default: break } } public func setAttributes(attributes:[String:String]?) { guard let attributes = attributes else { return } for (property, value) in attributes { setAttribute(value, forProperty: property) } } public var id: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.id) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.id, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func objectsWithId(id: String) -> [AnyObject] { return [] } }
import UIKit extension MiddleContent { /** * Create items */ func createItemViews() -> [ItemView] { let itemViews: [ItemView] = (0..<5).map {_ in let itemView: ItemView = .init(frame: .zero) self.addSubview(itemView) return itemView } itemViews.distributeAndSize(dir: .ver, width: self.frame.width, height: 48, spacing: 12, offset: .init(x: 24, y: 24)) return itemViews } }
// // Date+Cpf.swift // Demo // // Created by Aaron on 2023/6/5. // import Foundation import CPFChain extension Date: CpfCompatible {} extension Cpf where Wrapped == Date { /// 一天的秒数(60 * 60 * 24s),方便用于计算 static var secondsOfOneDay: TimeInterval { 60 * 60 * 24 } /// 昨天 static var yesterday: Date { let date = Date(timeIntervalSinceNow: secondsOfOneDay * -1) let calendar = Calendar.current return calendar.startOfDay(for: date) } }
import Foundation class MemoryData { static let sharedInstance = MemoryData() private var _tags: Set = ["groceries", "home", "work", "stuff", "longstringthatislong", "day"] class var tags: Set<String> { get { return sharedInstance._tags } set { sharedInstance._tags = newValue } } }
// // MyDelegate.swift // eggplant-brownie // // Created by Rodrigo Martins on 15/04/19. // Copyright © 2019 Rodrigo Martins. All rights reserved. // import Foundation protocol AddAMealDelegate { func add(_ meal:Meal) }
// // Store.swift // ReduxMe // // Created by Ilias Pavlidakis on 22/01/2020. // Copyright © 2020 Ilias Pavlidakis. All rights reserved. // import Foundation import Combine public final class Store<State: Hashable> { private let reducer: Reducer<State> private let serialDispatcher: SerialDispatching private var middleware: [Middleware<State>] private let subject: CurrentValueSubject<State, Never> public var state: State { subject.value } public convenience init( state: State, reducers: [Reducer<State>], middleware: [Middleware<State>] = []) { self.init( state: state, reducers: reducers, serialDispatcher: SerialDispatcher(), middleware: middleware) } init( state: State, reducers: [Reducer<State>], serialDispatcher: SerialDispatching, middleware: [Middleware<State>] ) { self.subject = CurrentValueSubject<State, Never>(state) self.reducer = Reducer<State>.compound(reducers) self.serialDispatcher = serialDispatcher self.middleware = middleware } } public extension Store { func dispatch(_ action: Action) { serialDispatcher.enqueue { [weak self] in guard let self = self else { return } let initialState = self.state self.middleware.forEach { $0.apply(initialState, action) } let newState = self.reducer.reduce(initialState, action) self.subject.value = newState } } func intercept(with middleware: Middleware<State>) { self.middleware.append(middleware) } func observe<Value>(keypath: KeyPath<State, Value>) -> AnyPublisher<Value, Never> { subject .map(keypath) .eraseToAnyPublisher() } }
// // SAModel+Methods.swift // CoremelysisML // // Created by Rafael Galdino on 02/11/20. // Copyright © 2020 Rafael Galdino. All rights reserved. // import NaturalLanguage import CoreML extension SAModel { // MARK: Exposed Methods ///Gives the predicted sentiment value of a given paragraph. Throws errors. /// ///Performs sentiment analysis using Apple's [Natural Language](https://developer.apple.com/documentation/naturallanguage) framework or another specified model ///and it's return value ranges from -1 to 1, for negative and positive values, respectively. /// - Parameters: /// - text: Body of text used in the inference. Should be at least one sentence long. /// - model: Model used for the inference. public func infer(text: String) throws -> Double { switch self { case .sentimentPolarity: return try SAModel.inferenceBySentimentPolarity(text) case .default: return try SAModel.inferenceByNaturalLanguage(text) case .customModel: return try SAModel.inferenceByCustomModel(text) @unknown default: throw Errors.noModelProvided } } // MARK: Inference Methods ///Uses Natural Language framework to give the predicted sentiment value of a string. /// ///Performs sentiment analysis using Apple's [Natural Language](https://developer.apple.com/documentation/naturallanguage) ///framework and it's return value ranges from -1 to 1, for negative and positive values, respectively. /// - Parameters: /// - data: Body of text used in the inference. Should be at least one sentence long. private static func inferenceByNaturalLanguage(_ data: String) throws -> Double { let tagger = NLTagger(tagSchemes: [.sentimentScore]) tagger.string = data let inferenceValue = tagger.tag(at: data.startIndex, unit: .paragraph, scheme: .sentimentScore).0 guard let inference = Double(inferenceValue?.rawValue ?? "nil") else { throw Errors.failedPrediction } return inference } ///Uses Sentiment Polarity model to give the predicted sentiment value of a string. /// ///Performs sentiment analysis using [Vadym Markov's Sentiment Polarity](https://github.com/cocoa-ai/SentimentCoreMLDemo/blob/master/SentimentPolarity/Resources/SentimentPolarity.mlmodel) model. /// - Parameters: /// - data: Body of text used in the inference. Should be at least one sentence long. private static func inferenceBySentimentPolarity(_ data: String) throws -> Double { let spModel = try SentimentPolarity(configuration: MLModelConfiguration()) let tokens = extractFeatures(from: data) if tokens.isEmpty { throw Errors.insufficientData } let prediction = try spModel.prediction(input: tokens) guard let score = prediction.classProbability[prediction.classLabel] else { throw Errors.failedPrediction } if prediction.classLabel == "Pos" { return score } else { return -score } } private static func inferenceByCustomModel(_ data: String) throws -> Double { guard let compiledModelName = UserDefaults.standard.string(forKey: "customModel"), !compiledModelName.isEmpty, let modelURL = FileManager.appSupportFileURL(for: compiledModelName) else { throw Errors.modelNotAvaiable } let customModel = try CustomSAModel(contentsOf: modelURL) let tokens = extractFeatures(from: data) if tokens.isEmpty { throw Errors.insufficientData } let prediction = try customModel.prediction(input: tokens) guard let score = prediction.classProbability[prediction.classLabel] else { throw Errors.failedPrediction } return score } // MARK: Auxiliary Methods ///Uses Apple's Natural Language framework to extract tokens from text data. /// ///It ignores punctuation and symbols ///words with 3 or less characters are not considered. /// - Parameters: /// - data: Text to be suffer feature extraction. /// - wordSize: static func extractFeatures(from data: String, wordSize: Int = 3) -> [String: Double] { var tokens = [String: Double]() let options: NLTagger.Options = [.omitWhitespace, .omitPunctuation, .omitOther] let scheme: NLTagScheme = NLTagScheme.nameType let tagger: NLTagger = NLTagger(tagSchemes: [scheme]) tagger.string = data let range = data.startIndex..<data.endIndex tagger.enumerateTags(in: range, unit: .word, scheme: scheme, options: options) { (_, tokenRange) -> Bool in let token = data[tokenRange].lowercased() if token.count > wordSize { if let value = tokens[token] { tokens[token] = value + 1.0 } else { tokens[token] = 1.0 } } return true } return tokens } public static func downloadModel(from externalURL: URL) throws { var downloadError: Error? FileManager.downloadFile(from: externalURL) { (result) in switch result { case .success(let url): do { deleteCustomModel() let compiledModelURL = try MLModel.compileModel(at: url) let compiledModelName = FileManager.persistFile(fileURL: compiledModelURL) UserDefaults.standard.setValue(compiledModelName, forKey: "customModel") } catch { downloadError = error } case .failure(let error): downloadError = error } } if let error = downloadError { throw error } } public static func deleteCustomModel() { guard let path = UserDefaults.standard.string(forKey: "customModel"), !path.isEmpty else { return } do { try FileManager.default.removeItem(atPath: path) UserDefaults.standard.setValue(String(), forKey: "customModel") } catch { return } } }
// // ProfileVIewModel.swift // WorldChatDidac // // Created by Dídac Edo Gibert on 21/4/21. // import SwiftUI class ProfileViewModel: ObservableObject { @Published var user: User init(user: User) { self.user = user checkIfUserIsFollowed() fetchUserStats() } func follow() { guard let uid = user.id else { return } UserService.follow(uid: uid) { _ in self.user.isFollowed = true } } func unfollow() { guard let uid = user.id else { return } UserService.unfollow(uid: uid) { _ in self.user.isFollowed = false } } func checkIfUserIsFollowed() { guard !user.isCurrentUser else { return } guard let uid = user.id else { return } UserService.checkIfUserIsFollowed(uid: uid) { isFollowed in self.user.isFollowed = false } } func fetchUserStats() { guard let uid = user.id else { return } COLLECTION_FOLLOWING.document(uid).collection("user-following").getDocuments { snapshot, _ in guard let following = snapshot?.documents.count else { return } COLLECTION_FOLLOWERS.document(uid).collection("user-followers").getDocuments { snapshot, _ in guard let followers = snapshot?.documents.count else { return } COLLECTION_POSTS.whereField("ownerUid", isEqualTo: uid).getDocuments { snapshot ,_ in guard let posts = snapshot?.documents.count else { return } self.user.stats = UserStats(Siguiendo: following, Publicaciones: posts, Seguidores: followers) } } } } }
import CombineX import Foundation #if !COCOAPODS import CXNamespace #endif extension CXWrappers { open class NSObject<Base: Foundation.NSObject>: CXWrapper { public let base: Base public required init(wrapping base: Base) { self.base = base } } } extension NSObject: CXWrapping { public typealias CX = CXWrappers.NSObject<NSObject> } #if canImport(ObjectiveC) // FIXME: NSObject.KeyValueObservingPublisher doesn't conform ot `Publisher` protocol, 🤔. extension NSObject.CX { func keyValueObservingPublisher<Value>(_ keyPath: KeyPath<Base, Value>, _ options: NSKeyValueObservingOptions) -> KeyValueObservingPublisher<Base, Value> { return .init(object: self.base, keyPath: keyPath, options: options) } } extension NSObject.CX { /// A publisher that emits events when the value of a KVO-compliant property changes. public struct KeyValueObservingPublisher<Subject, Value>: Equatable where Subject: NSObject { public let object: Subject public let keyPath: KeyPath<Subject, Value> public let options: NSKeyValueObservingOptions public init(object: Subject, keyPath: KeyPath<Subject, Value>, options: NSKeyValueObservingOptions) { self.object = object self.keyPath = keyPath self.options = options } } } #endif
// // ViewController.swift // SignInWithApple // // Created by Fedor Volchkov on 12/20/19. // Copyright © 2019 Fedor Volchkov. All rights reserved. // import UIKit import AuthenticationServices class ViewController: UIViewController { var appleLogInButton : ASAuthorizationAppleIDButton = { let button = ASAuthorizationAppleIDButton() button.addTarget(self, action: #selector(handleLogInWithAppleID), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(appleLogInButton) appleLogInButton.center = view.center } @objc func handleLogInWithAppleID() { let request = ASAuthorizationAppleIDProvider().createRequest() request.requestedScopes = [.fullName, .email] let controller = ASAuthorizationController(authorizationRequests: [request]) controller.delegate = self controller.presentationContextProvider = self controller.performRequests() } } extension ViewController: ASAuthorizationControllerDelegate { func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { switch authorization.credential { case let appleIDCredential as ASAuthorizationAppleIDCredential: let userIdentifier = appleIDCredential.user print(userIdentifier) break default: break } } } extension ViewController: ASAuthorizationControllerPresentationContextProviding { func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { return self.view.window! } }
// // AlertDeleteDiagnose.swift // HISmartPhone // // Created by DINH TRIEU on 12/26/17. // Copyright © 2017 MACOS. All rights reserved. // import UIKit protocol AlertDeleteControllerDelegate: class { func didSelectDelete() func didSelectCancel() } class AlertDeleteController: BaseAlertViewController { var delegate: AlertDeleteControllerDelegate? //MARK: UIControl private let containtView: UIView = { let view = UIView() view.backgroundColor = Theme.shared.defaultBGColor view.layer.cornerRadius = Dimension.shared.normalCornerRadius view.layer.masksToBounds = true return view }() private let messageLabel: UILabel = { let label = UILabel() label.text = "Bạn chắc chắn muốn \n xoá Chẩn đoán và \n Hướng dẫn điều trị này" label.textColor = Theme.shared.darkBlueTextColor label.textAlignment = .center label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize) label.numberOfLines = 0 return label }() private let acceptButton: UIButton = { let button = UIButton() button.setTitle("XÁC NHẬN", for: .normal) button.backgroundColor = Theme.shared.primaryColor button.layer.cornerRadius = Dimension.shared.heightButtonAlert / 2 return button }() private let cancelButton: UIButton = { let button = UIButton() button.setTitle("HUỶ", for: .normal) button.backgroundColor = Theme.shared.accentColor button.layer.cornerRadius = Dimension.shared.heightButtonAlert / 2 return button }() //MARK: Initialize override func setupView() { self.setupViewContaintView() self.setupViewMessageLabel() self.setupViewAcceptButton() self.setupViewCancelButton() } //MARK: Action UIControl @objc func handleAcceptButton() { self.dismissAlert() self.delegate?.didSelectDelete() } @objc func handleCancelButton() { self.dismissAlert() self.delegate?.didSelectCancel() } //MARK: Feature public func setMessage(_ message: String) { self.messageLabel.text = message } //MARK: SetupView private func setupViewContaintView() { self.view.addSubview(self.containtView) self.containtView.snp.makeConstraints { (make) in make.width.equalTo(Dimension.shared.widthAlertDeleteDiagnose) make.centerX.centerY.equalToSuperview() } } private func setupViewMessageLabel() { self.containtView.addSubview(self.messageLabel) self.messageLabel.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.left.equalToSuperview().offset(38 * Dimension.shared.widthScale) make.right.equalToSuperview().offset(-38 * Dimension.shared.widthScale) make.top.equalToSuperview().offset(Dimension.shared.largeVerticalMargin) } } private func setupViewAcceptButton() { self.containtView.addSubview(self.acceptButton) self.acceptButton.snp.makeConstraints { (make) in make.top.equalTo(self.messageLabel.snp.bottom).offset(Dimension.shared.largeVerticalMargin_32) make.width.equalTo(Dimension.shared.widthButtonAlert) make.height.equalTo(Dimension.shared.heightButtonAlert) make.centerX.equalToSuperview() } self.acceptButton.addTarget(self, action: #selector(handleAcceptButton), for: .touchUpInside) } private func setupViewCancelButton() { self.containtView.addSubview(self.cancelButton) self.cancelButton.snp.makeConstraints { (make) in make.top.equalTo(self.acceptButton.snp.bottom).offset(Dimension.shared.normalVerticalMargin) make.width.equalTo(Dimension.shared.widthButtonAlert) make.height.equalTo(Dimension.shared.heightButtonAlert) make.centerX.equalToSuperview() make.bottom.equalToSuperview().offset(-Dimension.shared.normalVerticalMargin) } self.cancelButton.addTarget(self, action: #selector(handleCancelButton), for: .touchUpInside) } }
// // InputCoordinateViewController.swift // googleMapz // // Created by Macbook on 6/18/21. // import UIKit import MapKit import CoreLocation protocol InputCoordinateViewControllerDelegate { func didFinishInputCoordinate(coord:CLLocationCoordinate2D, name:String) } class InputCoordinateViewController: UIViewController { var delegate:InputCoordinateViewControllerDelegate? @IBOutlet weak var LatTextField: UITextField! @IBOutlet weak var lonTextField: UITextField! @IBOutlet weak var nameTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func DoneButtonPressed(_ sender: UIButton) { guard let latString = LatTextField.text else {return} guard let lonString = lonTextField.text else {return} let name = nameTextField.text ?? "default Name" guard let latDegree = CLLocationDegrees(latString) else {return} guard let lonDegree = CLLocationDegrees(lonString) else {return} let coords = CLLocationCoordinate2D(latitude: latDegree, longitude: lonDegree) self.delegate?.didFinishInputCoordinate(coord: coords, name: name) self.dismiss(animated: true, completion: nil) } }
// // CustomsTableViewCell.swift // Covid19Layout // // Created by User on 6/11/20. // Copyright © 2020 hung. All rights reserved. // import UIKit class CustomsTableViewCell: UITableViewCell { let containerView: UIView = { let viewCrt = UIView() // viewCrt.backgroundColor = UIColor.backgroundColor() viewCrt.backgroundColor = UIColor.white return viewCrt }() let label: UILabel = { let label = UILabel() label.textColor = UIColor.fontColor() label.font = UIFont.systemFont(ofSize: 24) // label.text = "COVID - 19 Test Request" return label }() let ovalView: UIView = { let ovalview = UIView() return ovalview }() override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state setupLayout() self.backgroundColor = UIColor.backgroundColor() } func setupLayout() { self.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8).isActive = true containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8).isActive = true containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true self.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.centerYAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0).isActive = true label.widthAnchor.constraint(equalTo: containerView.widthAnchor, multiplier: 0.8).isActive = true // label.heightAnchor.constraint(equalToConstant: self.frame.size.height/1).isActive = true label.heightAnchor.constraint(equalToConstant: 30).isActive = true label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16).isActive = true // label.backgroundColor = .red containerView.addSubview(ovalView) ovalView.translatesAutoresizingMaskIntoConstraints = false ovalView.widthAnchor.constraint(equalToConstant: 135).isActive = true ovalView.heightAnchor.constraint(equalToConstant: 135).isActive = true ovalView.topAnchor.constraint(equalTo: label.topAnchor, constant: 0).isActive = true ovalView.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: 0).isActive = true ovalView.backgroundColor = UIColor.fontColor() } override func draw(_ rect: CGRect) { ovalView.layer.cornerRadius = ovalView.bounds.width/2 ovalView.layer.masksToBounds = true containerView.clipsToBounds = true } }
// // Area.swift // TplInsurancTesting // // Created by Tahir Raza on 31/07/2019. // Copyright © 2019 Mohammed Ahsan. All rights reserved. // import Foundation struct Area: Decodable { let Id: Int let Name: String static func decodeJsonData(data: Data) -> [Area]? { let decodedObject = try? JSONDecoder().decode([Area].self, from: data) return decodedObject } }
// // StockNotificationResponse.swift // carWash // // Created by Juliett Kuroyan on 30.12.2019. // Copyright © 2019 VooDooLab. All rights reserved. // import Foundation struct SaleNotificationResponse { var id: Int }
// // GardenListMainVC.swift // CropBook // // Created by jon on 2018-07-27. // Copyright © 2018 CMPT276-Group15. All rights reserved. // import UIKit import Firebase import CoreData var SHARED_GARDEN_LIST=[MyGarden?]() var MY_GARDEN: MyGarden = MyGarden(Name: "My Garden", Address: "") var SIGNED_IN = false @objc protocol gardenButtonClicked{ func openCrops() func postGardenPrompt() func openSharedCrops(index: Int) func openMap(index: Int) } class MyGardenMainVC: UIViewController,gardenButtonClicked{ @IBOutlet weak var viewContainer : UIView! @IBOutlet weak var segControl : UISegmentedControl! @IBOutlet weak var signInSignOut : UIButton! var views: [UIView]! var sharedVC : SharedGardenView = SharedGardenView() var myGardenVC : MyGardenView = MyGardenView() var cropsCore = [CropProfileCore]() var gardenIndex : Int? let fetchRequest: NSFetchRequest<CropProfileCore> = CropProfileCore.fetchRequest() override func viewDidLoad() { super.viewDidLoad() loadCoreData() if let _=Auth.auth().currentUser{ self.signInSignOut.setTitle("Sign Out", for: UIControlState.normal) } addChildViewController(sharedVC) addChildViewController(myGardenVC) myGardenVC.delegate = self sharedVC.delegate = self views = [UIView]() views.append(myGardenVC.view) views.append(sharedVC.view) for v in views { v.isUserInteractionEnabled = false viewContainer.addSubview(v) } views[0].isUserInteractionEnabled = true viewContainer.bringSubview(toFront: views[0]) } override func viewWillAppear(_ animated: Bool) { if let _=Auth.auth().currentUser{ self.signInSignOut.setTitle("Sign Out", for: UIControlState.normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //load coredata func loadCoreData(){ do { let cropsCore = try PersistenceService.context.fetch(fetchRequest) self.cropsCore = cropsCore } catch {} for crop in cropsCore{ print(crop.cropName!) let info = lib.searchByName(cropName: crop.cropName!) print(info) let profile = CropProfile(cropInfo: info!, profName: crop.profName!) let surfaceArea = crop.plotLength * crop.plotWidth profile.coreData = crop profile.setSurfaceArea(area: surfaceArea) print(crop.plotLength) print(crop.plotWidth) MY_GARDEN.AddCrop(New: profile) } } // Switch between MyGardenView and SharedGardenView @IBAction func switchViewAction(_ sender: UISegmentedControl){ if let _=Auth.auth().currentUser{ switchViews(index: sender.selectedSegmentIndex) } else { if sender.selectedSegmentIndex == 1{ self.SignIn() } } } func switchViews(index: Int) { for i in 0...(views.count-1){ self.views[i].isUserInteractionEnabled = (i == index) } self.viewContainer.bringSubview(toFront: views[index]) } func postGardenPrompt() { // Make sure user is logged in if let _=Auth.auth().currentUser{ let alertController = UIAlertController(title: "Post Garden?", message: "Garden can be seen by others", preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Address (Optional)" } alertController.addTextField { (textField) in textField.placeholder = "City" } alertController.addTextField { (textField) in textField.placeholder = "Postal Code" } let shareAction = UIAlertAction(title: "Post", style: .default) { (_) in let addressField = alertController.textFields![0] let cityField = alertController.textFields![1] let postalField = alertController.textFields![2] let address = addressField.text let city = cityField.text let postalCode = postalField.text if city != "" && postalCode != "" { MY_GARDEN.setAddress(address: address!, city: city!, postalCode: postalCode!) self.postGarden() } else { alertController.dismiss(animated: true, completion: nil) let alert = UIAlertController(title: "Missing Entries", message: nil, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated:true, completion:nil) })) self.present(alert, animated: true, completion: nil) } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(shareAction) alertController.addAction(cancelAction) DispatchQueue.main.async { self.present(alertController, animated: true, completion: nil) } } else { self.SignIn() } } //Write Garden into Firebase func postGarden() { //Assign Garden inside array with ID print("Posting") MY_GARDEN.setIsOnline(state: true) //Assign Attribute into garden let ref=Database.database().reference() let garden = MY_GARDEN.gardenName let address = MY_GARDEN.address let gardenID = ref.child("Gardens").childByAutoId().key MY_GARDEN.gardenID=gardenID ref.child("Gardens/\(gardenID)/gardenName").setValue(garden) //self.ref.child("Gardens/\(gardenID)/Crops").setValue() ref.child("Gardens/\(gardenID)/Address").setValue(address) //Save gardenID into the user profile guard let userid=Auth.auth().currentUser?.uid else {return} let gardenRef=ref.child("Users/\(userid)/Gardens").child(gardenID) print(gardenID) gardenRef.setValue(true) //create another attribute members so we know who's participating let memberRef=ref.child("Gardens/\(gardenID)/members/\(userid)") let userEmail = Auth.auth().currentUser?.email memberRef.setValue(userEmail) let ownerRef = ref.child("Gardens/\(gardenID)/Owner") ownerRef.setValue(userEmail) print("Adding Crops") for i in 0..<MY_GARDEN.getSize(){ //let gardenID=GardenList[gardenIndex]?.gardenID let cropname = MY_GARDEN.cropProfile[i]?.GetCropName() let profName = MY_GARDEN.cropProfile[i]?.profName let cropRef=ref.child("Gardens/\(gardenID)/CropList").childByAutoId() cropRef.child("CropName").setValue(cropname) cropRef.child("ProfName").setValue(profName) print("Crop added") } self.sharedVC.GetOnlineGardens() } func forceOfflineView(){ for i in 0...(views.count-1){ self.views[i].isUserInteractionEnabled = (i == 0) } self.viewContainer.bringSubview(toFront: views[0]) } @IBAction internal func SignInSelected(_ sender: Any){ if let _=Auth.auth().currentUser{ try! Auth.auth().signOut() self.forceOfflineView() self.segControl.selectedSegmentIndex = 0 self.signInSignOut.setTitle("Sign In", for: UIControlState.normal) } else { self.SignIn() } } func SignIn(){ let alertController = UIAlertController(title: nil, message: "Login", preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Email" textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 30)) textField.keyboardType = .emailAddress } alertController.addTextField { (textField) in textField.placeholder = "Password" textField.isSecureTextEntry = true textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 30)) } let loginAction = UIAlertAction(title: "Login", style: .default) { (_) in let emailField = alertController.textFields![0] let passwordField = alertController.textFields![1] //Perform validation or whatever you do want with the text of textfield guard let username = emailField.text else{return} guard let password = passwordField.text else{return} //Login With Firebase Auth.auth().signIn(withEmail: username, password: password){user, error in if error == nil && user != nil{ // signInSuccess self.sharedVC.GetOnlineGardens() self.switchViews(index: self.segControl.selectedSegmentIndex) self.signInSignOut.setTitle("Sign Out", for: UIControlState.normal) } else { print("Error : \(error!.localizedDescription)") self.switchViews(index: 0) self.segControl.selectedSegmentIndex = 0 let alert = UIAlertController(title: "Inavlid Username/Password", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated:true, completion:nil) })) self.present(alert, animated:true, completion:nil) } } } let signupAction = UIAlertAction(title: "Signup", style: .default) { (_) in alertController.dismiss(animated: true, completion: nil) self.signup() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){ (_) in self.switchViews(index: 0) self.segControl.selectedSegmentIndex = 0 } alertController.addAction(loginAction) alertController.addAction(signupAction) alertController.addAction(cancelAction) DispatchQueue.main.async { self.present(alertController, animated: true, completion: nil) } } func signup(){ let alertController = UIAlertController(title: nil, message: "Signup", preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Email" textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 30)) textField.keyboardType = .emailAddress } alertController.addTextField { (textField) in textField.placeholder = "Password" textField.isSecureTextEntry = true textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 30)) } alertController.addTextField { (textField) in textField.placeholder = "Confirm Password" textField.isSecureTextEntry = true textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 30)) } let signupAction = UIAlertAction(title: "Signup", style: .default) { (_) in let emailField = alertController.textFields![0] let passwordField = alertController.textFields![1] let confirmPasswordField = alertController.textFields![2] //Perform validation or whatever you do want with the text of textfield guard let username = emailField.text else{return} guard let password = passwordField.text else{return} guard let confirmPassword = confirmPasswordField.text else{return} if password != confirmPassword { //passwords don't match alertController.dismiss(animated: true, completion: nil) self.switchViews(index: 0) self.segControl.selectedSegmentIndex = 0 let alert = UIAlertController(title: "Passwords do not match", message: nil, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated:true, completion:nil) })) self.present(alert, animated:true, completion:nil) } //Signup With Firebase Auth.auth().createUser(withEmail: username, password: password){user, error in if error == nil && user != nil{ print("User is saved") self.sharedVC.GetOnlineGardens() self.switchViews(index: self.segControl.selectedSegmentIndex) self.signInSignOut.setTitle("Sign Out", for: UIControlState.normal) } else { self.switchViews(index: 0) self.segControl.selectedSegmentIndex = 0 print("Error : \(error!.localizedDescription)") let alert = UIAlertController(title: "Inavlid Username/Password", message: "Password must be at least 6 Characters. Email must be valid.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated:true, completion:nil) })) self.present(alert, animated:true, completion:nil) } } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){ (_) in self.switchViews(index: 0) self.segControl.selectedSegmentIndex = 0 } alertController.addAction(signupAction) alertController.addAction(cancelAction) DispatchQueue.main.async { self.present(alertController, animated: true, completion: nil) } } func openSharedCrops(index: Int){ self.gardenIndex = index performSegue(withIdentifier: "showSharedCrops", sender: self) } func openCrops(){ performSegue(withIdentifier: "showCrops", sender: self) } func openMap(index: Int) { self.gardenIndex = index performSegue(withIdentifier: "showMap", sender: self) } 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. if (segue.identifier == "showCrops") { let nextController=segue.destination as!GardenCropList nextController.Online=false } else if (segue.identifier == "showSharedCrops") { let nextController=segue.destination as!GardenCropList nextController.gardenIndex = gardenIndex! nextController.Online=true } else if (segue.identifier == "showMap") { let nextController=segue.destination as!MapVC nextController.gardenIndex = gardenIndex! } } }
// // PartnerVC.swift // GardenCoceral // // Created by shiliuhua on 2018/5/22. // Copyright © 2018年 tongna. All rights reserved. // import UIKit class PartnerVC: BaseViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet var tableView: UITableView! var bassClass:ProjectProjectBaseClass! var viewModel:PartnerViewModel! var currentPage = 2 var tempArray:NSMutableArray! override func viewDidLoad() { super.viewDidLoad() self.title = "合作项目" tableView.delegate = self tableView.dataSource = self tableView.register(UINib.init(nibName: "PartnerCell", bundle: nil), forCellReuseIdentifier: "PartnerCell") tableView.rowHeight = 300 tableView.tableFooterView = UIView() // Do any additional setup after loading the view. tempArray = NSMutableArray.init(capacity: 0) self.tableView.mj_header = setUpMJHeader(refreshingClosure: { self.getProjectList() }) self.tableView.mj_footer = setUpMJFooter(refreshingClosure: { print("加载更多") self.getMoreProjectList() }) self.tableView.mj_header.beginRefreshing() getProjectList() } //获取合作项目列表 func getProjectList() -> Void { startRequest(requestURLStr: projectListUrl, dic: ["commerce":1,"userToken":userToken(),"no":1,"size":10], actionHandler: { (jsonStr) in print("proJsonStr = \(jsonStr)") self.bassClass = ProjectProjectBaseClass(json: jsonStr) self.tempArray = NSMutableArray(array: self.bassClass.list!) self.tableView.reloadData() self.currentPage = 2 self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.resetNoMoreData() }) { } } //获取更多合作项目列表 func getMoreProjectList() -> Void { startRequest(requestURLStr: projectListUrl, dic: ["commerce":1,"userToken":userToken(),"no":currentPage,"size":10], actionHandler: { (jsonStr) in print("proJsonStr = \(jsonStr)") if self.bassClass.list?.count == 0 { self.tableView.mj_footer.endRefreshingWithNoMoreData() }else{ self.bassClass = ProjectProjectBaseClass(json: jsonStr) self.tempArray.addObjects(from: self.bassClass.list!) self.currentPage = self.currentPage + 1 self.tableView.reloadData() self.tableView.mj_footer.endRefreshing() } }) { } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.bassClass != nil ? self.tempArray.count : 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PartnerCell") as! PartnerCell let listModel:ProjectList = tempArray.object(at: indexPath.row) as! ProjectList viewModel = PartnerViewModel(projectListModel: listModel) cell.configure(with: viewModel) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let listModel:ProjectList = tempArray.object(at: indexPath.row) as! ProjectList let vc = ProjectDetailVC() vc.projectId = listModel.id ?? 0 self.navigationController?.pushViewController(vc) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // CampusCalendarViewController.swift // berkeley-mobile // // Created by Kevin Hu on 9/22/20. // Copyright © 2020 ASUC OCTO. All rights reserved. // import UIKit import Firebase fileprivate let kCardPadding: UIEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) fileprivate let kViewMargin: CGFloat = 16 /// Displays the campus-wide and org. events in the Calendar tab. class CampusCalendarViewController: UIViewController { /// Categories to include from all events private static let categories = ["Career"] private var scrollingStackView: ScrollingStackView! private var upcomingMissingView: MissingDataView! private var eventsCollection: CardCollectionView! private var calendarMissingView: MissingDataView! private var calendarTable: UITableView! private var calendarEntries: [EventCalendarEntry] = [] override func viewDidLoad() { super.viewDidLoad() // Note: The top inset value will be also used as a vertical margin for `scrollingStackView`. self.view.layoutMargins = UIEdgeInsets(top: 8, left: 16, bottom: 16, right: 16) setupScrollView() // remove upcoming card for now because it doesn't add any new information/value // setupUpcoming() setupCalendarList() DataManager.shared.fetch(source: EventDataSource.self) { calendarEntries in self.calendarEntries = (calendarEntries as? [EventCalendarEntry])?.filter({ entry -> Bool in return CampusCalendarViewController.categories.contains(entry.category) }) ?? [] self.calendarEntries = self.calendarEntries.sorted(by: { $0.date.compare($1.date) == .orderedAscending }) self.calendarEntries = self.calendarEntries.filter({ $0.date > Date() }) if (self.calendarEntries.count == 0) { // self.upcomingMissingView.isHidden = false self.calendarMissingView.isHidden = false self.calendarTable.isHidden = true } else { // self.upcomingMissingView.isHidden = true self.calendarMissingView.isHidden = true self.calendarTable.isHidden = false } self.calendarTable.reloadData() // self.eventsCollection.reloadData() } } } // MARK: - Calendar Table Delegates extension CampusCalendarViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return calendarEntries.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: CampusEventTableViewCell.kCellIdentifier, for: indexPath) as? CampusEventTableViewCell { if let entry = calendarEntries[safe: indexPath.row] { cell.updateContents(event: entry) return cell } } return UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = CampusEventDetailViewController() if let entry = calendarEntries[safe: indexPath.row] { vc.event = entry present(vc, animated: true) tableView.deselectRow(at: indexPath, animated: true) } } } // MARK: - Upcoming Card Delegates extension CampusCalendarViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return min(calendarEntries.count, 4) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CampusEventCollectionViewCell.kCellIdentifier, for: indexPath) if let card = cell as? CampusEventCollectionViewCell { if let entry = calendarEntries[safe: indexPath.row] { card.updateContents(event: entry) } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = CampusEventDetailViewController() if let entry = calendarEntries[safe: indexPath.row] { vc.event = entry present(vc, animated: true) } } } // MARK: - View extension CampusCalendarViewController { private func setupScrollView() { scrollingStackView = ScrollingStackView() scrollingStackView.setLayoutMargins(view.layoutMargins) scrollingStackView.scrollView.showsVerticalScrollIndicator = false scrollingStackView.stackView.spacing = kViewMargin view.addSubview(scrollingStackView) scrollingStackView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true scrollingStackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true scrollingStackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true scrollingStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } // MARK: Upcoming Card private func setupUpcoming() { let card = CardView() card.layoutMargins = kCardPadding scrollingStackView.stackView.addArrangedSubview(card) let contentView = UIView() contentView.layer.masksToBounds = true card.addSubview(contentView) contentView.translatesAutoresizingMaskIntoConstraints = false contentView.setConstraintsToView(top: card, bottom: card, left: card, right: card) let headerLabel = UILabel() headerLabel.font = Font.bold(24) headerLabel.text = "Upcoming" contentView.addSubview(headerLabel) headerLabel.translatesAutoresizingMaskIntoConstraints = false headerLabel.topAnchor.constraint(equalTo: card.layoutMarginsGuide.topAnchor).isActive = true headerLabel.leftAnchor.constraint(equalTo: card.layoutMarginsGuide.leftAnchor).isActive = true headerLabel.rightAnchor.constraint(equalTo: card.layoutMarginsGuide.rightAnchor).isActive = true let collectionView = CardCollectionView(frame: .zero) collectionView.register(CampusEventCollectionViewCell.self, forCellWithReuseIdentifier: CampusEventCollectionViewCell.kCellIdentifier) collectionView.delegate = self collectionView.dataSource = self collectionView.contentInset = UIEdgeInsets(top: 0, left: card.layoutMargins.left, bottom: 0, right: card.layoutMargins.right) contentView.addSubview(collectionView) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.topAnchor.constraint(equalTo: headerLabel.bottomAnchor, constant: 16).isActive = true collectionView.heightAnchor.constraint(equalToConstant: CampusEventCollectionViewCell.kCardSize.height).isActive = true collectionView.leftAnchor.constraint(equalTo: card.leftAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: card.rightAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: card.layoutMarginsGuide.bottomAnchor).isActive = true eventsCollection = collectionView upcomingMissingView = MissingDataView(parentView: collectionView, text: "No upcoming events") } // MARK: Calendar Table private func setupCalendarList() { let card = CardView() card.layoutMargins = kCardPadding scrollingStackView.stackView.addArrangedSubview(card) card.translatesAutoresizingMaskIntoConstraints = false card.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true let table = UITableView() table.register(CampusEventTableViewCell.self, forCellReuseIdentifier: CampusEventTableViewCell.kCellIdentifier) table.rowHeight = CampusEventTableViewCell.kCellHeight table.delegate = self table.dataSource = self table.showsVerticalScrollIndicator = false table.separatorStyle = .none card.addSubview(table) table.translatesAutoresizingMaskIntoConstraints = false table.topAnchor.constraint(equalTo: card.layoutMarginsGuide.topAnchor).isActive = true table.leftAnchor.constraint(equalTo: card.layoutMarginsGuide.leftAnchor).isActive = true table.rightAnchor.constraint(equalTo: card.layoutMarginsGuide.rightAnchor).isActive = true table.bottomAnchor.constraint(equalTo: card.layoutMarginsGuide.bottomAnchor).isActive = true calendarTable = table calendarMissingView = MissingDataView(parentView: card, text: "No events found") } } extension CampusCalendarViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Analytics.logEvent("opened_campus_wide_events", parameters: nil) } }
// // ValueExpression.swift // CouchbaseLite // // Copyright (c) 2018 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Value Expression. /* internal */ class ValueExpression: QueryExpression { init(value: Any?) { super.init(CBLQueryExpression.value(ValueExpression.convertValue(value))) } static func convertValue(_ value: Any?) -> Any? { switch value { case let v as [String: Any]: return ValueExpression.convertDictionary(v) case let v as [Any]: return ValueExpression.convertArray(v) case let v as ExpressionProtocol: return v.toImpl() default: return value } } static func convertDictionary(_ dictionary: [String: Any]) -> [String: Any] { var result: [String: Any] = [:] for (key, value) in dictionary { result[key] = ValueExpression.convertValue(value)! } return result } static func convertArray(_ array: [Any]) -> [Any] { var result: [Any] = []; for v in array { result.append(ValueExpression.convertValue(v)!) } return result } }
// // ViewController.swift // Calculator // // Created by Stephan Thordal Larsen on 03/06/15. // Copyright (c) 2015 Stephan Thordal. All rights reserved. // import UIKit class CalculatorViewController: UIViewController { // Outlets @IBOutlet weak var history: UILabel! @IBOutlet weak var display: UILabel! // Variables var brain = CalculatorBrain() private var userTyping = false private var displayValue: Double? { get{ if display.text!.rangeOfString("=") != nil { display.text = display.text!.stringByReplacingOccurrencesOfString("=", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) } if let value = NSNumberFormatter().numberFromString(display.text!) { let doubleValue = value.doubleValue if doubleValue != 0 { return doubleValue } } return nil } set{ if newValue != nil { display.text = "\(newValue!)" } else { display.text = "NaN" } userTyping = false } } // Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destination = segue.destinationViewController as? UIViewController if let navCon = destination as? UINavigationController { destination = navCon.visibleViewController! } if let gvc = destination as? GraphViewController { gvc.brain = brain } } // Actions @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userTyping { display.text = display.text! + digit } else { display.text = digit userTyping = true } } @IBAction func appendPoint(sender: UIButton) { let point = sender.currentTitle! if display.text!.rangeOfString(point) == nil { if userTyping { display.text = display.text! + point } else { display.text = "0" + point userTyping = true } } } @IBAction func saveVariable() { brain.variableValues["M"] = displayValue userTyping = false showResult(brain.evaluate()) } @IBAction func updateHistory() { history.text = brain.description } @IBAction func enter() { userTyping = false if let value = displayValue { displayValue = brain.pushOperand(value) } updateHistory() } @IBAction func addVariable() { brain.pushOperand("M") userTyping = false updateHistory() } @IBAction func clear() { brain.clearStack() brain.variableValues = [String:Double]() displayValue = 0 updateHistory() } @IBAction func backspace() { if userTyping { display.text = dropLast(display.text!) if count(display.text!) == 0 { displayValue = nil } } } @IBAction func invertSign() { if let value = displayValue { displayValue = value * (-1) } } @IBAction func operate(sender: UIButton) { if userTyping { enter() } if let operation = sender.currentTitle { showResult(brain.performOperation(operation)) } } private func showResult(result: Double?) { displayValue = result display.text = "= " + display.text! updateHistory() } }
// // ArtMusicTableViewCell.swift // SwiftCaiYIQuan // // Created by 朴子hp on 2018/6/30. // Copyright © 2018年 朴子hp. All rights reserved. // import UIKit class ArtMusicTableViewCell: UITableViewCell { //MARK: -- >> 用户信息 @IBOutlet weak var userIcon: UIImageView! @IBOutlet weak var userIdentity: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var idType: UILabel! @IBOutlet weak var sexIcon: UIImageView! @IBOutlet weak var ageLab: UILabel! @IBOutlet weak var artType: UILabel! //MARK: -- >> 用户位置信息 @IBOutlet weak var cityName: UILabel! @IBOutlet weak var distance: UILabel! var model: HomeSubArtMusicModel?{ didSet{ userName.text = model?.UserName cityName.text = model?.City distance.text = String.init(format: "%@km", (model?.Distance)!) print("celltest--\(String(describing: model?.UserName))") } } var dict: [String:AnyObject]?{ didSet{ //用户信息 userIcon.kf.setImage(with:URL.init(string: String.init(format: "%@%@", IMAGE_SERVER,(dict?["PhotoID"] as? String)! )), placeholder: UIImage.init(named: "b2_ico_head"), options:nil, progressBlock:nil, completionHandler: nil) userIcon.layer.cornerRadius = 30.0 userIcon.layer.masksToBounds = true let authInfo = dict?["AuthType"] as? String if (authInfo?.isEmpty)! { userIdentity.isHidden = true }else{ userIdentity.isHidden = false } if authInfo == "0" { idType.text = "学生" }else if authInfo == "1"{ idType.text = "教师" }else if authInfo == "2"{ idType.text = "名人" }else{ idType.text = "" } userName.text = dict?["UserName"] as? String let sex = dict?["Gender"] as? NSString if (sex?.isEqual(to: "男"))! { sexIcon.image = UIImage.init(named: "b10_ico_male") }else{ sexIcon.image = UIImage.init(named: "b10_ico_malefe") } let age = dict?["Age"] as? NSString if (age?.isEqual(to: ""))! { ageLab.text = "0" }else{ ageLab.text = age! as String } //用户位置信息 cityName.text = dict?["City"] as? String distance.text = String.init(format: "%@km", (dict?["Distance"] as? String)!) } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
// // LocationTableViewCell.swift // GoogleMapTest // // Created by Yermakov Anton on 2/17/19. // Copyright © 2019 Yermakov Anton. All rights reserved. // import UIKit class LocationTableViewCell: UITableViewCell { @IBOutlet weak var locationName: UILabel! @IBOutlet weak var locationLatitude: UILabel! @IBOutlet weak var locationLongtitude: UILabel! func setUpCell(location: Location){ locationName.text = location.title locationLatitude.text = location.latitude.description locationLongtitude.text = location.longtitude.description } 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 } }
// // ViewController.swift // UnSplash_Rodrigo_Elo // // Created by Rodrigo Elo on 27/06/18. // Copyright © 2018 Rodrigo Elo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var fieldSearch: UITextField! @IBOutlet weak var searchBtn: UIButton! @IBAction func searchBtn(_ sender: Any) { if fieldSearch.text != ""{ if let destination = storyboard?.instantiateViewController(withIdentifier: "firstView") as? ContentTableViewController{ destination.query = fieldSearch.text navigationController?.pushViewController(destination, animated: true) } } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // LinksURl.swift // Rampage // // Created by lapstore on 7/27/18. // Copyright © 2018 AmrSobhy. All rights reserved. // import Foundation class LinksURL { static let url: String = "https://api.themoviedb.org/3/discover/movie?" static var api_key: String = url + "api_key=ceb888b71023afda704f84975d2642b5" }
// // SuggestListModel.swift // NewSwift // // Created by gail on 2019/8/1. // Copyright © 2019 NewSwift. All rights reserved. // import UIKit import ObjectMapper class SuggestListModel: Mappable { var page : Page? var array : [SuggestModel]? var code = "" var message = "" required init?(map: Map){} func mapping(map: Map){ page <- map["Page"] array <- map["Data"] code <- map["Code"] message <- map["Message"] } } class SuggestModel: Mappable{ lazy var stateArr = ["待处理","已处理","继续跟踪"] var FeedbackId = "" var InsId = "" var SchoolName = "" var UserType = 0 var UserId = "" var UserName = "" var Mobile = "" var FeedbackTime = "" var FeedbackType = 0 var Title = "" var Content = "" var UserRead = 0 var opState = "" var OpState = 0 { didSet{ opState = stateArr[OpState] } } var OpContent = "" var OpTime = "" required init?(map: Map){} func mapping(map: Map){ FeedbackId <- map["FeedbackId"] InsId <- map["InsId"] SchoolName <- map["SchoolName"] UserType <- map["UserType"] UserId <- map["UserId"] UserName <- map["UserName"] Mobile <- map["Mobile"] FeedbackTime <- map["FeedbackTime"] FeedbackType <- map["FeedbackType"] Title <- map["Title"] Content <- map["Content"] UserRead <- map["UserRead"] OpState <- map["OpState"] OpContent <- map["OpContent"] OpTime <- map["OpTime"] } }
// // ResponseSerializer.swift // ZapAnimatableCell // // Created by Alessio Boerio on 29/03/2019. // Copyright © 2019 Alessio Boerio. All rights reserved. // import Foundation import Alamofire import Argo enum ZErrorCode: Int { case unknown // connection error case noInternetConnection = 9999 // server errors case badRequest = 400 case unauthorized = 401 case forbidden = 403 case notFound = 404 case serverError = 500 case serverDown = 503 // app errors case jsonSerialization = -6006 case emptyArray = -2222 static func create(withCode code: Int?) -> ZErrorCode { return code == nil ? .unknown : (ZErrorCode(rawValue: code!) ?? .unknown) } } struct ZError: Error { let code: ZErrorCode let description: String init(_ code: ZErrorCode, description aDescription: String) { self.code = code self.description = aDescription } init(_ error: NSError) { code = ZErrorCode.create(withCode: error.code) description = error.description } init(_ serviceCode: ServiceCode, description aDescription: String) { self.description = aDescription switch serviceCode { default: code = .unknown } } } enum Resource<T> { case found(T) case notFound(ZError) } enum ResourceWithError<T, E: ServiceError> { case success(T?) case clientError (E?) case error(ZError) } enum Result { case success case failure(ZError) } extension DataRequest { @discardableResult func responseObject<T: Argo.Decodable>(keyName: String? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self where T == T.DecodedType { let responseSerializer = DataResponseSerializer<T> { request, response, data, error in guard error == nil, let response = response else { let errDesc = error?.localizedDescription ?? "unknown" return .failure(ZError(ZErrorCode.unknown, description: errDesc)) } let JSONResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { //Response contains a valid JSON case .success(let value): let value = value as AnyObject print("\(value)") //Status code 2XX: expecting a resource object if case 200 ... 299 = response.statusCode { //Process headers //Check if JSON contains a valid resource object let obj: Decoded<T> if keyName != nil, let subValue = value[keyName!], subValue != nil { obj = decode(subValue!) } else { obj = decode(value) } switch (obj) { //Object successfully decoded from JSON case let .success(value): return .success(value) //JSON format unexpected case .failure(let err): return .failure(ZError(.jsonSerialization, description: "JSON format unexpected: \(err.description)")) } } //Status code 401: invalid user session else if case 401 = response.statusCode { //self.endSession() return .failure(ZError(.unauthorized, description: "401: unauthorized")) } //Status code 4XX/5XX: expecting an error object else { print("status code \(response.statusCode)") if case 500 ... 599 = response.statusCode { if let vc = UIApplication.z_topViewController() { UIAlertController.z_showOkAlertController(in: vc, withTitle: "Errore", andMessage: "Servizio temporaneamente offline, riprova tra un po'.") } } return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Error code: \(response.statusCode)")) } //Response does not contain a valid JSON case .failure(let error): return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Desc: \(error.localizedDescription)")) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } @discardableResult func responseCollection<T: Argo.Decodable>(arrayName: String = "objects", completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self where T == T.DecodedType { let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in guard error == nil, let response = response else { let errDesc = error?.localizedDescription ?? "unknown" return .failure(ZError(ZErrorCode.unknown, description: errDesc)) } let JSONResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { //Response contains a valid JSON case .success(let value): let value = value as AnyObject print("\(value)") //Status code 2XX: expecting a resource object if case 200 ... 299 = response.statusCode { //Process headers //Check if JSON contains a valid resource object if let params = value[arrayName], params != nil { let obj: Decoded<[T]> = decode(params!) switch (obj) { //Object successfully decoded from JSON case let .success(value): return .success(value) //JSON format unexpected case .failure(let err): return .failure(ZError(.jsonSerialization, description: "JSON format unexpected: \(err.description)")) } } print("no objects array found") return .failure(ZError(.jsonSerialization, description: "No objects array found")) } //Status code 401: invalid user session else if case 401 = response.statusCode { //self.endSession() return .failure(ZError(.unauthorized, description: "401: unauthorized")) } //Status code 4XX/5XX: expecting an error object else { print("status code \(response.statusCode)") if case 500 ... 599 = response.statusCode { if let vc = UIApplication.z_topViewController() { UIAlertController.z_showOkAlertController(in: vc, withTitle: "Errore", andMessage: "Servizio temporaneamente offline, riprova tra un po'.") } } return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Error code: \(response.statusCode)")) } //Response does not contain a valid JSON case .failure(let error): return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Desc: \(error.localizedDescription)")) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } @discardableResult func responseArray<T: Argo.Decodable>(completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self where T == T.DecodedType { let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in guard error == nil, let response = response else { let errDesc = error?.localizedDescription ?? "unknown" return .failure(ZError(ZErrorCode.unknown, description: errDesc)) } let JSONResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { //Response contains a valid JSON case .success(let value): print("\(value)") //Status code 2XX: expecting a resource object if case 200 ... 299 = response.statusCode { //Process headers //Check if JSON contains a valid resource object let obj: Decoded<[T]> = decode(value) switch (obj) { //Object successfully decoded from JSON case let .success(value): return .success(value) //JSON format unexpected case .failure(let err): return .failure(ZError(.jsonSerialization, description: "JSON format unexpected: \(err.description)")) } } //Status code 401: invalid user session else if case 401 = response.statusCode { //self.endSession() return .failure(ZError(.unauthorized, description: "401: unauthorized")) } //Status code 4XX/5XX: expecting an error object else { print("status code \(response.statusCode)") if case 500 ... 599 = response.statusCode { if let vc = UIApplication.z_topViewController() { UIAlertController.z_showOkAlertController(in: vc, withTitle: "Errore", andMessage: "Servizio temporaneamente offline, riprova tra un po'.") } } return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Error code: \(response.statusCode)")) } //Response does not contain a valid JSON case .failure(let error): return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Desc: \(error.localizedDescription)")) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } @discardableResult func responseServiceObject<T: Argo.Decodable, E: ServiceError>(completionHandler: @escaping (DataResponse<ServiceResult<T, E>>) -> Void) -> Self where T == T.DecodedType, E == E.DecodedType { let responseSerializer = DataResponseSerializer<ServiceResult<T, E>> { request, response, data, error in guard error == nil, let response = response else { let errDesc = error?.localizedDescription ?? "unknown" return .failure(ZError(ZErrorCode.unknown, description: errDesc)) } let JSONResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { //Response contains a valid JSON case .success(let value): let value = value as AnyObject print("\(value)") //Status code 2XX: expecting a resource object if case 200 ... 299 = response.statusCode { let decoded: Decoded<ServiceResult<T, E>> = decode(value) switch decoded { case .success(let serviceResult): return .success(serviceResult) case .failure(let err): return .failure(ZError(.jsonSerialization, description: "JSON format unexpected: \(err.description)")) } } //Status code 401: invalid user session else if case 401 = response.statusCode { //self.endSession() return .failure(ZError(.unauthorized, description: "401: unauthorized")) } //Status code 4XX/5XX: expecting an error object else { print("status code \(response.statusCode)") if case 500 ... 599 = response.statusCode { if let vc = UIApplication.z_topViewController() { UIAlertController.z_showOkAlertController(in: vc, withTitle: "Errore", andMessage: "Servizio temporaneamente offline, riprova tra un po'.") } } return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Error code: \(response.statusCode)")) } //Response does not contain a valid JSON case .failure(let error): return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Desc: \(error.localizedDescription)")) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } @discardableResult func responseServiceCollection<T: Argo.Decodable, E: ServiceError>(completionHandler: @escaping (DataResponse<ServiceResultCollection<T, E>>) -> Void) -> Self where T == T.DecodedType, E == E.DecodedType { let responseSerializer = DataResponseSerializer<ServiceResultCollection<T, E>> { request, response, data, error in guard error == nil, let response = response else { let errDesc = error?.localizedDescription ?? "unknown" return .failure(ZError(ZErrorCode.unknown, description: errDesc)) } let JSONResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { //Response contains a valid JSON case .success(let value): let value = value as AnyObject print("\(value)") //Status code 2XX: expecting a resource object if case 200 ... 299 = response.statusCode { let decoded: Decoded<ServiceResultCollection<T, E>> = decode(value) switch decoded { case .success(let serviceResult): return .success(serviceResult) case .failure(let err): return .failure(ZError(.jsonSerialization, description: "JSON format unexpected: \(err.description)")) } } //Status code 401: invalid user session else if case 401 = response.statusCode { //self.endSession() return .failure(ZError(.unauthorized, description: "401: unauthorized")) } //Status code 4XX/5XX: expecting an error object else { print("status code \(response.statusCode)") if case 500 ... 599 = response.statusCode { if let vc = UIApplication.z_topViewController() { UIAlertController.z_showOkAlertController(in: vc, withTitle: "Errore", andMessage: "Servizio temporaneamente offline, riprova tra un po'.") } } return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Error code: \(response.statusCode)")) } //Response does not contain a valid JSON case .failure(let error): return .failure(ZError(ZErrorCode(rawValue: response.statusCode) ?? .unknown, description: "Desc: \(error.localizedDescription)")) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } }
// // ClampPIX.swift // PixelKit // // Created by Anton Heestand on 2019-04-01. // import Foundation import CoreGraphics import RenderKit import Resolution final public class ClampPIX: PIXSingleEffect, PIXViewable { override public var shaderName: String { return "effectSingleClampPIX" } // MARK: - Public Properties @LiveFloat("low", range: 0.0...1.0) public var low: CGFloat = 0.0 @LiveFloat("high", range: 0.0...1.0) public var high: CGFloat = 1.0 @LiveBool("clampAlpha") public var clampAlpha: Bool = false public enum Style: String, Enumable { case hold case relative case loop case mirror case zero public var index: Int { switch self { case .hold: return 0 case .loop: return 1 case .mirror: return 2 case .zero: return 3 case .relative: return 4 } } public var typeName: String { rawValue } public var name: String { switch self { case .hold: return "Hold" case .relative: return "Relative" case .loop: return "Loop" case .mirror: return "Mirror" case .zero: return "Zero" } } } @LiveEnum("style") public var style: Style = .hold // MARK: - Property Helpers public override var liveList: [LiveWrap] { [_low, _high, _clampAlpha, _style] } override public var values: [Floatable] { [low, high, clampAlpha, style] } // MARK: - Life Cycle public required init() { super.init(name: "Clamp", typeName: "pix-effect-single-clamp") } required init(from decoder: Decoder) throws { try super.init(from: decoder) } } public extension NODEOut { func pixClamp(low: CGFloat = 0.0, high: CGFloat = 1.0) -> ClampPIX { let clampPix = ClampPIX() clampPix.name = ":clamp:" clampPix.input = self as? PIX & NODEOut clampPix.low = low clampPix.high = high return clampPix } }
//: [Previous](@previous) class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { guard nums.count > 0 else { return 0 } var index = 0 while index < nums.count { let num = nums[index] if num == val { nums.remove(at: index) } else { index += 1 } } return nums.count } } //: [Next](@next)
// // AppFont.swift // homefinancing // // Created by 辰 宫 on 4/6/16. // Copyright © 2016 wph. All rights reserved. // func AppFont(_ size:CGFloat) -> UIFont { return UIFont.systemFont(ofSize: size) }
// // TemplateExample.swift // 100Views // // Created by Mark Moeykens on 9/27/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct MyBasicTemplate: View { var body: some View { VStack(spacing: 20) { // 20 points of space between each item in the VStack Text("Title") // Shows text on the screen .font(.largeTitle) // Format text to be largest Text("Subtitle") .font(.title) // Format text to be second largest .foregroundColor(.gray) // Change color of text to gray Text("Short description of what I am demonstrating goes here.") .frame(maxWidth: .infinity) // Extend until you can't go anymore .padding() // Add space all around this text .font(.title) // Format text to be second largest .background(Color.blue) // Add the color blue behind the text .foregroundColor(Color.white) // Change text color to white .layoutPriority(1) Text("(Content of what I am demonstrating goes here.)") .font(.title) } } } struct MyBasicTemplate_Previews: PreviewProvider { static var previews: some View { MyBasicTemplate() } }
import UIKit class ViewController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Spinner instance let spinner = TDSwiftSpinner(viewController: self) // Show spinner spinner.show() } }
// // SampeView.swift // UIAnimation // // Created by ayako_sayama on 2017-07-07. // Copyright © 2017 ayako_sayama. All rights reserved. // import UIKit class SampleView: UIView { override init(frame: CGRect) { super.init(frame:frame ) loadXibView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadXibView() } func loadXibView() { let view = Bundle.main.loadNibNamed("SampleView", owner: self, options: nil)?.first as! UIView view.frame = self.bounds self.addSubview(view) } }
// // AppState.swift // Dash // // Created by Yuji Nakayama on 2021/05/29. // Copyright © 2021 Yuji Nakayama. All rights reserved. // import UIKit import MapKit class AppState { static let activityType = "com.yujinakayama.Dash.AppState" let window: UIWindow init(window: UIWindow) { self.window = window } var userActivityForPreservation: NSUserActivity { let preservation = Preservation(app: app) return preservation.userActivity } func restore(from userActivity: NSUserActivity) { guard let restoration = Restoration(userActivity: userActivity, app: app) else { return } restoration.perform() } private var app: App { return App(window: window) } } extension AppState { class App { let window: UIWindow init(window: UIWindow) { self.window = window } lazy var storyboard = UIStoryboard(name: "Main", bundle: nil) var tabBarController: TabBarController { return window.rootViewController as! TabBarController } var dashboardViewController: DashboardViewController? { return tabBarController.viewController(for: .dashboard) as? DashboardViewController } var etcSplitViewController: ETCSplitViewController? { return tabBarController.viewController(for: .etc) as? ETCSplitViewController } var mapsViewController: MapsViewController? { let navigationController = tabBarController.viewController(for: .maps) as? UINavigationController return navigationController?.viewControllers.first as? MapsViewController } } } extension AppState { class Preservation { let app: App init(app: App) { self.app = app } var userActivity: NSUserActivity { let userActivity = NSUserActivity(activityType: AppState.activityType) userActivity.userInfo = userInfo return userActivity } private var userInfo: [AnyHashable: Any] { let userInfo = AppState.propertyTypes.reduce(into: [String: Any]()) { (partialResult, type) in let property = type.init(app: app) if let value = property.serialize() { partialResult[property.key] = value } } logger.debug(userInfo) return userInfo } } } extension AppState { class Restoration { let userActivity: NSUserActivity let app: App init?(userActivity: NSUserActivity, app: App) { guard userActivity.activityType == AppState.activityType else { return nil } self.userActivity = userActivity self.app = app } func perform() { guard let userInfo = userActivity.userInfo else { return } UIView.performWithoutAnimation { for type in AppState.propertyTypes { let property = type.init(app: app) if let value = userInfo[property.key] { property.restore(value) } } } } } } extension AppState { class Property { let app: App required init(app: AppState.App) { self.app = app } var key: String { return String(describing: Self.self) } func serialize() -> Any? { return nil } func restore(_ value: Any) { } } class SelectedTab: Property { override func serialize() -> Any? { return app.tabBarController.selectedIndex } override func restore(_ value: Any) { guard let value = value as? Int else { return } app.tabBarController.selectedIndex = value } } class DashboardLayoutMode: Property { override func serialize() -> Any? { return app.dashboardViewController?.currentLayoutMode.rawValue } override func restore(_ value: Any) { guard let value = value as? Int, let mode = DashboardViewController.LayoutMode(rawValue: value) else { return } app.dashboardViewController?.switchLayout(to: mode) } } class SelectedWidgetPage: Property { override func serialize() -> Any? { return app.dashboardViewController?.widgetViewController.currentPage } override func restore(_ value: Any) { guard let value = value as? Int else { return } app.dashboardViewController?.widgetViewController.currentPage = value } } class DisplayedETCPaymentHistory: Property { override func serialize() -> Any? { guard let paymentTableViewController = app.etcSplitViewController?.masterNavigationController.topViewController as? ETCPaymentTableViewController else { return nil } if let card = paymentTableViewController.card { return card.uuid.uuidString } else { return NSNull() } } override func restore(_ value: Any) { let paymentTableViewController = app.storyboard.instantiateViewController(identifier: "ETCPaymentTableViewController") as! ETCPaymentTableViewController if let value = value as? String, let cardUUID = UUID(uuidString: value) { paymentTableViewController.restoreCard(for: cardUUID) } else if value is NSNull { paymentTableViewController.card = nil } else { return } app.etcSplitViewController?.masterNavigationController.pushViewController(paymentTableViewController, animated: false) } } class MapsMapType: Property { override func serialize() -> Any? { return app.mapsViewController?.mapView.mapType.rawValue } override func restore(_ value: Any) { guard let value = value as? UInt, let mapType = MKMapType(rawValue: value) else { return } guard let mapsViewController = app.mapsViewController else { return } mapsViewController.mapTypeSegmentedControl.selectedMapType = mapType mapsViewController.mapTypeSegmentedControlDidChange() } } // We should order these in inner to outer order // to avoid "Unbalanced calls to begin/end appearance transitions" (view[Will/Did][Appear/Disappear]). static let propertyTypes: [Property.Type] = [ SelectedWidgetPage.self, DashboardLayoutMode.self, DisplayedETCPaymentHistory.self, MapsMapType.self, SelectedTab.self, ] }
// // newTableViewCell.swift // flowerheader_Footer // // Created by Mac on 21/09/19. // Copyright © 2019 Mac. All rights reserved. // import UIKit class newTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBOutlet weak var flowerimg: UIImageView! @IBOutlet weak var flowername: UILabel! override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // PersistHero.swift // MarvelsApp // // Created by aliunco on 3/11/19. // Copyright © 2019 Zibazi. All rights reserved. // import Foundation extension Character: DefaultStorable { static private var localValue: Character? static private var hasLocalValue: Bool = { Character.localValue = Character.localValue ?? Character.read(forKey: Character.defaultIdentifier) return Character.localValue != nil }() static var shared: Character? { get { if !Character.hasLocalValue { return nil } Character.localValue = Character.localValue ?? Character.read(forKey: Character.defaultIdentifier) return Character.localValue } } static func clear() { Character.hasLocalValue = false Character.localValue = nil UserDefaults.standard.removeObject(forKey: self.defaultIdentifier) } func write() { Character.hasLocalValue = true Character.localValue = self UserDefaults.standard.df.store(self, forKey: Character.defaultIdentifier) } }
// // XRPTransaction.swift // XRPKit // // Created by Mitch Lang on 5/10/19. // import Foundation import NIO public class XRPTransaction: XRPRawTransaction { var wallet: XRPWallet @available(*, unavailable) override init(fields: [String:Any]) { fatalError() } internal init(wallet: XRPWallet, fields: [String:Any]) { self.wallet = wallet var _fields = fields _fields["Account"] = wallet.address super.init(fields: _fields) } // autofills ledger sequence, fee, and sequence func autofill() -> EventLoopFuture<XRPTransaction> { let promise = eventGroup.next().makePromise(of: XRPTransaction.self) // network calls to retrive current account and ledger info _ = XRPLedger.currentLedgerInfo().map { (ledgerInfo) in _ = XRPLedger.getAccountInfo(account: self.wallet.address).map { (accountInfo) in // dictionary containing transaction fields let filledFields: [String:Any] = [ "LastLedgerSequence" : ledgerInfo.index+5, "Fee" : "40", // FIXME: determine fee automatically "Sequence" : accountInfo.sequence, ] self.fields = self.fields.merging(self.enforceJSONTypes(fields: filledFields)) { (_, new) in new } promise.succeed(self) }.recover { (error) in promise.fail(error) } }.recover { (error) in promise.fail(error) } return promise.futureResult } public func send() -> EventLoopFuture<NSDictionary> { let promise = eventGroup.next().makePromise(of: NSDictionary.self) // autofill missing transaction fields (online) _ = self.autofill().map { (tx) in // sign the transaction (offline) let signedTransaction = try! tx.sign(wallet: tx.wallet) // submit the transaction (online) _ = signedTransaction.submit().map { (dict) in promise.succeed(dict) }.recover { (error) in promise.fail(error) } }.recover { (error) in promise.fail(error) } return promise.futureResult } }
// // StatsTests.swift // DemoEPOS // // Created by Fortes, Francisco on 7/25/17. // Copyright © 2017 Wirecard. All rights reserved. // import Foundation import XCTest import WDePOS enum paymentOperation { case regularCard case cardAuth case cardPreAuth } class SpireTestsSwift: BaseTestsSwift, WDManagerDelegate { var configCompletionStatus : WDUpdateConfigurationStatus! /* IMPORTANT NOTE: -This test requires an actual iOS device (not simulator). -You have to have a Spire terminal paired through your iOS device settings. -Your terminal must have been provided by Wirecard, and be turned on. -If your backend settings include cash management with mandatory cash registers, you will need to run CashTests first (to have valid ids) */ override func setUp() { super.setUp() } func setupSpire() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else //PART 1: We log-in and request user data //-------------------------------------- if (loggedUser == nil || (loggedUser?.isKind(of: WDMerchantUser.self)) == false) { XCTFail("Error, did not return Merchant User. Are your credentials correct? Try login into the backend through internet browser.") } else { UserHelper.sharedInstance().setUser(loggedUser) } //PART 2: We discover Spire terminals //paired to your iOS device. //-------------------------------------- expectation = self.expectation(description: "Discovering devices") self.discoverDevices(.WDPosMateExtensionUUID) self.waitForExpectations(timeout: 100, handler: nil) if (self.selectedDevice == nil) { XCTFail("No paired terminal found. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } else { sdk.terminalManager.add(self, forDevice: selectedDevice!) } //PART 3: We check for updates on the terminal //--------------------------------------------- expectation = self.expectation(description: "Checking for terminal update") self.checkingForTerminalConfigUpdates() self.waitForExpectations(timeout: 300, handler: nil) if (self.configCompletionStatus == .failure) { XCTFail("Error when updating the terminal. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } #endif } func testCardPurchaseAndRefund() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else setupSpire() doPurchaseAndRefund() #endif } func testAuthorisedAndCapture() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else setupSpire() doAuthorisedAndCapture() #endif } func testPreAuthorisedAndSupplement() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else setupSpire() doPreAuthorisedAndSupplement() #endif } func testSepaEFTPayment() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else setupSpire() doSepaEFTPayment() #endif } func doPurchaseAndRefund() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else //PART 4: We do a card sale using Spire terminal //--------------------------------------------- expectation = self.expectation(description: "Card sale") self.doCardPayment(paymentOperation: .regularCard) self.waitForExpectations(timeout: 300, handler: nil) if (self.saleResponse == nil) { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") //NOTE: if your merchant settings have cash mgmt enabled in backend, you will need to run cash tests first - otherwise you will receive a "not authorized" kind of error } else { SaleHelper.sharedInstance().saleToSaveId(from:self.saleResponse) } //PART 5: We refund the sale we just did //(for testing purposes; this is important if you develop using an actual credit card) //Algo note that refunds are allowed only for some period of time (ie: midnight on current time, or next 24 hours, etc) and after that, only reversals are allowed. But refunds are for free, while reversals actually cost money (so use reversals responsibly!) //------------------------------------------- expectation = self.expectation(description: "Refund sale") self.refundTransaction() self.waitForExpectations(timeout: 300, handler: nil) if let response = self.saleResponse, response.status != .returned && response.status != .partiallyReturned { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } else if self.saleResponse == nil { XCTFail("Sale response empty. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } #endif } func doAuthorisedAndCapture() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else //PART 4: We do a card sale using Spire terminal //--------------------------------------------- expectation = self.expectation(description: "Card auth") self.doCardPayment(paymentOperation: .cardAuth) self.waitForExpectations(timeout: 300, handler: nil) if (self.saleResponse == nil) { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") //NOTE: if your merchant settings have cash mgmt enabled in backend, you will need to run cash tests first - otherwise you will receive a "not authorized" kind of error } else { SaleHelper.sharedInstance().saleToSaveId(from:self.saleResponse) } //PART 5: We capture the sale we just did //(for testing purposes; this is important if you develop using an actual credit card) //Algo note that refunds are allowed only for some period of time (ie: midnight on current time, or next 24 hours, etc) and after that, only reversals are allowed. But refunds are for free, while reversals actually cost money (so use reversals responsibly!) //------------------------------------------- expectation = self.expectation(description: "Capture the auth") self.captureSale() self.waitForExpectations(timeout: 300, handler: nil) if let response = self.saleResponse, let payment = response.payments.first as? WDPaymentDetail, payment.status != .captured { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } else if self.saleResponse == nil { XCTFail("Sale response empty. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } #endif } func doPreAuthorisedAndSupplement() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else //PART 4: We do a card pre-auth using Spire terminal //--------------------------------------------- expectation = self.expectation(description: "Card pre-auth") self.doCardPayment(paymentOperation: .cardPreAuth) self.waitForExpectations(timeout: 300, handler: nil) if (self.saleResponse == nil) { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") //NOTE: if your merchant settings have cash mgmt enabled in backend, you will need to run cash tests first - otherwise you will receive a "not authorized" kind of error } else { SaleHelper.sharedInstance().saleToSaveId(from:self.saleResponse) } //PART 5: We add a supplement to the previous pre-auth payment (to increase the pre-auth amount on the sale) //------------------------------------------- expectation = self.expectation(description: "Add supplement to pre-auth") self.addSupplement() self.waitForExpectations(timeout: 300, handler: nil) if let response = self.saleResponse, let payment = response.payments.first as? WDPaymentDetail, payment.status != .completed { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } else if self.saleResponse == nil { XCTFail("Sale response empty. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") } #endif } func checkingForTerminalConfigUpdates() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else let completionUpdate : UpdateTerminalCompletion = {[weak self](updStatus : WDUpdateConfigurationStatus?, updError : Error?) in //Note that completion here will happen when: // 1- The update has been completed, but also the terminal has fully restarted and entered stand-by (this may take a couple of minutes in the case of firmware) // 2- There was no response from terminal (something went wrong) for several seconds, meaning update failed. self?.returnedErr = updError self?.configCompletionStatus = updStatus self?.expectation.fulfill() } let progress : UpdateConfigurationProgress = {(progressUpdate : WDUpdateConfigurationProgressUpdate) in print("Terminal update progress: \(progressUpdate.rawValue)") } //Note: You may update the application (Spire devices) or firmware (others) using WDTerminalUpdateTypeApplication or WDTerminalUpdateTypeFirmware in updateType below //Note: The accept SDK will keep track of what version was previously installed, and decide if an update is required by comparing with the latest in backend. //This means, the first time you run this test, the configuration will be updated on the terminal. A second time will tell you "WDUpdateConfigurationStatusUnnecessary" //To force the actual update again you will have to remove the demo app from your iOS device and re-run the test. sdk.terminalManager.update(selectedDevice!, updateType:WDTerminalUpdateTypeMaskConfiguration, progress:progress, completion:completionUpdate) #endif } func doCardPayment(paymentOperation : paymentOperation) { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else guard let sale = SaleHelper.sharedInstance().newSale() else { XCTFail("Something went really wrong - doCardPayment") self.expectation.fulfill() return } self.aSale = sale self.aSale.cashRegisterId = UserHelper.sharedInstance()?.selectedCashRegisterId() ?? "" self.aSale.addSaleItem(NSDecimalNumber(string: "3.4"), quantity:NSDecimalNumber(string: "5"), taxRate:UserHelper.sharedInstance().preferredSaleItemTax(), itemDescription:"Red Apple", productId:"Dummy ID 1", externalProductId : nil) self.aSale.addSaleItem(NSDecimalNumber(string: "2.25"), quantity:NSDecimalNumber(string: "3"), taxRate:UserHelper.sharedInstance().preferredSaleItemTax(), itemDescription:"Orange", productId:"Dummy ID 2", externalProductId : nil) //You can add a service charge to the whole basket -- but this is optional self.aSale.addServiceChargeRate(UserHelper.sharedInstance().serviceChargeRate(), taxRate:UserHelper.sharedInstance().serviceChargeTax()) //You can add a tip of any value you want. Notice that backend validate taxes, so their values should match the ones your merchant has defined in setup. self.aSale.addGratuity(NSDecimalNumber(string: "1.0"), taxRate:UserHelper.sharedInstance().tipTax()) //You can add a discount for the whole basket when productId is nil, or per productId otherwise. Below, a discount of 6% self.aSale.addFlatDiscount(NSDecimalNumber(string: "6.0")) // self.aSale.cashRegisterId = UserHelper.sharedInstance().selectedCashRegisterId() //Note: if your backend settings have cash mgmt enabled in backend, you will need to run cash tests first to get this value as well as shiftId below self.aSale.shiftId = UserHelper.sharedInstance().lastShiftId() self.aSale.resetPayments() if paymentOperation == .cardAuth { self.aSale.addCardAuthorization(self.aSale.totalToPay() ?? .zero, terminal:self.selectedDevice!) } else if paymentOperation == .regularCard { self.aSale.addCardPayment(self.aSale.totalToPay() ?? .zero, terminal:self.selectedDevice!) } else if paymentOperation == .cardPreAuth { self.aSale.addCardPreAuthorization(NSDecimalNumber(string: "5"), terminal: self.selectedDevice!) } if let paymentConfiguration : WDSaleRequestConfiguration = WDSaleRequestConfiguration.init(saleRequest: self.aSale) { sdk.terminalManager.setActive(self.selectedDevice, completion:{[weak self]() in self?.sdk.saleManager.pay(paymentConfiguration, with: (self?.paymentHandler)!) }) } #endif } func refundTransaction() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else guard let saleToBeRefunded = self.saleResponse!.saleReturn() else { XCTFail("Something went really wrong - refundTransaction saleReturn") self.expectation.fulfill() return } //This is an example of full refund: all items are refunded, EXCEPT SERVICE CHARGE and GRATUITY saleToBeRefunded.removeServiceCharge() saleToBeRefunded.removeGratuity() guard let totalToPay = saleToBeRefunded.totalToPay() else { XCTFail("Something went really wrong - refundTransaction totalToPay") self.expectation.fulfill() return } saleToBeRefunded.cashRegisterId = UserHelper.sharedInstance().selectedCashRegisterId() //saleToBeRefunded.cashierId = self.aSale.cashierId saleToBeRefunded.customerId = self.aSale.customerId //This is an example of full refund: all items are refunded, EXCEPT SERVICE CHARGE saleToBeRefunded.removeServiceCharge() //For partial refund, see CashTests example saleToBeRefunded.addCardPayment(totalToPay, terminal:WDTerminal.init()) //terminal is unnecessary here self.saleResponse = nil sdk.saleManager.refundSale(saleToBeRefunded, message:"Refunded in demo app for testing reasons", completion:{[weak self](acceptSale : WDSaleResponse?, error : Error?) in self?.returnedErr = error self?.saleResponse = acceptSale self?.expectation.fulfill() }) #endif } func captureSale() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else guard let saleToBeCaptured = self.saleResponse else { XCTFail("Something went really wrong - no sale to capture") self.expectation.fulfill() return } let refSaleRequest = saleToBeCaptured.referenceSaleRequest() refSaleRequest.addCardCapture(saleToBeCaptured.totalToPay() ?? NSDecimalNumber.one, originalPaymentId: saleToBeCaptured.processedCardPayments().first?.internalId ?? "") if let paymentConfiguration = WDSaleRequestConfiguration(saleRequest: refSaleRequest) { sdk.terminalManager.setActive(self.selectedDevice, completion:{[weak self]() in self?.sdk.saleManager.pay(paymentConfiguration, with: (self?.paymentHandler)!) }) } #endif } func addSupplement() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else guard let currentSale = self.saleResponse else { XCTFail("Something went really wrong - no sale to capture") self.expectation.fulfill() return } let refSaleRequest = currentSale.referenceSaleRequest() refSaleRequest.addCardPreAuthorizationSupplement(NSDecimalNumber.one, originalTransactionId: currentSale.processedCardPayments().first?.internalId ?? "", authorizationCode:currentSale.processedCardPayments().first?.authorizationCode ?? "") if let paymentConfiguration = WDSaleRequestConfiguration(saleRequest: refSaleRequest) { sdk.terminalManager.setActive(self.selectedDevice, completion:{[weak self]() in self?.sdk.saleManager.pay(paymentConfiguration, with: (self?.paymentHandler)!) }) } #endif } func doSepaEFTPayment() { #if arch(i386) || arch(x86_64) let file:NSString = (#file as NSString).lastPathComponent as NSString NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function); return #else //PART 4: We do a card sale using Spire terminal //--------------------------------------------- expectation = self.expectation(description: "SEPA EFT sale") guard let sale = SaleHelper.sharedInstance().newSale() else { XCTFail("Something went really wrong - doSepaEFTPayment") self.expectation.fulfill() return } self.aSale = sale self.aSale.cashRegisterId = UserHelper.sharedInstance()?.selectedCashRegisterId() ?? "" self.aSale.addSaleItem(NSDecimalNumber(string: "3.4"), quantity:NSDecimalNumber(string: "5"), taxRate:UserHelper.sharedInstance().preferredSaleItemTax(), itemDescription:"Red Apple", productId:"Dummy ID 1", externalProductId : nil) // self.aSale.cashRegisterId = UserHelper.sharedInstance().selectedCashRegisterId() //Note: if your backend settings have cash mgmt enabled in backend, you will need to run cash tests first to get this value as well as shiftId below self.aSale.shiftId = UserHelper.sharedInstance().lastShiftId() self.aSale.resetPayments() self.aSale.addEFTCardPayment(self.aSale.totalToPay() ?? .zero, terminal:self.selectedDevice!) if let paymentConfiguration : WDSaleRequestConfiguration = WDSaleRequestConfiguration.init(saleRequest: self.aSale) { sdk.terminalManager.setActive(self.selectedDevice, completion:{[weak self]() in self?.sdk.saleManager.pay(paymentConfiguration, with: (self?.paymentHandler)!) }) } self.waitForExpectations(timeout: 300, handler: nil) if (self.saleResponse == nil) { XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).") //NOTE: if your merchant settings have cash mgmt enabled in backend, you will need to run cash tests first - otherwise you will receive a "not authorized" kind of error } else { SaleHelper.sharedInstance().saleToSaveId(from:self.saleResponse) } #endif } func device(_ device: WDTerminal, connectionStatusDidChange status:WDExtensionConnectionStatus) { print("Connection status changed \(status)") } func discoverDevices(_ extensionUUID: WDExtensionTypeUUID) { sdk.terminalManager.discoverDevices(extensionUUID, completion: {[weak self](arr : [WDTerminal]?, error : Error?) in self?.selectedDevice = arr?.first self?.returnedErr = error self?.expectation.fulfill() }) } }
import Foundation struct Card { let suit: Suit let rank: Rank let deckNumber: Int } extension Card { init(id: Int) { guard 8 ... 115 ~= id else { fatalError("Unable to initialize card. Invalid ID") } if id >= 114 { self.suit = .rightBower self.rank = .rightBower self.deckNumber = id % 114 + 1 } else if id >= 112 { self.suit = .leftBower self.rank = .leftBower self.deckNumber = id % 112 + 1 } else { let suit = id % 4 self.suit = Suit(rawValue: suit)! let rank = id / 8 self.rank = Rank(rawValue: rank)! let deckNumber = id % 8 < 4 ? 1 : 2 self.deckNumber = deckNumber } } init(string: String) { let stringArray = Array(string) if let deckNumberString = string.last, let deckNumber = Int(String(deckNumberString)) { self.deckNumber = deckNumber } else { fatalError("Invalid deck number") } if string.lowercased().starts(with: "rb") || string.lowercased().starts(with: "lb") { if string.lowercased().starts(with: "rb") { self.rank = .rightBower self.suit = .rightBower } else { self.rank = .leftBower self.suit = .leftBower } return } guard 3 ... 4 ~= string.count else { fatalError("Invalid string") } guard let suit = stringArray.first else { fatalError("Invalid suit") } switch suit.lowercased() { case "♦️", "d": self.suit = .diamonds case "♠️", "s": self.suit = .spades case "❤️", "h": self.suit = .hearts case "♣️", "c": self.suit = .clubs default: fatalError("Invalid suit") } let rank: String if string.count == 3 { rank = String(stringArray[1]) } else { rank = String(stringArray[1...2]) } switch rank.lowercased() { case "k": self.rank = .king case "q": self.rank = .queen case "j": self.rank = .jack case "a": self.rank = .ace default: if let rank = Int(rank), let rankEnum = Rank(rawValue: rank) { self.rank = rankEnum } else { fatalError("Invalid rank") } } } } // Bowers extension Card { static let leftBower = Card(suit: .leftBower, rank: .leftBower, deckNumber: 1) static let rightBower = Card(suit: .rightBower, rank: .rightBower, deckNumber: 1) var isBower: Bool { rank == .rightBower || rank == .leftBower } } extension Card { var cardID: Int { if rank == .leftBower { return 112 + deckNumber - 1 } else if rank == .rightBower { return 114 + deckNumber - 1 } else{ return 8 * rank.rawValue + suit.rawValue + (deckNumber - 1) * 4 } } } extension Card: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(cardID) } } extension Card: CustomStringConvertible { var description: String { "\(suit)\(rank)(\(deckNumber))" } }
// // CoreFilesConfig.swift // CoreKit // // Created by Vishal on 09/01/19. // Copyright © 2019 Vishal. All rights reserved. // import UIKit public struct CoreFilesConfig { public var enabledFileTypes: [CoreMediaTypes] = [CoreMediaTypes.image, .audio, .video, .document, .other] public var maxSizeInBytes: UInt = 209715200 public var rotateImageIfRequired: Bool = true public var enableResizingImage: Bool = false var maxResolution: CGFloat = 1024 static var maxSizeAllowedToUploadInMB: UInt { let maxSizeInBytes = CoreKit.shared.filesConfig.maxSizeInBytes return maxSizeInBytes / (1024 * 1024) } public init() { } public init(json: [String: Any]) { } static func defaultConfig() -> CoreFilesConfig { let config = CoreFilesConfig(json: [:]) return config } public func toJson() -> [String: Any] { var dict = [String: Any]() let rawSupportedFileTypes = enabledFileTypes.map {$0.rawValue} dict["supported_file_type"] = rawSupportedFileTypes dict["max_upload_file_size"] = self.maxSizeInBytes return dict } public func checkForDataSelectionLimit(url: URL) -> Bool { do { let dataCountInMB = try Data.init(contentsOf: url).count/(1024 * 1024) return dataCountInMB < CoreFilesConfig.maxSizeAllowedToUploadInMB } catch { return false } } }
// // UserDefaults.swift // TodoList // // Created by Christian Oberdörfer on 22.03.19. // Copyright © 2019 Christian Oberdörfer. All rights reserved. // import SwiftyUserDefaults // Configures preferences of UserDefaults extension DefaultsKeys { static let serverAddress = DefaultsKey<String>(Preferences.serverAddress, defaultValue: Preferences.serverAddressDefaultValue) }
// // Init.swift // ListableUI // // Created by Kyle Van Essen on 10/21/20. // import Foundation func modified<Value>(_ initial : Value, _ modify : (inout Value) -> ()) -> Value { var copy = initial modify(&copy) return copy }
// // TableViewDataController.swift // MVVMContainer // // Created by Omkar khedekar on 27/09/18. // Copyright © 2018 Omkar khedekar. All rights reserved. // import UIKit class TableViewDataController: NSObject { @IBOutlet var tabelView: UITableView! { didSet { self.tabelView.register(UITableViewCell.self, forCellReuseIdentifier: "CellIdentfier") } } } extension TableViewDataController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentfier", for: indexPath) cell.textLabel?.text = "\(indexPath.row)" return cell } } extension TableViewDataController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let rootViewController = UIApplication.shared.keyWindow?.rootViewController else { return } let alert = UIAlertController(title: "", message: "Selected \(indexPath)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) rootViewController.present(alert, animated: true, completion: nil) } }
// // HeWeatherBase.swift // HeWeatherIO // // Created by iMac on 2018/5/25. // Copyright © 2018年 iMac. All rights reserved. // import Foundation public class HeWeatherBase: Codable { var basic: LocationAttribute? var update: UpdateTimestamp? var status: ResponseStatus required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: HeWeatherBase.CodingKeys.self) basic = try? container.decode(LocationAttribute.self, forKey: .basic) update = try? container.decode(UpdateTimestamp.self, forKey: .update) status = ResponseStatus(rawValue: try container.decode(String.self, forKey: .status))! } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: HeWeatherBase.CodingKeys.self) try container.encode(basic, forKey: .basic) try container.encode(update, forKey: .update) try container.encode(status.rawValue, forKey: .status) } private enum CodingKeys: String, CodingKey { case basic case update case status } }
// // RemoteCakeImageLoader.swift // CakeClub // // Created by Vinicius Leal on 27/09/2020. // Copyright © 2020 Vinicius Leal. All rights reserved. // import SDWebImage import UIKit public class RemoteCakeImageLoader: CakeImageLoader { private var placeholderImage: UIImage? { UIImage(named: Constant.placeholderImageName) } public init() {} public func loadImage(from url: URL, into view: UIImageView) { view.sd_setImage(with: url, placeholderImage: placeholderImage, options: .highPriority) } }
// // LoginDetailsController.swift // Bottle // // Created by Will Schreiber on 7/28/16. // Copyright © 2016 Bottle. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import MBProgressHUD class LoginDetailsController: UIViewController, UITextFieldDelegate { @IBOutlet var handleField: UITextField! @IBOutlet var passwordField: UITextField! @IBOutlet var loginButton: UIButton! @IBOutlet var switchButton: UIButton! var handleResetTextField: UITextField? var displayHUD: MBProgressHUD? override func viewDidLoad() { super.viewDidLoad() self.loginButton.layer.cornerRadius = 4.0 self.loginButton.clipsToBounds = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if UserCoordinator.isLoggedIn() { let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(LoginDetailsController.leftBarButtonAction(_:))) self.navigationItem.leftBarButtonItem = cancel } else { //self.navigationItem.leftBarButtonItem = nil } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.handleField.becomeFirstResponder() } @IBAction func loginAction(_ sender: AnyObject) { self.attemptToLogin() } func attemptToLogin() { if self.handleField.text?.characters.count == 0 { self.showBenignAlert("You must enter a handle!", message: nil) } else if self.passwordField.text?.characters.count == 0 { self.showBenignAlert("You must enter a password!", message: nil) } else if let handle = self.handleField.text, let password = self.passwordField.text { self.displayHUD = MBProgressHUD.showAdded(to: self.view, animated: true) self.displayHUD?.mode = MBProgressHUDMode.indeterminate Alamofire.request(ServerHelper.URLWithMethod("login"), method: .post, parameters: ["handle": handle, "password": password], encoding: JSONEncoding.default) .validate(statusCode: 200..<300) .responseJSON(completionHandler: { response in switch response.result { case .success: self.displayHUD?.hide(animated: true) if let JSONString = response.result.value { let json = JSON(JSONString) let _ = UserCoordinator.login(attributes: json.dictionaryValue) NotificationCenter.default.post(name: NSNotification.Name(GlobalVariables.switchToMainViewNotificationName), object: nil) } break case .failure: self.displayHUD?.hide(animated: true) self.showBenignAlert("Incorrect handle or password!", message: "Try again") break } } ) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 1 { self.passwordField.becomeFirstResponder() } else if textField.tag == 2 { self.passwordField.resignFirstResponder() self.attemptToLogin() } return true } func leftBarButtonAction(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name(rawValue: GlobalVariables.switchToMainViewNotificationName), object: nil) } @IBAction func switchAction(_ sender: AnyObject) { let confirmSheet: UIAlertController = UIAlertController(title: "Reset Password", message: "Enter your handle and we'll send you a new password.", preferredStyle: .alert) confirmSheet.addTextField(configurationHandler: configurationTextField) confirmSheet.textFields?.first?.text = self.handleField.text let cancelButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in } confirmSheet.addAction(cancelButton) let saveButton: UIAlertAction = UIAlertAction(title: "Go", style: .default) { action -> Void in if let handle = self.handleResetTextField?.text { self.displayHUD = MBProgressHUD.showAdded(to: self.view, animated: true) self.displayHUD?.mode = MBProgressHUDMode.indeterminate let url = ServerHelper.URLWithMethod("password_reset_action") Alamofire.request(url, method: .post, parameters: ["handle":handle], encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .responseJSON(completionHandler: { response in switch response.result { case .success: self.displayHUD?.hide(animated: true) if let JSONString = response.result.value { let json = JSON(JSONString) let object = json.dictionaryValue if let notice = object["notice"]?.stringValue { self.showBenignAlert("Password Reset", message: notice) } else { self.showBenignAlert("Password Reset", message: nil) } } break case .failure: self.displayHUD?.hide(animated: true) print("request failed!") self.showBenignAlert("Failed to reset password.", message: nil) break } } ) } } confirmSheet.addAction(saveButton) self.present(confirmSheet, animated: true, completion: nil) } func configurationTextField(_ textField: UITextField!) { textField.placeholder = "@handle" textField.autocapitalizationType = .sentences self.handleResetTextField = textField } }
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: Jub_Common.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// Graphene role enum JUB_Proto_Common_ENUM_GRAPHENE_ROLE: SwiftProtobuf.Enum { typealias RawValue = Int case owner // = 0 case active // = 1 case UNRECOGNIZED(Int) init() { self = .owner } init?(rawValue: Int) { switch rawValue { case 0: self = .owner case 1: self = .active default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .owner: return 0 case .active: return 1 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Common_ENUM_GRAPHENE_ROLE: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Common_ENUM_GRAPHENE_ROLE] = [ .owner, .active, ] } #endif // swift(>=4.2) /// mnemonic strength enum JUB_Proto_Common_ENUM_MNEMONIC_STRENGTH: SwiftProtobuf.Enum { typealias RawValue = Int case strength128 // = 0 case strength192 // = 1 case strength256 // = 2 case UNRECOGNIZED(Int) init() { self = .strength128 } init?(rawValue: Int) { switch rawValue { case 0: self = .strength128 case 1: self = .strength192 case 2: self = .strength256 default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .strength128: return 0 case .strength192: return 1 case .strength256: return 2 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Common_ENUM_MNEMONIC_STRENGTH: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Common_ENUM_MNEMONIC_STRENGTH] = [ .strength128, .strength192, .strength256, ] } #endif // swift(>=4.2) /// curves enum JUB_Proto_Common_CURVES: SwiftProtobuf.Enum { typealias RawValue = Int case secp256K1 // = 0 case ed25519 // = 1 case nist256P1 // = 2 case UNRECOGNIZED(Int) init() { self = .secp256K1 } init?(rawValue: Int) { switch rawValue { case 0: self = .secp256K1 case 1: self = .ed25519 case 2: self = .nist256P1 default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .secp256K1: return 0 case .ed25519: return 1 case .nist256P1: return 2 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Common_CURVES: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Common_CURVES] = [ .secp256K1, .ed25519, .nist256P1, ] } #endif // swift(>=4.2) enum JUB_Proto_Common_ENUM_PUB_FORMAT: SwiftProtobuf.Enum { typealias RawValue = Int case hex // = 0 case xpub // = 1 case UNRECOGNIZED(Int) init() { self = .hex } init?(rawValue: Int) { switch rawValue { case 0: self = .hex case 1: self = .xpub default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .hex: return 0 case .xpub: return 1 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension JUB_Proto_Common_ENUM_PUB_FORMAT: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [JUB_Proto_Common_ENUM_PUB_FORMAT] = [ .hex, .xpub, ] } #endif // swift(>=4.2) /// Bip44_path /// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki struct JUB_Proto_Common_Bip44Path { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var change: Bool = false var addressIndex: UInt64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// Slip48_path /// https://github.com/satoshilabs/slips/issues/49 struct JUB_Proto_Common_Slip48Path { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var network: UInt64 = 0 var role: JUB_Proto_Common_ENUM_GRAPHENE_ROLE = .owner var addressIndex: UInt64 = 0 var keyIndex: UInt64 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct JUB_Proto_Common_ContextCfg { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var mainPath: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// device info struct JUB_Proto_Common_DeviceInfo { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var sn: String = String() var label: String = String() var bleVersion: String = String() var firmwareVersion: String = String() var pinRetry: UInt32 = 0 var pinMaxRetry: UInt32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// result with int return value struct JUB_Proto_Common_ResultInt { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var stateCode: UInt64 = 0 var value: UInt32 = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// result with string return value struct JUB_Proto_Common_ResultString { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var stateCode: UInt64 = 0 var value: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } /// result with DeviceInfo return value struct JUB_Proto_Common_ResultAny { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var stateCode: UInt64 = 0 var value: [SwiftProtobuf.Google_Protobuf_Any] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "JUB.Proto.Common" extension JUB_Proto_Common_ENUM_GRAPHENE_ROLE: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "OWNER"), 1: .same(proto: "ACTIVE"), ] } extension JUB_Proto_Common_ENUM_MNEMONIC_STRENGTH: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "STRENGTH128"), 1: .same(proto: "STRENGTH192"), 2: .same(proto: "STRENGTH256"), ] } extension JUB_Proto_Common_CURVES: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "SECP256K1"), 1: .same(proto: "ED25519"), 2: .same(proto: "NIST256P1"), ] } extension JUB_Proto_Common_ENUM_PUB_FORMAT: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "HEX"), 1: .same(proto: "XPUB"), ] } extension JUB_Proto_Common_Bip44Path: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Bip44Path" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "change"), 2: .standard(proto: "address_index"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularBoolField(value: &self.change) case 2: try decoder.decodeSingularUInt64Field(value: &self.addressIndex) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.change != false { try visitor.visitSingularBoolField(value: self.change, fieldNumber: 1) } if self.addressIndex != 0 { try visitor.visitSingularUInt64Field(value: self.addressIndex, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_Bip44Path, rhs: JUB_Proto_Common_Bip44Path) -> Bool { if lhs.change != rhs.change {return false} if lhs.addressIndex != rhs.addressIndex {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_Slip48Path: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Slip48Path" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "network"), 2: .same(proto: "role"), 3: .standard(proto: "address_index"), 4: .standard(proto: "key_index"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.network) case 2: try decoder.decodeSingularEnumField(value: &self.role) case 3: try decoder.decodeSingularUInt64Field(value: &self.addressIndex) case 4: try decoder.decodeSingularUInt64Field(value: &self.keyIndex) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.network != 0 { try visitor.visitSingularUInt64Field(value: self.network, fieldNumber: 1) } if self.role != .owner { try visitor.visitSingularEnumField(value: self.role, fieldNumber: 2) } if self.addressIndex != 0 { try visitor.visitSingularUInt64Field(value: self.addressIndex, fieldNumber: 3) } if self.keyIndex != 0 { try visitor.visitSingularUInt64Field(value: self.keyIndex, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_Slip48Path, rhs: JUB_Proto_Common_Slip48Path) -> Bool { if lhs.network != rhs.network {return false} if lhs.role != rhs.role {return false} if lhs.addressIndex != rhs.addressIndex {return false} if lhs.keyIndex != rhs.keyIndex {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_ContextCfg: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ContextCfg" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "main_path"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.mainPath) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.mainPath.isEmpty { try visitor.visitSingularStringField(value: self.mainPath, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_ContextCfg, rhs: JUB_Proto_Common_ContextCfg) -> Bool { if lhs.mainPath != rhs.mainPath {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_DeviceInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".DeviceInfo" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "sn"), 2: .same(proto: "label"), 3: .standard(proto: "ble_version"), 4: .standard(proto: "firmware_version"), 5: .standard(proto: "pin_retry"), 6: .standard(proto: "pin_max_retry"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.sn) case 2: try decoder.decodeSingularStringField(value: &self.label) case 3: try decoder.decodeSingularStringField(value: &self.bleVersion) case 4: try decoder.decodeSingularStringField(value: &self.firmwareVersion) case 5: try decoder.decodeSingularUInt32Field(value: &self.pinRetry) case 6: try decoder.decodeSingularUInt32Field(value: &self.pinMaxRetry) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.sn.isEmpty { try visitor.visitSingularStringField(value: self.sn, fieldNumber: 1) } if !self.label.isEmpty { try visitor.visitSingularStringField(value: self.label, fieldNumber: 2) } if !self.bleVersion.isEmpty { try visitor.visitSingularStringField(value: self.bleVersion, fieldNumber: 3) } if !self.firmwareVersion.isEmpty { try visitor.visitSingularStringField(value: self.firmwareVersion, fieldNumber: 4) } if self.pinRetry != 0 { try visitor.visitSingularUInt32Field(value: self.pinRetry, fieldNumber: 5) } if self.pinMaxRetry != 0 { try visitor.visitSingularUInt32Field(value: self.pinMaxRetry, fieldNumber: 6) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_DeviceInfo, rhs: JUB_Proto_Common_DeviceInfo) -> Bool { if lhs.sn != rhs.sn {return false} if lhs.label != rhs.label {return false} if lhs.bleVersion != rhs.bleVersion {return false} if lhs.firmwareVersion != rhs.firmwareVersion {return false} if lhs.pinRetry != rhs.pinRetry {return false} if lhs.pinMaxRetry != rhs.pinMaxRetry {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_ResultInt: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ResultInt" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "state_code"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.stateCode) case 2: try decoder.decodeSingularUInt32Field(value: &self.value) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.stateCode != 0 { try visitor.visitSingularUInt64Field(value: self.stateCode, fieldNumber: 1) } if self.value != 0 { try visitor.visitSingularUInt32Field(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_ResultInt, rhs: JUB_Proto_Common_ResultInt) -> Bool { if lhs.stateCode != rhs.stateCode {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_ResultString: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ResultString" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "state_code"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.stateCode) case 2: try decoder.decodeSingularStringField(value: &self.value) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.stateCode != 0 { try visitor.visitSingularUInt64Field(value: self.stateCode, fieldNumber: 1) } if !self.value.isEmpty { try visitor.visitSingularStringField(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_ResultString, rhs: JUB_Proto_Common_ResultString) -> Bool { if lhs.stateCode != rhs.stateCode {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension JUB_Proto_Common_ResultAny: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ResultAny" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "state_code"), 2: .same(proto: "value"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.stateCode) case 2: try decoder.decodeRepeatedMessageField(value: &self.value) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.stateCode != 0 { try visitor.visitSingularUInt64Field(value: self.stateCode, fieldNumber: 1) } if !self.value.isEmpty { try visitor.visitRepeatedMessageField(value: self.value, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: JUB_Proto_Common_ResultAny, rhs: JUB_Proto_Common_ResultAny) -> Bool { if lhs.stateCode != rhs.stateCode {return false} if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
import UIKit class IconViewController: UITableViewController { //協定代理 var delegate:ProtocolIconView? var icons = [String]() override func viewDidLoad() { super.viewDidLoad() self.title = "選取圖示" //所有的圖示名稱 icons.append("No Icon") icons.append("分享") icons.append("貨運") icons.append("記錄") icons.append("旅行") icons.append("提醒") icons.append("天氣") icons.append("衛生") icons.append("檔案") icons.append("心情") } //傳回資料行數 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return icons.count } //設定cell override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //取得cell let cell = tableView.dequeueReusableCellWithIdentifier("iconCell")! as UITableViewCell //取得圖示名稱 let icon = icons[indexPath.row] //設定標題為圖示名稱 cell.textLabel!.text = icon //根據圖示名稱設定縮圖 cell.imageView!.image = UIImage(named: icon) return cell } //選取圖示後 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //取得圖示name let iconName = icons[indexPath.row] self.delegate?.iconPicker(didPickIcon: iconName) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } //用於回調選取了圖示的方法 protocol ProtocolIconView{ func iconPicker( didPickIcon iconName:String) }
// // WelcomePageViewController.swift // waves-ios // // Created by Charlie White on 1/16/15. // Copyright (c) 2015 Charlie White. All rights reserved. // import UIKit class WelcomePageViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var pageViewController: UIPageViewController! @IBOutlet var pageView: UIView! @IBOutlet var pageControl: UIPageControl! @IBOutlet var button: UIButton! private let contentImages = ["walkthrough-intro", "walkthrough-1","walkthrough-2","walkthrough-3","walkthrough-4", "walkthrough-5"] private let buttonImages = ["intro-page-btn", "walkthrough-1-btn","walkthrough-2-btn","walkthrough-3-btn","walkthrough-4-btn", "walkthrough-5-btn"] override func viewDidLoad() { super.viewDidLoad() self.pageControl.numberOfPages = contentImages.count createPageViewController() setupPageControl() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: false) } func createPageViewController() { pageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil) pageViewController.delegate = self pageViewController.dataSource = self let firstController = getItemController(0)! let startingViewControllers: NSArray = [firstController] self.pageViewController.setViewControllers(startingViewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil) self.pageView.addSubview(self.pageViewController.view) self.pageViewController.didMoveToParentViewController(self) //self.view.bringSubviewToFront(self.button) } func setupPageControl() { let appearance = UIPageControl.appearance() appearance.pageIndicatorTintColor = UIColor(red: 227.0/255.0, green: 228.0/255.0, blue: 236.0/255.0, alpha: 1) appearance.currentPageIndicatorTintColor = UIColor(red: 145.0/255.0, green: 148.0/255.0, blue: 150.0/255.0, alpha: 1) //appearance.backgroundColor = UIColor.darkGrayColor() } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let itemController = viewController as WelcomeTourViewController if itemController.itemIndex > 0 { return getItemController(itemController.itemIndex-1) } return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let itemController = viewController as WelcomeTourViewController if itemController.itemIndex+1 < contentImages.count { return getItemController(itemController.itemIndex+1) } return nil } private func getItemController(itemIndex: Int) -> WelcomeTourViewController? { if itemIndex < contentImages.count { let pageItemController = WelcomeTourViewController(nibName: "WelcomeTourViewController", bundle: nil) pageItemController.itemIndex = itemIndex pageItemController.imageName = contentImages[itemIndex] return pageItemController } return nil } func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) { let pageItemController = pendingViewControllers.first as WelcomeTourViewController self.pageControl.currentPage = pageItemController.itemIndex let image = UIImage(named: self.buttonImages[pageItemController.itemIndex]) self.button.setImage(image, forState: UIControlState.Normal) } @IBAction func advance() { let currentVC = self.pageViewController.viewControllers.first as WelcomeTourViewController let newIndex = currentVC.itemIndex + 1 if (newIndex == 6) { self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } else { let firstController = getItemController(newIndex)! let startingViewControllers: NSArray = [firstController] self.pageViewController.setViewControllers(startingViewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: { (bool:Bool) in self.pageControl.currentPage = newIndex let image = UIImage(named: self.buttonImages[newIndex]) self.button.setImage(image, forState: UIControlState.Normal) }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // UtilsTest.swift // MercadoLibreAppTests // // Created by Daniel Beltran😎 on 3/11/20. // import XCTest @testable import MercadoLibreApp class UtilsTest: XCTestCase { func test_format_price() { XCTAssert( Utils.shared.formatPrice(1000000) == "$1,000,000.00") } }
import Cocoa import Alloy import MetalKit import SwiftMath class ViewController: NSViewController { // MARK: - IB @IBOutlet var mtkView: MTKView! // MARK: - Properties var context: MTLContext! var renderer: Renderer! var textureManager: MTLTextureManager! var textureTransform: Matrix4x4f = .identity var scale: Float = 1.0 // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() do { try self.setup() } catch { displayAlert(message: "ViewController setup failed, error: \(error)") } } override public func viewDidLayout() { super.viewDidLayout() self.drawTexture() } override public func magnify(with event: NSEvent) { guard let view = self.mtkView else { return } let zoomPoint = self.texturePoint(from: event.locationInWindow, in: view) let scale = 1 + Float(event.magnification) self.scale *= scale self.textureTransform = self.textureTransform * .translate(tx: zoomPoint.x, ty: zoomPoint.y, tz: 0) * .scale(sx: scale, sy: scale, sz: 1) * .translate(tx: -(zoomPoint.x), ty: -(zoomPoint.y), tz: 0) self.drawTexture() } override public func scrollWheel(with event: NSEvent) { guard let view = self.mtkView else { return } let translation = self.textureTranslation(from: .init(x: event.scrollingDeltaX, y: -event.scrollingDeltaY), in: view) self.textureTransform = self.textureTransform * .translate(tx: translation.x / self.scale, ty: translation.y / self.scale, tz: 0) self.drawTexture() } // MARK: - Setup func setup() throws { self.context = try .init() Renderer.configure(self.mtkView, with: self.context.device) self.renderer = try .init(context: self.context) self.textureManager = .init(context: self.context) } // MARK: - Draw func drawTexture() { guard let texture = self.textureManager .texture else { return } let finalTransform = self.textureTransform * self.aspectRatioTransform(for: texture, in: self.mtkView) let textureSize = CGSize(width: texture.width, height: texture.height) self.mtkView.drawableSize = textureSize try? self.context.scheduleAndWait { commandBuffer in self.renderer.draw(texture: texture, with: .init(finalTransform), on: self.mtkView, in: commandBuffer) } self.mtkView.needsDisplay = true } func texturePoint(from windowPoint: CGPoint, in textureView: MTKView) -> SIMD2<Float> { let textureViewSize: SIMD2<Float> = .init(.init(textureView.frame.width), .init(textureView.frame.height)) var point: SIMD2<Float> = .init(.init(windowPoint.x), .init(windowPoint.y)) point /= textureViewSize // normalize point *= 2 // convert point -= 1 // to metal let result: SIMD4<Float> = simd_float4x4(self.textureTransform.inversed) * .init(point.x, point.y, 0, 1) return .init(result.x, result.y) } func textureTranslation(from viewTranslation: CGPoint, in textureView: MTKView) -> SIMD2<Float> { let textureViewSize: SIMD2<Float> = .init(.init(textureView.frame.width), .init(textureView.frame.height)) var translation: SIMD2<Float> = .init(.init(viewTranslation.x), .init(viewTranslation.y)) translation /= textureViewSize // normalize return translation } func aspectRatioTransform(for texture: MTLTexture, in textureView: MTKView) -> Matrix4x4f { let textureAspectRatio: Float = .init(texture.width) / .init(texture.height) let textureViewAspectRatio: Float = .init(textureView.frame.width) / .init(textureView.frame.height) let scaleX = textureAspectRatio / textureViewAspectRatio return .scale(sx: scaleX, sy: 1, sz: 1) } }
// // Product.swift // GolbexSwift // // Created by Nikolay Dolgopolov on 04/11/2018. // import Foundation public class Product:Codable{ // var id = "" //id объекта в базе public var uid = "" //id пары BTC/USD public var first = "" //код первой валюты public var second = "" //код второй валюты public var increment = 0.0 //минимальная единица изменения прайса public var min = 0.0 //минимальный объем ордера public var max = 0.0 //максимальный объем ордера }
// // SearchClient.swift // Restaurants Near Me // // Created by Adrian.McGee on 1/10/18. // Copyright © 2018 Adrian.McGee. All rights reserved. // public final class HTTPRequestBuilder: HTTPRequestBuilderType { init(apiVersionKey: String, apiVersion: String) { headers[apiVersionKey] = apiVersion headers["Content-Type"] = "application/json" //default values path = "" method = .get isFirstQueryParameter = true } // MARK: - HTTPRequestBuilderType Conformance public func addPath(_ path: String) -> HTTPRequestBuilder { self.path = path return self } public func addMethod(_ method: HTTPMethod) -> HTTPRequestBuilder { self.method = method return self } public func addHeader(key: String, value: String) -> HTTPRequestBuilder { headers[key] = value return self } public func addQueryParameter(key: String, value: String) -> HTTPRequestBuilder { let escapedString = value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) if isFirstQueryParameter { path = path + key + "=" + escapedString! isFirstQueryParameter = false } else { path = path + "&" + key + "=" + escapedString! } return self } public func build() -> HTTPRequestType { return HTTPRequest(urlPath: path, httpMethod: method, httpHeaders: headers, parameters: parameters) } // MARK: - Private // MARK: Properties var path: String var method: HTTPMethod var headers: HTTPHeader = [:] var parameters: HTTPParameters? var isFirstQueryParameter: Bool }
// // Colors.swift // LucrezCeva // // Created by Suciu Radu on 26/11/2018. // Copyright © 2018 LucrezCeva. All rights reserved. // import Foundation import UIKit class Colors { static var colorGreen: UIColor = { return UIColor.init(named: "colorGreen") ?? UIColor.green }() static var colorDarkGray: UIColor = { return UIColor.init(named: "colorDarkGray") ?? UIColor.darkGray }() static var colorLightGray: UIColor = { return UIColor.init(named: "colorLightGray") ?? UIColor.lightGray }() static var colorLightWhite: UIColor = { return UIColor.init(named: "colorLightWhite") ?? UIColor.white }() static var colorRed: UIColor = { return UIColor.init(named: "colorRed") ?? UIColor.red }() static var colorPrimary: UIColor = { return UIColor.init(named: "colorPrimary") ?? UIColor.blue }() static var colorLightTurqoise: UIColor = { return UIColor.init(named: "colorLightTurqoise") ?? UIColor.blue }() static var colorMediumTurqoise: UIColor = { return UIColor.init(named: "colorMediumTurqoise") ?? UIColor.blue }() static var colorTopBlue: UIColor = { return UIColor.init(named: "colorTopBlue") ?? UIColor.blue }() }
// // Tool.swift // 先声 // // Created by Wangshuo on 14-8-5. // Copyright (c) 2014年 WangShuo. All rights reserved. // import Foundation @objc protocol APIGetter{ func getResult(APIName:String, results:AnyObject) func getError(APIName:String, statusCode:Int) } class HeraldAPI:HttpProtocol{ var httpController:HttpController var delegate:APIGetter? init(){ httpController = HttpController() } func sendAPI(APIName:String, APIParameter:String?...){ self.httpController.delegate = self let baseURL = "http://herald.seu.edu.cn/api/" let uuid = Config.UUID! let baseParameter:NSDictionary = ["uuid":uuid] switch APIName{ case "pe": let url = baseURL + "pe" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "pe") case "curriculum": let url = baseURL + "curriculum" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "curriculum") case "jwc": let url = baseURL + "jwc" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "jwc") case "srtp": let url = baseURL + "srtp" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "srtp") case "nic": let url = baseURL + "nic" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "nic") case "card": let url = baseURL + "card" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "card") case "cardDetail": let url = baseURL + "card" let parameter:NSDictionary = ["uuid":uuid,"timedelta":"30"] httpController.postToURLAF(url, parameter: parameter, tag: "cardDetail") case "phylab": let url = baseURL + "phylab" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "phylab") case "lecture": let url = baseURL + "lecture" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "lecture") case "lectureNotice": let url = baseURL + "lecturenotice" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "lectureNotice") case "searchBook": let url = baseURL + "search" let parameter:NSDictionary = ["uuid":uuid,"book":APIParameter[0] ?? ""] httpController.postToURLAF(url, parameter: parameter, tag: "searchBook") case "library": let url = baseURL + "library" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "library") case "libraryRenew": let url = baseURL + "renew" let parameter:NSDictionary = ["uuid":uuid,"barcode":APIParameter[0] ?? ""] httpController.postToURLAF(url, parameter: parameter, tag: "libraryRenew") case "schoolbus": let url = baseURL + "schoolbus" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "schoolbus") case "gpa": let url = baseURL + "gpa" let parameter = baseParameter httpController.postToURLAF(url, parameter: parameter, tag: "gpa") default: break } } func didReceiveDicResults(results: NSDictionary, tag: String) { var statusCode:Int? = results["code"] as? Int if(statusCode != 200){ self.delegate?.getError(tag, statusCode: 500) return } //有些API返回的状态码不一定代表真实情况,根据JSON的code来判断…… switch tag{ case "pe": self.delegate?.getResult(tag, results: results["content"] as! NSString) case "curriculum": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "jwc": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "srtp": self.delegate?.getResult(tag, results: results["content"] as! NSArray) case "nic": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "card": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "cardDetail": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "lecture": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "phylab": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "lectureNotice": self.delegate?.getResult(tag, results: results["content"] as! [NSDictionary]) case "searchBook": self.delegate?.getResult(tag, results: results["content"] as! NSArray) case "library": self.delegate?.getResult(tag, results: results["content"] as! NSArray) case "libraryRenew": self.delegate?.getResult(tag, results: results["content"] as! String) case "schoolbus": self.delegate?.getResult(tag, results: results["content"] as! NSDictionary) case "gpa": self.delegate?.getResult(tag, results: results["content"] as! NSArray) default: break } } func didReceiveErrorResult(code: Int, tag: String) { self.delegate?.getError(tag, statusCode: code) } func cancelAllRequest(){ httpController.cancelAllRequest() } } class Tool:NSObject { //网络请求的动画控制 class func dismissHUD() { ProgressHUD.dismiss() } class func showProgressHUD(text:String) { ProgressHUD.show(text) } class func showSuccessHUD(text:String) { ProgressHUD.showSuccess(text) } class func showErrorHUD(text:String) { ProgressHUD.showError(text) } //初始化在导航栏里面的所有VC class func initNavigationAPI(VC:UIViewController,navBarColor:UIColor) -> Bool{ VC.navigationController?.navigationBar.barTintColor = navBarColor Config.shareInstance().isNetworkRunning = CheckNetwork.doesExistenceNetwork() if Config.UUID == nil || Config.UUID!.isEmpty{ Tool.showSuccessHUD("请在边栏的个人资料中补全您的信息") } else if !Config.shareInstance().isNetworkRunning{ Tool.showErrorHUD("貌似你没有联网哦") } else{ return true } return false } }
// // ViewController.swift // karrrt // // Created by Robin Bonatesta on 9/5/15. // Copyright (c) 2015 Robin Bonatesta. All rights reserved. // import UIKit import AVFoundation import Alamofire import AlamofireObjectMapper import ObjectMapper import Socket_IO_Client_Swift class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { class Ok: Mappable { var ok: Bool? class func newInstance(map: Map) -> Mappable? { var ok = Ok() ok.ok <- map["ok"] return ok } func mapping(map: Map) { ok <- map["ok"] } } let session : AVCaptureSession = AVCaptureSession() var previewLayer : AVCaptureVideoPreviewLayer! var highlightView : UIView = UIView() @IBAction func viewCart(sender: AnyObject) { self.performSegueWithIdentifier("viewCart", sender: nil) } let socket = SocketIOClient(socketURL: "http://104.236.114.123") override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor(red: 83/255.0, green: 255/255.0, blue: 116/255.0, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // Allow view to resize self.highlightView.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin // Select the color you want for the completed scan reticle self.highlightView.layer.borderColor = UIColor.greenColor().CGColor self.highlightView.layer.borderWidth = 3 // Add it to our controller's view as a subview self.view.addSubview(self.highlightView) // Camera let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) //Create a nilable NSError to hand off to next method (must be var, not let) var error : NSError? let input : AVCaptureDeviceInput? = AVCaptureDeviceInput.deviceInputWithDevice(device, error: &error) as? AVCaptureDeviceInput // If our input is not nil, then add it to the session if input != nil { session.addInput(input) } else { // This should actually do something .. brb println(error) } let output = AVCaptureMetadataOutput() output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) session.addOutput(output) output.metadataObjectTypes = output.availableMetadataObjectTypes previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as! AVCaptureVideoPreviewLayer previewLayer.frame = self.view.bounds previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill self.view.layer.addSublayer(previewLayer) // Start the scanner. session.startRunning() socket.on("cart:status") {data, ack in let status = Mapper<Ok>().map(data![0]) if let status = status { if status.ok! { // make green self.navigationController?.navigationBar.barTintColor = UIColor(red: 83/255.0, green: 255/255.0, blue: 116/255.0, alpha: 1.0) } else { // make red self.navigationController?.navigationBar.barTintColor = UIColor(red: 255/255.0, green: 108/255.0, blue: 81/255.0, alpha: 1.0) } } } socket.connect() } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { var highlightViewRect = CGRectZero var barCodeObject : AVMetadataObject! var detectionString : String! let serverAddress = "http://104.236.114.123/" let barCodeTypes = [ AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode ] // The scanner can capture 2-d barcodes in one scan for metadata in metadataObjects{ for barCodeType in barCodeTypes{ if metadata.type == barCodeType { barCodeObject = self.previewLayer.transformedMetadataObjectForMetadataObject(metadata as! AVMetadataMachineReadableCodeObject) highlightViewRect = barCodeObject.bounds detectionString = (metadata as! AVMetadataMachineReadableCodeObject).stringValue self.session.stopRunning() break } } } let url = "http://104.236.114.123/upc/\(detectionString)" Alamofire.request(.GET, url) .responseObject { (response: Product?, error: NSError?) in if let response = response { self.performSegueWithIdentifier("showProductInfo", sender: response) } } println(detectionString) self.highlightView.frame = highlightViewRect self.view.bringSubviewToFront(self.highlightView) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showProductInfo" { if let productInfoViewController = segue.destinationViewController as? ProductInfoViewController { productInfoViewController.product = sender as? Product } } } @IBAction func unwindToScanner(segue: UIStoryboardSegue) { session.startRunning() self.highlightView.frame = CGRectZero } }
// // TimeCellView.swift // Liftoff // // Created by Pavol Margitfalvi on 20/12/2018. // Copyright © 2018 Pavol Margitfalvi. All rights reserved. // import UIKit class TimeCellView: UIView { let nibName = "TimeCellView" @IBOutlet weak var days: UILabel! @IBOutlet weak var hours: UILabel! @IBOutlet weak var minutes: UILabel! @IBOutlet weak var seconds: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) guard let view = loadFromNib() else { return } view.frame = bounds addSubview(view) leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true topAnchor.constraint(equalTo: view.topAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } private func loadFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as? UIView } }
// // PreviewViewController.swift // HippoAgent // // Created by Arohi Sharma on 10/02/21. // Copyright © 2021 Socomo Technologies Private Limited. All rights reserved. // import UIKit import CropViewController class PreviewViewController: UIViewController { //MARK:- IBOutlet @IBOutlet private var viewNavigation : NavigationBar! @IBOutlet var textView_PrivateNotes : UITextView!{ didSet{ textView_PrivateNotes.delegate = self } } @IBOutlet var imageView_Preview : UIImageView! @IBOutlet var label_Placeholder : UILabel!{ didSet{ label_Placeholder.text = HippoStrings.messagePlaceHolderText } } @IBOutlet weak var lblDocumentName: UILabel! @IBOutlet weak var btnEdit: UIButton! //MARK:- Properties var image : UIImage? var fileType : FileType? var sendBtnTapped : ((String?, UIImage?)->())? var path: URL? override func viewDidLoad() { super.viewDidLoad() HippoKeyboardManager.shared.enable = true viewNavigation.leftButton.addTarget(self, action: #selector(action_BackBtn), for: .touchUpInside) textView_PrivateNotes.textContainerInset = UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0) if fileType == .document{ imageView_Preview.contentMode = .center imageView_Preview.image = UIImage(named: "defaultDoc", in: FuguFlowManager.bundle, compatibleWith: nil) viewNavigation.title = "Document" lblDocumentName.text = path?.lastPathComponent }else{ imageView_Preview.image = image viewNavigation.title = "Preview" imageView_Preview.contentMode = .scaleAspectFit } lblDocumentName.isHidden = !(fileType == .document) btnEdit.isHidden = (fileType == .document) } override func viewDidDisappear(_ animated: Bool) { HippoKeyboardManager.shared.enable = false HippoKeyboardManager.shared.keyboardDistanceFromTextField = 0 } func drawPDFfromURL(url: URL) -> UIImage? { guard let document = CGPDFDocument(url as CFURL) else { return nil } guard let page = document.page(at: 1) else { return nil } let pageRect = page.getBoxRect(.mediaBox) let renderer = UIGraphicsImageRenderer(size: pageRect.size) let img = renderer.image { ctx in UIColor.white.set() ctx.fill(pageRect) ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height) ctx.cgContext.scaleBy(x: 1.0, y: -1.0) ctx.cgContext.drawPDFPage(page) } return img } } extension PreviewViewController : UITextViewDelegate{ func textViewDidChange(_ textView: UITextView) { label_Placeholder.isHidden = !(textView.text.isEmpty) } } extension PreviewViewController{ @IBAction func action_SendBtn(){ sendBtnTapped?(textView_PrivateNotes.text.trimWhiteSpacesAndNewLine(), self.image) action_BackBtn() } @IBAction func action_BackBtn(){ self.dismiss(animated: true, completion: nil) } @IBAction func btnEditTapped(_ sender: Any) { self.presentCropViewController() } func presentCropViewController() { guard let image = image else {return} let cropViewController = CropViewController(image: image) cropViewController.delegate = self cropViewController.modalPresentationStyle = .fullScreen let nav = UINavigationController(rootViewController: cropViewController) present(nav, animated: true, completion: nil) } } extension PreviewViewController : CropViewControllerDelegate{ func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) { // 'image' is the newly cropped version of the original image self.image = image imageView_Preview.image = image self.dismiss(animated: true, completion: nil) } }
// // myCollectionViewCell.swift // CollectionViewInTable // // Created by Vic on 2020/11/10. // Copyright © 2020 codeWalker. All rights reserved. // import UIKit class myCollectionViewCell: UICollectionViewCell { }
import AudioKit import AudioKitUI import AVFoundation import SoundpipeAudioKit import SwiftUI struct FlatFrequencyResponseReverbData { var reverbDuration: AUValue = 0.5 var rampDuration: AUValue = 0.02 var balance: AUValue = 0.5 } class FlatFrequencyResponseReverbConductor: ObservableObject, ProcessesPlayerInput { let engine = AudioEngine() let player = AudioPlayer() let reverb: FlatFrequencyResponseReverb let dryWetMixer: DryWetMixer let buffer: AVAudioPCMBuffer init() { buffer = Cookbook.sourceBuffer player.buffer = buffer player.isLooping = true reverb = FlatFrequencyResponseReverb(player) dryWetMixer = DryWetMixer(player, reverb) engine.output = dryWetMixer } @Published var data = FlatFrequencyResponseReverbData() { didSet { reverb.$reverbDuration.ramp(to: data.reverbDuration, duration: data.rampDuration) dryWetMixer.balance = data.balance } } func start() { do { try engine.start() } catch let err { Log(err) } } func stop() { engine.stop() } } struct FlatFrequencyResponseReverbView: View { @StateObject var conductor = FlatFrequencyResponseReverbConductor() var body: some View { ScrollView { PlayerControls(conductor: conductor) ParameterSlider(text: "Reverb Duration", parameter: self.$conductor.data.reverbDuration, range: 0...10, units: "Seconds") ParameterSlider(text: "Mix", parameter: self.$conductor.data.balance, range: 0...1, units: "%") DryWetMixView(dry: conductor.player, wet: conductor.reverb, mix: conductor.dryWetMixer) } .padding() .navigationBarTitle(Text("Flat Frequency Response Reverb")) .onAppear { self.conductor.start() } .onDisappear { self.conductor.stop() } } } struct FlatFrequencyResponseReverb_Previews: PreviewProvider { static var previews: some View { FlatFrequencyResponseReverbView() } }
/* * Copyright (c) 2015 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. * * 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 import Firebase class ChannelListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: Properties @IBOutlet var tableView:UITableView! var senderDisplayName: String = "Attorney" var newChannelTextField: UITextField? private var channelRefHandle: FIRDatabaseHandle? private var channels: [Channel] = [] private lazy var channelRef: FIRDatabaseReference = FIRDatabase.database().reference().child("channels") // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "Users list" observeChannels() } deinit { if let refHandle = channelRefHandle { channelRef.removeObserver(withHandle: refHandle) } } // MARK :Actions @IBAction func createChannel(_ sender: AnyObject) { if let name = newChannelTextField?.text { let newChannelRef = channelRef.childByAutoId() let channelItem = [ "name": name ] newChannelRef.setValue(channelItem) } } @IBAction func back() { _ = navigationController?.popViewController(animated: true) } // MARK: Firebase related methods private func observeChannels() { // We can use the observe method to listen for new // channels being written to the Firebase DB channelRefHandle = channelRef.observe(.childAdded, with: { (snapshot) -> Void in let channelData = snapshot.value as! Dictionary<String, AnyObject> let id = snapshot.key if let name = channelData["name"] as! String!, name.characters.count > 0, id != FIRAuth.auth()?.currentUser?.uid { self.channels.append(Channel(id: id, name: name)) self.tableView.reloadData() } else { print("Error! Could not decode channel data") } }) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let channel = sender as? Channel { let chatVc = segue.destination as! MessageViewController chatVc.senderDisplayName = senderDisplayName chatVc.channel = channel chatVc.channelRef = channelRef.child(channel.id) } } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return channels.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "ExistingChannel" let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) let textField = cell.viewWithTag(101) as! UILabel textField.text = channels[(indexPath as NSIndexPath).row].name return cell } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let channel = channels[(indexPath as NSIndexPath).row] self.performSegue(withIdentifier: "ShowChannel", sender: channel) } }
// // Notifications.swift // WavesWallet-iOS // // Created by mefilt on 24/10/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation extension Notification.Name { public static let changedSpamList = Notification.Name(rawValue: "com.waves.language.notification.changedSpamList") /** The notification object contained current Language */ }
// BounceButton // Copyright (c) 2016 David Rico // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit let kDRNUIViewDRNBounceButtonDefaultShrinkAnimationDuration: NSTimeInterval = 0.25 let kDRNUIViewDRNBounceButtonDefaultShrinkRatioDefault: Float = 0.8 let kDRNUIViewDRNBounceButtonDefaultDampingAnimationDuration: Float = 0.65 let kDRNUIViewDRNBounceButtonDefaultDampingValueAnimation: Float = 0.3 @objc(DRNBounceButton) class BounceButton : RichButton { override init(frame: CGRect) { super.init(frame: frame) addTarget(self, action:"buttonTapped:event:", forControlEvents: .AllEvents) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addTarget(self, action:"buttonTapped:event:", forControlEvents: .AllEvents) } func animateToShrink() { UIView.animateWithDuration(kDRNUIViewDRNBounceButtonDefaultShrinkAnimationDuration, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in let affineTransform = CGAffineTransformMakeScale(CGFloat( kDRNUIViewDRNBounceButtonDefaultShrinkRatioDefault), CGFloat(kDRNUIViewDRNBounceButtonDefaultShrinkRatioDefault)) self.layer.setAffineTransform(affineTransform) }, completion: nil) } func animateToNormalSize() { UIView.animateWithDuration(kDRNUIViewDRNBounceButtonDefaultShrinkAnimationDuration, delay: 0, usingSpringWithDamping:CGFloat(kDRNUIViewDRNBounceButtonDefaultDampingValueAnimation), initialSpringVelocity:0, options: .BeginFromCurrentState, animations: { () -> Void in self.layer.setAffineTransform(CGAffineTransformIdentity) }, completion: nil) } func cancelAnimation() { UIView.animateWithDuration(kDRNUIViewDRNBounceButtonDefaultShrinkAnimationDuration, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in self.layer.setAffineTransform(CGAffineTransformIdentity) }, completion: nil) } func buttonTapped(button: UIButton, event: UIEvent) { if let touch = event.allTouches()?.first { switch touch.phase { case .Began: animateToShrink() case .Moved: cancelAnimation() case .Ended: animateToNormalSize() default: break } } } }
// // Logic.swift // GitHubUserInfo // // Created by Admin on 14.09.2016. // Copyright © 2016 Michal Galeziowski. All rights reserved. // import Foundation import Alamofire typealias JSONStd = [[String : AnyObject]] public class SpecifiedUserResponse { public var jsonAnswer = [[String:String]]() func callAmo(userUrlPath: String, completion: @escaping ([[String : String]]) -> ()) { let urladdress = userUrlPath Alamofire.request(urladdress).responseJSON(completionHandler: { response in switch response.result{ case .success: let dic = self.parseData(JSONData: response.data!) completion(dic) case .failure: let alertController: UIAlertController = UIAlertController(title: "Error", message: "Cannot retreive data. Please check internet connection", preferredStyle: .alert) let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil) } }) } func parseData(JSONData : Data) -> [[String: String]]{ do { var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStd let counter = readableJSON.count //Filling the dictionary for item in 0...counter - 1 { let repoName = readableJSON[item]["full_name"] let creationDate = readableJSON[item]["created_at"] let lastUpdateDate = readableJSON[item]["updated_at"] let profile = readableJSON[item]["html_url"] let dict:[String:AnyObject] = ["repoName": repoName!, "created": creationDate!, "updated": lastUpdateDate!, "url" : profile! ] jsonAnswer.append(dict as! [String : String]) } } catch{ print("Error") } return jsonAnswer } func cutTheString(toCut: String) -> String { let index = toCut.index(toCut.startIndex, offsetBy: 10) let newString = toCut.substring(to: index) return newString } } public class TheResponse { public var jsonAnswer = [[String:String]]() var getRes: [[String : String]] { return jsonAnswer } func callAmo(completion: @escaping ([[String : String]]) -> ()) { let urladdress = "https://api.github.com/users" Alamofire.request(urladdress).responseJSON(completionHandler: { response in switch response.result{ case .success: let dic = self.parseData(JSONData: response.data!) completion(dic) case .failure: let alertController: UIAlertController = UIAlertController(title: "Error", message: "Cannot retreive data. Please check internet connection", preferredStyle: .alert) let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil) } }) } func parseData(JSONData : Data) -> [[String: String]]{ do { var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStd let counter = readableJSON.count //Filling the dictionary for item in 0...counter - 1 { let login = readableJSON[item]["login"] let avatar_url = readableJSON[item]["avatar_url"] let html_url = readableJSON[item]["repos_url"] let id = String(describing: readableJSON[item]["id"]) let dict:[String:AnyObject] = ["login": login!, "avatar": avatar_url!, "profile": html_url!, "id": id as AnyObject] jsonAnswer.append(dict as! [String : String]) } } catch{ print("Error") } return jsonAnswer } }
// // BiggerSailsUpgrade.swift // SailingThroughHistory // // Created by henry on 7/4/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // /// An Auxiliary upgrade that causes the ship experience greater weather effects. import Foundation class BiggerSailsUpgrade: AuxiliaryUpgrade { override var type: UpgradeType { return .biggerSails } override var name: String { return "Bigger sails" } override var cost: Int { return 1000 } override func getWeatherModifier() -> Double { return 2 } }
// // HomeViewModel.swift // Pokedex // // Created by Fathureza Januarza on 25/04/18. // Copyright © 2018 Fathureza Januarza. All rights reserved. // import Foundation final class HomeViewModel { }
// // ViewController.swift // MAMI RPG // // Created by USER on 2016/12/14. // Copyright © 2016年 USER. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var result: UILabel! let bgmpath = Bundle.main.bundleURL.appendingPathComponent("マミタスクエストBGM.mp3") var bgmPlayer = AVAudioPlayer() let atpath = Bundle.main.bundleURL.appendingPathComponent("kick-high1.mp3") var atPlayer = AVAudioPlayer() var i = 1//攻撃力 var hp = 47770000//初期HP var x = 0 @IBAction func button(_ sender: Any) { hp = hp-i result.text = String(hp)+"/47770000" //ここでhpにより画像を変えていく do{ atPlayer = try AVAudioPlayer(contentsOf: atpath, fileTypeHint: nil) atPlayer.play() } catch { print("エラー") } do{ if x == 0{ bgmPlayer = try AVAudioPlayer(contentsOf: bgmpath, fileTypeHint: nil) bgmPlayer.numberOfLoops = -1 bgmPlayer.play() x = x+1 } } catch { print("エラー") } } }
// // BaseUIViewController.swift // GitHub Viewer // // Created by Itamar Lourenço on 09/06/2018. // Copyright © 2018 Ilourenco. All rights reserved. // import Foundation import UIKit class BaseUIViewController: UIViewController{ override func viewWillAppear(_ animated: Bool) { if #available(iOS 11.0, *) { self.additionalSafeAreaInsets.top = 20 } if let customNavigationBar = self.navigationController!.navigationBar as? CustomNavigationBar{ customNavigationBar.resize = resizeNavigationBar() customNavigationBar.layoutSubviews() } } func resizeNavigationBar() -> Bool{ return false } }
// // SentMemesTableViewController.swift // MemeMe // // Created by Jason on 1/31/18. // Copyright © 2018 Jason. All rights reserved. // import UIKit class SentMemesTableViewController: UITableViewController { @IBOutlet weak var addButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //unhide Nav and Tab Bars navigationController?.isNavigationBarHidden = false tabBarController?.tabBar.isHidden = false //load Table with memes data tableView!.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print(Meme.count()) return Meme.count() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { //Percent of height return 100 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: AppModel.memesTableCellReuseIdentifier, for: indexPath) as! SentMemesTableViewCell let meme = Meme.getMemeStorage().memes[indexPath.row] cell.updateCell(meme) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //get selected object let memeDetail = self.storyboard?.instantiateViewController(withIdentifier: AppModel.memeDetailStoryboardIdentifier) as! MemeDetailViewController //populate the meme data from selected row memeDetail.meme = Meme.getMemeStorage().memes[indexPath.row] //MemeDetail navigationController?.pushViewController(memeDetail, animated: true) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: Meme.getMemeStorage().memes.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) default: return } } @IBAction func unwindToSentMemeTable(unwindSegue: UIStoryboardSegue) { //Learning from https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/ } }
// // ListCell.swift // Election // // Created by xxx on 13/12/2018. // Copyright © 2018 xxx. All rights reserved. // import UIKit class ListCell: UITableViewCell{ @IBOutlet weak var listImageView: UIImageView! @IBOutlet weak var listVotesLabel: UILabel! @IBOutlet weak var listTitleLabel: UILabel! @IBOutlet weak var listPercentLabel: UILabel! var courses = [Course]() func setCandidate(candidate: Course) { listTitleLabel.text = candidate.name listVotesLabel.text = String(candidate.votes) loadAllVotes(votes: Double(candidate.votes)) } func loadAllVotes(votes: Double) { let urlString = "http://localhost:3000/users/?gaveVote=true" let url = URL(string: urlString) URLSession.shared.dataTask(with: url!) { (data, _, err) in DispatchQueue.main.async { if let err = err { print("Failed to get data from url:", err) return } guard let data = data else { return } do { // link in description for video on JSONDecoder let decoder = JSONDecoder() // Swift 4.1 decoder.keyDecodingStrategy = .convertFromSnakeCase self.courses = try decoder.decode([Course].self, from: data) print("ile1: \(self.courses.count)") if self.courses.count == 0 { self.listPercentLabel.text = String(votes / 1) } else { print("ile: \(self.courses.count)") self.listPercentLabel.text = String((votes / Double(self.courses.count)) * 100 ) print(self.listPercentLabel.text!) } } catch let jsonErr { print("Failed to decode:", jsonErr) } } }.resume() } func loadMemberAvatar(userId: String) { let userId = userId let avatarUrl = URL(string: "http://localhost:3000/Images/avatar/\(userId)") var request = URLRequest(url:avatarUrl!) request.httpMethod = "GET"// Compose a query string let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in if error != nil { // self.displayMessage(userMessage: ". Please try again later") print("error=\(String(describing: error))") return } DispatchQueue.main.async { self.listImageView.image = UIImage(data: data!) self.listImageView.layer.cornerRadius = self.listImageView.frame.size.width / 2 self.listImageView.clipsToBounds = true self.listImageView.layer.borderColor = UIColor.darkGray.cgColor self.listImageView.layer.borderWidth = 6 } } task.resume() } }
// // QuestionTableViewCell.swift // Speak // // Created by Kei Sakaguchi on 7/22/17. // Copyright © 2017 KTSS. All rights reserved. // import UIKit import MRProgress class QuestionTableViewCell: LineTableViewCell { var audioProgressView: MRCircularProgressView! var audioPlayButton: UIButton! lazy var bubbleXPos: CGFloat = { return bubbleHorizontalGap }() lazy var bubbleYPos: CGFloat = { return bubbleVerticalGap }() static var identifier: String { return "QuestionCell" } override func layoutSubviews() { super.layoutSubviews() self.messageLabel?.textColor = UIColor.white self.messageLabel?.textAlignment = NSTextAlignment.left self.messageLabel?.frame = CGRect(x: self.bubbleXPos, y: self.bubbleYPos, width: self.bubbleWidth, height: self.bubbleHeight) self.messageLabel?.backgroundColor = UIColor.questionBubbleColor //get rid of magic numbers self.audioProgressView = MRCircularProgressView(frame: CGRect(x: self.bubbleXPos + self.bubbleWidth + 5, y: 5, width: 25, height: 25)) self.audioProgressView.mayStop = true self.addSubview(self.audioProgressView) self.audioProgressView.animationDuration = 5.0 self.audioProgressView.setProgress(1, animated: true) self.audioProgressView.tintColor = UIColor.orange self.audioPlayButton = UIButton(frame: CGRect(x: self.bubbleXPos + self.bubbleWidth + 5, y: 5, width: 25, height: 25)) // self.audioPlayButton.setImage(UIImage(named: "Speaker"), for: .selected) self.audioPlayButton.addTarget(self, action: #selector(playButtonPressed), for: .touchUpInside) self.addSubview(self.audioPlayButton) self.audioPlayButton.isSelected = false self.bringSubview(toFront: audioPlayButton) } func playButtonPressed(sender: UIButton) { if audioPlayButton.isSelected { self.audioPlayButton.isSelected = false self.audioProgressView.tintColor = UIColor.blue viewModel.play { self.stop() } } else { audioPlayButton.isSelected = true viewModel.stop() } } override func play() { self.hide() } override func stop() { self.show() } func hide() { self.audioProgressView.animationDuration = 5.0 self.audioProgressView.setProgress(1, animated: true) self.audioPlayButton.isSelected = false self.audioPlayButton.isOpaque = false } func show() { self.audioProgressView.setProgress(0, animated: false) self.audioPlayButton.isSelected = true self.audioPlayButton.isOpaque = true } }
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Combine import UIKit class SettingsViewController: UITableViewController { typealias Factory = ViewControllerFactory var factory: Factory! var presenter: SettingsPresenter! var subscriptions: Set<AnyCancellable> = .init() @IBOutlet var showHiddenItemsSwitch: UISwitch! @IBOutlet var syncICloudSwitch: UISwitch! @IBOutlet var versionLabel: UILabel! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = L10n.settingViewTitle self.presenter.view = self self.presenter.shouldHideHiddenItems .assign(to: \.isOn, on: self.showHiddenItemsSwitch) .store(in: &self.subscriptions) self.presenter.shouldSyncICloudEnabled .assign(to: \.isOn, on: self.syncICloudSwitch) .store(in: &self.subscriptions) self.presenter.displayVersion() } // MARK: - IBActions @IBAction func didChangeShouldShowHiddenItems(_ sender: UISwitch) { self.presenter.set(hideHiddenItems: sender.isOn) } @IBAction func didChangeSyncICloud(_ sender: UISwitch) { guard self.presenter.set(isICloudSyncEnabled: sender.isOn) else { sender.setOnSmoothly(!sender.isOn) return } } } extension SettingsViewController: SettingsViewProtocol { // MARK: - SettingsViewProtocol func set(version: String) { self.versionLabel.text = version } func set(isICloudSyncEnabled: Bool) { self.syncICloudSwitch.setOn(isICloudSyncEnabled, animated: true) } func confirmToUnavailabilityICloudSync(shouldTurnOff: @escaping (Bool) -> Void) { let alertController = UIAlertController(title: L10n.errorIcloudUnavailableTitle, message: L10n.errorIcloudUnavailableMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: L10n.confirmAlertOk, style: .default) { _ in shouldTurnOff(false) } let turnOffAction = UIAlertAction(title: L10n.errorIcloudUnavailableTurnOffAction, style: .cancel) { _ in shouldTurnOff(true) } alertController.addAction(okAction) alertController.addAction(turnOffAction) self.present(alertController, animated: true, completion: nil) } func confirmToUnavailabilityICloudSync(shouldTurnOn: @escaping (Bool) -> Void) { let alertController = UIAlertController(title: L10n.errorIcloudUnavailableTitle, message: L10n.errorIcloudUnavailableMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: L10n.confirmAlertOk, style: .default) { _ in shouldTurnOn(false) } let turnOnAction = UIAlertAction(title: L10n.errorIcloudUnavailableTurnOnAction, style: .cancel) { _ in shouldTurnOn(true) } alertController.addAction(okAction) alertController.addAction(turnOnAction) self.present(alertController, animated: true, completion: nil) } func confirmToTurnOffICloudSync(confirmation: @escaping (Bool) -> Void) { let alertController = UIAlertController(title: L10n.settingsConfirmIcloudSyncOffTitle, message: L10n.settingsConfirmIcloudSyncOffMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: L10n.confirmAlertOk, style: .default) { _ in confirmation(true) } let cancelAction = UIAlertAction(title: L10n.confirmAlertCancel, style: .cancel) { _ in confirmation(false) } alertController.addAction(okAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } }
// // ProfileCell.swift // MyLoqta // // Created by Ashish Chauhan on 04/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit protocol ProfileCellDelegate: class { } class ProfileCell: BaseTableViewCell, NibLoadableView, ReusableView { @IBOutlet weak var viewBottomLine: UIView! @IBOutlet weak var txtFieldProfile: UITextField! @IBOutlet weak var btnEye: UIButton! weak var weakDelegate: NameCellDelegate? var currentIndexPath : IndexPath? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.txtFieldProfile.autocorrectionType = .no } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(data: [String: String], indexPath: IndexPath) { self.currentIndexPath = indexPath self.btnEye.isHidden = true // self.txtFieldProfile.addInputAccessoryView(title: "Next".localize(), target: self, selector: #selector(tapNext(sender:))) if let placeHolder = data[Constant.keys.kTitle] { self.txtFieldProfile.placeholder = placeHolder } self.txtFieldProfile.text = data[Constant.keys.kValue] if indexPath.row == 3 { self.txtFieldProfile.keyboardType = .emailAddress } else { self.txtFieldProfile.keyboardType = .default //self.txtFieldProfile.isSecureTextEntry = true } if indexPath.row == 4 { self.txtFieldProfile.returnKeyType = .done self.btnEye.isHidden = false self.txtFieldProfile.isSecureTextEntry = true } else { self.txtFieldProfile.isSecureTextEntry = false } } @objc func tapNext(sender: UIButton) { if let delegate = self.weakDelegate { delegate.tapNexKeyboard(cell: self) } } @IBAction func tapShowPassword(_ sender: UIButton) { sender.isSelected = !sender.isSelected self.txtFieldProfile.isSecureTextEntry = sender.isSelected } } extension ProfileCell: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //WhiteSpace Entered if string == " " { return false } //Text Entered for Username if let text = textField.text, let textRange = Range(range, in: text), let delegate = self.weakDelegate { var finalText = text.replacingCharacters(in: textRange, with: string) if let indexPath = self.currentIndexPath { switch indexPath.row { case 2: let cs = NSCharacterSet(charactersIn: Constant.acceptableUsernameCharacters).inverted let filtered = string.components(separatedBy: cs).joined(separator: "") if string != filtered { return false } if finalText.isEmpty { finalText = "@" } if finalText.first != "@" { finalText = "@" + finalText } if finalText.count == Constant.validation.kUserNameMax { return false } Threads.performTaskAfterDealy(0.05) { textField.text = finalText } case 3: if finalText.count > Constant.validation.kEmailMax { return false } case 4: if finalText.count == Constant.validation.kPasswordMax { return false } default: break } } delegate.updateProfileData(cell: self, text: finalText) } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let delegate = self.weakDelegate { delegate.tapNexKeyboard(cell: self) } return true } }
// // SearchCommandTests.swift // // // Created by Vladislav Fitc on 26/03/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class SearchCommandTests: XCTestCase, AlgoliaCommandTest { func testSearch() { let command = Command.Search.Search(indexName: test.indexName, query: test.query, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/query", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: test.query.httpBody, requestOptions: test.requestOptions) } func testBrowseQuery() { let command = Command.Search.Browse(indexName: test.indexName, query: test.query, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/browse", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: test.query.httpBody, requestOptions: test.requestOptions) } func testBrowseCursor() { let command = Command.Search.Browse(indexName: test.indexName, cursor: test.cursor, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/browse", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: CursorWrapper(test.cursor).httpBody, requestOptions: test.requestOptions) } func testSearchForFacets() { let command = Command.Search.SearchForFacets(indexName: test.indexName, attribute: test.attribute, facetQuery: "test facet query", query: nil, requestOptions: test.requestOptions) let body = ParamsWrapper(Query().set(\.customParameters, to: ["facetQuery": "test facet query"]).urlEncodedString).httpBody check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/facets/testAttribute/query", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: body, requestOptions: test.requestOptions) } func testSearchForFacetsWithQuery() { let command = Command.Search.SearchForFacets(indexName: test.indexName, attribute: test.attribute, facetQuery: "test facet query", query: test.query, requestOptions: test.requestOptions) let query = test.query.set(\.customParameters, to: [ "customKey": "customValue", "facetQuery": "test facet query"]) let body = ParamsWrapper(query.urlEncodedString).httpBody check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/facets/testAttribute/query", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: body, requestOptions: test.requestOptions) } }
// // NetworkDispatcher.swift // CovidApp // // Created by Joan Martin Martrus on 21/01/2021. // import Foundation class NetworkDispatcher { class func request<T: Codable>(endpoint: Endpoint, completion: @escaping (Result<T, Error>) -> ()) { var components = URLComponents() components.scheme = endpoint.scheme components.host = endpoint.baseURL components.path = endpoint.path components.queryItems = endpoint.parameters guard let url = components.url else { return } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = endpoint.method let session = URLSession(configuration: .default) NetworkLogger.log(request: urlRequest) let dataTask = session.dataTask(with: urlRequest) { (data, response, error) in if let error = error { completion(.failure(error)) return } guard response != nil, let data = data else { return } DispatchQueue.main.async { do { let responseObject = try JSONDecoder().decode(T.self, from: data) completion(.success(responseObject)) } catch let error { completion(.failure(error)) } } if let httpResponse = response as? HTTPURLResponse { NetworkLogger.log(response: httpResponse, data: data, error: error) } } dataTask.resume() } }
// // PopupTest.swift // SwiftJava // // Created by John Holdsworth on 29/07/2016. // Copyright © 2016 John Holdsworth. All rights reserved. // // Original Java Version: http://java.happycodings.com/swing/code43.html import java_lang import java_awt import javax_swing var popupTest: PopupTest! public class PopupTest: JFrameBase { public static func main() { let app = PopupTest() class MyWindowAdapter: WindowAdapterBase { override func windowClosing( e: WindowEvent? ) { System.exit( 0 ) } } app.addWindowListener( MyWindowAdapter() ) } private var items: [JRadioButtonMenuItem]! var popupMenu: JPopupMenu! public init() { super.init(javaObject: nil) inherit(try! JFrameBase("Using JPopupMenus")) popupTest = self popupMenu = JPopupMenu() let handler = ItemHandler() let colors = ["Blue", "Yellow", "Red"] let colorGroup = ButtonGroup() items = [JRadioButtonMenuItem]( repeating: JRadioButtonMenuItem(), count: colors.count ) // construct each menu item and add to popup menu also // enable event handling for each menu item for i in 0..<items.count { items[ i ] = JRadioButtonMenuItem( colors[ i ] ) _ = popupMenu.add( items[ i ] ) colorGroup.add( items[ i ] ) items[ i ].addActionListener( handler ) } getContentPane().setBackground( Color.white ) // define a MouseListener for the window that displays // a JPopupMenu when the popup trigger event occurs class MyMouseAdapter: MouseAdapterBase { override func mousePressed( e: MouseEvent? ) { checkForTriggerEvent( e ) } override func mouseReleased( e: MouseEvent? ) { checkForTriggerEvent( e ) } private func checkForTriggerEvent( _ e: MouseEvent? ) { if ( e!.isPopupTrigger() ) { popupTest.popupMenu.show( e!.getComponent(), e!.getX(), e!.getY() ) } } } addMouseListener( MyMouseAdapter() ) setSize( 300, 200 ) show() } required public init(javaObject: jobject?) { fatalError("init(javaObject:) has not been implemented") } private class ItemHandler: ActionListenerBase { override func actionPerformed( e: ActionEvent? ) { let colorValues = [Color.blue, Color.yellow, Color.red] // determine which menu item was selected for i in 0..<popupTest.items.count { if ( e!.getSource().equals(popupTest.items[ i ]) ) { popupTest.getContentPane().setBackground( colorValues[ i ] ) popupTest.repaint() return } } } } }
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -enable-id-as-any %s // REQUIRES: objc_interop import Foundation func assertTypeIsAny(_: Any.Protocol) {} func staticType<T>(_: T) -> T.Type { return T.self } let idLover = IdLover() let t1 = staticType(idLover.makesId()) assertTypeIsAny(t1) struct ArbitraryThing {} idLover.takesId(ArbitraryThing()) var x: AnyObject = NSObject() idLover.takesArray(ofId: &x) var y: Any = NSObject() idLover.takesArray(ofId: &y) // expected-error{{}}